compiling version

This commit is contained in:
Alfredo Oliviero 2024-05-16 16:32:19 +02:00
parent c2dcfac36c
commit a2a1c03067
60 changed files with 407 additions and 10921 deletions

66
pom.xml
View File

@ -69,10 +69,6 @@
<artifactId>jersey-container-servlet-core</artifactId> <artifactId>jersey-container-servlet-core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.gcube.core</groupId> <groupId>org.gcube.core</groupId>
<artifactId>common-smartgears-app</artifactId> <artifactId>common-smartgears-app</artifactId>
@ -99,6 +95,7 @@
<artifactId>social-service-model</artifactId> <artifactId>social-service-model</artifactId>
<version>2.0.0-SNAPSHOT</version> <version>2.0.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.datastax.oss</groupId> <groupId>com.datastax.oss</groupId>
<artifactId>java-driver-query-builder</artifactId> <artifactId>java-driver-query-builder</artifactId>
@ -114,12 +111,10 @@
<artifactId>commons-lang</artifactId> <artifactId>commons-lang</artifactId>
<version>2.6</version> <version>2.6</version>
</dependency> </dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.2</version>
<scope>compile</scope>
</dependency>
<dependency> <dependency>
<groupId>org.gcube.common.portal</groupId> <groupId>org.gcube.common.portal</groupId>
<artifactId>portal-manager</artifactId> <artifactId>portal-manager</artifactId>
@ -138,11 +133,7 @@
<version>${enunciate.version}</version> <version>${enunciate.version}</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- END Required for Enunciate plugin --> <!-- END Required for Enunciate plugin -->
<!-- Test libraries --> <!-- Test libraries -->
@ -157,6 +148,51 @@
<artifactId>logback-classic</artifactId> <artifactId>logback-classic</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/jakarta.mail/jakarta.mail-api -->
<dependency>
<groupId>jakarta.mail</groupId>
<artifactId>jakarta.mail-api</artifactId>
<version>1.6.7</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>org.gcube.dvos</groupId>
<artifactId>usermanagement-core</artifactId>
<version>[2.0.0-SNAPSHOT, 3.0.0-SNAPSHOT)</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.applicationsupportlayer</groupId>
<artifactId>aslsocial</artifactId>
<version>[1.8.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>4.0.4</version>
</dependency>
<dependency>
<groupId>org.gcube.idm</groupId>
<artifactId>idm-common-library</artifactId>
<version>0.0.2-SNAPSHOT</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -1,7 +1,7 @@
package org.gcube.social_networking; package org.gcube.social_networking;
import javax.ws.rs.Path; import jakarta.ws.rs.Path;
import javax.ws.rs.core.Application; import jakarta.ws.rs.core.Application;
import org.gcube.social_networking.rest.HelloWorld; import org.gcube.social_networking.rest.HelloWorld;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

View File

@ -25,7 +25,7 @@ public class SocialServiceApplicationManager implements ApplicationManager {
logger.info("Starting social service"); logger.info("Starting social service");
try{ try{
String context = SecretManagerProvider.instance.get().getContext(); String context = SecretManagerProvider.get().getContext();
logger.info( logger.info(
"\n-------------------------------------------------------\n" "\n-------------------------------------------------------\n"
+ "Social Service is Starting on context {}\n" + "Social Service is Starting on context {}\n"
@ -49,7 +49,7 @@ public class SocialServiceApplicationManager implements ApplicationManager {
@Override @Override
public synchronized void onShutdown(){ public synchronized void onShutdown(){
String context = SecretManagerProvider.instance.get().getContext(); String context = SecretManagerProvider.get().getContext();
logger.trace( logger.trace(
"\n-------------------------------------------------------\n" "\n-------------------------------------------------------\n"

View File

@ -1,29 +1,25 @@
package org.gcube.social_networking.caches; package org.gcube.social_networking.caches;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite; import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite;
import org.gcube.common.portal.GCubePortalConstants; import org.gcube.common.portal.GCubePortalConstants;
import org.gcube.common.resources.gcore.ServiceEndpoint; import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.security.secrets.Secret;
import org.gcube.portal.social.networking.liferay.ws.GroupManagerWSBuilder; import org.gcube.idm.common.is.InfrastrctureServiceClient;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.smartgears.ContextProvider; import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.application.ApplicationContext; import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.social_networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.vomanagement.usermanagement.GroupManager; import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup; import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.gcube.vomanagement.usermanagement.model.VirtualGroup; import org.gcube.vomanagement.usermanagement.model.VirtualGroup;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
/** /**
* When a notification needs to be sent, this class offers utility to discover (starting from the scope) * When a notification needs to be sent, this class offers utility to discover (starting from the scope)
* the site information needed to build up the SocialNetworkingSite object (which, for instance, contains the * the site information needed to build up the SocialNetworkingSite object (which, for instance, contains the
@ -219,28 +215,44 @@ public class SocialNetworkingSiteFinder {
*/ */
private static String discoverHostOfServiceEndpoint(String gatewayName){ private static String discoverHostOfServiceEndpoint(String gatewayName){
String currentScope = ScopeProvider.instance.get(); // String RUNTIME_RESOURCE_NAME = "identity-manager";
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears // String CATEGORY = "org.gcube.auth";
ScopeProvider.instance.set("/"+ctx.container().configuration().infrastructure()); // String END_POINT_NAME = "d4science";
String host = null; // boolean IS_ROOT_SERVICE = true;
try{
SimpleQuery query = queryFor(ServiceEndpoint.class); Secret secret = InfrastrctureServiceClient.getSecretForInfrastructure();
query.addCondition("$resource/Profile/Name/text() eq '"+ gatewayName +"'"); List<ServiceEndpoint> resources = InfrastrctureServiceClient.getEndopintsFromIS(gatewayName, CATEGORY, true, secret);
query.addCondition("$resource/Profile/Category/text() eq '"+ CATEGORY +"'"); ServiceEndpoint serviceEndpoint = resources.get(0);
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class); String host = "https://" + serviceEndpoint.profile().runtime().hostedOn();
List<ServiceEndpoint> toReturn = client.submit(query); logger.info("Gateway host is " + host);
for (ServiceEndpoint serviceEndpoint : toReturn) {
host = "https://" + serviceEndpoint.profile().runtime().hostedOn();
logger.info("Gateway host is " + host);
break;
}
}catch(Exception e){ // IsServerConfig cfg = InfrastrctureServiceClient.serviceConfigFromIS(gatewayName, CATEGORY,
logger.error("Error while retrieving host for the gateway " + gatewayName); // END_POINT_NAME, IS_ROOT_SERVICE, current_secret);
}finally{
ScopeProvider.instance.set(currentScope);
}
// String currentScope = ScopeProvider.instance.get();
// ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
// ScopeProvider.instance.set("/"+ctx.container().configuration().infrastructure());
// String host = null;
// try{
// SimpleQuery query = queryFor(ServiceEndpoint.class);
// query.addCondition("$resource/Profile/Name/text() eq '"+ gatewayName +"'");
// query.addCondition("$resource/Profile/Category/text() eq '"+ CATEGORY +"'");
// DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
// List<ServiceEndpoint> toReturn = client.submit(query);
// for (ServiceEndpoint serviceEndpoint : toReturn) {
// host = "https://" + serviceEndpoint.profile().runtime().hostedOn();
// logger.info("Gateway host is " + host);
// break;
// }
// }catch(Exception e){
// logger.error("Error while retrieving host for the gateway " + gatewayName);
// }finally{
// ScopeProvider.instance.set(currentScope);
// }
return host; return host;

View File

@ -5,8 +5,8 @@ import java.util.List;
import net.sf.ehcache.Ehcache; import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element; import net.sf.ehcache.Element;
import org.gcube.portal.social.networking.liferay.ws.GroupManagerWSBuilder; import org.gcube.social_networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder; import org.gcube.social_networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.smartgears.ContextProvider; import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.application.ApplicationContext; import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.vomanagement.usermanagement.GroupManager; import org.gcube.vomanagement.usermanagement.GroupManager;

View File

@ -1,143 +0,0 @@
package org.gcube.social_networking.liferay.ws;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.Property;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KeycloakAPICredentials {
private static final Logger logger = LoggerFactory.getLogger(KeycloakAPICredentials.class);
// the singleton obj
private static KeycloakAPICredentials singleton = new KeycloakAPICredentials();
// properties that it contains
private String keycloakURL;
private String realm;
private String clientid;
private String password;
// Service endpoint properties
private final static String RUNTIME_RESOURCE_NAME = "IAM";
private final static String CATEGORY = "Service";
/**
* Private constructor
*/
private KeycloakAPICredentials() {
logger.debug("Building KeycloakAPICredentials object");
lookupPropertiesFromIs();
logger.debug("KeycloakAPICredentials object built");
}
/**
* Read the properties from the infrastructure
*/
private void lookupPropertiesFromIs() {
logger.debug("Starting creating KeycloakAPICredentials");
String oldContext = ScopeProvider.instance.get();
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
ScopeProvider.instance.set("/"+ctx.container().configuration().infrastructure());
logger.debug("Discovering liferay user's credentials in context " + ctx.container().configuration().infrastructure());
try{
List<ServiceEndpoint> resources = getConfigurationFromIS();
if (resources.size() == 0){
logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope.");
throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope.");
}
else {
for (ServiceEndpoint res : resources) {
Iterator<AccessPoint> accessPointIterator = res.profile().accessPoints().iterator();
while (accessPointIterator.hasNext()) {
ServiceEndpoint.AccessPoint accessPoint = (ServiceEndpoint.AccessPoint) accessPointIterator
.next();
if(accessPoint.name().equals("d4science")){
keycloakURL = accessPoint.address();
realm = accessPoint.name();
clientid = accessPoint.username();
password = StringEncrypter.getEncrypter().decrypt(accessPoint.password());
logger.info("Found accesspoint URL = " + keycloakURL);
}
}
}
}
}catch(Exception e){
logger.error("Unable to retrieve such service endpoint information!", e);
return;
}finally{
if(oldContext != null)
ScopeProvider.instance.set(oldContext);
}
logger.debug("Bean built " + toString());
}
/**
* Retrieve endpoints information from IS for DB
* @return list of endpoints for ckan database
* @throws Exception
*/
private List<ServiceEndpoint> getConfigurationFromIS() throws Exception{
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '"+ RUNTIME_RESOURCE_NAME +"'");
query.addCondition("$resource/Profile/Category/text() eq '"+ CATEGORY +"'");
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> toReturn = client.submit(query);
return toReturn;
}
public static KeycloakAPICredentials getSingleton() {
if (singleton == null)
singleton = new KeycloakAPICredentials();
return singleton;
}
public String getServerURL() {
return keycloakURL;
}
public String getClientid() {
return clientid;
}
public String getPassword() {
return password;
}
public String getRealm() {
return realm;
}
@Override
public String toString() {
return "KeycloakAPICredentials [keycloakURL=" + keycloakURL + ", realm=" + realm + ", clientid=" + clientid
+ ", password=**************]";
}
}

View File

@ -3,28 +3,25 @@ package org.gcube.social_networking.liferay.ws;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor; import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor; import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.Iterator; import java.rmi.ServerException;
import java.util.List; import java.util.List;
import java.util.Map;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.common.resources.gcore.ServiceEndpoint; import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint; import org.gcube.common.security.secrets.Secret;
import org.gcube.common.resources.gcore.ServiceEndpoint.Property; import org.gcube.idm.common.is.InfrastrctureServiceClient;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.idm.common.is.IsServerConfig;
import org.gcube.resources.discovery.client.api.DiscoveryClient; import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery; import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import jakarta.ws.rs.NotFoundException;
/** /**
* This is a singleton bean instantiated at service start up. It contains * This is a singleton bean instantiated at service start up. It contains
* the credentials of the user who is allowed to perform calls to Liferay. * the credentials of the user who is allowed to perform calls to Liferay.
* Its credentials are looked up from the infrastructure. * Its credentials are looked up from the infrastructure.
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public class LiferayJSONWsCredentials { public class LiferayJSONWsCredentials {
@ -41,12 +38,16 @@ public class LiferayJSONWsCredentials {
private String password; private String password;
private int port; private int port;
// The token of the user used to send notifications/messages when an application token is provided. (will be read from web.xml) // The token of the user used to send notifications/messages when an application
private String notifierUserToken; // token is provided. (will be read from web.xml)
private String notifierUserToken;
// Service endpoint properties // Service endpoint properties
private final static String RUNTIME_RESOURCE_NAME = "D4Science Infrastructure Gateway"; private final static String RUNTIME_RESOURCE_NAME = "D4Science Infrastructure Gateway";
private final static String CATEGORY = "Portal"; private final static String CATEGORY = "Portal";
private final static String END_POINT_NAME = "JSONWSUser";
private final static boolean IS_ROOT_SERVICE = true;
/** /**
* Private constructor * Private constructor
@ -62,10 +63,10 @@ public class LiferayJSONWsCredentials {
* Load the token of the notifier user * Load the token of the notifier user
*/ */
private void loadNotifierToken() { private void loadNotifierToken() {
try{ try {
notifierUserToken = ServletContextClass.getNotifierToken(); notifierUserToken = ServletContextClass.getNotifierToken();
logger.debug("Token read " + notifierUserToken.substring(0, 5)+ "*********************"); logger.debug("Token read " + notifierUserToken.substring(0, 5) + "*********************");
}catch(Exception e){ } catch (Exception e) {
logger.error("Failed to read notifier user token!", e); logger.error("Failed to read notifier user token!", e);
} }
} }
@ -74,90 +75,70 @@ public class LiferayJSONWsCredentials {
* Read the properties from the infrastructure * Read the properties from the infrastructure
*/ */
private void lookupPropertiesFromIs() { private void lookupPropertiesFromIs() {
Secret secret = InfrastrctureServiceClient.getSecretForInfrastructure();
logger.debug("Starting creating LiferayJSONWsCredentials"); IsServerConfig cfg;
try {
String oldContext = ScopeProvider.instance.get(); cfg = InfrastrctureServiceClient.serviceConfigFromIS(RUNTIME_RESOURCE_NAME, CATEGORY,
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears END_POINT_NAME, IS_ROOT_SERVICE, secret);
ScopeProvider.instance.set("/"+ctx.container().configuration().infrastructure()); } catch (NotFoundException | ServerException e) {
logger.info("Discovering liferay user's credentials in context " + ctx.container().configuration().infrastructure());
try{
List<ServiceEndpoint> resources = getConfigurationFromIS();
if (resources.size() == 0){
logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope.");
throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope.");
}
else {
for (ServiceEndpoint res : resources) {
Iterator<AccessPoint> accessPointIterator = res.profile().accessPoints().iterator();
while (accessPointIterator.hasNext()) {
ServiceEndpoint.AccessPoint accessPoint = (ServiceEndpoint.AccessPoint) accessPointIterator
.next();
if(accessPoint.name().equals("JSONWSUser")){
// get base path
Map<String, Property> properties = accessPoint.propertyMap();
host = accessPoint.address();
schema = (String)properties.get("schema").value();
user = StringEncrypter.getEncrypter().decrypt((String)properties.get("username").value());
password = StringEncrypter.getEncrypter().decrypt((String)properties.get("password").value());
port = Integer.valueOf(properties.get("port").value());
// break
break;
}
}
}
}
}catch(Exception e){
logger.error("Unable to retrieve such service endpoint information!", e); logger.error("Unable to retrieve such service endpoint information!", e);
e.printStackTrace();
return; return;
}finally{
if(oldContext != null)
ScopeProvider.instance.set(oldContext);
} }
host = cfg.getServerUrl();
schema = cfg.getProperty("schema");
user = cfg.getProperty("username");
password = cfg.getProperty("password");
// TODO: check if needs to be decrypted
// password = StringEncrypter.getEncrypter().decrypt(passsword);
port = Integer.valueOf(cfg.getProperty("port"));
logger.debug("Bean built " + toString()); logger.debug("Bean built " + toString());
} }
/** /**
* Retrieve endpoints information from IS for DB * Retrieve endpoints information from IS for DB
*
* @return list of endpoints for ckan database * @return list of endpoints for ckan database
* @throws Exception * @throws Exception
*/ */
private List<ServiceEndpoint> getConfigurationFromIS() throws Exception{ private List<ServiceEndpoint> getConfigurationFromIS() throws Exception {
SimpleQuery query = queryFor(ServiceEndpoint.class); SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '"+ RUNTIME_RESOURCE_NAME +"'"); query.addCondition("$resource/Profile/Name/text() eq '" + RUNTIME_RESOURCE_NAME + "'");
query.addCondition("$resource/Profile/Category/text() eq '"+ CATEGORY +"'"); query.addCondition("$resource/Profile/Category/text() eq '" + CATEGORY + "'");
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class); DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> toReturn = client.submit(query); List<ServiceEndpoint> toReturn = client.submit(query);
return toReturn; return toReturn;
} }
public static LiferayJSONWsCredentials getSingleton() { public static LiferayJSONWsCredentials getSingleton() {
return singleton; return singleton;
} }
public String getHost() { public String getHost() {
return host; return host;
} }
public String getSchema() { public String getSchema() {
return schema; return schema;
} }
public String getUser() { public String getUser() {
return user; return user;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public int getPort() { public int getPort() {
return port; return port;
} }

View File

@ -3,8 +3,6 @@ package org.gcube.social_networking.liferay.ws;
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; import javax.servlet.ServletContextListener;
import org.gcube.social_networking.caches.UsersCache;
/** /**
* Loaded at start up. This class performs some init - to be done once - operations. * Loaded at start up. This class performs some init - to be done once - operations.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)

View File

@ -6,7 +6,7 @@ import com.webcohesion.enunciate.metadata.rs.ResourceGroup;
import com.webcohesion.enunciate.metadata.rs.ResourceLabel; import com.webcohesion.enunciate.metadata.rs.ResourceLabel;
import org.gcube.social_networking.socialnetworking.model.shared.Comment; import org.gcube.social_networking.socialnetworking.model.shared.Comment;
import javax.ws.rs.*; import jakarta.ws.rs.*;
import java.util.List; import java.util.List;
@Path("comments") @Path("comments")

View File

@ -5,10 +5,10 @@ import org.gcube.social_networking.SocialServiceApplicationManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.ws.rs.GET; import jakarta.ws.rs.GET;
import javax.ws.rs.Path; import jakarta.ws.rs.Path;
import javax.ws.rs.Produces; import jakarta.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
@Path("test") @Path("test")
@ManagedBy(SocialServiceApplicationManager.class) @ManagedBy(SocialServiceApplicationManager.class)

View File

@ -1,11 +1,11 @@
package org.gcube.social_networking.rest; package org.gcube.social_networking.rest;
import javax.ws.rs.WebApplicationException; import jakarta.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status; import jakarta.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper; import jakarta.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider; import jakarta.ws.rs.ext.Provider;
/** /**
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)

View File

@ -0,0 +1,27 @@
package org.gcube.social_networking.rest;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResourceGroup;
import com.webcohesion.enunciate.metadata.rs.ResourceLabel;
@Path("/test")
@ResourceGroup("Comments APIs")
@ResourceLabel("Comments APIs")
@RequestHeaders ({
@RequestHeader( name = "Authorization", description = "Bearer token, see <a href=\"https://dev.d4science.org/how-to-access-resources\">https://dev.d4science.org/how-to-access-resources</a>")
})
public class TestRest {
@GET
@Path("/test")
@Produces({"application/json;charset=UTF-8", "application/vnd.api+json"})
public String test(){
return "{\"result\":\"funziona!!!\"}";
}
}

View File

@ -10,10 +10,10 @@ import org.gcube.social_networking.utils.ResponseBean;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import javax.ws.rs.*; import jakarta.ws.rs.*;
import javax.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
@Path("attachments") @Path("attachments")
@ResourceGroup("Attachments APIs") @ResourceGroup("Attachments APIs")

View File

@ -5,30 +5,37 @@ import org.gcube.social_networking.socialnetworking.model.shared.Invite;
import org.gcube.social_networking.socialnetworking.model.shared.InviteOperationResult; import org.gcube.social_networking.socialnetworking.model.shared.InviteOperationResult;
import org.gcube.social_networking.utils.ResourceNames; import org.gcube.social_networking.utils.ResourceNames;
import org.gcube.social_networking.utils.ResponseBean; import org.gcube.social_networking.utils.ResponseBean;
import org.gcube.social_networking.socialnetworking.model.shared.Resource; import org.gcube.social_networking.socialnetworking.model.shared.IdResource;
import javax.mail.internet.AddressException; import jakarta.ws.rs.core.Response;
import javax.ws.rs.core.Response;
import java.rmi.ServerException;
import java.util.List; import java.util.List;
public class Collection { public class Collection {
//Create // Create
public Response create(Resource resource) { public Response create(IdResource resource) {
String resourceName = resource.getClass().getSimpleName(); String resourceName = resource.getClass().getSimpleName();
if (resourceName.equals(ResourceNames.INVITE)){ if (resourceName.equals(ResourceNames.INVITE)) {
ResponseBean<InviteOperationResult> responseBean = new ResponseBean<>(); ResponseBean<InviteOperationResult> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
InviteOperationResult result; InviteOperationResult result;
try { try {
result = CassandraConnection.getInstance().getDatabookStore().saveInvite((Invite)resource); result = CassandraConnection.getInstance().getDatabookStore().saveInvite((Invite) resource);
} catch (AddressException e) { } catch (ServerException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
status = (result == InviteOperationResult.SUCCESS) ? Response.Status.CREATED : (result == InviteOperationResult.ALREADY_INVITED)? Response.Status.FOUND : Response.Status.INTERNAL_SERVER_ERROR; status = (result == InviteOperationResult.SUCCESS) ? Response.Status.CREATED
: (result == InviteOperationResult.ALREADY_INVITED) ? Response.Status.FOUND
: Response.Status.INTERNAL_SERVER_ERROR;
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setMessage((result == InviteOperationResult.SUCCESS) ? resourceName + " {" + resource.getId() + "} Created Successfully" : (result == InviteOperationResult.ALREADY_INVITED) ? resourceName + " {" + resource.getId() + "} already exists" : "Error"); responseBean.setMessage((result == InviteOperationResult.SUCCESS)
responseBean.setSuccess(result==InviteOperationResult.SUCCESS); ? resourceName + " {" + resource.getId() + "} Created Successfully"
: (result == InviteOperationResult.ALREADY_INVITED)
? resourceName + " {" + resource.getId() + "} already exists"
: "Error");
responseBean.setSuccess(result == InviteOperationResult.SUCCESS);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
@ -36,45 +43,52 @@ public class Collection {
Boolean result = CassandraConnection.getInstance().getDatabookStore().create(resource); Boolean result = CassandraConnection.getInstance().getDatabookStore().create(resource);
status = result ? Response.Status.CREATED : Response.Status.FOUND; status = result ? Response.Status.CREATED : Response.Status.FOUND;
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setMessage(result ? resourceName + " {" + resource.getId() + "} Created Successfully" : resourceName + " {" + resource.getId() + "} already exists"); responseBean.setMessage(result ? resourceName + " {" + resource.getId() + "} Created Successfully"
: resourceName + " {" + resource.getId() + "} already exists");
responseBean.setSuccess(result); responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
public Response createChildOf(String parentid, Resource childResource, String parentResourceName) { public Response createChildOf(String parentid, IdResource childResource, String parentResourceName) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
String childResourceName = childResource.getClass().getSimpleName(); String childResourceName = childResource.getClass().getSimpleName();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().createChildOf(parentid, childResource, parentResourceName); Boolean result = CassandraConnection.getInstance().getDatabookStore().createChildOf(parentid, childResource,
parentResourceName);
status = result ? Response.Status.CREATED : Response.Status.FOUND; status = result ? Response.Status.CREATED : Response.Status.FOUND;
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setMessage(result ? childResourceName + " {" + childResource.getId() + "} Created Successfully for " + parentResourceName + "{" + parentid + "}." responseBean.setMessage(result
? childResourceName + " {" + childResource.getId() + "} Created Successfully for " + parentResourceName
+ "{" + parentid + "}."
: childResourceName + " {" + childResource.getId() + "} already exists"); : childResourceName + " {" + childResource.getId() + "} already exists");
responseBean.setSuccess(result); responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
public Response BatchCreateChildOfWithParameter(String parentid, String parameterName, String parameterValue, List<Resource> childResource, String parentResourceName, String childResourceName) { public Response BatchCreateChildOfWithParameter(String parentid, String parameterName, String parameterValue,
List<IdResource> childResource, String parentResourceName, String childResourceName) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().BatchCreateChildOfWithParameter(parentid, parameterName, parameterValue, childResource, parentResourceName, childResourceName); Boolean result = CassandraConnection.getInstance().getDatabookStore().BatchCreateChildOfWithParameter(parentid,
parameterName, parameterValue, childResource, parentResourceName, childResourceName);
status = result ? Response.Status.OK : Response.Status.NOT_FOUND; status = result ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(result ? childResourceName + " created Successfully" : childResourceName + " cannot be found"); responseBean.setMessage(
result ? childResourceName + " created Successfully" : childResourceName + " cannot be found");
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setSuccess(result); responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
// Read
//Read
public Response read(String id, String resourceName) { public Response read(String id, String resourceName) {
ResponseBean<Resource> responseBean = new ResponseBean<>(); ResponseBean<IdResource> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
Resource resource = CassandraConnection.getInstance().getDatabookStore().read(id, resourceName); IdResource resource = CassandraConnection.getInstance().getDatabookStore().read(id, resourceName);
status = resource != null ? Response.Status.OK : Response.Status.NOT_FOUND; status = resource != null ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(resource != null ? resourceName + " {" + id + "} fetched Successfully" : resourceName + " {" + id + "} cannot be found"); responseBean.setMessage(resource != null ? resourceName + " {" + id + "} fetched Successfully"
: resourceName + " {" + id + "} cannot be found");
responseBean.setSuccess(resource != null); responseBean.setSuccess(resource != null);
responseBean.setResult(resource); responseBean.setResult(resource);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
@ -83,42 +97,50 @@ public class Collection {
public Response check(String id, String parameterName, String parameterValue, String resourceName) { public Response check(String id, String parameterName, String parameterValue, String resourceName) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().check(id, parameterName, parameterValue, resourceName); Boolean result = CassandraConnection.getInstance().getDatabookStore().check(id, parameterName, parameterValue,
resourceName);
status = result != null ? Response.Status.OK : Response.Status.NOT_FOUND; status = result != null ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(result != null ? resourceName + " {" + id + "} checked Successfully" : resourceName + " {" + id + "} cannot be found"); responseBean.setMessage(result != null ? resourceName + " {" + id + "} checked Successfully"
: resourceName + " {" + id + "} cannot be found");
responseBean.setSuccess(result != null); responseBean.setSuccess(result != null);
responseBean.setResult(result); responseBean.setResult(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
public Response checkChildOf(String parentid, String parameterName, String parameterValue, String parentResourceName, String childResourceName) { public Response checkChildOf(String parentid, String parameterName, String parameterValue,
String parentResourceName, String childResourceName) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().checkChildOf(parentid, parameterName, parameterValue, parentResourceName, childResourceName); Boolean result = CassandraConnection.getInstance().getDatabookStore().checkChildOf(parentid, parameterName,
parameterValue, parentResourceName, childResourceName);
status = result != null ? Response.Status.OK : Response.Status.NOT_FOUND; status = result != null ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(result != null ? childResourceName + " {" + parentid + "} checked Successfully" : childResourceName + " {" + parentid + "} cannot be found"); responseBean.setMessage(result != null ? childResourceName + " {" + parentid + "} checked Successfully"
: childResourceName + " {" + parentid + "} cannot be found");
responseBean.setSuccess(result != null); responseBean.setSuccess(result != null);
responseBean.setResult(result); responseBean.setResult(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
public Response readAll(String resourceName) { public Response readAll(String resourceName) {
ResponseBean<List<Resource>> responseBean = new ResponseBean<>(); ResponseBean<List<IdResource>> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
List<Resource> resources = CassandraConnection.getInstance().getDatabookStore().readAll(resourceName); List<IdResource> resources = CassandraConnection.getInstance().getDatabookStore().readAll(resourceName);
status = resources != null ? Response.Status.OK : Response.Status.NOT_FOUND; status = resources != null ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(resources != null ? resourceName + "s {" + "} fetched Successfully" : resourceName + "s {" + "} cannot be found"); responseBean.setMessage(resources != null ? resourceName + "s {" + "} fetched Successfully"
: resourceName + "s {" + "} cannot be found");
responseBean.setSuccess(resources != null); responseBean.setSuccess(resources != null);
responseBean.setResult(resources); responseBean.setResult(resources);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
public Response readChildOf(String parentid, String parentResourceName, String childResourceName) { public Response readChildOf(String parentid, String parentResourceName, String childResourceName) {
ResponseBean<List<Resource>> responseBean = new ResponseBean<>(); ResponseBean<List<IdResource>> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
List<Resource> resources = CassandraConnection.getInstance().getDatabookStore().readChildOf(parentid, parentResourceName, childResourceName); List<IdResource> resources = CassandraConnection.getInstance().getDatabookStore().readChildOf(parentid,
parentResourceName, childResourceName);
status = resources != null ? Response.Status.OK : Response.Status.NOT_FOUND; status = resources != null ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(resources != null ? childResourceName + " of " + parentResourceName + " {" + parentid + "} fetched Successfully" responseBean.setMessage(resources != null
? childResourceName + " of " + parentResourceName + " {" + parentid + "} fetched Successfully"
: parentResourceName + " {" + parentid + "} cannot be found"); : parentResourceName + " {" + parentid + "} cannot be found");
responseBean.setSuccess(resources != null); responseBean.setSuccess(resources != null);
responseBean.setResult(resources); responseBean.setResult(resources);
@ -126,11 +148,13 @@ public class Collection {
} }
public Response readWithParameter(String parameterName, String parameterValue, String resourceName) { public Response readWithParameter(String parameterName, String parameterValue, String resourceName) {
ResponseBean<List<Resource>> responseBean = new ResponseBean<>(); ResponseBean<List<IdResource>> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
List<Resource> resources = CassandraConnection.getInstance().getDatabookStore().readWithParameter(parameterName, parameterValue, resourceName); List<IdResource> resources = CassandraConnection.getInstance().getDatabookStore().readWithParameter(parameterName,
parameterValue, resourceName);
status = resources != null ? Response.Status.OK : Response.Status.NOT_FOUND; status = resources != null ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(resources != null ? resourceName + "with " + parameterName + "=" + parameterValue + " fetched Successfully" responseBean.setMessage(resources != null
? resourceName + "with " + parameterName + "=" + parameterValue + " fetched Successfully"
: resourceName + "with " + parameterName + "=" + parameterValue + " cannot be found"); : resourceName + "with " + parameterName + "=" + parameterValue + " cannot be found");
responseBean.setSuccess(resources != null); responseBean.setSuccess(resources != null);
responseBean.setResult(resources); responseBean.setResult(resources);
@ -138,100 +162,120 @@ public class Collection {
} }
public Response readChildOfWithParameter(String parentid, String parameterName, String parameterValue, public Response readChildOfWithParameter(String parentid, String parameterName, String parameterValue,
String parentResourceName, String childResourceName) { String parentResourceName, String childResourceName) {
ResponseBean<List<Resource>> responseBean = new ResponseBean<>(); ResponseBean<List<IdResource>> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
List<Resource> resources = CassandraConnection.getInstance().getDatabookStore().readChildOfWithParameter(parentid, parameterName, parameterValue, parentResourceName, childResourceName); List<IdResource> resources = CassandraConnection.getInstance().getDatabookStore().readChildOfWithParameter(
parentid, parameterName, parameterValue, parentResourceName, childResourceName);
status = resources != null ? Response.Status.OK : Response.Status.NOT_FOUND; status = resources != null ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(resources != null ? childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "=" + parameterValue + " fetched Successfully" responseBean.setMessage(resources != null
: childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "=" + parameterValue + " cannot be found"); ? childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "="
+ parameterValue + " fetched Successfully"
: childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "="
+ parameterValue + " cannot be found");
responseBean.setSuccess(resources != null); responseBean.setSuccess(resources != null);
responseBean.setResult(resources); responseBean.setResult(resources);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
//Update // Update
public Response update(String id, Resource resource) { public Response update(String id, IdResource resource) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
String resourceName = resource.getClass().getSimpleName(); String resourceName = resource.getClass().getSimpleName();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().update(resource); Boolean result = CassandraConnection.getInstance().getDatabookStore().update(resource);
status = result ? Response.Status.OK : Response.Status.NOT_FOUND; status = result ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(result ? resourceName + " {" + id + "} updated Successfully" : resourceName + " {" + id + "} cannot be found"); responseBean.setMessage(result ? resourceName + " {" + id + "} updated Successfully"
: resourceName + " {" + id + "} cannot be found");
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setSuccess(result); responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
public Response updateChildOf(String parentid, String childid, Resource childResource, String parentResourceName) { public Response updateChildOf(String parentid, String childid, IdResource childResource, String parentResourceName) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
String childResourceName = childResource.getClass().getSimpleName(); String childResourceName = childResource.getClass().getSimpleName();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().updateChildOf(parentid, childid, childResource, parentResourceName); Boolean result = CassandraConnection.getInstance().getDatabookStore().updateChildOf(parentid, childid,
childResource, parentResourceName);
status = result ? Response.Status.OK : Response.Status.NOT_FOUND; status = result ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(result ? childResourceName + " {" + childid + "} updated Successfully" : childResourceName + " {" + childid + "} cannot be found"); responseBean.setMessage(result ? childResourceName + " {" + childid + "} updated Successfully"
: childResourceName + " {" + childid + "} cannot be found");
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setSuccess(result); responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
public Response BatchUpdateChildOf(String parentid, List<Resource> childResource, String parentResourceName) { public Response BatchUpdateChildOf(String parentid, List<IdResource> childResource, String parentResourceName) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
String childResourceName = childResource.get(0).getClass().getSimpleName(); String childResourceName = childResource.get(0).getClass().getSimpleName();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().BatchUpdateChildOf(parentid, childResource, parentResourceName); Boolean result = CassandraConnection.getInstance().getDatabookStore().BatchUpdateChildOf(parentid,
childResource, parentResourceName);
status = result ? Response.Status.OK : Response.Status.NOT_FOUND; status = result ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(result ? childResourceName + " updated Successfully" : childResourceName + " cannot be found"); responseBean.setMessage(
result ? childResourceName + " updated Successfully" : childResourceName + " cannot be found");
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setSuccess(result); responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
public Response updateWithParameter(String parameterName, String parameterValue, Resource resource) { public Response updateWithParameter(String parameterName, String parameterValue, IdResource resource) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
String resourceName = resource.getClass().getSimpleName(); String resourceName = resource.getClass().getSimpleName();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().updateWithParameter(parameterName, parameterValue, resource); Boolean result = CassandraConnection.getInstance().getDatabookStore().updateWithParameter(parameterName,
parameterValue, resource);
status = result ? Response.Status.OK : Response.Status.NOT_FOUND; status = result ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(result ? resourceName + " with" + parameterName + "=" + parameterValue + " updated Successfully" responseBean.setMessage(
: resourceName + " with" + parameterName + "=" + parameterValue + " cannot be found"); result ? resourceName + " with" + parameterName + "=" + parameterValue + " updated Successfully"
: resourceName + " with" + parameterName + "=" + parameterValue + " cannot be found");
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setSuccess(result); responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
public Response updateChildOfWithParameter(String parentid, String parameterName, String parameterValue, public Response updateChildOfWithParameter(String parentid, String parameterName, String parameterValue,
Resource childResource, String parentResourceName) { IdResource childResource, String parentResourceName) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
String childResourceName = childResource.getClass().getSimpleName(); String childResourceName = childResource.getClass().getSimpleName();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().updateChildOfWithParameter(parentid, parameterName, parameterValue, childResource, parentResourceName); Boolean result = CassandraConnection.getInstance().getDatabookStore().updateChildOfWithParameter(parentid,
parameterName, parameterValue, childResource, parentResourceName);
status = result ? Response.Status.OK : Response.Status.NOT_FOUND; status = result ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(result ? childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "=" + parameterValue + " updated Successfully" responseBean.setMessage(result
: childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "=" + parameterValue + " cannot be found"); ? childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "="
+ parameterValue + " updated Successfully"
: childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "="
+ parameterValue + " cannot be found");
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setSuccess(result); responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
//Delete // Delete
public Response delete(String id, String resourceName) { public Response delete(String id, String resourceName) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().delete(id, resourceName); Boolean result = CassandraConnection.getInstance().getDatabookStore().delete(id, resourceName);
status = result ? Response.Status.OK : Response.Status.NOT_FOUND; status = result ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(result ? resourceName + " {" + id + "} deleted Successfully" : resourceName + " {" + id + "} cannot be found"); responseBean.setMessage(result ? resourceName + " {" + id + "} deleted Successfully"
: resourceName + " {" + id + "} cannot be found");
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setSuccess(result); responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
public Response deleteChildOf(String parentid, String childid, String parentResourceName, String childResourceName) { public Response deleteChildOf(String parentid, String childid, String parentResourceName,
String childResourceName) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().deleteChildOf(parentid, childid, childResourceName); Boolean result = CassandraConnection.getInstance().getDatabookStore().deleteChildOf(parentid, childid,
childResourceName);
status = result ? Response.Status.OK : Response.Status.NOT_FOUND; status = result ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(result ? childResourceName + " {" + childid + "} deleted Successfully for " + parentResourceName + "{" + parentid + "}." responseBean.setMessage(result
? childResourceName + " {" + childid + "} deleted Successfully for " + parentResourceName + "{"
+ parentid + "}."
: childResourceName + " {" + childid + "} cannot be found"); : childResourceName + " {" + childid + "} cannot be found");
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setSuccess(result); responseBean.setSuccess(result);
@ -241,36 +285,45 @@ public class Collection {
public Response deleteWithParameter(String parameterName, String parameterValue, String resourceName) { public Response deleteWithParameter(String parameterName, String parameterValue, String resourceName) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().deleteWithParameter(parameterName, parameterValue, resourceName); Boolean result = CassandraConnection.getInstance().getDatabookStore().deleteWithParameter(parameterName,
parameterValue, resourceName);
status = result ? Response.Status.OK : Response.Status.NOT_FOUND; status = result ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setMessage(result ? resourceName + " with" + parameterName + "=" + parameterValue + " deleted Successfully" responseBean.setMessage(
: resourceName + " with" + parameterName + "=" + parameterValue + " cannot be found"); result ? resourceName + " with" + parameterName + "=" + parameterValue + " deleted Successfully"
: resourceName + " with" + parameterName + "=" + parameterValue + " cannot be found");
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setSuccess(result); responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
public Response deleteChildOfWithParameter(String parentid, String childid, String parameterName, String parameterValue, String parentResourceName, String childResourceName) { public Response deleteChildOfWithParameter(String parentid, String childid, String parameterName,
ResponseBean<Boolean> responseBean = new ResponseBean<>(); String parameterValue, String parentResourceName, String childResourceName) {
Response.Status status; ResponseBean<Boolean> responseBean = new ResponseBean<>();
Boolean result = CassandraConnection.getInstance().getDatabookStore().deleteChildOfWithParameter(parentid, childid, parameterName, parameterValue, parentResourceName, childResourceName); Response.Status status;
status = result ? Response.Status.OK : Response.Status.NOT_FOUND; Boolean result = CassandraConnection.getInstance().getDatabookStore().deleteChildOfWithParameter(parentid,
responseBean.setMessage(result ? childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "=" + parameterValue + " deleted Successfully" childid, parameterName, parameterValue, parentResourceName, childResourceName);
: childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "=" + parameterValue + " cannot be found"); status = result ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setResult(result); responseBean.setMessage(result
responseBean.setSuccess(result); ? childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "="
return Response.status(status).entity(responseBean).build(); + parameterValue + " deleted Successfully"
: childResourceName + " of " + parentResourceName + "{" + parentid + "}" + "with " + parameterName + "="
+ parameterValue + " cannot be found");
responseBean.setResult(result);
responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build();
} }
public Response BatchDeleteChildOfWithParameter (String parentid, String parameterName, String public Response BatchDeleteChildOfWithParameter(String parentid, String parameterName, String parameterValue,
parameterValue, List < Resource > childResource, String parentResourceName, String childResourceName){ List<IdResource> childResource, String parentResourceName, String childResourceName) {
ResponseBean<Boolean> responseBean = new ResponseBean<>(); ResponseBean<Boolean> responseBean = new ResponseBean<>();
Response.Status status; Response.Status status;
Boolean result = CassandraConnection.getInstance().getDatabookStore().BatchDeleteChildOfWithParameter(parentid, parameterName, parameterValue, childResource, parentResourceName, childResourceName); Boolean result = CassandraConnection.getInstance().getDatabookStore().BatchDeleteChildOfWithParameter(parentid,
status = result ? Response.Status.OK : Response.Status.NOT_FOUND; parameterName, parameterValue, childResource, parentResourceName, childResourceName);
responseBean.setMessage(result ? childResourceName + " deleted Successfully" : childResourceName + " cannot be found"); status = result ? Response.Status.OK : Response.Status.NOT_FOUND;
responseBean.setResult(result); responseBean.setMessage(
responseBean.setSuccess(result); result ? childResourceName + " deleted Successfully" : childResourceName + " cannot be found");
return Response.status(status).entity(responseBean).build(); responseBean.setResult(result);
responseBean.setSuccess(result);
return Response.status(status).entity(responseBean).build();
} }
} }

View File

@ -10,10 +10,10 @@ import org.gcube.social_networking.utils.ResponseBean;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import javax.ws.rs.*; import jakarta.ws.rs.*;
import javax.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
@Path("comments") @Path("comments")
@ResourceGroup("Comments APIs") @ResourceGroup("Comments APIs")

View File

@ -11,9 +11,9 @@ import org.gcube.social_networking.utils.ResponseBean;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import javax.ws.rs.*; import jakarta.ws.rs.*;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View File

@ -10,10 +10,10 @@ import org.gcube.social_networking.utils.ResponseBean;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import javax.ws.rs.*; import jakarta.ws.rs.*;
import javax.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
@Path("invites") @Path("invites")
@ResourceGroup("Invites APIs") @ResourceGroup("Invites APIs")

View File

@ -10,10 +10,10 @@ import org.gcube.social_networking.utils.ResponseBean;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import javax.ws.rs.*; import jakarta.ws.rs.*;
import javax.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
@Path("likes") @Path("likes")
@ResourceGroup("Likes APIs") @ResourceGroup("Likes APIs")

View File

@ -10,10 +10,10 @@ import org.gcube.social_networking.utils.ResponseBean;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import javax.ws.rs.*; import jakarta.ws.rs.*;
import javax.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
@Path("notifications") @Path("notifications")
@ResourceGroup("Notifications APIs") @ResourceGroup("Notifications APIs")

View File

@ -11,10 +11,10 @@ import org.gcube.social_networking.utils.Schema;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import javax.ws.rs.*; import jakarta.ws.rs.*;
import javax.ws.rs.core.MediaType; import jakarta.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
@Path("posts") @Path("posts")
@ResourceGroup("Posts APIs") @ResourceGroup("Posts APIs")

View File

@ -11,10 +11,10 @@ import org.gcube.social_networking.utils.ResponseBean;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import javax.ws.rs.*; import jakarta.ws.rs.*;
import javax.ws.rs.core.GenericType; import jakarta.ws.rs.core.GenericType;
import javax.ws.rs.core.Response; import jakarta.ws.rs.core.Response;
import java.util.*; import java.util.*;

View File

@ -1,10 +1,11 @@
package org.gcube.social_networking.server; package org.gcube.social_networking.server;
import java.rmi.ServerException;
import java.time.Instant; import java.time.Instant;
import java.util.*; import java.util.*;
import javax.mail.internet.AddressException; // import jakarta.mail.internet.AddressException;
import javax.mail.internet.InternetAddress; // import jakarta.mail.internet.InternetAddress;
import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.cql.*; import com.datastax.oss.driver.api.core.cql.*;
@ -80,7 +81,7 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
* *
*/ */
@Override @Override
public Boolean create(Resource resource) { public Boolean create(IdResource resource) {
String resourceName = resource.getClass().getSimpleName(); String resourceName = resource.getClass().getSimpleName();
if(resourceName.equals(ResourceNames.POST)){ if(resourceName.equals(ResourceNames.POST)){
try { try {
@ -98,7 +99,7 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
@Override @Override
public Boolean createChildOf(String parentid, Resource childResource, String parentResourceName){ public Boolean createChildOf(String parentid, IdResource childResource, String parentResourceName){
String resourceName = childResource.getClass().getSimpleName(); String resourceName = childResource.getClass().getSimpleName();
if(parentResourceName.equals(ResourceNames.VRE)) { if(parentResourceName.equals(ResourceNames.VRE)) {
if(resourceName.equals(ResourceNames.POST)){ if(resourceName.equals(ResourceNames.POST)){
@ -130,11 +131,11 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
@Override @Override
public Boolean BatchCreateChildOfWithParameter(String parentid, String parameterName, String parameterValue, List<Resource> childResource, String parentResourceName, String childResourceName){ public Boolean BatchCreateChildOfWithParameter(String parentid, String parameterName, String parameterValue, List<IdResource> childResource, String parentResourceName, String childResourceName){
if(parentResourceName.equals(ResourceNames.VRE)){ if(parentResourceName.equals(ResourceNames.VRE)){
if(childResourceName.equals(ResourceNames.HASHTAG)){ if(childResourceName.equals(ResourceNames.HASHTAG)){
List<String> hashtags = new ArrayList<>(); List<String> hashtags = new ArrayList<>();
for(Resource r: childResource){ for(IdResource r: childResource){
Hashtag h = (Hashtag) r; Hashtag h = (Hashtag) r;
hashtags.add(h.getHashtag()); hashtags.add(h.getHashtag());
} }
@ -157,7 +158,7 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
@Override @Override
public Resource read(String id, String resourceName) { public IdResource read(String id, String resourceName) {
if(resourceName.equals(ResourceNames.POST)){ if(resourceName.equals(ResourceNames.POST)){
try { try {
return readPost(id); return readPost(id);
@ -224,7 +225,7 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
@Override @Override
public List<Resource> readAll(String resourceName) { public List<IdResource> readAll(String resourceName) {
if(resourceName.equals(ResourceNames.VRE)){ if(resourceName.equals(ResourceNames.VRE)){
return new ArrayList<>(getAllVREIds()); return new ArrayList<>(getAllVREIds());
} }
@ -233,7 +234,7 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
} }
@Override @Override
public List<Resource>readChildOf(String parentid, String parentResourceName, String childResourceName){ public List<IdResource>readChildOf(String parentid, String parentResourceName, String childResourceName){
if (parentResourceName.equals(ResourceNames.POST)){ if (parentResourceName.equals(ResourceNames.POST)){
if(childResourceName.equals(ResourceNames.COMMENT)){ if(childResourceName.equals(ResourceNames.COMMENT)){
return getAllChildrenByPost(parentid, COMMENTS); return getAllChildrenByPost(parentid, COMMENTS);
@ -283,7 +284,7 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
@Override @Override
public List<Resource> readChildOfWithParameter(String parentid, String parameterName, String parameterValue, String parentResourceName, String childResourceName){ public List<IdResource> readChildOfWithParameter(String parentid, String parameterName, String parameterValue, String parentResourceName, String childResourceName){
if(parentResourceName.equals(ResourceNames.VRE)) { if(parentResourceName.equals(ResourceNames.VRE)) {
if (childResourceName.equals(ResourceNames.POST)) { if (childResourceName.equals(ResourceNames.POST)) {
if (parameterName.equals(ParameterNames.RECENT_LIMIT)) { if (parameterName.equals(ParameterNames.RECENT_LIMIT)) {
@ -372,10 +373,10 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
}else if (parameterName.equals(ParameterNames.NOTIFICATION_TYPE)) { }else if (parameterName.equals(ParameterNames.NOTIFICATION_TYPE)) {
try { try {
List<Resource> resources = new ArrayList<>(); List<IdResource> resources = new ArrayList<>();
List<NotificationChannelType> notificationChannelTypes = getUserNotificationChannels(parentid, NotificationType.valueOf(parameterName)); List<NotificationChannelType> notificationChannelTypes = getUserNotificationChannels(parentid, NotificationType.valueOf(parameterName));
for (NotificationChannelType n: notificationChannelTypes) { for (NotificationChannelType n: notificationChannelTypes) {
Resource x = new Resource() { IdResource x = new IdResource() {
String notChannel = n.toString(); String notChannel = n.toString();
@Override @Override
public String getId() { public String getId() {
@ -405,7 +406,7 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
@Override @Override
public List<Resource> readWithParameter(String parameterName, String parameterValue, String resourceName) { public List<IdResource> readWithParameter(String parameterName, String parameterValue, String resourceName) {
if(resourceName.equals(Post.class.getSimpleName())){ if(resourceName.equals(Post.class.getSimpleName())){
try { try {
if(parameterName.equals(PRIVACY)){ if(parameterName.equals(PRIVACY)){
@ -458,11 +459,11 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
@Override @Override
public Boolean BatchDeleteChildOfWithParameter(String parentid, String parameterName, String parameterValue, List<Resource> childResource, String parentResourceName, String childResourceName){ public Boolean BatchDeleteChildOfWithParameter(String parentid, String parameterName, String parameterValue, List<IdResource> childResource, String parentResourceName, String childResourceName){
if(parentResourceName.equals(ResourceNames.VRE)){ if(parentResourceName.equals(ResourceNames.VRE)){
if(childResourceName.equals(ResourceNames.HASHTAG)){ if(childResourceName.equals(ResourceNames.HASHTAG)){
List<String> hashtags = new ArrayList<>(); List<String> hashtags = new ArrayList<>();
for(Resource r: childResource){ for(IdResource r: childResource){
Hashtag h = (Hashtag) r; Hashtag h = (Hashtag) r;
hashtags.add(h.getHashtag()); hashtags.add(h.getHashtag());
} }
@ -501,7 +502,7 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
@Override @Override
public Boolean update(Resource resource) { public Boolean update(IdResource resource) {
String resourceName = resource.getClass().getSimpleName(); String resourceName = resource.getClass().getSimpleName();
if(resourceName.equals(Notification.class.getSimpleName())){ if(resourceName.equals(Notification.class.getSimpleName())){
@ -525,7 +526,7 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
@Override @Override
public Boolean updateChildOf(String parentid, String childid, Resource childResource, String parentResourceName){ public Boolean updateChildOf(String parentid, String childid, IdResource childResource, String parentResourceName){
if(parentResourceName.equals(ResourceNames.USER)) { if(parentResourceName.equals(ResourceNames.USER)) {
String childResourceName = childResource.getClass().getSimpleName(); String childResourceName = childResource.getClass().getSimpleName();
if (childResourceName.equals(ResourceNames.NOTIFICATION)){ if (childResourceName.equals(ResourceNames.NOTIFICATION)){
@ -543,12 +544,12 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
return null; return null;
} }
@Override @Override
public Boolean BatchUpdateChildOf(String parentid, List<Resource> childResource, String parentResourceName){ public Boolean BatchUpdateChildOf(String parentid, List<IdResource> childResource, String parentResourceName){
if(parentResourceName.equals(ResourceNames.USER)) { if(parentResourceName.equals(ResourceNames.USER)) {
String childResourceName = childResource.get(0).getClass().getSimpleName(); String childResourceName = childResource.get(0).getClass().getSimpleName();
if (childResourceName.equals(NOTIFICATION_PREFERENCES)){ if (childResourceName.equals(NOTIFICATION_PREFERENCES)){
List<NotificationPreference> notificationPreferences = new ArrayList<>(); List<NotificationPreference> notificationPreferences = new ArrayList<>();
for(Resource r: childResource){ for(IdResource r: childResource){
notificationPreferences.add((NotificationPreference) r); notificationPreferences.add((NotificationPreference) r);
} }
return setUserNotificationPreferences(parentid, notificationPreferences); return setUserNotificationPreferences(parentid, notificationPreferences);
@ -558,12 +559,12 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
} }
@Override @Override
public Boolean updateWithParameter(String parameterName, String parameterValue, Resource resource) { public Boolean updateWithParameter(String parameterName, String parameterValue, IdResource resource) {
return null; return null;
} }
@Override @Override
public Boolean updateChildOfWithParameter(String parentid, String parameterName, String parameterValue, Resource childResource, String parentResourceName){ public Boolean updateChildOfWithParameter(String parentid, String parameterName, String parameterValue, IdResource childResource, String parentResourceName){
if(parentResourceName.equals(ResourceNames.VRE)){ if(parentResourceName.equals(ResourceNames.VRE)){
String childResourceName = childResource.getClass().getSimpleName(); String childResourceName = childResource.getClass().getSimpleName();
if(childResourceName.equals(ResourceNames.INVITE)){ if(childResourceName.equals(ResourceNames.INVITE)){
@ -694,9 +695,9 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
_log.info("Delete Post OK"); _log.info("Delete Post OK");
return true; return true;
} }
private List<Resource> getAllChildrenByPost(String postid,String childType){ private List<IdResource> getAllChildrenByPost(String postid,String childType){
ResultSet result = null; ResultSet result = null;
List<Resource> toReturn = new ArrayList<>(); List<IdResource> toReturn = new ArrayList<>();
CqlSession session = conn.getKeyspaceSession(); CqlSession session = conn.getKeyspaceSession();
PreparedStatement stmtFind = session.prepare(QueryBuilder PreparedStatement stmtFind = session.prepare(QueryBuilder
.selectFrom(childType).all() .selectFrom(childType).all()
@ -705,7 +706,7 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
try { try {
result = session.execute(stmtFind.bind(UUID.fromString(postid))); result = session.execute(stmtFind.bind(UUID.fromString(postid)));
for (Row row: result) { for (Row row: result) {
Resource toAdd = childType.equals(LIKES) ? readLikeFromRow(row) : IdResource toAdd = childType.equals(LIKES) ? readLikeFromRow(row) :
childType.equals(COMMENTS)? readCommentFromRow(row) : childType.equals(COMMENTS)? readCommentFromRow(row) :
childType.equals(ATTACHMENTS)?readAttachmentFromRow(row) : null; childType.equals(ATTACHMENTS)?readAttachmentFromRow(row) : null;
if(toAdd == null) throw new Exception("No child resource named " + childType); if(toAdd == null) throw new Exception("No child resource named " + childType);
@ -1520,8 +1521,8 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
// retrieve the like of the user for the post // retrieve the like of the user for the post
if(isPostOk){ if(isPostOk){
List<Resource> likes = getAllChildrenByPost(postid, LIKES); List<IdResource> likes = getAllChildrenByPost(postid, LIKES);
for (Resource x : likes) { for (IdResource x : likes) {
Like like = (Like) x; Like like = (Like) x;
if(like.getTime().getTime() >= timeInMillis && like.getUserid().equals(userid)) if(like.getTime().getTime() >= timeInMillis && like.getUserid().equals(userid))
toReturn.add(toCheck); toReturn.add(toCheck);
@ -1818,12 +1819,12 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
@Override @Override
public InviteOperationResult saveInvite(Invite invite) throws AddressException { public InviteOperationResult saveInvite(Invite invite) throws ServerException {
if (invite == null) if (invite == null)
throw new NullArgumentException("Invite instance is null"); throw new NullArgumentException("Invite instance is null");
String email = invite.getInvitedEmail(); String email = invite.getInvitedEmail();
if (! verifyEmail(email)) if (! verifyEmail(email))
throw new AddressException("Email is not valid ->" + email); throw new ServerException("Email is not valid ->" + email);
if (invite.getVreid() == null || invite.getVreid().equals("")) if (invite.getVreid() == null || invite.getVreid().equals(""))
throw new NullArgumentException("VREId is null or empty"); throw new NullArgumentException("VREId is null or empty");
_log.debug("isExistingInvite? " + invite.getInvitedEmail() + " in " + invite.getVreid()); _log.debug("isExistingInvite? " + invite.getInvitedEmail() + " in " + invite.getVreid());
@ -2548,14 +2549,16 @@ public final class SocialDBDatastaxDriver implements SocialDBDriver{
*/ */
private boolean verifyEmail(String email) { private boolean verifyEmail(String email) {
boolean isValid = false; boolean isValid = false;
try { // TODO: validation
InternetAddress internetAddress = new InternetAddress(email); return true;
internetAddress.validate(); // try {
isValid = true; // InternetAddress internetAddress = new InternetAddress(email);
} catch (AddressException e) { // internetAddress.validate();
_log.error("Validation Exception Occurred for email: " + email); // isValid = true;
} // } catch (AddressException e) {
return isValid; // _log.error("Validation Exception Occurred for email: " + email);
// }
// return isValid;
} }

View File

@ -1,11 +1,9 @@
package org.gcube.social_networking.server; package org.gcube.social_networking.server;
import java.rmi.ServerException;
import java.util.List; import java.util.List;
import java.util.Map;
import javax.mail.internet.AddressException; import org.gcube.social_networking.socialnetworking.model.shared.IdResource;
import org.gcube.social_networking.socialnetworking.model.shared.Resource;
import org.gcube.social_networking.socialnetworking.model.shared.Invite; import org.gcube.social_networking.socialnetworking.model.shared.Invite;
import org.gcube.social_networking.socialnetworking.model.shared.InviteOperationResult; import org.gcube.social_networking.socialnetworking.model.shared.InviteOperationResult;
@ -19,20 +17,20 @@ public interface SocialDBDriver {
/** /**
* create a resource in the DB * create a resource in the DB
*/ */
Boolean create(Resource resource); Boolean create(IdResource resource);
/** /**
* create a child resource given its parent id in the DB * create a child resource given its parent id in the DB
*/ */
Boolean createChildOf(String parentid, Resource childResource, String parentResourceName); Boolean createChildOf(String parentid, IdResource childResource, String parentResourceName);
/** /**
* batch create a child resource given its parent id in the DB * batch create a child resource given its parent id in the DB
*/ */
Boolean BatchCreateChildOfWithParameter(String parentid, String parameterName, String parameterValue, List<Resource> childResource, String parentResourceName, String childResourceName); Boolean BatchCreateChildOfWithParameter(String parentid, String parameterName, String parameterValue, List<IdResource> childResource, String parentResourceName, String childResourceName);
/** /**
* read a resource given its id from the DB * read a resource given its id from the DB
*/ */
Resource read(String id, String resourceName); IdResource read(String id, String resourceName);
/** /**
* check attribute value of a resource given its id from the DB * check attribute value of a resource given its id from the DB
*/ */
@ -44,39 +42,39 @@ public interface SocialDBDriver {
/** /**
* list all instances of a resource in the DB * list all instances of a resource in the DB
*/ */
List<Resource> readAll(String resourceName); List<IdResource> readAll(String resourceName);
/** /**
* read a list of the children of a resource given its id from the DB * read a list of the children of a resource given its id from the DB
*/ */
List<Resource>readChildOf(String parentid, String parentResourceName, String childResourceName); List<IdResource>readChildOf(String parentid, String parentResourceName, String childResourceName);
/** /**
* read a list of resources with a specific attribute value * read a list of resources with a specific attribute value
*/ */
List<Resource> readWithParameter(String parameterName, String parameterValue, String resourceName); List<IdResource> readWithParameter(String parameterName, String parameterValue, String resourceName);
/** /**
* read a list of the children of a resource with a specific attribute value * read a list of the children of a resource with a specific attribute value
*/ */
List<Resource> readChildOfWithParameter(String parentid, String parameterName, String parameterValue, String parentResourceName, String childResourceName); List<IdResource> readChildOfWithParameter(String parentid, String parameterName, String parameterValue, String parentResourceName, String childResourceName);
/** /**
* update a resource given its id in the DB * update a resource given its id in the DB
*/ */
Boolean update(Resource resource); Boolean update(IdResource resource);
/** /**
* update a child resource given its id and its parent id in the DB * update a child resource given its id and its parent id in the DB
*/ */
Boolean updateChildOf(String parentid, String childid, Resource childResource, String parentResourceName); Boolean updateChildOf(String parentid, String childid, IdResource childResource, String parentResourceName);
/** /**
* Batch update a child resource given its id and its parent id in the DB * Batch update a child resource given its id and its parent id in the DB
*/ */
Boolean BatchUpdateChildOf(String parentid, List<Resource> childResource, String parentResourceName); Boolean BatchUpdateChildOf(String parentid, List<IdResource> childResource, String parentResourceName);
/** /**
* update a resource with a certain attribute value * update a resource with a certain attribute value
*/ */
Boolean updateWithParameter(String parameterName, String parameterValue, Resource resource); Boolean updateWithParameter(String parameterName, String parameterValue, IdResource resource);
/** /**
* update a child resource with a certain attribute value given its parent id * update a child resource with a certain attribute value given its parent id
*/ */
Boolean updateChildOfWithParameter(String parentid, String parameterName, String parameterValue, Resource childResource,String parentResourceName); Boolean updateChildOfWithParameter(String parentid, String parameterName, String parameterValue, IdResource childResource,String parentResourceName);
/** /**
* delete a resource given its id in the DB * delete a resource given its id in the DB
@ -97,7 +95,7 @@ public interface SocialDBDriver {
/** /**
* batch delete a child resource with a certain attribute value given its parent id * batch delete a child resource with a certain attribute value given its parent id
*/ */
Boolean BatchDeleteChildOfWithParameter(String parentid, String parameterName, String parameterValue, List<Resource> childResource, String parentResourceName, String childResourceName); Boolean BatchDeleteChildOfWithParameter(String parentid, String parameterName, String parameterValue, List<IdResource> childResource, String parentResourceName, String childResourceName);
@ -108,7 +106,7 @@ public interface SocialDBDriver {
//List<Notification> getRangeNotificationsByUser(String userid, int from, int quantity) throws NotificationTypeNotFoundException, ColumnNameNotFoundException, NotificationIDNotFoundException; //List<Notification> getRangeNotificationsByUser(String userid, int from, int quantity) throws NotificationTypeNotFoundException, ColumnNameNotFoundException, NotificationIDNotFoundException;
InviteOperationResult saveInvite(Invite invite) throws AddressException; InviteOperationResult saveInvite(Invite invite) throws ServerException;
/** /**
* close the connection to the underlying database * close the connection to the underlying database

View File

@ -1,19 +0,0 @@
package org.gcube.social_networking.ws;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/")
@Singleton
public class WelcomeService {
@GET
@Produces(MediaType.TEXT_HTML)
public Response sayHtmlHello() {
return Response.ok("<html><body><h2>The social networking web service is up and running!</h2></body></html>").build();
}
}

View File

@ -1,50 +0,0 @@
package org.gcube.social_networking.ws.docs;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("api-docs")
public class DocsGenerator {
private static Logger logger = LoggerFactory.getLogger(DocsGenerator.class);
@GET
@Path("/{any: .*}")
public InputStream toDoc(@Context HttpServletRequest req) throws WebApplicationException {
logger.info(DocsGenerator.class.getSimpleName() + " toDoc called");
String pathInfo = req.getPathInfo();
logger.debug("pathInfo {}", pathInfo);
try {
if (pathInfo.endsWith("/api-docs")) {
pathInfo += "index.html";
}
if (pathInfo.endsWith("/api-docs/")) {
pathInfo += "index.html";
}
logger.info("going to {}", pathInfo);
String realPath = req.getServletContext().getRealPath(pathInfo);
return new FileInputStream(new File(realPath));
} catch (Exception e) {
e.printStackTrace();
//MANAGE THE EXCEPTION
}
return null;
}
}

View File

@ -1,28 +0,0 @@
package org.gcube.social_networking.ws.ex;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.slf4j.LoggerFactory;
/**
* Exception gets thrown when @Valid fail
*/
@Provider
public class ApplicationException implements ExceptionMapper<Exception> {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ApplicationException.class);
public Response toResponse(Exception e) {
logger.warn("ApplicationException invoked for exception ", e);
return Response
.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
.type(MediaType.APPLICATION_JSON)
.entity(new ResponseBean(false, e.getMessage(), null))
.build();
}
}

View File

@ -1,16 +0,0 @@
package org.gcube.social_networking.ws.ex;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response.Status;
public class AuthException extends WebApplicationException {
/**
*
*/
private static final long serialVersionUID = 1L;
public AuthException(Throwable cause) {
super(cause, Status.FORBIDDEN);
}
}

View File

@ -1,36 +0,0 @@
package org.gcube.social_networking.ws.ex;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.slf4j.LoggerFactory;
/**
* Exception thrown on fail
* @author Costantino Perciante at ISTI-CNR
*/
@Provider
public class ValidationException implements ExceptionMapper<javax.validation.ValidationException> {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ValidationException.class);
@Override
public Response toResponse(javax.validation.ValidationException e) {
final StringBuilder strBuilder = new StringBuilder();
for (ConstraintViolation<?> cv : ((ConstraintViolationException) e).getConstraintViolations()) {
strBuilder.append(cv.getMessage());
break;
}
logger.warn("ValidationException invoked, returning " + strBuilder.toString());
return Response
.status(Response.Status.BAD_REQUEST.getStatusCode())
.type(MediaType.APPLICATION_JSON)
.entity(new ResponseBean(false, strBuilder.toString(), null))
.build();
}
}

View File

@ -1,42 +0,0 @@
package org.gcube.social_networking.ws.inputs;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Application id object
* @author Costantino Perciante at ISTI-CNR
*/
//@ApiModel(description="An object containing the app_id field", value="Application")
public class ApplicationId {
@JsonProperty("app_id")
@NotNull(message="app_id cannot be null")
@Size(message="app_id cannot be empty", min=1)
private String appId;
public ApplicationId() {
super();
}
public ApplicationId(String appId) {
super();
this.appId = appId;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
@Override
public String toString() {
return "ApplicationId [appId=" + appId + "]";
}
}

View File

@ -1,72 +0,0 @@
package org.gcube.social_networking.ws.inputs;
import java.io.Serializable;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.webcohesion.enunciate.metadata.DocumentationExample;
/**
* Generic input bean for methods that allow to comment posts
*/
@JsonIgnoreProperties(ignoreUnknown = true) // ignore in serialization/deserialization
public class CommentInputBean implements Serializable{
private static final long serialVersionUID = 5274608088828232980L;
@JsonProperty("text")
@NotNull(message="text cannot be null")
@Size(min=1, message="text cannot be empty")
@DocumentationExample("I would like to comment that ...")
/**
* text the text of the comment
*/
private String text;
@NotNull(message="postid cannot be null")
@JsonProperty("postid")
/**
* postid the postid of the post where you attach the comment
*/
private String postid;
public CommentInputBean() {
super();
}
/**
* @param text
* @param postid
*/
public CommentInputBean(String text, String postid) {
super();
this.text = text;
this.postid = postid;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getPostid() {
return postid;
}
public void setPostid(String postid) {
this.postid = postid;
}
@Override
public String toString() {
return "CommentInputBean [text=" + text + ", postid=" + postid + "]";
}
}

View File

@ -1,60 +0,0 @@
package org.gcube.social_networking.ws.inputs;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Like Bean object
*/
public class LikeInputBean {
@JsonProperty("likeid")
@NotNull(message="likeid cannot be null")
@Size(message="likeid cannot be empty", min=1)
private String likeid;
@JsonProperty("postid")
@NotNull(message="postid cannot be null")
@Size(message="postid cannot be empty", min=1)
private String postid;
public LikeInputBean() {
super();
}
/**
* @param likeid
* @param postid
*/
public LikeInputBean(String likeid, String postid) {
super();
this.likeid = likeid;
this.postid = postid;
}
public String getLikeid() {
return likeid;
}
public void setLikeid(String likeid) {
this.likeid = likeid;
}
public String getPostid() {
return postid;
}
public void setPostid(String postid) {
this.postid = postid;
}
@Override
public String toString() {
return "LikeInputBean [likeid=" + likeid + ", postid=" + postid + "]";
}
}

View File

@ -1,43 +0,0 @@
package org.gcube.social_networking.ws.inputs;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Application id object
*/
public class PostId {
@JsonProperty("postid")
@NotNull(message="postid cannot be null")
@Size(message="postid cannot be empty", min=1)
private String postId;
public PostId() {
super();
}
public PostId(String postId) {
super();
this.postId = postId;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
@Override
public String toString() {
return "PostId [postid=" + postId + "]";
}
}

View File

@ -1,146 +0,0 @@
package org.gcube.social_networking.ws.inputs;
import java.io.Serializable;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.webcohesion.enunciate.metadata.DocumentationExample;
/**
* Generic input bean for methods that allow to write posts
* @author Costantino Perciante at ISTI-CNR
*/
@JsonIgnoreProperties(ignoreUnknown = true) // ignore in serialization/deserialization
public class PostInputBean implements Serializable{
private static final long serialVersionUID = 5274608088828232980L;
@JsonProperty("text")
@NotNull(message="text cannot be null")
@Size(min=1, message="text cannot be empty")
@DocumentationExample("Dear vre members, ...")
/**
* text the text of the post
*/
private String text;
private String previewtitle;
@JsonProperty("preview_description")
private String previewdescription;
@JsonProperty("preview_host")
private String previewhost;
@JsonProperty("preview_url")
private String previewurl;
/**
* param httpimageurl An image url for the preview"
*/
@JsonProperty("image_url")
private String httpimageurl;
/**
* enablenotification If true send a notification to the other vre members about this post
*/
@JsonProperty("enable_notification")
private boolean enablenotification;
@JsonProperty("params")
private String params;
public PostInputBean() {
super();
}
public PostInputBean(String text, String previewtitle,
String previewdescription, String previewhost, String previewurl,
String httpimageurl, boolean enablenotification, String params) {
super();
this.text = text;
this.previewtitle = previewtitle;
this.previewdescription = previewdescription;
this.previewhost = previewhost;
this.previewurl = previewurl;
this.httpimageurl = httpimageurl;
this.enablenotification = enablenotification;
this.params = params;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getPreviewtitle() {
return previewtitle;
}
public void setPreviewtitle(String previewtitle) {
this.previewtitle = previewtitle;
}
public String getPreviewdescription() {
return previewdescription;
}
public void setPreviewdescription(String previewdescription) {
this.previewdescription = previewdescription;
}
public String getPreviewhost() {
return previewhost;
}
public void setPreviewhost(String previewhost) {
this.previewhost = previewhost;
}
public String getPreviewurl() {
return previewurl;
}
public void setPreviewurl(String previewurl) {
this.previewurl = previewurl;
}
public String getHttpimageurl() {
return httpimageurl;
}
public void setHttpimageurl(String httpimageurl) {
this.httpimageurl = httpimageurl;
}
public boolean isEnablenotification() {
return enablenotification;
}
public void setEnablenotification(boolean enablenotification) {
this.enablenotification = enablenotification;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
@Override
public String toString() {
return "PostInputBean [text=" + text + ", previewtitle=" + previewtitle
+ ", previewdescription=" + previewdescription
+ ", previewhost=" + previewhost + ", previewurl=" + previewurl
+ ", httpimageurl=" + httpimageurl + ", enablenotification="
+ enablenotification + ", params=" + params + "]";
}
}

View File

@ -1,63 +0,0 @@
package org.gcube.social_networking.ws.inputs;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
*
*
*/
public class UserSetNotificationBean {
@JsonProperty("username")
@NotNull(message="username cannot be null")
@Size(message="username cannot be empty", min=1)
private String username;
@JsonProperty("disableNotification")
@NotNull(message="disableNotification cannot be null")
private Boolean disableNotification;
public UserSetNotificationBean() {
super();
}
/**
* @param username
* @param disableNotification
*/
public UserSetNotificationBean(String username, boolean disableNotification) {
super();
this.username = username;
this.disableNotification = disableNotification;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public boolean isDisableNotification() {
return disableNotification;
}
public void setDisableNotification(boolean disableNotification) {
this.disableNotification = disableNotification;
}
@Override
public String toString() {
return "UserSetNotificationBean [username=" + username + ", disableNotification=" + disableNotification + "]";
}
}

View File

@ -1,28 +0,0 @@
package org.gcube.social_networking.ws.mappers;
import org.gcube.portal.databook.shared.NotificationType;
import org.gcube.portal.databook.shared.ex.NotificationTypeNotFoundException;
import org.gcube.social_networking.socialnetworking.model.beans.catalogue.CatalogueEventType;
public class CatalogueEventTypeMapper {
public CatalogueEventTypeMapper() {
}
public static NotificationType getType(CatalogueEventType type) throws NotificationTypeNotFoundException {
switch (type) {
case ITEM_PUBLISHED:
return NotificationType.CAT_ITEM_PUBLISHED;
case ITEM_REJECTED:
return NotificationType.CAT_ITEM_REJECTED;
case ITEM_REMOVED:
return NotificationType.CAT_ITEM_DELETE;
case ITEM_SUBMITTED:
return NotificationType.CAT_ITEM_SUBMITTED;
case ITEM_UPDATED:
return NotificationType.CAT_ITEM_UPDATED;
default:
throw new NotificationTypeNotFoundException("The Catalogue event could not be mapped");
}
}
}

View File

@ -1,64 +0,0 @@
package org.gcube.social_networking.ws.mappers;
import org.gcube.portal.databook.shared.JobStatusType;
import org.gcube.portal.databook.shared.RunningJob;
import org.gcube.social_networking.socialnetworking.model.beans.JobNotificationBean;
import org.gcube.social_networking.socialnetworking.model.beans.JobStatusModelType;
public class JobMapper {
public JobMapper() {
}
public static RunningJob getJob(JobNotificationBean item) {
String jobId = null;
String jobName = null;
JobStatusType status = null;
String message = null;
String serviceName = null; // i.e., Dataminer, SmartExecutor..
try {
jobId = item.getJobId();
jobName = item.getJobName();
status = getType(item.getStatus());
message = item.getStatusMessage();
serviceName = item.getServiceName();
} catch (Exception e) {
e.printStackTrace();
}
return new RunningJob(jobId, jobName, status, message, serviceName);
}
public static JobStatusType getType(JobStatusModelType type) {
JobStatusType toReturn = null;
switch (type) {
case CANCELLED:
return JobStatusType.CANCELLED;
case DELETED:
return JobStatusType.DELETED;
case FAILED:
return JobStatusType.FAILED;
case CANCELLING:
return JobStatusType.CANCELLING;
case DELETING:
return JobStatusType.DELETING;
case EXECUTING:
return JobStatusType.EXECUTING;
case NEW:
return JobStatusType.NEW;
case SUBMITTED:
return JobStatusType.SUBMITTED;
case SUCCEEDED:
return JobStatusType.SUCCEEDED;
case TIMED_OUT:
return JobStatusType.TIMED_OUT;
case WAITING:
return JobStatusType.WAITING;
default:
break;
}
return toReturn;
}
}

View File

@ -1,57 +0,0 @@
package org.gcube.social_networking.ws.mappers;
import org.gcube.applicationsupportlayer.social.shared.SocialFileItem;
import org.gcube.applicationsupportlayer.social.shared.SocialSharedFolder;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.FileItemBean;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.FolderBean;
public class WorkspaceItemMapper {
public WorkspaceItemMapper() {
// TODO Auto-generated constructor stub
}
public static SocialFileItem getFileItem(FileItemBean item) {
String id = null;
String name= null;
String title= null;
String path= null;
SocialSharedFolder parent = null;
try {
id = item.getId();
name = item.getName();
title = item.getTitle();
path = item.getPath();
parent = getSharedFolder(item.getParent());
} catch (Exception e) {
e.printStackTrace();
}
SocialFileItem toReturn = new SocialFileItem(id, name, title, path, parent);
return toReturn;
}
public static SocialSharedFolder getSharedFolder(FolderBean item) {
String id = null;
String name= null;
String title= null;
String displayName= null;
String path= null;
String parentId= null;
boolean vreFolder = false;
try {
id = item.getId();
name = item.getName();
title = item.getTitle();
displayName = item.getDisplayName();
path = item.getPath();
parentId = item.getParentId();
vreFolder = item.isVreFolder();
} catch (Exception e) {
e.printStackTrace();
}
SocialSharedFolder toReturn = new SocialSharedFolder(id, name, title, displayName, path, parentId, vreFolder);
return toReturn;
}
}

View File

@ -1,233 +0,0 @@
package org.gcube.social_networking.ws.methods.v2;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.validation.Valid;
import javax.validation.ValidationException;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.shared.Comment;
import org.gcube.portal.databook.shared.Feed;
import org.gcube.portal.databook.shared.ex.FeedIDNotFoundException;
import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.social_networking.ws.inputs.CommentInputBean;
import org.gcube.social_networking.ws.inputs.PostInputBean;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.Filters;
import org.gcube.social_networking.ws.utils.SocialUtils;
import org.gcube.socialnetworking.socialtoken.SocialMessageParser;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.slf4j.LoggerFactory;
import com.liferay.portlet.journal.FeedIdException;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/**
* REST interface for the social networking library (comments).
* @author Ahmed Ibrahim ISTI-CNR
*/
@Path("2/comments")
@RequestHeaders ({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json")
})
public class Comments {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Comments.class);
/*
* Retrieve the list of comments belonging to the post id (key) of the token in the related context
* @param key the key as in the POST JSON representation
* @pathExample /get-comments-by-post-id?key=9ea137e9-6606-45ff-a1a2-94d4e8760583
* @return the list of comments belonging to the post identified by the key in the context identified by the token
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("get-comments-by-post-id")
@StatusCodes ({
@ResponseCode ( code = 200, condition = "The list of comments is put into the 'result' field"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getAllCommentsByPostId(
@NotNull
@QueryParam("key")
String key) {
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
String username = caller.getClient().getId();
List<Comment> comments = null;
try{
logger.debug("Retrieving comments for user id " + username);
comments = CassandraConnection.getInstance().getDatabookStore().getAllCommentByPost(key);
Filters.filterCommentsPerContext(comments, context);
responseBean.setResult(comments);
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Unable to retrieve such comments.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/*
* Retrieve the list of comments belonging to the owner of the token in the related context
* @return the list of comments belonging to the owner of the token in the related context.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("get-comments-user")
@StatusCodes ({
@ResponseCode ( code = 200, condition = "The list of comments is put into the 'result' field"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getCommentsUser() {
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
String username = caller.getClient().getId();
List<Comment> comments = null;
try{
logger.debug("Retrieving comments for user id " + username);
comments = CassandraConnection.getInstance().getDatabookStore().getRecentCommentsByUserAndDate(username, 0);
Filters.filterCommentsPerContext(comments, context);
responseBean.setResult(comments);
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Unable to retrieve such comments.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/*
* Retrieve comments of the token owner in the context bound to the token itself and filter them by date
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("get-comments-user-by-time")
public Response getCommentsUserByTime(
@QueryParam("time")
@Min(value = 0, message="time cannot be negative")
long timeInMillis
) throws ValidationException{
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
String username = caller.getClient().getId();
List<Comment> comments = null;
try{
logger.debug("Retrieving comments for user id " + username);
comments = CassandraConnection.getInstance().getDatabookStore().getRecentCommentsByUserAndDate(username, timeInMillis);
Filters.filterCommentsPerContext(comments, context);
responseBean.setResult(comments);
responseBean.setMessage("");
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Unable to retrieve such comments.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Create a new comment to a post having as owner the auth token's owner
* @param comment The CommentInputBean object
* @return
* @throws ValidationException
*/
@POST
@Path("comment-post")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 201, condition = "Successfull created, the new comment is reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response writeComment(
@NotNull(message="Comment to write is missing")
@Valid
CommentInputBean comment) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
logger.debug("Request of writing a comment coming from user " + username);
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
try {
String postId = comment.getPostid();
String commentText = comment.getText();
String userid = username;
Date time = new Date();
String postOwnerId = CassandraConnection.getInstance().getDatabookStore().readPost(postId).getEntityId();
Comment theComment = SocialUtils.commentPost(userid, time, postId, commentText, postOwnerId, context);
if (theComment != null)
logger.debug("Added comment " + theComment.toString());
else {
logger.error("Unable to write comment");
responseBean.setMessage("Unable to write comment, something went wrong please see server log");
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
return Response.status(status).entity(responseBean).build();
}
responseBean.setResult(theComment);
responseBean.setSuccess(true);
return Response.status(status).entity(responseBean).build();
} catch(FeedIDNotFoundException ex) {
logger.error("Unable to find a post comment", ex);
responseBean.setMessage("Could not reach the DB to write the comment, something went wrong");
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
return Response.status(status).entity(responseBean).build();
}
catch(Exception e) {
logger.error("Unable to write comment", e);
responseBean.setMessage("Could not reach the DB to write the comment, something went wrong");
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
return Response.status(status).entity(responseBean).build();
}
}
}

View File

@ -1,167 +0,0 @@
package org.gcube.social_networking.ws.methods.v2;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.portal.databook.shared.EnhancedFeed;
import org.gcube.portal.databook.shared.Feed;
import org.gcube.portal.social.networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.ws.utils.ElasticSearchConnection;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.Filters;
import org.gcube.social_networking.ws.utils.TokensUtils;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/**
* REST interface for the social networking library (post and its comments).
*/
@Path("2/full-text-search")
@RequestHeaders ({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json")
})
public class FullTextSearch {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(FullTextSearch.class);
/**
* Retrieve posts/comments that match the given query
* @param httpServletRequest
* @param query A string to search for
* @param from the index of the base result to be returned, range[0, infinity], defaults from = 0
* @param quantity defines how many results are most are to be returned, range[1, infinity], defaults from = 0,
* @return The posts/comments returned belong to the context bound to the AUTH Token
* @throws ValidationException
*/
@GET
@Path("search-by-query")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successful retrieval of posts/comments that match the query, reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response searchByQuery(
@Context HttpServletRequest httpServletRequest,
@QueryParam("query") @NotNull(message="query cannot be null") @Size(min=1, message="query cannot be empty")
String query,
@DefaultValue("0") @QueryParam("from") @Min(value=0, message="from cannot be negative")
int from,
@DefaultValue("10") @QueryParam("quantity") @Min(value=0, message="quantity cannot be negative")
int quantity
) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.BAD_REQUEST;
responseBean.setMessage("This method can be only invoked by using a user token.");
if(!TokensUtils.isUserToken(caller))
return Response.status(status).entity(responseBean).build();
status = Status.OK;
responseBean.setMessage(null);
GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
try{
// Retrieve user's vres in which we must search
Set<String> vres = new HashSet<String>();
// get the group id from the current context
long currentGroupId = groupManager.getGroupIdFromInfrastructureScope(context);
GCubeUser currUser = userManager.getUserByUsername(username);
List<GCubeGroup> userContexts = groupManager.listGroupsByUser(currUser.getUserId());
if (groupManager.isRootVO(currentGroupId)) {
for (GCubeGroup group : groupManager.listGroupsByUser(currUser.getUserId())) {
if (groupManager.isVRE(group.getGroupId()) && userContexts.contains(group)) {
vres.add(groupManager.getInfrastructureScope(group.getGroupId()));
}
}
}
else if(groupManager.isVO(currentGroupId)){
for (GCubeGroup group : groupManager.listGroupsByUser(currUser.getUserId())) {
if (groupManager.isVRE(group.getGroupId()) && group.getParentGroupId() == currentGroupId && userContexts.contains(group)) {
vres.add(groupManager.getInfrastructureScope(group.getGroupId()));
}
}
}
else {
vres.add(context);
}
// query elastic search
List<EnhancedFeed> enhancedFeeds = ElasticSearchConnection.getSingleton().getElasticSearchClient().search(query, vres, from, quantity);
Filters.hideSensitiveInformation(enhancedFeeds, caller.getClient().getId());
DatabookStore store = CassandraConnection.getInstance().getDatabookStore();
// retrieve the ids of liked feeds by the user
List<String> likedFeeds = store.getAllLikedFeedIdsByUser(username);
// update fields "liked" and "isuser"
for (EnhancedFeed enhancedFeed : enhancedFeeds) {
if(isUsers(enhancedFeed.getFeed(), username))
enhancedFeed.setUsers(true);
if(likedFeeds.contains(enhancedFeed.getFeed().getKey()))
enhancedFeed.setLiked(true);
}
responseBean.setResult((ArrayList<EnhancedFeed>) enhancedFeeds);
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Something went wrong while searching", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* tell if a feed belongs to the current user or not
* @param tocheck
* @param username
* @return true if this feed is of the current user
*/
private static final boolean isUsers(Feed tocheck, String username) {
return (tocheck.getEntityId().equals(username));
}
}

View File

@ -1,84 +0,0 @@
package org.gcube.social_networking.ws.methods.v2;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.ValidationException;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.portal.databook.shared.Post;
import org.gcube.portal.social.networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/**
* REST interface for the social networking library (hash tags).
* @author Ahmed Ibrahim ISTI-CNR
*/
@Path("2/hashtags")
@RequestHeaders ({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json")
})
public class HashTags {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(HashTags.class);
@GET
@Path("get-hashtags-and-occurrences/")
@Produces({MediaType.APPLICATION_JSON})
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Hashtags and occurrences retrieved, reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
/**
* @return hashtags in the context bound to the auth token
*/
public Response getHashTagsAndOccurrences(){
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
logger.debug("User " + username + " has requested hashtags of context " + context);
try{
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
// TODO handle the case of VO and ROOT
boolean isVRE = GroupManagerWSBuilder.getInstance().getGroupManager().isVRE(GroupManagerWSBuilder.getInstance().getGroupManager().getGroupIdFromInfrastructureScope(context));
if(isVRE){
Map<String, Integer> map = datastore.getVREHashtagsWithOccurrence(context);
responseBean.setResult(map);
responseBean.setSuccess(true);
}else{
responseBean.setMessage("Please provide a VRE token. VO and ROOT VO cases are not yet managed.");
responseBean.setResult(false);
}
}catch(Exception e){
logger.error("Failed to retrieve hashtags", e);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
}

View File

@ -1,168 +0,0 @@
package org.gcube.social_networking.ws.methods.v2;
import java.util.List;
import javax.validation.Valid;
import javax.validation.ValidationException;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.shared.Like;
import org.gcube.social_networking.ws.inputs.LikeInputBean;
import org.gcube.social_networking.ws.inputs.PostId;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.SocialUtils;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/**
* REST interface for the social networking library (likes).
* @author Ahmed Ibrahim ISTI-CNR
*/
@Path("2/likes")
@RequestHeaders ({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json")
})
public class Likes {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Likes.class);
/*
* Retrieve the list of likes belonging to the post id (key) of the token in the related context
* @param key the key as in the POST JSON representation
* @pathExample /get-likes-by-post-id?key=9ea137e9-6606-45ff-a1a2-94d4e8760583
* @return the list of likes belonging to the post identified by the key in the context identified by the token
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("get-likes-by-post-id")
@StatusCodes ({
@ResponseCode ( code = 200, condition = "The list of likes is put into the 'result' field"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getAllLikesByPostId(
@NotNull
@QueryParam("key")
String key) {
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
String username = caller.getClient().getId();
List<Like> likes = null;
try{
logger.debug("Retrieving likes for user id " + username);
likes = CassandraConnection.getInstance().getDatabookStore().getAllLikesByPost(key);
responseBean.setResult(likes);
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Unable to retrieve such likes.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Create a new like to a post in the context of the token
* @param postid The post id to be liked
* @return true if everything is OK
* @throws ValidationException
*/
@POST
@Path("like-post")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 201, condition = "Successful created, the like operation result is reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response like(
@NotNull(message="Post to like is missing")
@Valid
PostId post) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
logger.debug("Request of like coming from user " + username);
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
boolean likeResultOperation = SocialUtils.like(username, post.getPostId(), context);
if (likeResultOperation)
logger.debug("Added like OK to postId " + post.getPostId());
else {
logger.error("Unable to like this post"+ post.getPostId());
responseBean.setMessage("Unable to like, something went wrong please see server log");
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
return Response.status(status).entity(responseBean).build();
}
responseBean.setResult(true);
responseBean.setSuccess(true);
return Response.status(status).entity(responseBean).build();
}
/**
* Unlike to a post in the context of the token
* @param postid The post id to be liked
* @return true if everything is OK
* @throws ValidationException
*/
@POST
@Path("unlike-post")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 201, condition = "The unlike operation result is reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response unlike(
@NotNull(message="Post to unlike is missing")
@Valid
LikeInputBean likeInputBean) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
logger.debug("Request of unlike coming from user " + username);
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
boolean likeResultOperation = SocialUtils.unlike(username, likeInputBean.getLikeid(), likeInputBean.getPostid());
if (likeResultOperation)
logger.debug("Unlike OK to postId " + likeInputBean.getPostid());
else {
logger.error("Unable to unlike this post"+ likeInputBean.getPostid());
responseBean.setMessage("Unable to unlike, something went wrong please see server log");
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
return Response.status(status).entity(responseBean).build();
}
responseBean.setResult(true);
responseBean.setSuccess(true);
return Response.status(status).entity(responseBean).build();
}
}

View File

@ -1,295 +0,0 @@
package org.gcube.social_networking.ws.methods.v2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.ValidationException;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager;
import org.gcube.applicationsupportlayer.social.NotificationsManager;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingUser;
import org.gcube.common.authorization.control.annotations.AuthorizationControl;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.storagehub.client.plugins.AbstractPlugin;
import org.gcube.common.storagehub.client.proxies.MessageManagerClient;
import org.gcube.common.storagehub.model.messages.Message;
import org.gcube.portal.notifications.bean.GenericItemBean;
import org.gcube.portal.notifications.thread.MessageNotificationsThread;
import org.gcube.portal.social.networking.liferay.ws.LiferayJSONWsCredentials;
import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.social_networking.caches.SocialNetworkingSiteFinder;
import org.gcube.social_networking.socialnetworking.model.beans.MessageInputBean;
import org.gcube.social_networking.socialnetworking.model.beans.Recipient;
import org.gcube.social_networking.ws.ex.AuthException;
import org.gcube.social_networking.ws.inputs.UserSetNotificationBean;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.TokensUtils;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/**
* Messages services REST interface
* @author Costantino Perciante at ISTI-CNR
* (costantino.perciante@isti.cnr.it)
*/
@Path("2/messages")
@RequestHeaders ({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json")
})
public class Messages {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Messages.class);
/**
* Write a message to another user. The sender is the token's owner by default
* @responseExample application/json {"success": true, "message": null, "result": "556142e3-d6f5-4550-b2fa-abe5626625d3"}
* @param input The message to write"
* @param httpServletRequest
* @return see response example
* @throws ValidationException
* @throws UserManagementSystemException
* @throws UserRetrievalFault
*/
@POST
@Path("write-message/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successful write a message. Its id is reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response writeMessage(
@NotNull(message="Message to send is missing")
@Valid
MessageInputBean input,
@Context HttpServletRequest httpServletRequest) throws ValidationException, UserManagementSystemException, UserRetrievalFault{
logger.debug("Incoming message bean is " + input);
Caller caller = AuthorizationProvider.instance.get();
UserManager um = UserManagerWSBuilder.getInstance().getUserManager();
GCubeUser senderUser = null;
SocialNetworkingUser user = null;
// check if the token belongs to an application token. In this case use J.A.R.V.I.S (the username used to communicate with Liferay)
String username = null;
String fullName = "";
logger.debug("Catalogue Notification called by " + caller.getClient().getId() + " isUser?"+TokensUtils.isUserToken(caller));
if(!TokensUtils.isUserToken(caller)){
GCubeUser jarvis = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser());
SecurityTokenProvider.instance.set(LiferayJSONWsCredentials.getSingleton().getNotifierUserToken());
username = jarvis.getUsername();
fullName = caller.getClient().getId().replace("service-account-", ""); // the actual name of the IAM Client
senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName, senderUser.getUserAvatarURL());
}else{
username = caller.getClient().getId();
senderUser = um.getUserByUsername(username);
fullName = senderUser.getFullname();
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName, senderUser.getUserAvatarURL());
}
String scope = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.CREATED;
String body = input.getBody();
String subject = input.getSubject();
List<Recipient> recipientsIds = input.getRecipients(); // "recipients":[{"recipient":"id recipient"}, ......]
logger.debug("Sender is going to be [" + fullName + "]");
// get the recipients ids (simple check, trim)
List<String> recipientsListFiltered = new ArrayList<String>();
List<GenericItemBean> recipientsBeans = new ArrayList<GenericItemBean>();
for (Recipient recipientId : recipientsIds) {
try{
String tempId = recipientId.getId().trim();
if(tempId.isEmpty())
continue;
GCubeUser userRecipient = UserManagerWSBuilder.getInstance().getUserManager().getUserByUsername(tempId);
if(userRecipient == null)
userRecipient = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(tempId);
if(userRecipient != null){
GenericItemBean beanUser = new GenericItemBean(userRecipient.getUsername(), userRecipient.getUsername(), userRecipient.getFullname(), userRecipient.getUserAvatarURL());
recipientsBeans.add(beanUser);
recipientsListFiltered.add(userRecipient.getUsername());
}
}catch(Exception e){
logger.error("Unable to retrieve recipient information for recipient with id " + recipientId, e);
}
}
if(recipientsListFiltered.isEmpty()){
logger.error("Missing/wrong request parameters");
status = Status.BAD_REQUEST;
responseBean.setMessage(ErrorMessages.MISSING_PARAMETERS);
return Response.status(status).entity(responseBean).build();
}
try{
logger.debug("Trying to send message with body " + body + " subject " + subject + " to users " + recipientsIds + " from " + username);
// send message
MessageManagerClient client = AbstractPlugin.messages().build();
logger.debug("Sending message to " + recipientsListFiltered);
String messageId = client.sendMessage(recipientsListFiltered, subject, body, input.getAttachmentIds());
// send notification
logger.debug("Message sent to " + recipientsIds + ". Sending message notification to: " + recipientsIds);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(scope);
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, ScopeProvider.instance.get(), user);
new Thread(new MessageNotificationsThread(recipientsBeans, messageId, subject, body, nm)).start();
responseBean.setSuccess(true);
responseBean.setResult(messageId);
}catch(Exception e){
logger.error("Unable to send message.", e);
status = Status.INTERNAL_SERVER_ERROR;
responseBean.setMessage(e.toString());
}
return Response.status(status).entity(responseBean).build();
}
@GET
@Path("get-sent-messages")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successful read of the sent messages, reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
/**
*
* @return the list of sent messages of the user (the token's owner)
*/
public Response getSentMessages(){
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
logger.debug("Request for retrieving sent messages by " + username);
try{
MessageManagerClient client = AbstractPlugin.messages().build();
List<Message> sentMessages = client.getSentMessages();
Collections.reverse(sentMessages);
responseBean.setSuccess(true);
logger.debug("Result is " + sentMessages);
responseBean.setResult(sentMessages);
}catch(Exception e){
logger.error("Unable to retrieve sent messages", e);
responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
@GET
@Path("get-received-messages")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successful read of the received messages, reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
/**
*
* @return the list of received messages of the user (the token's owner)
*/
public Response getReceivedMessages(){
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
logger.debug("Request for retrieving received messages by " + username);
try{
MessageManagerClient client = AbstractPlugin.messages().build();
List<Message> getMessages =client.getReceivedMessages();
Collections.reverse(getMessages);
responseBean.setSuccess(true);
responseBean.setResult(getMessages);
}catch(Exception e){
logger.error("Unable to retrieve sent messages", e);
responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Set message read or unread
* @param messageId the message identifier
* @param read true to set read, false to set unread
* @return the result of the operation
* @throws ValidationException
*/
@POST
@Path("set-message-read/")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Message set Read or Unread is correctly executed"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response setMessageRead(
@NotNull(message="input is missing")
@FormParam("messageId") String messageId,
@FormParam("read") Boolean read) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
String opExecutor = "";
try{
opExecutor = caller.getClient().getId();
MessageManagerClient client = AbstractPlugin.messages().build();
client.setRead(messageId, read);
String toReturn = "set Message id:" + messageId + (read ? " read" : " unread");
logger.debug("set Message id:" + messageId + " read?" + read + " for " + opExecutor);
responseBean.setSuccess(true);
responseBean.setResult(toReturn);
} catch(Exception e){
logger.error("Unable to set message read / unread property for user " + opExecutor, e);
responseBean.setSuccess(false);
responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
}

View File

@ -1,684 +0,0 @@
package org.gcube.social_networking.ws.methods.v2;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.ValidationException;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager;
import org.gcube.applicationsupportlayer.social.NotificationsManager;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingUser;
import org.gcube.common.authorization.control.annotations.AuthorizationControl;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.portal.databook.shared.Notification;
import org.gcube.portal.databook.shared.NotificationChannelType;
import org.gcube.portal.databook.shared.NotificationType;
import org.gcube.portal.databook.shared.RunningJob;
import org.gcube.portal.notifications.bean.GenericItemBean;
import org.gcube.portal.notifications.thread.JobStatusNotificationThread;
import org.gcube.portal.social.networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.portal.social.networking.liferay.ws.LiferayJSONWsCredentials;
import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.social_networking.caches.SocialNetworkingSiteFinder;
import org.gcube.social_networking.caches.UsersCache;
import org.gcube.social_networking.socialnetworking.model.beans.JobNotificationBean;
import org.gcube.social_networking.socialnetworking.model.beans.catalogue.CatalogueEvent;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.AddedItemEvent;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.DeletedItemEvent;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.FolderAddedUserEvent;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.FolderAdminDowngradeEvent;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.FolderAdminUpgradeEvent;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.FolderRemovedUserEvent;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.RenamedFolderEvent;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.SharedFolderEvent;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.UnsharedFolderEvent;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.UpdatedItemEvent;
import org.gcube.social_networking.socialnetworking.model.beans.workspace.WorkspaceEvent;
import org.gcube.social_networking.ws.ex.AuthException;
import org.gcube.social_networking.ws.mappers.CatalogueEventTypeMapper;
import org.gcube.social_networking.ws.mappers.JobMapper;
import org.gcube.social_networking.ws.mappers.WorkspaceItemMapper;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.TokensUtils;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.mortbay.log.Log;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/**
* REST interface for the social networking library (notifications).
* @author Ahmed Ibrahim ISTI-CNR
*/
@Path("2/notifications")
@RequestHeaders ({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json")
})
public class Notifications {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Notifications.class);
private static final String INFRASTRUCTURE_MANAGER_ROLE = "Infrastructure-Manager";
/**
* Retrieve notifications of the token's owner
* @param from must be greater or equal to 1, range[0, infinity]
* @param quantity quantity must be greater or equal to 0
* @return notifications up to quantity
* @throws ValidationException
*/
@GET
@Path("get-range-notifications/")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Notifications retrieved and reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getRangeNotifications(
@DefaultValue("1") @QueryParam("from") @Min(value=1, message="from must be greater or equal to 1")
int from,
@DefaultValue("10") @QueryParam("quantity") @Min(value=0, message="quantity must be greater or equal to 0")
int quantity
) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
logger.debug("Retrieving " + quantity + " notifications of user = " + username + " from " + from);
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
List<Notification> notifications = null;
try{
notifications = CassandraConnection.getInstance().getDatabookStore().getRangeNotificationsByUser(username, from, quantity);
responseBean.setResult(notifications);
responseBean.setSuccess(true);
logger.debug("List of notifications retrieved");
}catch(Exception e){
logger.error("Unable to retrieve such notifications.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Return whether the notifications for this user are enabled or not
* @pathExample /is-user-disabled?username=john.smith
* @responseExample application/json { "success": true, "message": null "result": true }
* @param username the username you want to check
* @return true if the notification for the user are disabled (Catalogue and Workspace ones)
*
*/
@GET
@Path("is-user-disabled/")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "true if the notification for the username given as query param are disabled (Catalogue and Workspace ones), false otherwise"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
@AuthorizationControl(allowedRoles={INFRASTRUCTURE_MANAGER_ROLE}, exception=AuthException.class)
public Response isUserDisabled(
@QueryParam("username") @NotNull(message="username cannot be null")
String username) throws ValidationException{
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
try{
Boolean userDisabled= !isNotificationEnabled(username);
responseBean.setResult(userDisabled);
responseBean.setSuccess(true);
logger.debug("are User " + username + " Notifications Disabled?"+userDisabled);
}catch(Exception e){
logger.error("Unable to read whether the notifications for this user are enabled or not.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
// /**
// * Set user notification enabled or disabled
// * @param disable true if you want to disable the notifications for this user, false if you want to enable them
// * @return the result of the operation
// * @throws ValidationException
// */
// @POST
// @Path("set-user-notifications/")
// @Consumes(MediaType.APPLICATION_JSON)
// @Produces(MediaType.APPLICATION_JSON)
// @StatusCodes ({
// @ResponseCode ( code = 200, condition = "Notification set Off or On correctly executed"),
// @ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
// })
// @AuthorizationControl(allowedRoles={INFRASTRUCTURE_MANAGER_ROLE}, exception=AuthException.class)
// public Response setUserNotifications(
// @NotNull(message="input is missing")
// @Valid
// UserSetNotificationBean setting) throws ValidationException{
//
// Caller caller = AuthorizationProvider.instance.get();
// String context = ScopeProvider.instance.get();
// ResponseBean responseBean = new ResponseBean();
// Status status = Status.OK;
//
//
// try{
// String opExecutor = caller.getClient().getId();
// Boolean result = setUserNotificationsOnOff(setting.getUsername(), setting.isDisableNotification(), opExecutor);
// String toReturn = "Could not set notifications";
// if (result) {
// toReturn = "Notifications have been set";
// toReturn += setting.isDisableNotification() ? " OFF (for 29 days unless re-enabled manually) ": " ON ";
// toReturn += "for username=" + setting.getUsername();
// }
// responseBean.setSuccess(true);
// responseBean.setResult(toReturn);
//
// } catch(Exception e){
// logger.error("Unable to set user notification", e);
// responseBean.setSuccess(false);
// responseBean.setMessage(e.getMessage());
// status = Status.INTERNAL_SERVER_ERROR;
// }
//
//
// return Response.status(status).entity(responseBean).build();
// }
/**
* @deprecated
* @param usernameToCheck
* @return true if notification are enabled for this user
* @throws IOException
*/
private boolean isNotificationEnabled(String usernameToCheck) throws IOException {
// MemcachedClient entries = new DistributedCacheClient().getMemcachedClient();
// String key = SocialUtils.DISABLED_USERS_NOTIFICATIONS_NAMESPACE+usernameToCheck;
// Boolean userEnabled = false;
// if(entries.get(key) == null)
// userEnabled = true;
// entries.getConnection().shutdown();
// return userEnabled;
return true;
}
// /**
// *
// * @param username the user you want to disable or enable notifications (max 29 days)
// * @param callerId the username or clientid of the operation executor
// * @param disable true if you want to disable the notifications for this user
// * @return true if the operation was performed
// * @throws IOException
// */
// private Boolean setUserNotificationsOnOff(String username, boolean disable, String callerId) throws IOException {
// MemcachedClient entries = new DistributedCacheClient().getMemcachedClient();
// String key = SocialUtils.DISABLED_USERS_NOTIFICATIONS_NAMESPACE+username;
// OperationFuture<Boolean> result = null;
// if (disable) {
// result = entries.set(key, SocialUtils.CACHING_TIME_TO_EXPIRATION, "op.ex:" + callerId); //operator executor is who silenced the user
// } else {
// result = entries.delete(key);
// }
// try {
// boolean res = result.getStatus().isSuccess();
// entries.getConnection().shutdown();
// return res;
// } catch (Exception e) {
// entries.getConnection().shutdown();
// e.printStackTrace();
// }
// return null;
// }
/**
* Send a JOB notification to a given recipient
* @param job The job bean
* @return
* @throws ValidationException
*/
@POST
@Path("notify-job-status/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Notification is sent correctly"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response notifyJobStatus(
@NotNull(message="input is missing")
@Valid
JobNotificationBean job) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
String appQualifier = caller.getClient().getId();
logger.debug("Received request from app " + appQualifier + " to notify job status described by bean " + job);
try{
String recipient = job.getRecipient();
GCubeUser userRecipient = UserManagerWSBuilder.getInstance().getUserManager().getUserByUsername(recipient);
GenericItemBean recipientBean = new GenericItemBean(userRecipient.getUsername(), userRecipient.getUsername(), userRecipient.getFullname(), userRecipient.getUserAvatarURL());
// notifications are sent by using the user allowed to use liferay's json apis
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(context);
GCubeUser senderUser = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser());
SocialNetworkingUser user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), senderUser.getFullname(), senderUser.getUserAvatarURL());
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, context, user);
RunningJob theJob = JobMapper.getJob(job);
new Thread(new JobStatusNotificationThread(theJob, Arrays.asList(recipientBean), nm)).start();
responseBean.setSuccess(true);
responseBean.setResult("Notification thread started");
}catch(Exception e){
logger.error("Unable to send job notification", e);
responseBean.setSuccess(false);
responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Send a Catalogue notification to a given user
* @param event
* @return
* @throws ValidationException
*/
@POST
@Path("catalogue/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Catalogue Notification is sent correctly"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response catalogue(
@NotNull(message="input is missing")
@Valid
CatalogueEvent event) throws ValidationException, UserManagementSystemException, UserRetrievalFault{
Caller caller = AuthorizationProvider.instance.get();
UserManager um = UserManagerWSBuilder.getInstance().getUserManager();
GCubeUser senderUser = null;
SocialNetworkingUser user = null;
// check if the token belongs to an application token. In this case use J.A.R.V.I.S (the username used to communicate with Liferay)
String username = null;
String fullName = "";
logger.debug("Catalogue Notification called by " + caller.getClient().getId() + " isUser?"+TokensUtils.isUserToken(caller));
if(!TokensUtils.isUserToken(caller)){
GCubeUser jarvis = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser());
SecurityTokenProvider.instance.set(LiferayJSONWsCredentials.getSingleton().getNotifierUserToken());
username = jarvis.getUsername();
fullName = caller.getClient().getId().replace("service-account-", ""); // the actual name of the IAM Client
senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName, senderUser.getUserAvatarURL());
}else{
username = caller.getClient().getId();
senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), senderUser.getFullname(), senderUser.getUserAvatarURL());
}
String context = ScopeProvider.instance.get();
logger.debug("catalogue notifications from user = " + username);
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
boolean deliveryResult = false;
try {
//logger.debug("catalogue notifications type is " + event.getType());
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(context);
//logger.debug("social networking site is " + site.getName());
//logger.debug("context is " + context);
//logger.debug("user is " + user.getUsername());
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, context, user);
String[] idsToNotify = event.getIdsToNotify();
if (! event.idsAsGroup()) {
for (int i = 0; i < idsToNotify.length; i++) {
String userIdToNotify = idsToNotify[i];
if (isNotificationEnabled(userIdToNotify)) {
String username2Notify = null;
try {
username2Notify = um.getUserByUsername(userIdToNotify).getUsername();
}
catch (Exception e) {
status = Status.BAD_REQUEST;
logger.error("Username not found", e);
responseBean.setSuccess(false);
responseBean.setMessage("Username not found, got: " + userIdToNotify);
return Response.status(status).entity(responseBean).build();
}
//logger.debug("username2notify " + username2Notify);
//logger.debug("type is " + CatalogueEventTypeMapper.getType(event.getType()));
//logger.debug("item id is " + event.getItemId());
//logger.debug("item text is " + event.getNotifyText());
//logger.debug("item url is " + event.getItemURL());
deliveryResult =
nm.notifyCatalogueEvent(
CatalogueEventTypeMapper.getType(event.getType()),
username2Notify,
event.getItemId(),
event.getNotifyText(),
event.getItemURL());
}
else {
Log.info("Notification disabled (admin) for user "+userIdToNotify + " will not notify");
}
}
} else { //the ids are contexts
for (int i = 0; i < idsToNotify.length; i++) {
String contextId = idsToNotify[i];
try {
ScopeBean scope = new ScopeBean(contextId);
if (scope.type() != ScopeBean.Type.VRE) {
logger.error("Context not a VRE");
status = Status.BAD_REQUEST;
responseBean.setSuccess(false);
responseBean.setMessage("Not a VRE Context, only VREs are supported");
return Response.status(status).entity(responseBean).build();
} else { // it is a context and it is a valid VRE
String[] userIdsToNotify = getUsernamesByContext(scope).toArray(new String[0]); //resolve the members
for (int j = 0; j < userIdsToNotify.length; j++) {
String userIdToNotify = userIdsToNotify[j];
if (isNotificationEnabled(userIdToNotify)) {
deliveryResult =
nm.notifyCatalogueEvent(
CatalogueEventTypeMapper.getType(event.getType()),
userIdToNotify,
event.getItemId(),
event.getNotifyText(),
event.getItemURL());
} else {
Log.info("Notification disabled (admin) for user "+userIdToNotify + " will not notify");
}
}
}
}
catch(IllegalArgumentException e) {
status = Status.BAD_REQUEST;
logger.error("Context not valid", e);
responseBean.setSuccess(false);
responseBean.setMessage("Context not valid, must start with / " + e.getMessage());
return Response.status(status).entity(responseBean).build();
}
}
}
} catch(Exception e){
logger.error("Unable to send job notification", e);
responseBean.setSuccess(false);
responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR;
}
logger.debug("catalogue notifications should have been sent");
if (deliveryResult) {
responseBean.setSuccess(true);
responseBean.setMessage("catalogue notification delivered correctly");
responseBean.setResult(new Boolean(true));
} else {
responseBean.setSuccess(false);
responseBean.setMessage("An error occurred between this service and Cassandra DB, notification not delivered correctly");
responseBean.setResult(new Boolean(false));
}
return Response.status(status).entity(responseBean).build();
}
/**
* Send a Workspace notification to a given user
* @param event
* @return
* @throws ValidationException
*/
@POST
@Path("workspace/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Workspace Notification is sent correctly"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response workspace(
@NotNull(message="input is missing")
@Valid
WorkspaceEvent event) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
String username = caller.getClient().getId();
logger.debug("workspace notifications from = " + username);
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
boolean deliveryResult = false;
try {
GCubeUser senderUser = null;
SocialNetworkingUser user = null;
String fullName = "";
logger.debug("workspace notifications type is " + event.getType());
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(context);
UserManager um = UserManagerWSBuilder.getInstance().getUserManager();
logger.debug("Workspace Notification called by " + caller.getClient().getId() + " isUser?"+TokensUtils.isUserToken(caller));
if(!TokensUtils.isUserToken(caller)){
GCubeUser jarvis = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser());
SecurityTokenProvider.instance.set(LiferayJSONWsCredentials.getSingleton().getNotifierUserToken());
username = jarvis.getUsername();
fullName = caller.getClient().getId().replace("service-account-", ""); // the actual name of the IAM Client
senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName, senderUser.getUserAvatarURL());
}else{
username = caller.getClient().getId();
senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), senderUser.getFullname(), senderUser.getUserAvatarURL());
}
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, context, user);
String[] idsToNotify = event.getIdsToNotify();
if (! event.idsAsGroup()) {
for (int i = 0; i < idsToNotify.length; i++) {
String userIdToNotify = idsToNotify[i];
if (isNotificationEnabled(userIdToNotify)) {
String username2Notify = "";
try {
username2Notify = um.getUserByUsername(userIdToNotify).getUsername();
}
catch (Exception e) {
status = Status.NOT_ACCEPTABLE;
logger.error("Username not found", e);
responseBean.setSuccess(false);
responseBean.setMessage("Username not found, received: " + userIdToNotify);
return Response.status(status).entity(responseBean).build();
}
deliveryResult = notifyWorkspaceEvent(event, nm, username2Notify);
}
else {
Log.info("Notification disabled (admin) for user "+userIdToNotify + " will not notify");
}
}
} else { //the ids are contexts
for (int i = 0; i < idsToNotify.length; i++) {
String contextId = idsToNotify[i];
try {
ScopeBean scope = new ScopeBean(contextId);
if (scope.type() != ScopeBean.Type.VRE) {
logger.error("Context not a VRE");
status = Status.BAD_REQUEST;
responseBean.setSuccess(false);
responseBean.setMessage("Not a VRE Context, only VREs are supported");
return Response.status(status).entity(responseBean).build();
} else { // it is a context and it is a valid VRE
String[] userIdsToNotify = getUsernamesByContext(scope).toArray(new String[0]); //resolve the members
for (int j = 0; j < userIdsToNotify.length; j++) {
String userIdToNotify = userIdsToNotify[j];
if (isNotificationEnabled(userIdToNotify))
deliveryResult = notifyWorkspaceEvent(event, nm, userIdToNotify);
else {
Log.info("Notification disabled (admin) for user "+userIdToNotify + " will not notify");
}
}
}
}
catch(IllegalArgumentException e) {
status = Status.BAD_REQUEST;
logger.error("Context not valid", e);
responseBean.setSuccess(false);
responseBean.setMessage("Context not valid, must start with / " + e.getMessage());
return Response.status(status).entity(responseBean).build();
}
}
}
} catch(Exception e){
logger.error("Unable to send job notification", e);
responseBean.setSuccess(false);
responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR;
}
logger.debug("workspace notifications should have been sent");
if (deliveryResult) {
responseBean.setSuccess(true);
responseBean.setMessage("Workspace notification delivered correctly");
responseBean.setResult(new Boolean(true));
} else {
responseBean.setSuccess(false);
responseBean.setMessage("An error occurred between this service and Cassandra DB, notification not delivered correctly");
responseBean.setResult(new Boolean(false));
}
return Response.status(status).entity(responseBean).build();
}
/**
*
* @param event
* @param nm
* @param idToNotify
* @return
*/
private boolean notifyWorkspaceEvent(WorkspaceEvent event, NotificationsManager nm, String idToNotify) {
try {
switch (event.getType()) {
case ITEM_NEW: {
AddedItemEvent itemBean = (AddedItemEvent) event;
return nm.notifyAddedItem(idToNotify, WorkspaceItemMapper.getFileItem(itemBean.getItem()), WorkspaceItemMapper.getSharedFolder(itemBean.getItem().getParent()));
}
case ITEM_UPDATE: {
UpdatedItemEvent itemBean = (UpdatedItemEvent) event;
return nm.notifyUpdatedItem(idToNotify, WorkspaceItemMapper.getFileItem(itemBean.getItem()), WorkspaceItemMapper.getSharedFolder(itemBean.getItem().getParent()));
}
case ITEM_DELETE: {
DeletedItemEvent itemBean = (DeletedItemEvent) event;
return nm.notifyRemovedItem(idToNotify, itemBean.getItemName(), WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()));
}
case FOLDER_SHARE: {
SharedFolderEvent itemBean = (SharedFolderEvent) event;
return nm.notifyFolderSharing(idToNotify, WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()));
}
case FOLDER_UNSHARE: {
UnsharedFolderEvent itemBean = (UnsharedFolderEvent) event;
return nm.notifyFolderUnsharing(idToNotify, itemBean.getUnsharedFolderId(), itemBean.getUnsharedFolderName());
}
case FOLDER_RENAME: {
RenamedFolderEvent itemBean = (RenamedFolderEvent) event;
return nm.notifyFolderRenaming(idToNotify, itemBean.getPreviousName(), itemBean.getNewName(), itemBean.getRenamedFolderId());
}
case FOLDER_ADMIN_UPGRADE: {
FolderAdminUpgradeEvent itemBean = (FolderAdminUpgradeEvent) event;
return nm.notifyAdministratorUpgrade(idToNotify, WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()));
}
case FOLDER_ADMIN_DOWNGRADE: {
FolderAdminDowngradeEvent itemBean = (FolderAdminDowngradeEvent) event;
return nm.notifyAdministratorDowngrade(idToNotify, WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()));
}
case FOLDER_ADDEDUSER: {
FolderAddedUserEvent itemBean = (FolderAddedUserEvent) event;
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
return nm.notifyFolderAddedUsers(idToNotify, WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()), itemBean.getNewAddedUserIds(), userManager);
}
case FOLDER_REMOVEDUSER: {
FolderRemovedUserEvent itemBean = (FolderRemovedUserEvent) event;
return nm.notifyFolderRemovedUser(idToNotify, WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()));
}
default:
break;
}
} catch(Exception e){
logger.error("Unable to send job notification", e);
return false;
}
return false;
}
/**
*
* @param context
* @return
* @throws Exception
*/
private List<String> getUsernamesByContext(ScopeBean context) throws Exception {
List<String> usernames = new ArrayList<String>();
GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
long groupId = groupManager.getGroupIdFromInfrastructureScope(context.toString());
// first retrieve ids
List<Long> userIds = userManager.getUserIdsByGroup(groupId);
// check info in cache when available
UsersCache cache = UsersCache.getSingleton();
for (Long userId : userIds) {
if(cache.getUser(userId) == null){
GCubeUser theUser = userManager.getUserById(userId);
if(theUser != null){
usernames.add(theUser.getUsername());
cache.pushEntry(userId, theUser);
}
}else
usernames.add(cache.getUser(userId).getUsername());
}
return usernames;
}
}

View File

@ -1,105 +0,0 @@
package org.gcube.social_networking.ws.methods.v2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.social.networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.portal.social.networking.liferay.ws.RoleManagerWSBuilder;
import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.TokensUtils;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/**
* REST interface for the social service (people). Used by OAUTH 2.0 apps/users.
*/
@RequestHeaders ({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json")
})
@Path("2/people")
public class People {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(People.class);
/**
* @responseExample application/json { "success" : true, "message" : null, "result" : { "roles" : [ ], "context" : "***", "avatar" : "https://*****3D", "fullname" : "John Smith", "username" : "john.smith" } }
* @return the user's profile. The user in this case is the one bound to the token
*/
@Produces(MediaType.APPLICATION_JSON)
@GET
@Path("profile")
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successful retrieval of user's profile, reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getProfile(){
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
GCubeUser user = null;
String scope = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
if(!TokensUtils.isUserToken(caller)){
status = Status.FORBIDDEN;
responseBean.setMessage("User's information can only be retrieved through a user token");
logger.warn("Trying to access users method via a token different than 'user-token' is not allowed");
}else{
try{
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager();
GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
user = userManager.getUserByUsername(username);
Map<String, Object> toReturn = new HashMap<String, Object>();
toReturn.put("username", user.getUsername());
toReturn.put("avatar", user.getUserAvatarURL());
toReturn.put("fullname", user.getFullname());
toReturn.put("context", scope);
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(user.getUserId(), groupManager.getGroupIdFromInfrastructureScope(scope));
List<String> rolesNames = new ArrayList<String>();
for (GCubeRole gCubeRole : roles) {
rolesNames.add(gCubeRole.getRoleName());
}
toReturn.put("roles", rolesNames);
responseBean.setResult(toReturn);
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Unable to retrieve user's profile", e);
responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR;
}
}
return Response.status(status).entity(responseBean).build();
}
}

View File

@ -1,702 +0,0 @@
package org.gcube.social_networking.ws.methods.v2;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.ValidationException;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.portal.databook.shared.PostWithAttachment;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.portal.databook.shared.*;
import org.gcube.portal.databook.shared.ex.ColumnNameNotFoundException;
import org.gcube.portal.databook.shared.ex.FeedIDNotFoundException;
import org.gcube.portal.databook.shared.ex.FeedTypeNotFoundException;
import org.gcube.portal.databook.shared.ex.PrivacyLevelTypeNotFoundException;
import org.gcube.social_networking.ws.inputs.PostInputBean;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.Filters;
import org.gcube.social_networking.ws.utils.SocialUtils;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/**
* REST interface for the social networking library (posts).
* @author Ahmed Ibrahim ISTI-CNR
*/
@Path("2/posts")
@RequestHeaders ({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json")
})
public class Posts {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Posts.class);
/**
* Retrieve posts of the auth token's owner, and allow to filter them by time"
* @param timeInMillis The reference time since when retrieving posts
* @return the posts
* @throws ValidationException
*/
@GET
@Path("get-posts-user-since/")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successful retrieval of posts, reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getRecentPostsByUserAndDate(
@QueryParam("time") @Min(value = 0, message="time cannot be negative")
long timeInMillis
) throws ValidationException{
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
String username = caller.getClient().getId();
List<Post> posts = null;
try{
logger.debug("Retrieving post for user id " + username + " and reference time " + timeInMillis);
posts = CassandraConnection.getInstance().getDatabookStore().getRecentPostsByUserAndDate(username, timeInMillis);
Filters.filterPostsPerContext(posts, context);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
responseBean.setResult(posts);
responseBean.setMessage("");
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Unable to retrieve such posts.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Retrieve all user's posts
* @return all posts of the auth token's owner in the context identified by the token
*/
@GET
@Path("get-posts-user/")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successful retrieval of posts, reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getAllPostsByUser() {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
List<Post> posts = null;
try{
logger.debug("Retrieving posts for user with id " + username);
posts = CassandraConnection.getInstance().getDatabookStore().getAllPostsByUser(username);
Filters.filterPostsPerContext(posts, context);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
responseBean.setResult(posts);
responseBean.setMessage("");
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Unable to retrieve such feeds.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Retrieve a post by id
* @return the post if the post id belongs to a post in the context identified by the token
*/
@GET
@Path("get-post/")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successful retrieval of posts, reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getPost(@QueryParam("id") String id) {
String context = ScopeProvider.instance.get();
Caller caller = AuthorizationProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
List<Post> posts = new ArrayList<>();
try{
logger.debug("Retrieving post with id " + id);
try {
posts.add(CassandraConnection.getInstance().getDatabookStore().readPost(id));
} catch(FeedIDNotFoundException e){
responseBean.setMessage("The post with id " + id + " does not exist in context " + context);
responseBean.setSuccess(false);
return Response.status(status).entity(responseBean).build();
}
Filters.filterPostsPerContext(posts, context);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
if (posts.isEmpty()) {
responseBean.setMessage("The post with id " + id + " does not belong to this context " + context);
responseBean.setSuccess(false);
status = Status.FORBIDDEN;
return Response.status(status).entity(responseBean).build();
}
responseBean.setResult(posts.get(0));
responseBean.setMessage("");
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Unable to retrieve such post.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Retrieve a given quantity of latest user's posts
* @param quantity the number of latest post to get
* @pathExample /get-posts-user-quantity?quantity=10
* @return all posts of the auth token's owner in the context identified by the token, in reverse chronological order up to quantity (at most)
* @throws ValidationException
*/
@GET
@Path("get-posts-user-quantity/")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successful retrieval of posts, reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getQuantityPostsByUser(
@DefaultValue("10")
@QueryParam("quantity")
@Min(value=0, message="quantity cannot be negative")
int quantity) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
List<Post> posts = new ArrayList<>();
// if quantity is zero, just return an empty list
if(quantity == 0){
responseBean.setSuccess(true);
return Response.status(status).entity(responseBean).build();
}
try{
logger.debug("getRecentPostsByUser first, posts made by user " + username);
posts = CassandraConnection.getInstance().getDatabookStore().getAllPostsByUser(username);
if (posts != null)
logger.debug("got " + posts.size() + " posts");
logger.debug("Retrieving last " + quantity + " posts made by user " + username + " in context = "+context);
Filters.filterPostsPerContext(posts, context);
quantity = (quantity > posts.size()) ? posts.size() : quantity;
posts = posts.subList(0, quantity);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
responseBean.setResult(posts);
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Unable to retrieve such posts.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Create a new user post having as owner the auth token's owner
* @param post The post to be written
* @return
* @throws ValidationException
*/
@POST
@Path("write-post-user")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 201, condition = "Successfull created, the new post is reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response writePostUser(
@NotNull(message="Post to write is missing")
@Valid
PostInputBean post) throws ValidationException{
logger.debug("Request of writing a feed coming from user " + post);
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.CREATED;
// parse
String postText = post.getText();
String previewTitle = post.getPreviewtitle();
String previewDescription = post.getPreviewdescription();
String previewHost = post.getPreviewhost();
String previewUrl = post.getPreviewurl();
String httpImageUrl = post.getHttpimageurl();
boolean enableNotification = post.isEnablenotification();
// convert enablenotification parameter
if(enableNotification)
logger.debug("Enable notification for this user post.");
else
logger.debug("Disable notification for this user post.");
// try to share
logger.debug("Trying to share user post...");
Post res = SocialUtils.shareUserUpdate(
username,
postText,
context,
previewTitle,
previewDescription,
previewHost,
previewUrl,
httpImageUrl,
enableNotification
);
if(res != null){
logger.debug("Post correctly written by user " + username);
responseBean.setResult(res);
responseBean.setSuccess(true);
return Response.status(status).entity(responseBean).build();
}
logger.error("Unable to write post.");
responseBean.setMessage("Unable to write post");
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
return Response.status(status).entity(responseBean).build();
}
/**
* Retrieve the application's posts
* @return the application (IAM Client) posts belonging to the token's owner (i.e., an application)"
*/
@GET
@Path("get-posts-app/")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successfull created, the new post is reported in the 'result' field of the returned object"),
@ResponseCode ( code = 403, condition = "\"There is no application profile with such token"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getAllPostsByApp() {
Caller caller = AuthorizationProvider.instance.get();
String appId = caller.getClient().getId();
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
// check if the token actually matches an application
ApplicationProfile appProfile = SocialUtils.getProfileFromInfrastrucure(appId, context);
if(appProfile == null){
logger.error("The given token is not belonging to an application!!!");
status = Status.FORBIDDEN;
responseBean.setSuccess(false);
responseBean.setMessage(ErrorMessages.NOT_APP_TOKEN);
return Response.status(status).entity(responseBean).build();
}
try{
logger.debug("Retrieving posts for app with id " + appId);
List<Post> feeds = CassandraConnection.getInstance().getDatabookStore().getAllPostsByApp(appId);
Filters.filterPostsPerContext(feeds, context);
responseBean.setSuccess(true);
responseBean.setResult(feeds);
}catch(Exception e){
logger.error("Unable to retrieve such feeds.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Create a new application post having as owner-application the token's owner (the IAM Client), note that the application must be registered on the Information System
* @param post The post to be written
* @return
*/
@POST
@Path("write-post-app")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successfull created, the new post is reported in the 'result' field of the returned object"),
@ResponseCode ( code = 403, condition = "\"There is no application profile with such token"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response writePostApp(
@NotNull(message="Post to write is null")
@Valid
PostInputBean post){
Caller caller = AuthorizationProvider.instance.get();
String appId = caller.getClient().getId();
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.CREATED;
logger.debug("Request of writing a feed coming from an application.");
// check if the token actually matches an application profile
ApplicationProfile appProfile = SocialUtils.getProfileFromInfrastrucure(appId, context);
if(appProfile == null){
logger.error("The given token doesn't belong to an application!!!");
responseBean.setSuccess(false);
responseBean.setMessage(ErrorMessages.NOT_APP_TOKEN);
status = Status.FORBIDDEN;
return Response.status(status).entity(responseBean).build();
}
// parse
String postText = post.getText();
String previewTitle = post.getPreviewtitle();
String previewDescription = post.getPreviewdescription();
String httpImageUrl = post.getHttpimageurl();
boolean enableNotification = post.isEnablenotification();
String params = post.getParams();
// convert enablenotification parameter
if(enableNotification)
logger.debug("Enable notification for this application post.");
else
logger.debug("Disable notification for this application post.");
// write post + notification if it is the case
Post written = SocialUtils.shareApplicationUpdate(
postText,
params,
previewTitle,
previewDescription,
httpImageUrl,
appProfile,
caller,
enableNotification
);
if(written != null){
responseBean.setResult(written);
responseBean.setSuccess(true);
return Response.status(status).entity(responseBean).build();
}
logger.error("Unable to write post.");
responseBean.setMessage("Unable to write post");
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
return Response.status(status).entity(responseBean).build();
}
/**
*
* @return all the posts in the context bound to the auth token
*/
@GET
@Path("get-posts-vre/")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 201, condition = "Sccessfull retrieved posts, they are reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getAllPostsByVRE() {
String context = ScopeProvider.instance.get();
Caller caller = AuthorizationProvider.instance.get();
logger.debug("Retrieving all posts coming from vre = " + context);
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
try{
List<Post> posts = CassandraConnection.getInstance().getDatabookStore().getAllPostsByVRE(context);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
responseBean.setResult(posts);
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Unable to retrieve posts for vre = " + context, e);
status = Status.INTERNAL_SERVER_ERROR;
responseBean.setMessage(e.toString());
responseBean.setSuccess(false);
}
return Response.status(status).entity(responseBean).build();
}
/**
* return the most recent posts for this vre up to quantity param and the last index of the posts in the timeline
* lastReturnedPostTimelineIndex is useful to know from where to start the range the next time you ask, because there are deletions
*
* @param from the range start (most recent feeds for this vre) has to be greater than 0
* @param quantity the number of most recent feeds for this vre starting from "from" param
* @pathExample /get-recent-posts-vre-by-range?from=1&quantity=10
* @return a <class>RangePosts</class> containing of most recent feeds for this vre
* @throws FeedTypeNotFoundException
* @throws PrivacyLevelTypeNotFoundException
* @throws ColumnNameNotFoundException
*/
@GET
@Path("get-recent-posts-vre-by-range/")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 201, condition = "Sccessfull retrieved posts, they are reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getRecentPostsByVREAndRange(
@QueryParam("from")
@Min(value=1, message="from cannot be negative")
int from,
@QueryParam("quantity")
@Min(value=1, message="quantity cannot be negative")
int quantity) throws ValidationException {
String context = ScopeProvider.instance.get();
Caller caller = AuthorizationProvider.instance.get();
logger.debug("Retrieving all posts coming from vre = " + context);
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
try{
RangePosts rangePosts = CassandraConnection.getInstance().getDatabookStore().getRecentPostsByVREAndRange(context, from, quantity);
Filters.hideSensitiveInformation(rangePosts.getPosts(), caller.getClient().getId());
responseBean.setResult(rangePosts);
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Unable to retrieve posts for vre = " + context, e);
status = Status.INTERNAL_SERVER_ERROR;
responseBean.setMessage(e.toString());
responseBean.setSuccess(false);
}
return Response.status(status).entity(responseBean).build();
}
/**
* Retrieve posts containing the hashtag in the context bound to the auth token
* @param hashtag he hashtag to be contained within the posts
* @pathExample /get-posts-by-hashtag?hashtag=#thehashtag
* @return the posts in the context bound to the auth token matching the hashtag
* @throws ValidationException
*/
@GET
@Path("get-posts-by-hashtag/")
@Produces({MediaType.APPLICATION_JSON})
@StatusCodes ({
@ResponseCode ( code = 201, condition = "Sccessfull retrieved posts, they are reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getPostsByHashTags(
@QueryParam("hashtag")
@NotNull(message="hashtag cannot be missing")
String hashtag) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
logger.debug("User " + username + " has requested posts containing hashtag " + hashtag + " in context " + context);
try{
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
List<Post> posts = datastore.getVREPostsByHashtag(context, hashtag);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
responseBean.setResult(posts);
responseBean.setSuccess(true);
}catch(Exception e){
logger.error("Failed to retrieve hashtags", e);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Retrieve ids (UUID) of the liked posts by the user
* @return ids (UUID) of the liked posts by the user in the context bound to the auth token
*/
@GET
@Path("get-id-liked-posts/")
@Produces({MediaType.APPLICATION_JSON})
@StatusCodes ({
@ResponseCode ( code = 201, condition = "Sccessfull retrieved ids, they are reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getAllLikedPostIdsByUser() {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
logger.debug("Retrieving all liked posts for user with id " + username + " in context " + context);
List<String> retrievedLikedPostsIds = null;
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
try{
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
retrievedLikedPostsIds = datastore.getAllLikedPostIdsByUser(username);
Filters.filterFeedsPerContextById(retrievedLikedPostsIds, context);
responseBean.setResult(retrievedLikedPostsIds);
responseBean.setSuccess(true);
logger.debug("Ids of liked posts by " + username + " retrieved");
}catch(Exception e){
logger.error("Unable to read such ids of liked Posts.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
/**
* Retrieve posts liked by the user
* @param limit The maximum number of posts to be retrieved
* @return posts liked by the user (up to a given quantity) in the context bound to the auth token
* @throws ValidationException
*/
@GET
@Path("get-liked-posts/")
@Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 200, condition = "Successfull retrieved posts, they are reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getAllLikedPostsByUser(
@DefaultValue("10")
@QueryParam("limit")
@Min(message="limit cannot be negative", value = 0)
int limit) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
List<Post> retrievedLikedPosts = null;
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
try{
logger.debug("Retrieving " + limit + " liked posts for user with id " + username + " in context " + context);
retrievedLikedPosts = CassandraConnection.getInstance().getDatabookStore().getAllLikedPostsByUser(username, limit);
Filters.filterPostsPerContext(retrievedLikedPosts, context);
Filters.hideSensitiveInformation(retrievedLikedPosts, caller.getClient().getId());
responseBean.setResult(retrievedLikedPosts);
responseBean.setSuccess(true);
logger.debug("Liked posts by " + username + " retrieved");
}catch(Exception e){
logger.error("Unable to read such liked posts.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
//libapi
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("save-user-post-attachments-lib")
public Response saveUserPostLib(
@NotNull(message="post to add is missing")
@Valid
PostWithAttachment postWithAttachment
) throws ValidationException{
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
try{
Post post = postWithAttachment.getPost();
logger.debug("Post is " + post);
List<Attachment> attachments = postWithAttachment.getAttachments();
logger.debug("Attachments are " + attachments);
boolean result = CassandraConnection.getInstance().getDatabookStore().saveUserPost(post,attachments);
responseBean.setResult(result);
responseBean.setMessage("");
responseBean.setSuccess(result);
}catch(Exception e){
logger.error("Unable to write comment.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("save-app-post-attachments-lib")
public Response saveAppPostLib(
@NotNull(message="post to add is missing")
@Valid
PostWithAttachment postWithAttachment
) throws ValidationException{
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
try{
Post post = postWithAttachment.getPost();
List<Attachment> attachments = postWithAttachment.getAttachments();
boolean result = CassandraConnection.getInstance().getDatabookStore().saveAppPost(post,attachments);
responseBean.setResult(result);
responseBean.setMessage("");
responseBean.setSuccess(result);
}catch(Exception e){
logger.error("Unable to write comment.", e);
responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(responseBean).build();
}
}

View File

@ -1,89 +0,0 @@
package org.gcube.social_networking.ws.methods.v2;
import static org.gcube.common.authorization.client.Constants.authorizationService;
import javax.validation.Valid;
import javax.validation.ValidationException;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.shared.ApplicationProfile;
import org.gcube.social_networking.ws.inputs.ApplicationId;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.SocialUtils;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/**
* REST interface for the social networking library (tokens).
*/
@Path("2/tokens")
@Deprecated
public class Tokens {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Tokens.class);
@POST
@Path("generate-application-token/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@StatusCodes ({
@ResponseCode ( code = 201, condition = "Successful creation of the token, reported in the 'result' field of the returned object"),
@ResponseCode ( code = 403, condition = "There is no application profile with such id"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
/**
* Generate a legacy application auth token for the application with id app_id
* @param input The bean containing the app_id field
* @return the legacy application token
* @throws ValidationException
*/
public Response generateApplicationToken(
@NotNull(message="Missing input parameter")
@Valid
ApplicationId input) throws ValidationException{
logger.debug("Incoming request for app token generation.");
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.CREATED;
String appId = input.getAppId();
try {
// check if the token actually matches an application profile
ApplicationProfile appProfile = SocialUtils.getProfileFromInfrastrucure(appId, context);
if(appProfile == null){
logger.error("The given id doesn't belong to an application!!!");
responseBean.setSuccess(false);
responseBean.setMessage(ErrorMessages.NOT_APP_ID);
status = Status.FORBIDDEN;
return Response.status(status).entity(responseBean).build();
}
logger.debug("Generating token for the application with id " + appId);
// each token is related to an identifier and the context
String appToken = authorizationService().generateExternalServiceToken(appId);
responseBean.setSuccess(true);
responseBean.setResult(appToken);
} catch (Exception e) {
logger.error("Unable to generate token for app " + appId + " and scope " + context);
status = Status.INTERNAL_SERVER_ERROR;
responseBean.setSuccess(false);
responseBean.setMessage(ErrorMessages.TOKEN_GENERATION_APP_FAILED);
return Response.status(status).entity(responseBean).build();
}
return Response.status(status).entity(responseBean).build();
}
}

View File

@ -1,135 +0,0 @@
package org.gcube.social_networking.ws.methods.v2;
import java.util.List;
import javax.validation.ValidationException;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.portal.social.networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.portal.social.networking.liferay.ws.RoleManagerWSBuilder;
import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.TokensUtils;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.gcube.vomanagement.usermanagement.model.GatewayRolesNames;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
/**
* REST interface for the social networking library (vres).
*/
@Path("2/vres")
@RequestHeaders ({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json")
})
public class VREs {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Users.class);
/**
* @responseExample application/json {
"success" : true,
"message" : null,
"result" : [ {
"name" : "NextNext",
"context" : "/gcube/devNext/NextNext",
"description" : "NextNext description AAA"
}, {
"name" : "devVRE",
"context" : "/gcube/devsec/devVRE",
"description" : "devVRE description BBB"
} ]
}
* @pathExample /get-my-vres?getManagers=false
* @param getManagers set true if you also want to know the VRE-Managers
* @return the list of vres along with some metadata
* @throws ValidationException
*/
@SuppressWarnings("unchecked")
@GET
@Path("get-my-vres/")
@Produces(MediaType.APPLICATION_JSON)
public Response getMyVres(
@DefaultValue("false") @QueryParam("getManagers") boolean getManagers
) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
if(!TokensUtils.isUserToken(caller)){
status = Status.FORBIDDEN;
responseBean.setMessage("This method can only be invoked with a user token!");
logger.warn("Trying to access get-my-vres method via a token different than USER is not allowed");
}else{
GroupManager gmManager = GroupManagerWSBuilder.getInstance().getGroupManager();
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager();
try{
GCubeUser user = userManager.getUserByUsername(username);
List<GCubeGroup> vres = gmManager.listVresByUser(user.getUserId());
JSONArray toReturn = new JSONArray();
for (GCubeGroup group : vres) {
// # ticket 9333
JSONObject obj = new JSONObject();
obj.put("name", group.getGroupName());
obj.put("context", gmManager.getInfrastructureScope(group.getGroupId()));
obj.put("description", group.getDescription());
//obj.put("thumbnail_url", ...); // TODO
JSONArray managers = new JSONArray();
if(getManagers){
List<GCubeUser> vreManagers = userManager.listUsersByGroupAndRole(group.getGroupId(),
roleManager.getRoleIdByName(GatewayRolesNames.VRE_MANAGER.getRoleName()));
for (GCubeUser vreManager : vreManagers) {
JSONObject manager = new JSONObject();
manager.put("username", vreManager.getUsername());
manager.put("fullname", vreManager.getFullname());
managers.add(manager);
}
obj.put("managers", managers);
}
toReturn.add(obj);
}
responseBean.setSuccess(true);
responseBean.setResult(toReturn);
}catch(Exception e){
logger.error("Unable to retrieve vres for user.", e);
responseBean.setMessage(e.toString());
responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR;
}
}
return Response.status(status).entity(responseBean).build();
}
}

View File

@ -1,77 +0,0 @@
package org.gcube.social_networking.ws.outputs;
import java.io.Serializable;
/**
* Response bean
*
*/
public class ResponseBean implements Serializable {
private static final long serialVersionUID = -2725238162673879658L;
/**
* The result of the request: true if it succeeded, false otherwise
*/
private boolean success;
/**
* An error message if something wrong happened, null/empty otherwise
*/
private String message;
/**
* The result object of the request
*/
private Object result;
public ResponseBean() {
super();
}
/**
* @param success
* @param message
* @param result
*/
public ResponseBean(boolean success, String message, Object result) {
super();
this.success = success;
this.message = message;
this.result = result;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
@Override
public String toString() {
return "ResponseBean [success=" + success
+ ", message=" + message + ", result=" + result + "]";
}
}

View File

@ -1,37 +0,0 @@
package org.gcube.social_networking.ws.providers;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
@Provider
/**
* Custom mapper with property CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES to perform serialization/deserialization
* with snake case over camel case for json beans.
* TODO check https://github.com/FasterXML/jackson-docs/wiki/JacksonMixInAnnotations for applying such transformation
* only to some classes.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class CustomObjectMapper implements ContextResolver<ObjectMapper> {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CustomObjectMapper.class);
private final ObjectMapper mapper;
public CustomObjectMapper() {
logger.debug("new ObjectMapperResolver()");
mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
}
@Override
public ObjectMapper getContext(Class<?> type) {
logger.debug("ObjectMapperResolver.getContext(...) invoked");
return mapper;
}
}

View File

@ -1,50 +0,0 @@
package org.gcube.social_networking.ws.utils;
import org.gcube.portal.databook.server.DBCassandraAstyanaxImpl;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.slf4j.LoggerFactory;
/**
* Cassandra connection class.
* @author Costantino Perciante at ISTI-CNR
*/
public class CassandraConnection {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CassandraConnection.class);
// databook store (singleton)
private static DatabookStore store;
private static CassandraConnection singleton = new CassandraConnection();
private CassandraConnection(){
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
logger.debug("Getting connection to cassandra");
store = new DBCassandraAstyanaxImpl(ctx.container().configuration().infrastructure());
logger.debug("Connection to cassandra created");
}
/**
* Returns the object to query the cassandra cluster.
* @return connection pool to cassandra cluster
*/
public DatabookStore getDatabookStore(){
return store;
}
/**
* Get the instance
* @return
*/
public static CassandraConnection getInstance(){
return singleton;
}
}

View File

@ -1,52 +0,0 @@
package org.gcube.social_networking.ws.utils;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.socialnetworking.social_data_search_client.ElasticSearchClient;
import org.gcube.socialnetworking.social_data_search_client.ElasticSearchClientImpl;
import org.slf4j.LoggerFactory;
/**
* The class discovers and offer connections to the elastic search cluster.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class ElasticSearchConnection {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ElasticSearchConnection.class);
// databook store (singleton)
private ElasticSearchClient es;
// singleton
private static ElasticSearchConnection singleton = new ElasticSearchConnection();
private ElasticSearchConnection(){
try {
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
logger.debug("Creating connection to Elasticsearch");
es = new ElasticSearchClientImpl(ctx.container().configuration().infrastructure());
logger.debug("Elasticsearch connection created");
} catch (Exception e) {
logger.error("Failed to connect to elasticsearch", e);
}
}
public static ElasticSearchConnection getSingleton(){
return singleton;
}
/**
* Returns the object to connect to cassandra cluster.
* @return connection pool to cassandra cluster
* @throws Exception
*/
public ElasticSearchClient getElasticSearchClient(){
return es;
}
}

View File

@ -1,21 +0,0 @@
package org.gcube.social_networking.ws.utils;
/**
* Class that contains error messages to be returned in the HTTP responses.
* @author Costantino Perciante at ISTI-CNR
*/
public class ErrorMessages {
public static final String MISSING_TOKEN = "Missing token.";
public static final String MISSING_PARAMETERS = "Missing request parameters.";
public static final String INVALID_TOKEN = "Invalid token.";
public static final String TOKEN_GENERATION_APP_FAILED = "Token generation failed.";
public static final String NOT_APP_TOKEN = "Invalid token: not belonging to an application.";
public static final String NOT_APP_ID = "Invalid application id: it doesn't belong to an application.";
public static final String NO_APP_PROFILE_FOUND = "There is no application profile for this app id/scope.";
public static final String BAD_REQUEST = "Please check the parameter you passed, it seems a bad request";
public static final String ERROR_IN_API_RESULT = "The error is reported into the 'message' field of the returned object";
public static final String POST_OUTSIDE_VRE = "A post cannot be written into a context that is not a VRE";
public static final String DEPRECATED_METHOD = "This method is deprecated, must use version 2";
}

View File

@ -1,193 +0,0 @@
package org.gcube.social_networking.ws.utils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.portal.databook.shared.Comment;
import org.gcube.portal.databook.shared.EnhancedFeed;
import org.gcube.portal.databook.shared.Feed;
import org.gcube.portal.databook.shared.Post;
import org.gcube.portal.social.networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.slf4j.LoggerFactory;
/**
* Filters to apply to feeds/comments etc
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class Filters {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Filters.class);
private static List<String> getContexts(String context) throws IllegalArgumentException, UserManagementSystemException, GroupRetrievalFault{
// retrieve group information
GroupManager gm = GroupManagerWSBuilder.getInstance().getGroupManager();
GCubeGroup group = gm.getGroup(gm.getGroupIdFromInfrastructureScope(context));
List<String> contexts = new ArrayList<String>();
if(gm.isRootVO(group.getGroupId())){
}
else if(gm.isVO(group.getGroupId())){
List<GCubeGroup> vres = group.getChildren();
for (GCubeGroup gCubeGroup : vres) {
contexts.add(gm.getInfrastructureScope(gCubeGroup.getGroupId()));
}
}else{
contexts.add(gm.getInfrastructureScope(group.getGroupId()));
}
return contexts;
}
/**
* Given a list of not filtered feeds, the methods remove feeds unaccessible in this scope.
* If the initial context is the root: all feeds are returned;
* If the initial context is a VO: feeds for vres within the vo are returned;
* If the initial context is a vre: feeds of the vre are returned;
* @param feedsIds
* @param context
* @throws Exception
*/
public static void filterFeedsPerContextById(
List<String> feedsIds, String context) throws Exception {
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
List<Feed> feeds = new ArrayList<Feed>();
for (String feedId : feedsIds) {
try{
feeds.add(datastore.readFeed(feedId));
}catch(Exception e){
logger.error("Unable to read feed with id " + feedId, e);
}
}
// filter
filterFeedsPerContext(feeds, context);
// clear and convert
feedsIds.clear();
for (Feed feed : feeds) {
feedsIds.add(feed.getKey());
}
}
/**
* Given a list of not filtered feeds, the methods remove feeds unaccessible in this scope.
* If the initial context is the root: all feeds are returned;
* If the initial context is a VO: feeds for vres within the vo are returned;
* If the initial context is a vre: feeds of the vre are returned;
* @param feeds
* @param context
* @throws Exception
*/
@Deprecated
public static void filterFeedsPerContext(List<Feed> feeds, String context) throws Exception {
List<String> contexts = getContexts(context);
// filter
Iterator<Feed> iterator = feeds.iterator();
while (iterator.hasNext()) {
Feed feed = (Feed) iterator.next();
if(!contexts.contains(feed.getVreid()))
iterator.remove();
}
}
/**
* Given a list of not filtered posts, the methods remove posts unaccessible in this scope.
* If the initial context is the root: all posts are returned;
* If the initial context is a VO: posts for vres within the vo are returned;
* If the initial context is a vre: posts of the vre are returned;
* @param context
* @throws Exception
*/
public static void filterPostsPerContext(List<Post> posts, String context) throws Exception {
List<String> contexts = getContexts(context);
// filter
Iterator<Post> iterator = posts.iterator();
while (iterator.hasNext()) {
Post post = (Post) iterator.next();
if(!contexts.contains(post.getVreid()))
iterator.remove();
}
}
/**
* Filter comments per context
* @param comments
* @param context
* @throws Exception
*/
public static void filterCommentsPerContext(List<Comment> comments, String context) throws Exception {
List<String> contexts = getContexts(context);
// get cassandra store
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
// filter
Iterator<Comment> iterator = comments.iterator();
while (iterator.hasNext()) {
try{
Comment comment = (Comment) iterator.next();
Feed parent = datastore.readFeed(comment.getFeedid());
if(!contexts.contains(parent.getVreid()))
iterator.remove();
}catch(Exception e){
logger.warn("Failed to analyze this comment", e);
iterator.remove(); // remove it anyway
}
}
}
/**
* Depending on the type of object provided (e.g. Feed, Comment etc), some information are removed
* @param toClear
* @throws Exception
*/
public static <T> void hideSensitiveInformation(List<T> toClear, String usernameCaller){
if(toClear == null || toClear.isEmpty() || usernameCaller == null || usernameCaller.isEmpty())
return;
else{
// for feeds
if(toClear.get(0).getClass().equals(Feed.class)){
for (T feed : toClear) {
Feed feeded = ((Feed)feed);
if(!usernameCaller.equals(feeded.getEntityId()))
feeded.setEmail(""); // remove the email field
}
}else if(toClear.get(0).getClass().equals(EnhancedFeed.class)){
for (T enhancedFeed : toClear) {
Feed feeded = ((EnhancedFeed)enhancedFeed).getFeed();
if(!usernameCaller.equals(feeded.getEntityId()))
feeded.setEmail(""); // remove the email field
}
}
}
}
}

View File

@ -1,725 +0,0 @@
package org.gcube.social_networking.ws.utils;
import static org.gcube.resources.discovery.icclient.ICFactory.client;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager;
import org.gcube.applicationsupportlayer.social.NotificationsManager;
import org.gcube.applicationsupportlayer.social.ex.ApplicationProfileNotFoundException;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingUser;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.resources.gcore.utils.XPathHelper;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.portal.databook.shared.ApplicationProfile;
import org.gcube.portal.databook.shared.Comment;
import org.gcube.portal.databook.shared.Like;
import org.gcube.portal.databook.shared.Post;
import org.gcube.portal.databook.shared.PostType;
import org.gcube.portal.databook.shared.PrivacyLevel;
import org.gcube.portal.databook.shared.ex.FeedIDNotFoundException;
import org.gcube.portal.notifications.bean.GenericItemBean;
import org.gcube.portal.notifications.thread.CommentNotificationsThread;
import org.gcube.portal.notifications.thread.LikeNotificationsThread;
import org.gcube.portal.notifications.thread.MentionNotificationsThread;
import org.gcube.portal.notifications.thread.PostNotificationsThread;
import org.gcube.portal.social.networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.portlets.widgets.pickitem.shared.ItemBean;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.Query;
import org.gcube.resources.discovery.client.queries.impl.QueryBox;
import org.gcube.social_networking.caches.SocialNetworkingSiteFinder;
import org.gcube.social_networking.socialutillibrary.Utils;
import org.gcube.socialnetworking.socialtoken.SocialMessageParser;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.TeamRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
/**
* Utility class.
*/
@SuppressWarnings("deprecation")
public class SocialUtils {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SocialUtils.class);
public final static String NO_TEXT_FILE_SHARE = "_N0_73X7_SH4R3_";
public final static int CACHING_TIME_TO_EXPIRATION = 2506000;//29 days 6 minutes 40 seconds
public final static String DISABLED_USERS_NOTIFICATIONS_NAMESPACE = "dun:";
// name of the portlet for vre notification
public static final String NEWS_FEED_PORTLET_CLASSNAME = "org.gcube.portlets.user.newsfeed.server.NewsServiceImpl";
/**
*
* @param mentions the set of string containing the usernames
* @return a list of existing usernames associated with their fullnames
*/
private static ArrayList<GenericItemBean> getUsersFromUsernames(Set<String> mentions) {
if (mentions.isEmpty())
return new ArrayList<>();
ArrayList<GenericItemBean> toReturn = new ArrayList<>();
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
for (String username : mentions) {
try{
GCubeUser user = uManager.getUserByUsername(username);
String fullName = user.getFirstName() + " " + user.getLastName();
toReturn.add(new GenericItemBean(""+user.getUserId(), username, fullName, ""));
}catch(Exception e){
logger.error("Unable to get user informations for username=" + username);
}
}
return toReturn;
}
// utility method
private static ArrayList<ItemBean> convertToItemBean(Collection<GenericItemBean> items) {
ArrayList<ItemBean> toReturn = new ArrayList<>(items.size());
for (GenericItemBean item : items) {
toReturn.add(new ItemBean(item.getId(), item.getName(), item.getAlternativeName(), item.getThumbnailURL()));
}
return toReturn;
}
/**
* Method used when an application needs to publish something.
* @param postText
* @param uriParams
* @param previewTitle
* @param previewDescription
* @param httpImageUrl
* @return true upon success, false on failure
*/
public static Post shareApplicationUpdate(
String postText,
String uriParams,
String previewTitle,
String previewDescription,
String httpImageUrl,
ApplicationProfile applicationProfile,
Caller caller,
boolean notifyGroup
){
SocialMessageParser messageParser = new SocialMessageParser(postText);
String escapedPostText = messageParser.getParsedMessage();
List<String> hashtags = messageParser.getHashtags();
ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(postText));
ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
escapedPostText = Utils.convertMentionUsernamesAnchorHTML(escapedPostText, mentionedUsersToConvertInHTML, site.getSiteURL(), site.getSiteLandingPagePath());
logger.debug("*** Escaped post text is " + escapedPostText);
String scope = ScopeProvider.instance.get();
String appId = caller.getClient().getId();
Post toWrite =
buildPost(
escapedPostText,
uriParams == null ? "" : uriParams,
previewTitle == null ? "" : previewTitle,
previewDescription == null ? "" : previewDescription,
httpImageUrl == null ? "" : httpImageUrl,
applicationProfile,
scope);
// try to save it
boolean res = CassandraConnection.getInstance().getDatabookStore().saveAppPost(toWrite);
if(res){
logger.debug("Feed correctly written by application " + appId);
// wait a bit before saving hashtags
if(hashtags != null && !hashtags.isEmpty())
new Thread(()->{
try {
Thread.sleep(1000);
CassandraConnection.getInstance().getDatabookStore().saveHashTags(toWrite.getKey(), scope, hashtags);
} catch (Exception e1) {
logger.error("Failed to save hashtags in Cassandra", e1);
}
}).start();
// build the notification manager
SocialNetworkingUser user = new SocialNetworkingUser(appId, "", applicationProfile.getName(), applicationProfile.getImageUrl());
NotificationsManager nm = new ApplicationNotificationsManager(
UserManagerWSBuilder.getInstance().getUserManager(),
site,
scope,
user,
NEWS_FEED_PORTLET_CLASSNAME);
if (!mentionedUsers.isEmpty())
new Thread(new MentionNotificationsThread(toWrite.getKey(), toWrite.getDescription(), nm, null, mentionedUsers)).start();
if(notifyGroup){
logger.debug("Sending notifications for " + appId + " " + scope);
try{
String name = new ScopeBean(scope).name(); // scope such as devVRE
// retrieve group information
GroupManager gManager = GroupManagerWSBuilder.getInstance().getGroupManager();
long groupId = gManager.getGroupId(name);
String groupName = gManager.getGroup(groupId).getGroupName();
logger.debug("Company id and name " + groupId + " " + groupName);
// start notification thread
new Thread(new PostNotificationsThread(
UserManagerWSBuilder.getInstance().getUserManager(),
toWrite.getKey(),
toWrite.getDescription(),
""+groupId,
nm,
new HashSet<String>(hashtags),
new HashSet<String>())
).start();
}catch (Exception e) {
logger.debug("Feed succesfully created but unable to send notifications.");
}
}
return toWrite;
}
else
return null;
}
/**
* Build an ApplicationProfile Feed.
*
* @param description add a description for the update you are sharing
* @param uriParams the additional parameters your applicationProfile needs to open the subject of this update e.g. id=12345&type=foo
* @param previewTitle the title to show in the preview
* @param previewDescription the description to show in the preview
* @param previewThumbnailUrl the image url to show in the preview
* @return a feed instance ready to be written
*/
private static Post buildPost(
String description,
String uriParams,
String previewTitle,
String previewDescription,
String previewThumbnailUrl,
ApplicationProfile applicationProfile,
String scopeApp) {
String uri = applicationProfile.getUrl();
//add the GET params if necessary
if (uriParams != null && uriParams.compareTo("") != 0)
uri += "?"+uriParams;
Post toReturn = new Post(
UUID.randomUUID().toString(),
PostType.PUBLISH,
applicationProfile.getKey(),
new Date(),
scopeApp,
uri,
previewThumbnailUrl,
description,
PrivacyLevel.SINGLE_VRE,
applicationProfile.getName(),
"no-email",
applicationProfile.getImageUrl(),
previewTitle,
previewDescription,
"",
true);
return toReturn;
}
/**
* This method looks up the applicationProfile profile among the ones available in the infrastructure
* @param idApp as identifier of your application (as reported in the ApplicationProfile)
* @param scopeApp the scope of the application
*/
public static ApplicationProfile getProfileFromInfrastrucure(String idApp, String scopeApp) {
ScopeBean scope = new ScopeBean(scopeApp);
logger.debug("Trying to fetch applicationProfile profile from the infrastructure for " + idApp + " scope: " + scope);
// set the scope of the root infrastructure
String rootInfrastructure = scopeApp.split("/")[1];
ScopeProvider.instance.set("/"+rootInfrastructure);
try {
ApplicationProfile toReturn = new ApplicationProfile();
Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource " +
"where $profile/Profile/SecondaryType/string() eq 'ApplicationProfile' and $profile/Profile/Body/AppId/string() " +
" eq '" + idApp + "'" +
"return $profile");
DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q);
if (appProfile == null || appProfile.size() == 0)
throw new Exception("Your applicationProfile is not registered in the infrastructure");
else {
String elem = appProfile.get(0);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
XPathHelper helper = new XPathHelper(node);
List<String> currValue = null;
currValue = helper.evaluate("/Resource/Profile/Name/text()");
if (currValue != null && currValue.size() > 0) {
toReturn.setName(currValue.get(0));
}
else throw new ApplicationProfileNotFoundException("Your applicationProfile NAME was not found in the profile");
currValue = helper.evaluate("/Resource/Profile/Description/text()");
if (currValue != null && currValue.size() > 0) {
toReturn.setDescription(currValue.get(0));
}
else logger.warn("No Description exists for " + toReturn.getName());
currValue = helper.evaluate("/Resource/Profile/Body/AppId/text()");
if (currValue != null && currValue.size() > 0) {
toReturn.setKey(currValue.get(0));
}
else throw new ApplicationProfileNotFoundException("Your applicationProfile ID n was not found in the profile, consider adding <AppId> element in <Body>");
currValue = helper.evaluate("/Resource/Profile/Body/ThumbnailURL/text()");
if (currValue != null && currValue.size() > 0) {
toReturn.setImageUrl(currValue.get(0));
}
else throw new Exception("Your applicationProfile Image Url was not found in the profile, consider adding <ThumbnailURL> element in <Body>");
currValue = helper.evaluate("/Resource/Profile/Body/EndPoint/Scope/text()");
if (currValue != null && currValue.size() > 0) {
List<String> scopes = currValue;
boolean foundUrl = false;
for (int i = 0; i < scopes.size(); i++) {
if (currValue.get(i).trim().compareTo(scope.toString()) == 0) {
toReturn.setUrl(helper.evaluate("/Resource/Profile/Body/EndPoint/URL/text()").get(i));
toReturn.setScope(scope.toString());
foundUrl = true;
break;
}
}
if (! foundUrl)
throw new ApplicationProfileNotFoundException("Your applicationProfile URL was not found in the profile for Scope: " + scope.toString());
}
else throw new ApplicationProfileNotFoundException("Your applicationProfile EndPoint was not found in the profile, consider adding <EndPoint><Scope> element in <Body>");
logger.debug("Returning " + toReturn);
return toReturn;
}
} catch (Exception e) {
logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", e);
} finally{
// set the scope back
ScopeProvider.instance.set(scopeApp);
}
return null;
}
/**
* Allows user to post a feed in a certain vre.
* @param userId
* @param postText
* @param vreId
* @param previewTitle
* @param previewDescription
* @param previewHost
* @param previewUrl
* @param urlThumbnail
* @param notifyGroup
* @return The written Feed
*/
public static Post shareUserUpdate(
String userId,
String postText,
String vreId,
String previewTitle,
String previewDescription,
String previewHost,
String previewUrl,
String urlThumbnail,
boolean notifyGroup) {
SocialMessageParser messageParser = new SocialMessageParser(postText);
String escapedPostText = messageParser.getParsedMessage();
List<String> hashtags = messageParser.getHashtags();
//check if any mention exists
ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(postText));
ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
escapedPostText = Utils.convertMentionUsernamesAnchorHTML(escapedPostText, mentionedUsersToConvertInHTML, site.getSiteURL(), site.getSiteLandingPagePath());
GCubeUser user;
// retrieve group information
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
try {
user = uManager.getUserByUsername(userId);
} catch(Exception e){
logger.error("Unable to get user informations, post write fails.", e);
return null;
}
String email = user.getEmail();
String fullName = user.getFirstName() + " " + user.getLastName();
String thumbnailURL = user.getUserAvatarURL();
String linkTitle = previewTitle == null ? "" : previewTitle;
String linkDesc = previewDescription == null ? "" : previewDescription;
String host = previewHost == null ? "" : previewHost;
String url = previewUrl == null ? "" : previewUrl;
if (urlThumbnail == null)
urlThumbnail = "null";
//this means the user has shared a file without text in it.
String textToPost = "";
if (escapedPostText.trim().compareTo(NO_TEXT_FILE_SHARE) == 0) {
textToPost = org.gcube.social_networking.socialutillibrary.Utils.convertFileNameAnchorHTML(url);
} else {
textToPost = escapedPostText;
}
Post toShare = new Post(UUID.randomUUID().toString(), PostType.PUBLISH, userId, new Date(),
vreId, url, urlThumbnail, textToPost, PrivacyLevel.SINGLE_VRE, fullName, email, thumbnailURL, linkTitle, linkDesc, host);
logger.debug("Attempting to save Post with text: " + textToPost + " Level = " + PrivacyLevel.SINGLE_VRE + " Timeline = " + vreId);
boolean result = CassandraConnection.getInstance().getDatabookStore().saveUserPost(toShare);
if(vreId != null && vreId.compareTo("") != 0 && result) {
logger.trace("Attempting to write onto " + vreId);
try {
try{
logger.debug("Sleeping waiting for cassandra's update");
Thread.sleep(1000);
}catch(Exception e){
logger.error(e.toString());
}
CassandraConnection.getInstance().getDatabookStore().saveFeedToVRETimeline(toShare.getKey(), vreId);
if (hashtags != null && !hashtags.isEmpty())
CassandraConnection.getInstance().getDatabookStore().saveHashTags(toShare.getKey(), vreId, hashtags);
} catch (FeedIDNotFoundException e) {
logger.error("Error writing onto VRES Time Line" + vreId);
}
logger.trace("Success writing onto " + vreId);
}
if (!result)
return null;
SocialNetworkingUser socialUser =
new SocialNetworkingUser(userId, email, fullName, thumbnailURL);
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, vreId, socialUser, NEWS_FEED_PORTLET_CLASSNAME);
if (!mentionedUsers.isEmpty())
new Thread(new MentionNotificationsThread(toShare.getKey(), toShare.getDescription(), nm, null, mentionedUsers)).start();
//send the notification about this posts to everyone in the group if notifyGroup is true
if (vreId != null && vreId.compareTo("") != 0 && notifyGroup) {
try{
// retrieve group information
GroupManager gManager = GroupManagerWSBuilder.getInstance().getGroupManager();
// handle the scope
String name = new ScopeBean(vreId).name(); // scope such as devVR
long groupId = gManager.getGroupId(name);
String groupName = gManager.getGroup(groupId).getGroupName();
logger.debug("Company id and name " + groupId + " " + groupName);
new Thread(
new PostNotificationsThread(
UserManagerWSBuilder.getInstance().getUserManager(),
toShare.getKey(),
toShare.getDescription(),
""+groupId,
nm,
new HashSet<String>(),
new HashSet<String>(hashtags))
).start();
logger.debug("Start sending notifications for post written by " + userId);
}catch(Exception e){
logger.error("Unable to notify users", e);
}
}
return toShare;
}
/**
* Allows to comment post in a certain vre.
* @param userid the username
* @param time the date and time of the comment
* @param postId the key of the post that was commented
* @param commentText the text as it is, it will be parsed
* @param postOwnerId the username of the user who created the post that was commented
* @param context the VRE context
*
* @return the Comment instance if ok, null if somwthign went KO
* @throws FeedIDNotFoundException
*/
public static Comment commentPost(String userid, Date time, String postId, String commentText, String postOwnerId, String context) throws FeedIDNotFoundException {
SocialMessageParser messageParser = new SocialMessageParser(commentText);
String escapedCommentText = messageParser.getParsedMessage();
//check if any mention exists
ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(commentText));
ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
escapedCommentText = Utils.convertMentionUsernamesAnchorHTML(escapedCommentText, mentionedUsersToConvertInHTML, site.getSiteURL(), site.getSiteLandingPagePath());
// retrieve user information
GCubeUser user;
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
try {
user = uManager.getUserByUsername(userid);
} catch(Exception e){
logger.error("Unable to get user informations, comment write fails.", e);
return null;
}
String commentKey = UUID.randomUUID().toString(); // a unique id that goes in the DB
String email = user.getEmail();
String fullName = user.getFirstName() + " " + user.getLastName();
String thumbnailURL = user.getUserAvatarURL();
Comment theComment = new Comment(commentKey, userid, time, postId, escapedCommentText, fullName, thumbnailURL);
logger.debug("Attempting to save Comment with text: " + commentText + " postid="+postId);
boolean result = CassandraConnection.getInstance().getDatabookStore().addComment(theComment);
logger.debug("Added comment? " + theComment.toString() + " Result is " +result);
if (!result)
return null;
//if the comment was correctly delivered notify users involved
SocialNetworkingUser socialUser = new SocialNetworkingUser(userid, email, fullName, thumbnailURL);
NotificationsManager nm = new ApplicationNotificationsManager(uManager, site, context, socialUser, NEWS_FEED_PORTLET_CLASSNAME);
//if the user who commented this post is not the user who posted it notify the poster user (Post owner)
logger.debug("The post creator is " + postOwnerId);
if (! user.getUsername().equals(postOwnerId)) {
boolean resultNotifyOwnComment = nm.notifyOwnCommentReply(postOwnerId, postId, escapedCommentText, theComment.getKey());
logger.debug("Comment Notification to post creator added? " + resultNotifyOwnComment);
}
//if there are users who liked this post they get notified, asynchronously with this thread
ArrayList<Like> likes = getAllLikesByPost(postId);
Thread likesThread = new Thread(new LikeNotificationsThread(escapedCommentText, nm, likes, postOwnerId, theComment.getKey()));
likesThread.start();
//notify the other users who commented this post (excluding the ones above)
Thread commentsNotificationthread = new Thread(new CommentNotificationsThread(
CassandraConnection.getInstance().getDatabookStore(),
uManager, user.getUsername(), theComment.getFeedid(), escapedCommentText, nm, postOwnerId, theComment.getKey(), likes));
commentsNotificationthread.start();
//send the notification to the mentioned users, if any
if (mentionedUsers != null && mentionedUsers.size() > 0) {
ArrayList<GenericItemBean> toPass = new ArrayList<GenericItemBean>();
// among the mentionedUsers there could be groups of people
Map<String, ItemBean> uniqueUsersToNotify = new HashMap<>();
UserManager um = new LiferayUserManager();
for (ItemBean bean : mentionedUsersToConvertInHTML) {
if(bean.isItemGroup()){
// retrieve the users of this group
try {
List<GCubeUser> teamUsers = um.listUsersByTeam(Long.parseLong(bean.getId()));
for (GCubeUser userTeam : teamUsers) {
if(!uniqueUsersToNotify.containsKey(userTeam.getUsername()))
uniqueUsersToNotify.put(userTeam.getUsername(), new ItemBean(userTeam.getUserId()+"",
userTeam.getUsername(), userTeam.getFullname(), userTeam.getUserAvatarURL()));
}
} catch (NumberFormatException
| UserManagementSystemException
| TeamRetrievalFault | UserRetrievalFault e) {
logger.error("Unable to retrieve team information", e);
}
}else{
// it is a user, just add to the hashmap
if(!uniqueUsersToNotify.containsKey(bean.getName()))
uniqueUsersToNotify.put(bean.getName(), bean);
}
}
// iterate over the hashmap
Iterator<Entry<String, ItemBean>> userMapIterator = uniqueUsersToNotify.entrySet().iterator();
while (userMapIterator.hasNext()) {
Map.Entry<String, ItemBean> userEntry = (Map.Entry<String, ItemBean>) userMapIterator
.next();
ItemBean userBean = userEntry.getValue();
toPass.add(new GenericItemBean(userBean.getId(), userBean.getName(), userBean.getAlternativeName(), userBean.getThumbnailURL()));
}
Thread thread = new Thread(new MentionNotificationsThread(theComment.getFeedid(), escapedCommentText, nm, null, toPass));
thread.start();
}
return theComment;
}
private static ArrayList<Like> getAllLikesByPost(String postid) {
ArrayList<Like> toReturn = (ArrayList<Like>) CassandraConnection.getInstance().getDatabookStore().getAllLikesByPost(postid);
logger.debug("Asking likes for " + postid);
for (Like like : toReturn) {
// retrieve user information
GCubeUser user;
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
try {
user = uManager.getUserByUsername(like.getUserid());
} catch(Exception e){
logger.error("Unable to get user informations, comment write fails.", e);
return null;
}
String thumbnailURL = user.getUserAvatarURL();
like.setThumbnailURL(thumbnailURL == null ? "" : thumbnailURL);
}
return toReturn;
}
public static boolean like(String username, String postid, String context) {
boolean likeCommitResult = false;
// retrieve user information
GCubeUser user;
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
try {
user = uManager.getUserByUsername(username);
} catch(Exception e){
logger.error("Unable to get user informations, like write fails.", e);
return false;
}
String email = user.getEmail();
String fullName = user.getFirstName() + " " + user.getLastName();
String thumbnailURL = user.getUserAvatarURL();
SocialNetworkingUser socialUser = new SocialNetworkingUser(user.getUsername(), email, fullName, thumbnailURL);
Like toLike = new Like(UUID.randomUUID().toString(), user.getUsername(),
new Date(), postid, user.getFullname(), user.getUserAvatarURL());
Post thePost = null;
try {
logger.debug("Attempting to read post with id: " +postid);
thePost = CassandraConnection.getInstance().getDatabookStore().readPost(postid);
likeCommitResult = CassandraConnection.getInstance().getDatabookStore().like(toLike);
} catch (Exception e) {
logger.error("Post not found for this like ot could not like the post " + e.getMessage());
return false;
}
//if the like was correctly delivered notify the user who made the post
boolean resultNotifyLike =false;
if (likeCommitResult) {
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, context, socialUser, NEWS_FEED_PORTLET_CLASSNAME);
String postText = thePost.getDescription();
String postOwnerId = thePost.getEntityId();
SocialMessageParser messageParser = new SocialMessageParser(postText);
String escapedPostText = messageParser.getParsedMessage();
//if the user who liked this post is not the user who posted it notify the poster user (Post owner)
logger.debug("The post creator is " + postOwnerId);
if (! user.getUsername().equals(postOwnerId)) {
resultNotifyLike = nm.notifyLikedPost(postOwnerId, postid, escapedPostText);
logger.debug("Like Notification to post creator added? " + resultNotifyLike);
}
}
return likeCommitResult && resultNotifyLike;
}
public static boolean unlike(String username, String likeid, String postid) {
boolean unlikeCommitResult = false;
// retrieve user information
GCubeUser user;
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
try {
user = uManager.getUserByUsername(username);
} catch(Exception e){
logger.error("Unable to get user informations, unlike write fails.", e);
return false;
}
String fullName = user.getFirstName() + " " + user.getLastName();
String thumbnailURL = user.getUserAvatarURL();
try {
unlikeCommitResult = CassandraConnection.getInstance().getDatabookStore().unlike(username, likeid, postid);
} catch (Exception e) {
logger.error("Post not Found for this like ot could not unlike the post " + e.getMessage());
return false;
}
return unlikeCommitResult;
}
}

View File

@ -1,82 +0,0 @@
package org.gcube.social_networking.ws.utils;
import org.gcube.common.authorization.library.ClientType;
import org.gcube.common.authorization.library.utils.Caller;
import org.slf4j.LoggerFactory;
/**
* Tokens utils methods
*/
public class TokensUtils {
// a user context token (not qualified) has as qualifier the word "TOKEN"
private static final String DEFAULT_QUALIFIER_USER_TOKEN = "TOKEN";
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TokensUtils.class);
/**
* Check if it is a service token
* @return a boolean value
*/
public static boolean isServiceToken(Caller caller){
return caller.getClient().getType().equals(ClientType.SERVICE);
}
/**
* Check if it is an application token
* @return a boolean value
*/
public static boolean isApplicationToken(Caller caller){
String username = caller.getClient().getId();
if (username.startsWith("service-account-")) {
return true;
}
return caller.getClient().getType().equals(ClientType.EXTERNALSERVICE);
}
/**
* Check if it is a container token
* @return a boolean value
*/
public static boolean isContainerToken(Caller caller){
return caller.getClient().getType().equals(ClientType.CONTAINER);
}
/**
* Check if it is a user token
* @return a boolean value
*/
public static boolean isUserToken(Caller caller) {
logger.debug("\n ****** \n isUserToken: caller.getClient().getType().equals(ClientType.USER) => " + caller.getClient().getType().equals(ClientType.USER));
String username = caller.getClient().getId();
if (username.startsWith("service-account-")) {
return false;
}
return caller.getClient().getType().equals(ClientType.USER);
}
/**
* Check if it is a user token (not qualified)
* @return a boolean value
*/
public static boolean isUserTokenDefault(Caller caller){
return isUserToken(caller);
}
/**
* Check if it is a user token (qualified)
* @return a boolean value
*/
public static boolean isUserTokenQualified(Caller caller){
return caller.getClient().getType().equals(ClientType.USER) && !caller.getTokenQualifier().equals(DEFAULT_QUALIFIER_USER_TOKEN);
}
}

View File

@ -1,194 +0,0 @@
package org.gcube.social_networking.ws.utils;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserProfileExtendedWithVerifiedEmail {
@JsonProperty("id")
private String username;
@JsonProperty("roles")
private List<String> roles;
@JsonProperty("picture")
private String avatar;
@JsonProperty("name")
private String fullname;
@JsonProperty("middle_name")
private String middleName;
@JsonProperty("male")
private boolean male;
@JsonProperty("location_industry")
private String locationIndustry;
@JsonProperty("given_name")
private String firstName;
@JsonProperty("email")
private String email;
@JsonProperty("job_title")
private String jobTitle;
@JsonProperty("family_name")
private String lastName;
@JsonProperty("verified_email")
private boolean verifiedEmail = true;
public UserProfileExtendedWithVerifiedEmail() {
super();
}
/**
* @param username
* @param roles
* @param avatar
* @param fullname
*/
public UserProfileExtendedWithVerifiedEmail(String username, List<String> roles, String avatar, String fullname) {
this.username = username;
this.roles = roles;
this.avatar = avatar;
this.fullname = fullname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public boolean isMale() {
return male;
}
public void setMale(boolean male) {
this.male = male;
}
public String getLocationIndustry() {
return locationIndustry;
}
public void setLocationIndustry(String locationIndustry) {
this.locationIndustry = locationIndustry;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isVerifiedEmail() {
return verifiedEmail;
}
public void setVerifiedEmail(boolean verifiedEmail) {
this.verifiedEmail = verifiedEmail;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("UserProfileExtendedWithVerifiedEmail [username=");
builder.append(username);
builder.append(", roles=");
builder.append(roles);
builder.append(", avatar=");
builder.append(avatar);
builder.append(", fullname=");
builder.append(fullname);
builder.append(", middleName=");
builder.append(middleName);
builder.append(", male=");
builder.append(male);
builder.append(", locationIndustry=");
builder.append(locationIndustry);
builder.append(", firstName=");
builder.append(firstName);
builder.append(", email=");
builder.append(email);
builder.append(", jobTitle=");
builder.append(jobTitle);
builder.append(", lastName=");
builder.append(lastName);
builder.append(", verifiedEmail=");
builder.append(verifiedEmail);
builder.append("]");
return builder.toString();
}
}

View File

@ -1,78 +0,0 @@
/**
*
*/
package org.gcube.portal.test;
import static org.gcube.resources.discovery.icclient.ICFactory.client;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.List;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GcoreEndpointReader {
private static final String resource = "jersey-servlet";
private static final String serviceName = "SocialNetworking";
private static final String serviceClass = "Portal";
private static Logger logger = LoggerFactory.getLogger(GcoreEndpointReader.class);
private String resourceEntyName;
/**
* Instantiates a new gcore endpoint reader.
*
* @param scope the scope
* @throws Exception the exception
*/
public GcoreEndpointReader(String scope) throws Exception {
String currentScope = ScopeProvider.instance.get();
try{
logger.info("set scope "+scope);
ScopeProvider.instance.set(scope);
SimpleQuery query = queryFor(GCoreEndpoint.class);
query.addCondition(String.format("$resource/Profile/ServiceClass/text() eq '%s'",serviceClass));
query.addCondition("$resource/Profile/DeploymentData/Status/text() eq 'ready'");
query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'",serviceName));
query.setResult("$resource/Profile/AccessPoint/RunningInstanceInterfaces//Endpoint[@EntryName/string() eq \""+resource+"\"]/text()");
logger.debug("submitting quey "+query.toString());
DiscoveryClient<String> client = client();
List<String> endpoints = client.submit(query);
if (endpoints == null || endpoints.isEmpty()) throw new Exception("Cannot retrieve the GCoreEndpoint serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+scope);
this.resourceEntyName = endpoints.get(0);
if(resourceEntyName==null)
throw new Exception("Endpoint:"+resource+", is null for serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+scope);
logger.info("found entyname "+resourceEntyName+" for ckanResource: "+resource);
}catch(Exception e){
String error = "An error occurred during GCoreEndpoint discovery, serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+scope +".";
logger.error(error, e);
throw new Exception(error);
}finally{
if(currentScope != null)
ScopeProvider.instance.set(currentScope);
}
}
/**
* @return the ResourceEntyName
*/
public String getResourceEntyName() {
return resourceEntyName;
}
}

View File

@ -1,103 +0,0 @@
package org.gcube.portal.test;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.Iterator;
import java.util.List;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Retrieves the base url of the social-networking service in the scope provided
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class ServiceEndPointReaderSocial {
private String basePath = null;
private static Logger logger = LoggerFactory.getLogger(ServiceEndPointReaderSocial.class);
private final static String RUNTIME_RESOURCE_NAME = "SocialNetworking";
private final static String CATEGORY = "Portal";
public ServiceEndPointReaderSocial(String context){
if(context == null || context.isEmpty())
throw new IllegalArgumentException("A valid context is needed to discover the service");
String oldContext = ScopeProvider.instance.get();
ScopeProvider.instance.set(context);
try{
List<ServiceEndpoint> resources = getConfigurationFromIS();
if (resources.size() == 0){
logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope.");
throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope.");
}
else {
for (ServiceEndpoint res : resources) {
Iterator<AccessPoint> accessPointIterator = res.profile().accessPoints().iterator();
while (accessPointIterator.hasNext()) {
ServiceEndpoint.AccessPoint accessPoint = (ServiceEndpoint.AccessPoint) accessPointIterator
.next();
// get base path
basePath = accessPoint.address();
// break
break;
}
}
}
}catch(Exception e){
logger.error("Unable to retrieve such service endpoint information!", e);
}finally{
if(oldContext != null && !oldContext.equals(context))
ScopeProvider.instance.set(oldContext);
}
logger.info("Found base path " + basePath + " for the service");
}
/**
* Retrieve endpoints information from IS for DB
* @return list of endpoints for ckan database
* @throws Exception
*/
private List<ServiceEndpoint> getConfigurationFromIS() throws Exception{
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '"+ RUNTIME_RESOURCE_NAME +"'");
query.addCondition("$resource/Profile/Category/text() eq '"+ CATEGORY +"'");
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> toReturn = client.submit(query);
return toReturn;
}
/**
* Get the base path of the social networking service
* @return
*/
public String getBasePath() {
return basePath;
}
}