code format and organize imports

This commit is contained in:
Alfredo Oliviero 2024-09-02 16:46:48 +02:00
parent 97eae29a93
commit 858eb45b27
48 changed files with 1781 additions and 1739 deletions

View File

@ -5,6 +5,7 @@ import net.sf.ehcache.Ehcache;
/** /**
* Handle caches via Ehcache * Handle caches via Ehcache
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public class CachesManager { public class CachesManager {
@ -12,16 +13,17 @@ public class CachesManager {
private static CacheManager cacheManager; private static CacheManager cacheManager;
public static final CachesManager singleton = new CachesManager(); public static final CachesManager singleton = new CachesManager();
// the following caches are declared within the ehcache.xml (no default is available) // the following caches are declared within the ehcache.xml (no default is
// available)
public static final String SOCIAL_NETWORKING_SITES_CACHE = "social_networking_site_cache"; public static final String SOCIAL_NETWORKING_SITES_CACHE = "social_networking_site_cache";
public static final String USERS_CACHE = "users_cache"; public static final String USERS_CACHE = "users_cache";
public static final String GROUPS_CACHE = "groups_cache"; public static final String GROUPS_CACHE = "groups_cache";
private CachesManager(){ private CachesManager() {
cacheManager = CacheManager.newInstance(); cacheManager = CacheManager.newInstance();
} }
public static Ehcache getCache(String name){ public static Ehcache getCache(String name) {
return cacheManager.getEhcache(name); return cacheManager.getEhcache(name);
} }

View File

@ -12,9 +12,10 @@ public class GroupsCache {
/** /**
* Private constructor: build the cache * Private constructor: build the cache
*
* @return * @return
*/ */
private GroupsCache(){ private GroupsCache() {
logger.debug("Building cache"); logger.debug("Building cache");
CachesManager.getCache(CachesManager.GROUPS_CACHE); CachesManager.getCache(CachesManager.GROUPS_CACHE);
@ -30,12 +31,13 @@ public class GroupsCache {
/** /**
* Retrieve an entry * Retrieve an entry
*
* @param groupId * @param groupId
* @return user associated to the user * @return user associated to the user
*/ */
public GCubeGroup getGroup(long groupId){ public GCubeGroup getGroup(long groupId) {
Ehcache groupsCache = CachesManager.getCache(CachesManager.GROUPS_CACHE); Ehcache groupsCache = CachesManager.getCache(CachesManager.GROUPS_CACHE);
if(groupsCache.get(groupId) != null) if (groupsCache.get(groupId) != null)
return (GCubeGroup) groupsCache.get(groupId).getObjectValue(); return (GCubeGroup) groupsCache.get(groupId).getObjectValue();
else else
return null; return null;
@ -43,10 +45,11 @@ public class GroupsCache {
/** /**
* Save an entry into the cache * Save an entry into the cache
*
* @param id * @param id
* @param group * @param group
*/ */
public void pushEntry(long id, GCubeGroup group){ public void pushEntry(long id, GCubeGroup group) {
Ehcache groupsCache = CachesManager.getCache(CachesManager.GROUPS_CACHE); Ehcache groupsCache = CachesManager.getCache(CachesManager.GROUPS_CACHE);
groupsCache.put(new Element(id, group)); groupsCache.put(new Element(id, group));
} }

View File

@ -25,9 +25,12 @@ import org.gcube.vomanagement.usermanagement.model.VirtualGroup;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* 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
* the site information needed to build up the SocialNetworkingSite object (which, for instance, contains the * (starting from the scope)
* the site information needed to build up the SocialNetworkingSite object
* (which, for instance, contains the
* portal email). * portal email).
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public class SocialNetworkingSiteFinder { public class SocialNetworkingSiteFinder {
@ -51,10 +54,10 @@ public class SocialNetworkingSiteFinder {
/** /**
* Build the singleton instance * Build the singleton instance
*/ */
private SocialNetworkingSiteFinder(){ private SocialNetworkingSiteFinder() {
// read fallback properties // read fallback properties
try{ try {
logger.debug("Trying to read config.properties"); logger.debug("Trying to read config.properties");
ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("config.properties"); InputStream input = classLoader.getResourceAsStream("config.properties");
@ -63,7 +66,7 @@ public class SocialNetworkingSiteFinder {
PROD_FALLBACK_GATEWAY = properties.getProperty("PROD_FALLBACK_GATEWAY"); PROD_FALLBACK_GATEWAY = properties.getProperty("PROD_FALLBACK_GATEWAY");
DEV_FALLBACK_GATEWAY = properties.getProperty("DEV_FALLBACK_GATEWAY"); DEV_FALLBACK_GATEWAY = properties.getProperty("DEV_FALLBACK_GATEWAY");
PREPROD_FALLBACK_GATEWAY = properties.getProperty("PREPROD_FALLBACK_GATEWAY"); PREPROD_FALLBACK_GATEWAY = properties.getProperty("PREPROD_FALLBACK_GATEWAY");
}catch(Exception e){ } catch (Exception e) {
logger.warn("Failed to read config.properties...", e); logger.warn("Failed to read config.properties...", e);
} }
@ -72,7 +75,7 @@ public class SocialNetworkingSiteFinder {
/** /**
* Retrieve the singleton instance * Retrieve the singleton instance
*/ */
public static SocialNetworkingSiteFinder getInstance(){ public static SocialNetworkingSiteFinder getInstance() {
return singleton; return singleton;
@ -80,21 +83,22 @@ public class SocialNetworkingSiteFinder {
/** /**
* Retrieve the SocialNetworkingSite given the scope * Retrieve the SocialNetworkingSite given the scope
*
* @param scope * @param scope
* @return * @return
*/ */
public static SocialNetworkingSite getSocialNetworkingSiteFromScope(String scope){ public static SocialNetworkingSite getSocialNetworkingSiteFromScope(String scope) {
Ehcache socialSitesCache = CachesManager.getCache(CachesManager.SOCIAL_NETWORKING_SITES_CACHE);
if(scope == null || scope.isEmpty()) Ehcache socialSitesCache = CachesManager.getCache(CachesManager.SOCIAL_NETWORKING_SITES_CACHE);
if (scope == null || scope.isEmpty())
throw new IllegalArgumentException("Scope cannot be null/empty"); throw new IllegalArgumentException("Scope cannot be null/empty");
if(socialSitesCache != null && socialSitesCache.get(scope) != null) if (socialSitesCache != null && socialSitesCache.get(scope) != null)
return (SocialNetworkingSite) socialSitesCache.get(scope).getObjectValue(); return (SocialNetworkingSite) socialSitesCache.get(scope).getObjectValue();
else{ else {
SocialNetworkingSite site = discoverSite(scope); SocialNetworkingSite site = discoverSite(scope);
if(socialSitesCache != null && site != null) if (socialSitesCache != null && site != null)
socialSitesCache.put(new Element(scope, site)); socialSitesCache.put(new Element(scope, site));
return site; return site;
} }
@ -103,12 +107,13 @@ public class SocialNetworkingSiteFinder {
/** /**
* Discover the site for this scope * Discover the site for this scope
*
* @param scope * @param scope
* @return * @return
*/ */
private static SocialNetworkingSite discoverSite(String scope) { private static SocialNetworkingSite discoverSite(String scope) {
try{ try {
logger.info("Requested site for scope " + scope); logger.info("Requested site for scope " + scope);
GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager(); GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
@ -116,30 +121,31 @@ public class SocialNetworkingSiteFinder {
GCubeGroup matchingGateway = null; GCubeGroup matchingGateway = null;
if(groupManager.isVRE(groupId)){ if (groupManager.isVRE(groupId)) {
// get the Virtual groups for the groupid related to the scope // get the Virtual groups for the groupid related to the scope
List<VirtualGroup> virtualGroupsOfGroup = groupManager.getVirtualGroups(groupId); List<VirtualGroup> virtualGroupsOfGroup = groupManager.getVirtualGroups(groupId);
if(virtualGroupsOfGroup == null || virtualGroupsOfGroup.isEmpty()) if (virtualGroupsOfGroup == null || virtualGroupsOfGroup.isEmpty())
throw new Exception("It seems that the VRE is not linked to any VirtualGroups"); throw new Exception("It seems that the VRE is not linked to any VirtualGroups");
// get the gateways // get the gateways
List<GCubeGroup> gateways = groupManager.getGateways(); List<GCubeGroup> gateways = groupManager.getGateways();
if(gateways == null || gateways.isEmpty()) if (gateways == null || gateways.isEmpty())
throw new Exception("It seems there is no gateway here!"); throw new Exception("It seems there is no gateway here!");
logger.info("Retrieved Gateways are " + gateways); logger.info("Retrieved Gateways are " + gateways);
// now, retrieve the virtual groups for each gateway and stop when a VG matches with one of the group // now, retrieve the virtual groups for each gateway and stop when a VG matches
// with one of the group
// then, it is the gateway of interest // then, it is the gateway of interest
ext_loop: for (GCubeGroup gateway : gateways) { ext_loop: for (GCubeGroup gateway : gateways) {
List<VirtualGroup> gatewayVirtualGroups = groupManager.getVirtualGroups(gateway.getGroupId()); List<VirtualGroup> gatewayVirtualGroups = groupManager.getVirtualGroups(gateway.getGroupId());
if(gatewayVirtualGroups != null && !gatewayVirtualGroups.isEmpty()){ if (gatewayVirtualGroups != null && !gatewayVirtualGroups.isEmpty()) {
for (VirtualGroup gatewayVirtualGroup : gatewayVirtualGroups) { for (VirtualGroup gatewayVirtualGroup : gatewayVirtualGroups) {
if(virtualGroupsOfGroup.contains(gatewayVirtualGroup)){ if (virtualGroupsOfGroup.contains(gatewayVirtualGroup)) {
logger.debug("Matching gateway for scope " + scope + " is " + gateway); logger.debug("Matching gateway for scope " + scope + " is " + gateway);
matchingGateway = gateway; matchingGateway = gateway;
break ext_loop; break ext_loop;
@ -148,36 +154,37 @@ public class SocialNetworkingSiteFinder {
} }
} }
}else{ } else {
List<GCubeGroup> gateways = groupManager.getGateways(); List<GCubeGroup> gateways = groupManager.getGateways();
// vo and root vo cases are treated separately: in production environment services.d4science.org is used, instead // vo and root vo cases are treated separately: in production environment
// services.d4science.org is used, instead
// in dev next.d4science.org is used TODO better way... // in dev next.d4science.org is used TODO better way...
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
String rootContext = "/"+ctx.container().configuration().infrastructure(); String rootContext = "/" + ctx.container().configuration().infrastructure();
String matchingGatewayName = null; String matchingGatewayName = null;
if(isDevOrPreprod(rootContext)){ if (isDevOrPreprod(rootContext)) {
matchingGatewayName = DEV_FALLBACK_GATEWAY; matchingGatewayName = DEV_FALLBACK_GATEWAY;
}else{ } else {
matchingGatewayName = PROD_FALLBACK_GATEWAY; matchingGatewayName = PROD_FALLBACK_GATEWAY;
} }
// find the matching one among the gateways // find the matching one among the gateways
for (GCubeGroup gateway : gateways) { for (GCubeGroup gateway : gateways) {
if(gateway.getGroupName().equals(matchingGatewayName)){ if (gateway.getGroupName().equals(matchingGatewayName)) {
matchingGateway = gateway; matchingGateway = gateway;
break; break;
} }
} }
if(matchingGateway == null && isDevOrPreprod(rootContext)){ if (matchingGateway == null && isDevOrPreprod(rootContext)) {
logger.warn("Checking if it is the preprod environment"); logger.warn("Checking if it is the preprod environment");
matchingGatewayName = PREPROD_FALLBACK_GATEWAY; matchingGatewayName = PREPROD_FALLBACK_GATEWAY;
// find the matching one among the gateways // find the matching one among the gateways
for (GCubeGroup gateway : gateways) { for (GCubeGroup gateway : gateways) {
if(gateway.getGroupName().equals(matchingGatewayName)){ if (gateway.getGroupName().equals(matchingGatewayName)) {
matchingGateway = gateway; matchingGateway = gateway;
break; break;
} }
@ -187,21 +194,26 @@ public class SocialNetworkingSiteFinder {
} }
if(matchingGateway == null){ if (matchingGateway == null) {
logger.warn("There is no gateway for such scope. Returning null"); logger.warn("There is no gateway for such scope. Returning null");
return null; return null;
}else{ } else {
String siteName = matchingGateway.getGroupName(); String siteName = matchingGateway.getGroupName();
String emailSender = (String)groupManager.readCustomAttr(matchingGateway.getGroupId(), EMAIL_SENDER_SITE_CUSTOM_FIELD); String emailSender = (String) groupManager.readCustomAttr(matchingGateway.getGroupId(),
emailSender = emailSender.replace("\"", ""); //this is because otherwise it would contains double quotes and postfix would use it as first part before @ e.g. senderEmail="aginfra@d4science.org"@d4science.org EMAIL_SENDER_SITE_CUSTOM_FIELD);
emailSender = emailSender.replace("\"", ""); // this is because otherwise it would contains double
// quotes and postfix would use it as first part before
// @ e.g.
// senderEmail="aginfra@d4science.org"@d4science.org
String siteLandingPagePath = GCubePortalConstants.PREFIX_GROUP_URL + matchingGateway.getFriendlyURL(); String siteLandingPagePath = GCubePortalConstants.PREFIX_GROUP_URL + matchingGateway.getFriendlyURL();
String siteUrl = discoverHostOfServiceEndpoint(siteName); String siteUrl = discoverHostOfServiceEndpoint(siteName);
SocialNetworkingSite site = new SocialNetworkingSite(siteName, emailSender, siteUrl, siteLandingPagePath); SocialNetworkingSite site = new SocialNetworkingSite(siteName, emailSender, siteUrl,
siteLandingPagePath);
logger.info("Site is " + site); logger.info("Site is " + site);
return site; return site;
} }
}catch(Exception e){ } catch (Exception e) {
logger.error("Failed to determine the SocialNetworkingSite for scope " + scope, e); logger.error("Failed to determine the SocialNetworkingSite for scope " + scope, e);
} }
@ -214,20 +226,21 @@ public class SocialNetworkingSiteFinder {
/** /**
* Retrieve endpoint host from IS for this gateway * Retrieve endpoint host from IS for this gateway
*
* @return the host for the gateway * @return the host for the gateway
* @throws Exception * @throws Exception
*/ */
private static String discoverHostOfServiceEndpoint(String gatewayName){ private static String discoverHostOfServiceEndpoint(String gatewayName) {
String currentScope = ScopeProvider.instance.get(); String currentScope = ScopeProvider.instance.get();
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
ScopeProvider.instance.set("/"+ctx.container().configuration().infrastructure()); ScopeProvider.instance.set("/" + ctx.container().configuration().infrastructure());
String host = null; String host = null;
try{ try {
SimpleQuery query = queryFor(ServiceEndpoint.class); SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '"+ gatewayName +"'"); query.addCondition("$resource/Profile/Name/text() eq '" + gatewayName + "'");
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);
for (ServiceEndpoint serviceEndpoint : toReturn) { for (ServiceEndpoint serviceEndpoint : toReturn) {
@ -236,9 +249,9 @@ public class SocialNetworkingSiteFinder {
break; break;
} }
}catch(Exception e){ } catch (Exception e) {
logger.error("Error while retrieving host for the gateway " + gatewayName); logger.error("Error while retrieving host for the gateway " + gatewayName);
}finally{ } finally {
ScopeProvider.instance.set(currentScope); ScopeProvider.instance.set(currentScope);
} }

View File

@ -2,9 +2,6 @@ package org.gcube.portal.social.networking.caches;
import java.util.List; import java.util.List;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.gcube.portal.social.networking.liferay.ws.GroupManagerWSBuilder; import org.gcube.portal.social.networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder; import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.smartgears.ContextProvider; import org.gcube.smartgears.ContextProvider;
@ -14,35 +11,42 @@ import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeUser; import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
/** /**
* This cache will store GCubeUser of the users of the infrastructure as couples {user-id, user screename} * This cache will store GCubeUser of the users of the infrastructure as couples
* {user-id, user screename}
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public class UsersCache{ public class UsersCache {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(UsersCache.class); private static final org.slf4j.Logger logger = LoggerFactory.getLogger(UsersCache.class);
private static UsersCache singleton = new UsersCache(); private static UsersCache singleton = new UsersCache();
/** /**
* Private constructor: build the cache * Private constructor: build the cache
*
* @return * @return
*/ */
private UsersCache(){ private UsersCache() {
// create a thread to build the cache // create a thread to build the cache
new Thread(){ new Thread() {
public void run() { public void run() {
try{ try {
logger.debug("Fetching users and putting them into cache"); logger.debug("Fetching users and putting them into cache");
Ehcache usersCache = CachesManager.getCache(CachesManager.USERS_CACHE); Ehcache usersCache = CachesManager.getCache(CachesManager.USERS_CACHE);
GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager(); GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
List<GCubeUser> users = userManager.listUsersByGroup(groupManager.getGroupIdFromInfrastructureScope("/"+ctx.container().configuration().infrastructure())); List<GCubeUser> users = userManager.listUsersByGroup(groupManager
.getGroupIdFromInfrastructureScope("/" + ctx.container().configuration().infrastructure()));
for (GCubeUser gCubeUser : users) { for (GCubeUser gCubeUser : users) {
usersCache.put(new Element(gCubeUser.getUserId(), gCubeUser)); usersCache.put(new Element(gCubeUser.getUserId(), gCubeUser));
} }
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve user's usernames. Other users will be discovered later on", e); logger.error("Unable to retrieve user's usernames. Other users will be discovered later on", e);
} }
} }
@ -59,12 +63,13 @@ public class UsersCache{
/** /**
* Retrieve an entry * Retrieve an entry
*
* @param userId * @param userId
* @return user associated to the user * @return user associated to the user
*/ */
public GCubeUser getUser(long userId){ public GCubeUser getUser(long userId) {
Ehcache usersCache = CachesManager.getCache(CachesManager.USERS_CACHE); Ehcache usersCache = CachesManager.getCache(CachesManager.USERS_CACHE);
if(usersCache.get(userId) != null) if (usersCache.get(userId) != null)
return (GCubeUser) usersCache.get(userId).getObjectValue(); return (GCubeUser) usersCache.get(userId).getObjectValue();
else else
return null; return null;
@ -72,10 +77,11 @@ public class UsersCache{
/** /**
* Save an entry into the cache * Save an entry into the cache
*
* @param id * @param id
* @param user * @param user
*/ */
public void pushEntry(long id, GCubeUser user){ public void pushEntry(long id, GCubeUser user) {
Ehcache usersCache = CachesManager.getCache(CachesManager.USERS_CACHE); Ehcache usersCache = CachesManager.getCache(CachesManager.USERS_CACHE);
usersCache.put(new Element(id, user)); usersCache.put(new Element(id, user));
} }

View File

@ -7,26 +7,27 @@ import org.slf4j.LoggerFactory;
/** /**
* Class that builds a (singleton) GroupManagerWS object. * Class that builds a (singleton) GroupManagerWS object.
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public class GroupManagerWSBuilder { public class GroupManagerWSBuilder {
private static final Logger logger = LoggerFactory.getLogger(GroupManagerWSBuilder.class); private static final Logger logger = LoggerFactory.getLogger(GroupManagerWSBuilder.class);
private static GroupManagerWSBuilder singleton = new GroupManagerWSBuilder(); private static GroupManagerWSBuilder singleton = new GroupManagerWSBuilder();
private static GroupManager groupManagerWs; private static GroupManager groupManagerWs;
private GroupManagerWSBuilder(){ private GroupManagerWSBuilder() {
logger.debug("Building GroupManager please wait"); logger.debug("Building GroupManager please wait");
try{ try {
groupManagerWs = new LiferayWSGroupManager( groupManagerWs = new LiferayWSGroupManager(
LiferayJSONWsCredentials.getSingleton().getUser(), LiferayJSONWsCredentials.getSingleton().getUser(),
LiferayJSONWsCredentials.getSingleton().getPassword(), LiferayJSONWsCredentials.getSingleton().getPassword(),
LiferayJSONWsCredentials.getSingleton().getHost(), LiferayJSONWsCredentials.getSingleton().getHost(),
LiferayJSONWsCredentials.getSingleton().getSchema(), LiferayJSONWsCredentials.getSingleton().getSchema(),
LiferayJSONWsCredentials.getSingleton().getPort()); LiferayJSONWsCredentials.getSingleton().getPort());
}catch(Exception e){ } catch (Exception e) {
logger.error("Failed to build the GroupManager. ", e); logger.error("Failed to build the GroupManager. ", e);
return; return;
} }
@ -34,16 +35,17 @@ public class GroupManagerWSBuilder {
logger.debug("GroupManager instance built"); logger.debug("GroupManager instance built");
} }
/** /**
* Get the user manager instance * Get the user manager instance
*
* @return * @return
*/ */
public GroupManager getGroupManager(){ public GroupManager getGroupManager() {
return groupManagerWs; return groupManagerWs;
} }
public static GroupManagerWSBuilder getInstance(){ public static GroupManagerWSBuilder getInstance() {
return singleton; return singleton;
} }

View File

@ -5,12 +5,10 @@ import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map;
import org.gcube.common.encryption.encrypter.StringEncrypter; 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.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.Property;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
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;
@ -19,8 +17,6 @@ import org.gcube.smartgears.context.application.ApplicationContext;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public class KeycloakAPICredentials { public class KeycloakAPICredentials {
private static final Logger logger = LoggerFactory.getLogger(KeycloakAPICredentials.class); private static final Logger logger = LoggerFactory.getLogger(KeycloakAPICredentials.class);
@ -34,7 +30,6 @@ public class KeycloakAPICredentials {
private String clientid; private String clientid;
private String password; private String password;
// Service endpoint properties // Service endpoint properties
private final static String RUNTIME_RESOURCE_NAME = "IAM"; private final static String RUNTIME_RESOURCE_NAME = "IAM";
private final static String CATEGORY = "Service"; private final static String CATEGORY = "Service";
@ -58,37 +53,39 @@ public class KeycloakAPICredentials {
String oldContext = ScopeProvider.instance.get(); String oldContext = ScopeProvider.instance.get();
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
ScopeProvider.instance.set("/"+ctx.container().configuration().infrastructure()); ScopeProvider.instance.set("/" + ctx.container().configuration().infrastructure());
logger.debug("Discovering liferay user's credentials in context " + ctx.container().configuration().infrastructure()); logger.debug("Discovering liferay user's credentials in context "
+ ctx.container().configuration().infrastructure());
try{ try {
List<ServiceEndpoint> resources = getConfigurationFromIS(); List<ServiceEndpoint> resources = getConfigurationFromIS();
if (resources.size() == 0){ if (resources.size() == 0) {
logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope."); logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME + " and Category "
throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope."); + CATEGORY + " in this scope.");
} throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME
else { + " and Category " + CATEGORY + " in this scope.");
} else {
for (ServiceEndpoint res : resources) { for (ServiceEndpoint res : resources) {
Iterator<AccessPoint> accessPointIterator = res.profile().accessPoints().iterator(); Iterator<AccessPoint> accessPointIterator = res.profile().accessPoints().iterator();
while (accessPointIterator.hasNext()) { while (accessPointIterator.hasNext()) {
ServiceEndpoint.AccessPoint accessPoint = (ServiceEndpoint.AccessPoint) accessPointIterator ServiceEndpoint.AccessPoint accessPoint = (ServiceEndpoint.AccessPoint) accessPointIterator
.next(); .next();
if(accessPoint.name().equals("d4science")){ if (accessPoint.name().equals("d4science")) {
keycloakURL = accessPoint.address(); keycloakURL = accessPoint.address();
realm = accessPoint.name(); realm = accessPoint.name();
clientid = accessPoint.username(); clientid = accessPoint.username();
password = StringEncrypter.getEncrypter().decrypt(accessPoint.password()); password = StringEncrypter.getEncrypter().decrypt(accessPoint.password());
logger.info("Found accesspoint URL = " + keycloakURL); logger.info("Found accesspoint URL = " + keycloakURL);
} }
} }
} }
} }
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such service endpoint information!", e); logger.error("Unable to retrieve such service endpoint information!", e);
return; return;
}finally{ } finally {
if(oldContext != null) if (oldContext != null)
ScopeProvider.instance.set(oldContext); ScopeProvider.instance.set(oldContext);
} }
@ -97,39 +94,40 @@ public class KeycloakAPICredentials {
/** /**
* 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 KeycloakAPICredentials getSingleton() { public static KeycloakAPICredentials getSingleton() {
if (singleton == null) if (singleton == null)
singleton = new KeycloakAPICredentials(); singleton = new KeycloakAPICredentials();
return singleton; return singleton;
} }
public String getServerURL() { public String getServerURL() {
return keycloakURL; return keycloakURL;
} }
public String getClientid() { public String getClientid() {
return clientid; return clientid;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public String getRealm() { public String getRealm() {
return realm; return realm;
} }
@ -138,6 +136,5 @@ public class KeycloakAPICredentials {
return "KeycloakAPICredentials [keycloakURL=" + keycloakURL + ", realm=" + realm + ", clientid=" + clientid return "KeycloakAPICredentials [keycloakURL=" + keycloakURL + ", realm=" + realm + ", clientid=" + clientid
+ ", password=**************]"; + ", password=**************]";
} }
} }

View File

@ -19,12 +19,11 @@ import org.gcube.smartgears.context.application.ApplicationContext;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* 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,8 +40,9 @@ 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";
@ -62,10 +62,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);
} }
} }
@ -79,29 +79,32 @@ public class LiferayJSONWsCredentials {
String oldContext = ScopeProvider.instance.get(); String oldContext = ScopeProvider.instance.get();
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
ScopeProvider.instance.set("/"+ctx.container().configuration().infrastructure()); ScopeProvider.instance.set("/" + ctx.container().configuration().infrastructure());
logger.info("Discovering liferay user's credentials in context " + ctx.container().configuration().infrastructure()); logger.info("Discovering liferay user's credentials in context "
+ ctx.container().configuration().infrastructure());
try{ try {
List<ServiceEndpoint> resources = getConfigurationFromIS(); List<ServiceEndpoint> resources = getConfigurationFromIS();
if (resources.size() == 0){ if (resources.size() == 0) {
logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope."); logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME + " and Category "
throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope."); + CATEGORY + " in this scope.");
} throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME
else { + " and Category " + CATEGORY + " in this scope.");
} else {
for (ServiceEndpoint res : resources) { for (ServiceEndpoint res : resources) {
Iterator<AccessPoint> accessPointIterator = res.profile().accessPoints().iterator(); Iterator<AccessPoint> accessPointIterator = res.profile().accessPoints().iterator();
while (accessPointIterator.hasNext()) { while (accessPointIterator.hasNext()) {
ServiceEndpoint.AccessPoint accessPoint = (ServiceEndpoint.AccessPoint) accessPointIterator ServiceEndpoint.AccessPoint accessPoint = (ServiceEndpoint.AccessPoint) accessPointIterator
.next(); .next();
if(accessPoint.name().equals("JSONWSUser")){ if (accessPoint.name().equals("JSONWSUser")) {
// get base path // get base path
Map<String, Property> properties = accessPoint.propertyMap(); Map<String, Property> properties = accessPoint.propertyMap();
host = accessPoint.address(); host = accessPoint.address();
schema = (String)properties.get("schema").value(); schema = (String) properties.get("schema").value();
user = StringEncrypter.getEncrypter().decrypt((String)properties.get("username").value()); user = StringEncrypter.getEncrypter().decrypt((String) properties.get("username").value());
password = StringEncrypter.getEncrypter().decrypt((String)properties.get("password").value()); password = StringEncrypter.getEncrypter()
.decrypt((String) properties.get("password").value());
port = Integer.valueOf(properties.get("port").value()); port = Integer.valueOf(properties.get("port").value());
// break // break
@ -110,11 +113,11 @@ public class LiferayJSONWsCredentials {
} }
} }
} }
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such service endpoint information!", e); logger.error("Unable to retrieve such service endpoint information!", e);
return; return;
}finally{ } finally {
if(oldContext != null) if (oldContext != null)
ScopeProvider.instance.set(oldContext); ScopeProvider.instance.set(oldContext);
} }
@ -123,41 +126,42 @@ public class LiferayJSONWsCredentials {
/** /**
* 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

@ -7,26 +7,27 @@ import org.slf4j.LoggerFactory;
/** /**
* Class that builds a (singleton) UserManagerWS object. * Class that builds a (singleton) UserManagerWS object.
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public class RoleManagerWSBuilder { public class RoleManagerWSBuilder {
private static final Logger logger = LoggerFactory.getLogger(UserManagerWSBuilder.class); private static final Logger logger = LoggerFactory.getLogger(UserManagerWSBuilder.class);
private static RoleManagerWSBuilder singleton = new RoleManagerWSBuilder(); private static RoleManagerWSBuilder singleton = new RoleManagerWSBuilder();
private RoleManager roleManagerWs; private RoleManager roleManagerWs;
private RoleManagerWSBuilder(){ private RoleManagerWSBuilder() {
logger.debug("Building UserManager please wait"); logger.debug("Building UserManager please wait");
try{ try {
roleManagerWs = new LiferayWSRoleManager( roleManagerWs = new LiferayWSRoleManager(
LiferayJSONWsCredentials.getSingleton().getUser(), LiferayJSONWsCredentials.getSingleton().getUser(),
LiferayJSONWsCredentials.getSingleton().getPassword(), LiferayJSONWsCredentials.getSingleton().getPassword(),
LiferayJSONWsCredentials.getSingleton().getHost(), LiferayJSONWsCredentials.getSingleton().getHost(),
LiferayJSONWsCredentials.getSingleton().getSchema(), LiferayJSONWsCredentials.getSingleton().getSchema(),
LiferayJSONWsCredentials.getSingleton().getPort()); LiferayJSONWsCredentials.getSingleton().getPort());
}catch(Exception e){ } catch (Exception e) {
logger.error("Failed to build the UserManager. ", e); logger.error("Failed to build the UserManager. ", e);
return; return;
} }
@ -34,16 +35,17 @@ public class RoleManagerWSBuilder {
logger.debug("UserManager instance built"); logger.debug("UserManager instance built");
} }
/** /**
* Get the role manager instance * Get the role manager instance
*
* @return * @return
*/ */
public RoleManager getRoleManager(){ public RoleManager getRoleManager() {
return roleManagerWs; return roleManagerWs;
} }
public static RoleManagerWSBuilder getInstance(){ public static RoleManagerWSBuilder getInstance() {
return singleton; return singleton;
} }

View File

@ -3,34 +3,35 @@ package org.gcube.portal.social.networking.liferay.ws;
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; import javax.servlet.ServletContextListener;
import org.gcube.portal.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)
*/ */
public class ServletContextClass implements ServletContextListener public class ServletContextClass implements ServletContextListener {
{
private static String notifierToken; private static String notifierToken;
public void contextInitialized(ServletContextEvent arg0) { public void contextInitialized(ServletContextEvent arg0) {
// get the token and save it // get the token and save it
notifierToken = arg0.getServletContext().getInitParameter("NOTIFIER_TOKEN"); notifierToken = arg0.getServletContext().getInitParameter("NOTIFIER_TOKEN");
// start the thread to retrieve infrastructure users (which is, build up the singleton) // start the thread to retrieve infrastructure users (which is, build up the
//UsersCache.getSingleton(); // singleton)
// UsersCache.getSingleton();
} }
@Override @Override
public void contextDestroyed(ServletContextEvent arg0){ public void contextDestroyed(ServletContextEvent arg0) {
// on shutdown // on shutdown
} }
/** /**
* Returns the token of the Liferay's User. * Returns the token of the Liferay's User.
*
* @return * @return
*/ */
public static String getNotifierToken() { public static String getNotifierToken() {

View File

@ -7,6 +7,7 @@ import org.slf4j.LoggerFactory;
/** /**
* Class that builds a (singleton) UserManagerWS object. * Class that builds a (singleton) UserManagerWS object.
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public class UserManagerWSBuilder { public class UserManagerWSBuilder {
@ -15,18 +16,18 @@ public class UserManagerWSBuilder {
private static UserManagerWSBuilder singleton = new UserManagerWSBuilder(); private static UserManagerWSBuilder singleton = new UserManagerWSBuilder();
private UserManager userManagerWs; private UserManager userManagerWs;
private UserManagerWSBuilder(){ private UserManagerWSBuilder() {
logger.debug("Building UserManager please wait"); logger.debug("Building UserManager please wait");
try{ try {
userManagerWs = new LiferayWSUserManager( userManagerWs = new LiferayWSUserManager(
LiferayJSONWsCredentials.getSingleton().getUser(), LiferayJSONWsCredentials.getSingleton().getUser(),
LiferayJSONWsCredentials.getSingleton().getPassword(), LiferayJSONWsCredentials.getSingleton().getPassword(),
LiferayJSONWsCredentials.getSingleton().getHost(), LiferayJSONWsCredentials.getSingleton().getHost(),
LiferayJSONWsCredentials.getSingleton().getSchema(), LiferayJSONWsCredentials.getSingleton().getSchema(),
LiferayJSONWsCredentials.getSingleton().getPort()); LiferayJSONWsCredentials.getSingleton().getPort());
}catch(Exception e){ } catch (Exception e) {
logger.error("Failed to build the UserManager. ", e); logger.error("Failed to build the UserManager. ", e);
return; return;
} }
@ -34,16 +35,17 @@ public class UserManagerWSBuilder {
logger.debug("UserManager instance built"); logger.debug("UserManager instance built");
} }
/** /**
* Get the user manager instance * Get the user manager instance
*
* @return * @return
*/ */
public UserManager getUserManager(){ public UserManager getUserManager() {
return userManagerWs; return userManagerWs;
} }
public static UserManagerWSBuilder getInstance(){ public static UserManagerWSBuilder getInstance() {
return singleton; return singleton;
} }

View File

@ -14,6 +14,7 @@ public class WelcomeService {
@GET @GET
@Produces(MediaType.TEXT_HTML) @Produces(MediaType.TEXT_HTML)
public Response sayHtmlHello() { public Response sayHtmlHello() {
return Response.ok("<html><body><h2>The social networking web service is up and running!</h2></body></html>").build(); return Response.ok("<html><body><h2>The social networking web service is up and running!</h2></body></html>")
.build();
} }
} }

View File

@ -27,14 +27,13 @@ public class DocsGenerator {
logger.debug("pathInfo {}", pathInfo); logger.debug("pathInfo {}", pathInfo);
try { try {
if (pathInfo.endsWith("/api-docs")) { if (pathInfo.endsWith("/api-docs")) {
pathInfo += "index.html"; pathInfo += "index.html";
} }
if (pathInfo.endsWith("/api-docs/")) {
pathInfo += "index.html";
}
if (pathInfo.endsWith("/api-docs/")) {
pathInfo += "index.html";
}
logger.info("going to {}", pathInfo); logger.info("going to {}", pathInfo);
@ -42,9 +41,9 @@ public class DocsGenerator {
return new FileInputStream(new File(realPath)); return new FileInputStream(new File(realPath));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
//MANAGE THE EXCEPTION // MANAGE THE EXCEPTION
} }
return null; return null;
} }
} }

View File

@ -8,7 +8,6 @@ import javax.ws.rs.ext.Provider;
import org.gcube.portal.social.networking.ws.outputs.ResponseBean; import org.gcube.portal.social.networking.ws.outputs.ResponseBean;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* Exception gets thrown when @Valid fail * Exception gets thrown when @Valid fail
*/ */

View File

@ -3,10 +3,10 @@ package org.gcube.portal.social.networking.ws.ex;
import javax.ws.rs.WebApplicationException; import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.Status;
public class AuthException extends WebApplicationException { public class AuthException extends WebApplicationException {
/** /**
* *
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public AuthException(Throwable cause) { public AuthException(Throwable cause) {

View File

@ -12,12 +12,14 @@ import org.slf4j.LoggerFactory;
/** /**
* Exception thrown on fail * Exception thrown on fail
*
* @author Costantino Perciante at ISTI-CNR * @author Costantino Perciante at ISTI-CNR
*/ */
@Provider @Provider
public class ValidationException implements ExceptionMapper<javax.validation.ValidationException> { public class ValidationException implements ExceptionMapper<javax.validation.ValidationException> {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ValidationException.class); private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ValidationException.class);
@Override @Override
public Response toResponse(javax.validation.ValidationException e) { public Response toResponse(javax.validation.ValidationException e) {
final StringBuilder strBuilder = new StringBuilder(); final StringBuilder strBuilder = new StringBuilder();

View File

@ -5,17 +5,18 @@ import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
/** /**
* Application id object * Application id object
*
* @author Costantino Perciante at ISTI-CNR * @author Costantino Perciante at ISTI-CNR
*/ */
//@ApiModel(description="An object containing the app_id field", value="Application") // @ApiModel(description="An object containing the app_id field",
// value="Application")
public class ApplicationId { public class ApplicationId {
@JsonProperty("app_id") @JsonProperty("app_id")
@NotNull(message="app_id cannot be null") @NotNull(message = "app_id cannot be null")
@Size(message="app_id cannot be empty", min=1) @Size(message = "app_id cannot be empty", min = 1)
private String appId; private String appId;
public ApplicationId() { public ApplicationId() {

View File

@ -8,29 +8,30 @@ import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.webcohesion.enunciate.metadata.DocumentationExample; import com.webcohesion.enunciate.metadata.DocumentationExample;
/** /**
* Generic input bean for methods that allow to comment posts * Generic input bean for methods that allow to comment posts
*/ */
@JsonIgnoreProperties(ignoreUnknown = true) // ignore in serialization/deserialization @JsonIgnoreProperties(ignoreUnknown = true) // ignore in serialization/deserialization
public class CommentInputBean implements Serializable{ public class CommentInputBean implements Serializable {
private static final long serialVersionUID = 5274608088828232980L; private static final long serialVersionUID = 5274608088828232980L;
@JsonProperty("text") @JsonProperty("text")
@NotNull(message="text cannot be null") @NotNull(message = "text cannot be null")
@Size(min=1, message="text cannot be empty") @Size(min = 1, message = "text cannot be empty")
@DocumentationExample("I would like to comment that ...") @DocumentationExample("I would like to comment that ...")
/** /**
* text the text of the comment * text the text of the comment
*/ */
private String text; private String text;
@NotNull(message="postid cannot be null") @NotNull(message = "postid cannot be null")
@JsonProperty("postid") @JsonProperty("postid")
/** /**
* postid the postid of the post where you attach the comment * postid the postid of the post where you attach the comment
*/ */
private String postid; private String postid;
public CommentInputBean() { public CommentInputBean() {
super(); super();
@ -39,7 +40,7 @@ public class CommentInputBean implements Serializable{
/** /**
* @param text * @param text
* @param postid * @param postid
*/ */
public CommentInputBean(String text, String postid) { public CommentInputBean(String text, String postid) {
super(); super();
this.text = text; this.text = text;
@ -66,7 +67,5 @@ public class CommentInputBean implements Serializable{
public String toString() { public String toString() {
return "CommentInputBean [text=" + text + ", postid=" + postid + "]"; return "CommentInputBean [text=" + text + ", postid=" + postid + "]";
} }
} }

View File

@ -5,20 +5,19 @@ import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
/** /**
* Like Bean object * Like Bean object
*/ */
public class LikeInputBean { public class LikeInputBean {
@JsonProperty("likeid") @JsonProperty("likeid")
@NotNull(message="likeid cannot be null") @NotNull(message = "likeid cannot be null")
@Size(message="likeid cannot be empty", min=1) @Size(message = "likeid cannot be empty", min = 1)
private String likeid; private String likeid;
@JsonProperty("postid") @JsonProperty("postid")
@NotNull(message="postid cannot be null") @NotNull(message = "postid cannot be null")
@Size(message="postid cannot be empty", min=1) @Size(message = "postid cannot be empty", min = 1)
private String postid; private String postid;
public LikeInputBean() { public LikeInputBean() {
@ -56,5 +55,4 @@ public class LikeInputBean {
return "LikeInputBean [likeid=" + likeid + ", postid=" + postid + "]"; return "LikeInputBean [likeid=" + likeid + ", postid=" + postid + "]";
} }
} }

View File

@ -5,16 +5,15 @@ import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
/** /**
* Application id object * Application id object
*
*/ */
public class PostId { public class PostId {
@JsonProperty("postid") @JsonProperty("postid")
@NotNull(message="postid cannot be null") @NotNull(message = "postid cannot be null")
@Size(message="postid cannot be empty", min=1) @Size(message = "postid cannot be empty", min = 1)
private String postId; private String postId;
public PostId() { public PostId() {
@ -39,5 +38,4 @@ public class PostId {
return "PostId [postid=" + postId + "]"; return "PostId [postid=" + postId + "]";
} }
} }

View File

@ -8,31 +8,33 @@ import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.webcohesion.enunciate.metadata.DocumentationExample; import com.webcohesion.enunciate.metadata.DocumentationExample;
/** /**
* Generic input bean for methods that allow to write posts * Generic input bean for methods that allow to write posts
*
* @author Costantino Perciante at ISTI-CNR * @author Costantino Perciante at ISTI-CNR
*/ */
@JsonIgnoreProperties(ignoreUnknown = true) // ignore in serialization/deserialization @JsonIgnoreProperties(ignoreUnknown = true) // ignore in serialization/deserialization
public class PostInputBean implements Serializable{ public class PostInputBean implements Serializable {
private static final long serialVersionUID = 5274608088828232980L; private static final long serialVersionUID = 5274608088828232980L;
@JsonProperty("text") @JsonProperty("text")
@NotNull(message="text cannot be null") @NotNull(message = "text cannot be null")
@Size(min=1, message="text cannot be empty") @Size(min = 1, message = "text cannot be empty")
@DocumentationExample("Dear vre members, ...") @DocumentationExample("Dear vre members, ...")
/** /**
* text the text of the post * text the text of the post
*/ */
private String text; private String text;
private String previewtitle; private String previewtitle;
@JsonProperty("preview_description") @JsonProperty("preview_description")
private String previewdescription; private String previewdescription;
@JsonProperty("preview_host") @JsonProperty("preview_host")
private String previewhost; private String previewhost;
@JsonProperty("preview_url") @JsonProperty("preview_url")
private String previewurl; private String previewurl;
@ -44,7 +46,8 @@ public class PostInputBean implements Serializable{
private String httpimageurl; private String httpimageurl;
/** /**
* enablenotification If true send a notification to the other vre members about this post * enablenotification If true send a notification to the other vre members about
* this post
*/ */
@JsonProperty("enable_notification") @JsonProperty("enable_notification")
private boolean enablenotification; private boolean enablenotification;

View File

@ -5,7 +5,6 @@ import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
/** /**
* *
* *
@ -13,19 +12,18 @@ import com.fasterxml.jackson.annotation.JsonProperty;
public class UserSetNotificationBean { public class UserSetNotificationBean {
@JsonProperty("username") @JsonProperty("username")
@NotNull(message="username cannot be null") @NotNull(message = "username cannot be null")
@Size(message="username cannot be empty", min=1) @Size(message = "username cannot be empty", min = 1)
private String username; private String username;
@JsonProperty("disableNotification") @JsonProperty("disableNotification")
@NotNull(message="disableNotification cannot be null") @NotNull(message = "disableNotification cannot be null")
private Boolean disableNotification; private Boolean disableNotification;
public UserSetNotificationBean() { public UserSetNotificationBean() {
super(); super();
} }
/** /**
* @param username * @param username
* @param disableNotification * @param disableNotification
@ -36,7 +34,6 @@ public class UserSetNotificationBean {
this.disableNotification = disableNotification; this.disableNotification = disableNotification;
} }
public String getUsername() { public String getUsername() {
return username; return username;
} }
@ -53,11 +50,9 @@ public class UserSetNotificationBean {
this.disableNotification = disableNotification; this.disableNotification = disableNotification;
} }
@Override @Override
public String toString() { public String toString() {
return "UserSetNotificationBean [username=" + username + ", disableNotification=" + disableNotification + "]"; return "UserSetNotificationBean [username=" + username + ", disableNotification=" + disableNotification + "]";
} }
} }

View File

@ -11,18 +11,18 @@ public class CatalogueEventTypeMapper {
public static NotificationType getType(CatalogueEventType type) throws NotificationTypeNotFoundException { public static NotificationType getType(CatalogueEventType type) throws NotificationTypeNotFoundException {
switch (type) { switch (type) {
case ITEM_PUBLISHED: case ITEM_PUBLISHED:
return NotificationType.CAT_ITEM_PUBLISHED; return NotificationType.CAT_ITEM_PUBLISHED;
case ITEM_REJECTED: case ITEM_REJECTED:
return NotificationType.CAT_ITEM_REJECTED; return NotificationType.CAT_ITEM_REJECTED;
case ITEM_REMOVED: case ITEM_REMOVED:
return NotificationType.CAT_ITEM_DELETE; return NotificationType.CAT_ITEM_DELETE;
case ITEM_SUBMITTED: case ITEM_SUBMITTED:
return NotificationType.CAT_ITEM_SUBMITTED; return NotificationType.CAT_ITEM_SUBMITTED;
case ITEM_UPDATED: case ITEM_UPDATED:
return NotificationType.CAT_ITEM_UPDATED; return NotificationType.CAT_ITEM_UPDATED;
default: default:
throw new NotificationTypeNotFoundException("The Catalogue event could not be mapped"); throw new NotificationTypeNotFoundException("The Catalogue event could not be mapped");
} }
} }
} }

View File

@ -9,14 +9,14 @@ public class JobMapper {
public JobMapper() { public JobMapper() {
} }
public static RunningJob getJob(JobNotificationBean item) { public static RunningJob getJob(JobNotificationBean item) {
String jobId = null; String jobId = null;
String jobName = null; String jobName = null;
JobStatusType status = null; JobStatusType status = null;
String message = null; String message = null;
String serviceName = null; // i.e., Dataminer, SmartExecutor.. String serviceName = null; // i.e., Dataminer, SmartExecutor..
try { try {
jobId = item.getJobId(); jobId = item.getJobId();
jobName = item.getJobName(); jobName = item.getJobName();
@ -32,33 +32,32 @@ public class JobMapper {
public static JobStatusType getType(JobStatusModelType type) { public static JobStatusType getType(JobStatusModelType type) {
JobStatusType toReturn = null; JobStatusType toReturn = null;
switch (type) { switch (type) {
case CANCELLED: case CANCELLED:
return JobStatusType.CANCELLED; return JobStatusType.CANCELLED;
case DELETED: case DELETED:
return JobStatusType.DELETED; return JobStatusType.DELETED;
case FAILED: case FAILED:
return JobStatusType.FAILED; return JobStatusType.FAILED;
case CANCELLING: case CANCELLING:
return JobStatusType.CANCELLING; return JobStatusType.CANCELLING;
case DELETING: case DELETING:
return JobStatusType.DELETING; return JobStatusType.DELETING;
case EXECUTING: case EXECUTING:
return JobStatusType.EXECUTING; return JobStatusType.EXECUTING;
case NEW: case NEW:
return JobStatusType.NEW; return JobStatusType.NEW;
case SUBMITTED: case SUBMITTED:
return JobStatusType.SUBMITTED; return JobStatusType.SUBMITTED;
case SUCCEEDED: case SUCCEEDED:
return JobStatusType.SUCCEEDED; return JobStatusType.SUCCEEDED;
case TIMED_OUT: case TIMED_OUT:
return JobStatusType.TIMED_OUT; return JobStatusType.TIMED_OUT;
case WAITING: case WAITING:
return JobStatusType.WAITING; return JobStatusType.WAITING;
default: default:
break; break;
} }
return toReturn; return toReturn;
} }
} }

View File

@ -13,9 +13,9 @@ public class WorkspaceItemMapper {
public static SocialFileItem getFileItem(FileItemBean item) { public static SocialFileItem getFileItem(FileItemBean item) {
String id = null; String id = null;
String name= null; String name = null;
String title= null; String title = null;
String path= null; String path = null;
SocialSharedFolder parent = null; SocialSharedFolder parent = null;
try { try {
@ -34,12 +34,12 @@ public class WorkspaceItemMapper {
public static SocialSharedFolder getSharedFolder(FolderBean item) { public static SocialSharedFolder getSharedFolder(FolderBean item) {
String id = null; String id = null;
String name= null; String name = null;
String title= null; String title = null;
String displayName= null; String displayName = null;
String path= null; String path = null;
String parentId= null; String parentId = null;
boolean vreFolder = false; boolean vreFolder = false;
try { try {
id = item.getId(); id = item.getId();
name = item.getName(); name = item.getName();

View File

@ -1,9 +1,7 @@
package org.gcube.portal.social.networking.ws.methods.v2; package org.gcube.portal.social.networking.ws.methods.v2;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.UUID;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.ValidationException; import javax.validation.ValidationException;
@ -23,22 +21,15 @@ import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller; import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.shared.Comment; 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.databook.shared.ex.FeedIDNotFoundException;
import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.portal.social.networking.ws.inputs.CommentInputBean; import org.gcube.portal.social.networking.ws.inputs.CommentInputBean;
import org.gcube.portal.social.networking.ws.inputs.PostInputBean;
import org.gcube.portal.social.networking.ws.outputs.ResponseBean; import org.gcube.portal.social.networking.ws.outputs.ResponseBean;
import org.gcube.portal.social.networking.ws.utils.CassandraConnection; import org.gcube.portal.social.networking.ws.utils.CassandraConnection;
import org.gcube.portal.social.networking.ws.utils.ErrorMessages; import org.gcube.portal.social.networking.ws.utils.ErrorMessages;
import org.gcube.portal.social.networking.ws.utils.Filters; import org.gcube.portal.social.networking.ws.utils.Filters;
import org.gcube.portal.social.networking.ws.utils.SocialUtils; import org.gcube.portal.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 org.slf4j.LoggerFactory;
import com.liferay.portlet.journal.FeedIdException;
import com.webcohesion.enunciate.metadata.rs.RequestHeader; import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders; import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResponseCode; import com.webcohesion.enunciate.metadata.rs.ResponseCode;
@ -46,12 +37,13 @@ import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/** /**
* REST interface for the social networking library (comments). * REST interface for the social networking library (comments).
*
* @author Ahmed Ibrahim ISTI-CNR * @author Ahmed Ibrahim ISTI-CNR
*/ */
@Path("2/comments") @Path("2/comments")
@RequestHeaders ({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), @RequestHeader(name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json") @RequestHeader(name = "Content-Type", description = "application/json")
}) })
public class Comments { public class Comments {
@ -59,22 +51,26 @@ public class Comments {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Comments.class); 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 * 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 * @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 * @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 @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("get-comments-by-post-id") @Path("get-comments-by-post-id")
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "The list of comments is put into the 'result' field"), @ResponseCode(code = 200, condition = "The list of comments is put into the 'result' field"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getAllCommentsByPostId( public Response getAllCommentsByPostId(
@NotNull @NotNull @QueryParam("key") String key) {
@QueryParam("key")
String key) {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
@ -83,13 +79,13 @@ public class Comments {
String username = caller.getClient().getId(); String username = caller.getClient().getId();
List<Comment> comments = null; List<Comment> comments = null;
try{ try {
logger.debug("Retrieving comments for user id " + username); logger.debug("Retrieving comments for user id " + username);
comments = CassandraConnection.getInstance().getDatabookStore().getAllCommentByPost(key); comments = CassandraConnection.getInstance().getDatabookStore().getAllCommentByPost(key);
Filters.filterCommentsPerContext(comments, context); Filters.filterCommentsPerContext(comments, context);
responseBean.setResult(comments); responseBean.setResult(comments);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such comments.", e); logger.error("Unable to retrieve such comments.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -98,16 +94,20 @@ public class Comments {
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
/* /*
* Retrieve the list of comments belonging to the owner of the token in the related context * Retrieve the list of comments belonging to the owner of the token in the
* @return the list of comments belonging to the owner of the token in the related context. * related context
*
* @return the list of comments belonging to the owner of the token in the
* related context.
*/ */
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("get-comments-user") @Path("get-comments-user")
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "The list of comments is put into the 'result' field"), @ResponseCode(code = 200, condition = "The list of comments is put into the 'result' field"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getCommentsUser() { public Response getCommentsUser() {
@ -118,13 +118,13 @@ public class Comments {
String username = caller.getClient().getId(); String username = caller.getClient().getId();
List<Comment> comments = null; List<Comment> comments = null;
try{ try {
logger.debug("Retrieving comments for user id " + username); logger.debug("Retrieving comments for user id " + username);
comments = CassandraConnection.getInstance().getDatabookStore().getRecentCommentsByUserAndDate(username, 0); comments = CassandraConnection.getInstance().getDatabookStore().getRecentCommentsByUserAndDate(username, 0);
Filters.filterCommentsPerContext(comments, context); Filters.filterCommentsPerContext(comments, context);
responseBean.setResult(comments); responseBean.setResult(comments);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such comments.", e); logger.error("Unable to retrieve such comments.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -135,16 +135,15 @@ public class Comments {
} }
/* /*
* Retrieve comments of the token owner in the context bound to the token itself and filter them by date * Retrieve comments of the token owner in the context bound to the token itself
* and filter them by date
*/ */
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("get-comments-user-by-time") @Path("get-comments-user-by-time")
public Response getCommentsUserByTime( public Response getCommentsUserByTime(
@QueryParam("time") @QueryParam("time") @Min(value = 0, message = "time cannot be negative") long timeInMillis)
@Min(value = 0, message="time cannot be negative") throws ValidationException {
long timeInMillis
) throws ValidationException{
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
@ -153,14 +152,15 @@ public class Comments {
String username = caller.getClient().getId(); String username = caller.getClient().getId();
List<Comment> comments = null; List<Comment> comments = null;
try{ try {
logger.debug("Retrieving comments for user id " + username); logger.debug("Retrieving comments for user id " + username);
comments = CassandraConnection.getInstance().getDatabookStore().getRecentCommentsByUserAndDate(username, timeInMillis); comments = CassandraConnection.getInstance().getDatabookStore().getRecentCommentsByUserAndDate(username,
timeInMillis);
Filters.filterCommentsPerContext(comments, context); Filters.filterCommentsPerContext(comments, context);
responseBean.setResult(comments); responseBean.setResult(comments);
responseBean.setMessage(""); responseBean.setMessage("");
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such comments.", e); logger.error("Unable to retrieve such comments.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -169,8 +169,10 @@ public class Comments {
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
/** /**
* Create a new comment to a post having as owner the auth token's owner * Create a new comment to a post having as owner the auth token's owner
*
* @param comment The CommentInputBean object * @param comment The CommentInputBean object
* @return * @return
* @throws ValidationException * @throws ValidationException
@ -179,14 +181,13 @@ public class Comments {
@Path("comment-post") @Path("comment-post")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 201, condition = "Successfull created, the new comment is reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response writeComment( public Response writeComment(
@NotNull(message="Comment to write is missing") @NotNull(message = "Comment to write is missing") @Valid CommentInputBean comment)
@Valid throws ValidationException {
CommentInputBean comment) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
logger.debug("Request of writing a comment coming from user " + username); logger.debug("Request of writing a comment coming from user " + username);
@ -215,14 +216,13 @@ public class Comments {
responseBean.setResult(theComment); responseBean.setResult(theComment);
responseBean.setSuccess(true); responseBean.setSuccess(true);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} catch(FeedIDNotFoundException ex) { } catch (FeedIDNotFoundException ex) {
logger.error("Unable to find a post comment", 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.setMessage("Could not reach the DB to write the comment, something went wrong");
responseBean.setSuccess(false); responseBean.setSuccess(false);
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} } catch (Exception e) {
catch(Exception e) {
logger.error("Unable to write comment", e); logger.error("Unable to write comment", e);
responseBean.setMessage("Could not reach the DB to write the comment, something went wrong"); responseBean.setMessage("Could not reach the DB to write the comment, something went wrong");
responseBean.setSuccess(false); responseBean.setSuccess(false);

View File

@ -49,10 +49,10 @@ import com.webcohesion.enunciate.metadata.rs.StatusCodes;
* REST interface for the social networking library (post and its comments). * REST interface for the social networking library (post and its comments).
*/ */
@Path("2/full-text-search") @Path("2/full-text-search")
@RequestHeaders ({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), @RequestHeader(name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json") @RequestHeader(name = "Content-Type", description = "application/json")
}) })
public class FullTextSearch { public class FullTextSearch {
// Logger // Logger
@ -60,29 +60,30 @@ public class FullTextSearch {
/** /**
* Retrieve posts/comments that match the given query * Retrieve posts/comments that match the given query
*
* @param httpServletRequest * @param httpServletRequest
* @param query A string to search for * @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 from the index of the base result to be returned,
* @param quantity defines how many results are most are to be returned, range[1, infinity], defaults from = 0, * range[0, infinity], defaults from = 0
* @return The posts/comments returned belong to the context bound to the AUTH Token * @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 * @throws ValidationException
*/ */
@GET @GET
@Path("search-by-query") @Path("search-by-query")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @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 = 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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response searchByQuery( public Response searchByQuery(
@Context HttpServletRequest httpServletRequest, @Context HttpServletRequest httpServletRequest,
@QueryParam("query") @NotNull(message="query cannot be null") @Size(min=1, message="query cannot be empty") @QueryParam("query") @NotNull(message = "query cannot be null") @Size(min = 1, message = "query cannot be empty") String query,
String query, @DefaultValue("0") @QueryParam("from") @Min(value = 0, message = "from cannot be negative") int from,
@DefaultValue("0") @QueryParam("from") @Min(value=0, message="from cannot be negative") @DefaultValue("10") @QueryParam("quantity") @Min(value = 0, message = "quantity cannot be negative") int quantity)
int from, throws ValidationException {
@DefaultValue("10") @QueryParam("quantity") @Min(value=0, message="quantity cannot be negative")
int quantity
) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
@ -90,45 +91,45 @@ public class FullTextSearch {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.BAD_REQUEST; Status status = Status.BAD_REQUEST;
responseBean.setMessage("This method can be only invoked by using a user token."); responseBean.setMessage("This method can be only invoked by using a user token.");
if(!TokensUtils.isUserToken(caller)) if (!TokensUtils.isUserToken(caller))
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
status = Status.OK; status = Status.OK;
responseBean.setMessage(null); responseBean.setMessage(null);
GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager(); GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
try{ try {
// Retrieve user's vres in which we must search // Retrieve user's vres in which we must search
Set<String> vres = new HashSet<String>(); Set<String> vres = new HashSet<String>();
// get the group id from the current context // get the group id from the current context
long currentGroupId = groupManager.getGroupIdFromInfrastructureScope(context); long currentGroupId = groupManager.getGroupIdFromInfrastructureScope(context);
GCubeUser currUser = userManager.getUserByUsername(username); GCubeUser currUser = userManager.getUserByUsername(username);
List<GCubeGroup> userContexts = groupManager.listGroupsByUser(currUser.getUserId()); List<GCubeGroup> userContexts = groupManager.listGroupsByUser(currUser.getUserId());
if (groupManager.isRootVO(currentGroupId)) { if (groupManager.isRootVO(currentGroupId)) {
for (GCubeGroup group : groupManager.listGroupsByUser(currUser.getUserId())) { for (GCubeGroup group : groupManager.listGroupsByUser(currUser.getUserId())) {
if (groupManager.isVRE(group.getGroupId()) && userContexts.contains(group)) { if (groupManager.isVRE(group.getGroupId()) && userContexts.contains(group)) {
vres.add(groupManager.getInfrastructureScope(group.getGroupId())); vres.add(groupManager.getInfrastructureScope(group.getGroupId()));
} }
} }
} } else if (groupManager.isVO(currentGroupId)) {
else if(groupManager.isVO(currentGroupId)){ for (GCubeGroup group : groupManager.listGroupsByUser(currUser.getUserId())) {
for (GCubeGroup group : groupManager.listGroupsByUser(currUser.getUserId())) { if (groupManager.isVRE(group.getGroupId()) && group.getParentGroupId() == currentGroupId
if (groupManager.isVRE(group.getGroupId()) && group.getParentGroupId() == currentGroupId && userContexts.contains(group)) { && userContexts.contains(group)) {
vres.add(groupManager.getInfrastructureScope(group.getGroupId())); vres.add(groupManager.getInfrastructureScope(group.getGroupId()));
} }
} }
} } else {
else {
vres.add(context); vres.add(context);
} }
// query elastic search // query elastic search
List<EnhancedFeed> enhancedFeeds = ElasticSearchConnection.getSingleton().getElasticSearchClient().search(query, vres, from, quantity); List<EnhancedFeed> enhancedFeeds = ElasticSearchConnection.getSingleton().getElasticSearchClient()
.search(query, vres, from, quantity);
Filters.hideSensitiveInformation(enhancedFeeds, caller.getClient().getId()); Filters.hideSensitiveInformation(enhancedFeeds, caller.getClient().getId());
DatabookStore store = CassandraConnection.getInstance().getDatabookStore(); DatabookStore store = CassandraConnection.getInstance().getDatabookStore();
@ -137,14 +138,14 @@ public class FullTextSearch {
// update fields "liked" and "isuser" // update fields "liked" and "isuser"
for (EnhancedFeed enhancedFeed : enhancedFeeds) { for (EnhancedFeed enhancedFeed : enhancedFeeds) {
if(isUsers(enhancedFeed.getFeed(), username)) if (isUsers(enhancedFeed.getFeed(), username))
enhancedFeed.setUsers(true); enhancedFeed.setUsers(true);
if(likedFeeds.contains(enhancedFeed.getFeed().getKey())) if (likedFeeds.contains(enhancedFeed.getFeed().getKey()))
enhancedFeed.setLiked(true); enhancedFeed.setLiked(true);
} }
responseBean.setResult((ArrayList<EnhancedFeed>) enhancedFeeds); responseBean.setResult((ArrayList<EnhancedFeed>) enhancedFeeds);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Something went wrong while searching", e); logger.error("Something went wrong while searching", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -156,6 +157,7 @@ public class FullTextSearch {
/** /**
* tell if a feed belongs to the current user or not * tell if a feed belongs to the current user or not
*
* @param tocheck * @param tocheck
* @param username * @param username
* @return true if this feed is of the current user * @return true if this feed is of the current user

View File

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

View File

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

View File

@ -23,7 +23,6 @@ import org.gcube.applicationsupportlayer.social.ApplicationNotificationsManager;
import org.gcube.applicationsupportlayer.social.NotificationsManager; import org.gcube.applicationsupportlayer.social.NotificationsManager;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite; import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingUser; 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.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.utils.Caller; import org.gcube.common.authorization.library.utils.Caller;
@ -36,8 +35,6 @@ import org.gcube.portal.notifications.thread.MessageNotificationsThread;
import org.gcube.portal.social.networking.caches.SocialNetworkingSiteFinder; import org.gcube.portal.social.networking.caches.SocialNetworkingSiteFinder;
import org.gcube.portal.social.networking.liferay.ws.LiferayJSONWsCredentials; import org.gcube.portal.social.networking.liferay.ws.LiferayJSONWsCredentials;
import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder; import org.gcube.portal.social.networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.portal.social.networking.ws.ex.AuthException;
import org.gcube.portal.social.networking.ws.inputs.UserSetNotificationBean;
import org.gcube.portal.social.networking.ws.outputs.ResponseBean; import org.gcube.portal.social.networking.ws.outputs.ResponseBean;
import org.gcube.portal.social.networking.ws.utils.ErrorMessages; import org.gcube.portal.social.networking.ws.utils.ErrorMessages;
import org.gcube.portal.social.networking.ws.utils.TokensUtils; import org.gcube.portal.social.networking.ws.utils.TokensUtils;
@ -56,14 +53,15 @@ import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/** /**
* Messages services REST interface * Messages services REST interface
* @author Costantino Perciante at ISTI-CNR *
* (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR
* (costantino.perciante@isti.cnr.it)
*/ */
@Path("2/messages") @Path("2/messages")
@RequestHeaders ({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), @RequestHeader(name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json") @RequestHeader(name = "Content-Type", description = "application/json")
}) })
public class Messages { public class Messages {
// Logger // Logger
@ -71,8 +69,10 @@ public class Messages {
/** /**
* Write a message to another user. The sender is the token's owner by default * 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" * @responseExample application/json {"success": true, "message": null,
* "result": "556142e3-d6f5-4550-b2fa-abe5626625d3"}
* @param input The message to write"
* @param httpServletRequest * @param httpServletRequest
* @return see response example * @return see response example
* @throws ValidationException * @throws ValidationException
@ -83,15 +83,14 @@ public class Messages {
@Path("write-message/") @Path("write-message/")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successful write a message. Its id is reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response writeMessage( public Response writeMessage(
@NotNull(message="Message to send is missing") @NotNull(message = "Message to send is missing") @Valid MessageInputBean input,
@Valid @Context HttpServletRequest httpServletRequest)
MessageInputBean input, throws ValidationException, UserManagementSystemException, UserRetrievalFault {
@Context HttpServletRequest httpServletRequest) throws ValidationException, UserManagementSystemException, UserRetrievalFault{
logger.debug("Incoming message bean is " + input); logger.debug("Incoming message bean is " + input);
@ -99,62 +98,69 @@ public class Messages {
UserManager um = UserManagerWSBuilder.getInstance().getUserManager(); UserManager um = UserManagerWSBuilder.getInstance().getUserManager();
GCubeUser senderUser = null; GCubeUser senderUser = null;
SocialNetworkingUser user = 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) // 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 username = null;
String fullName = ""; String fullName = "";
logger.debug("Catalogue Notification called by " + caller.getClient().getId() + " isUser?"+TokensUtils.isUserToken(caller)); logger.debug("Catalogue Notification called by " + caller.getClient().getId() + " isUser?"
if(!TokensUtils.isUserToken(caller)){ + TokensUtils.isUserToken(caller));
GCubeUser jarvis = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser()); if (!TokensUtils.isUserToken(caller)) {
GCubeUser jarvis = UserManagerWSBuilder.getInstance().getUserManager()
.getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser());
SecurityTokenProvider.instance.set(LiferayJSONWsCredentials.getSingleton().getNotifierUserToken()); SecurityTokenProvider.instance.set(LiferayJSONWsCredentials.getSingleton().getNotifierUserToken());
username = jarvis.getUsername(); username = jarvis.getUsername();
fullName = caller.getClient().getId().replace("service-account-", ""); // the actual name of the IAM Client fullName = caller.getClient().getId().replace("service-account-", ""); // the actual name of the IAM Client
senderUser = um.getUserByUsername(username); senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName, senderUser.getUserAvatarURL()); user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName,
}else{ senderUser.getUserAvatarURL());
} else {
username = caller.getClient().getId(); username = caller.getClient().getId();
senderUser = um.getUserByUsername(username); senderUser = um.getUserByUsername(username);
fullName = senderUser.getFullname(); fullName = senderUser.getFullname();
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName, senderUser.getUserAvatarURL()); user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName,
} senderUser.getUserAvatarURL());
}
String scope = ScopeProvider.instance.get(); String scope = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.CREATED; Status status = Status.CREATED;
String body = input.getBody(); String body = input.getBody();
String subject = input.getSubject(); String subject = input.getSubject();
List<Recipient> recipientsIds = input.getRecipients(); // "recipients":[{"recipient":"id recipient"}, ......] List<Recipient> recipientsIds = input.getRecipients(); // "recipients":[{"recipient":"id recipient"}, ......]
logger.debug("Sender is going to be [" + fullName + "]"); logger.debug("Sender is going to be [" + fullName + "]");
// get the recipients ids (simple check, trim) // get the recipients ids (simple check, trim)
List<String> recipientsListFiltered = new ArrayList<String>(); List<String> recipientsListFiltered = new ArrayList<String>();
List<GenericItemBean> recipientsBeans = new ArrayList<GenericItemBean>(); List<GenericItemBean> recipientsBeans = new ArrayList<GenericItemBean>();
for (Recipient recipientId : recipientsIds) { for (Recipient recipientId : recipientsIds) {
try{ try {
String tempId = recipientId.getId().trim(); String tempId = recipientId.getId().trim();
if(tempId.isEmpty()) if (tempId.isEmpty())
continue; continue;
GCubeUser userRecipient = UserManagerWSBuilder.getInstance().getUserManager().getUserByUsername(tempId); GCubeUser userRecipient = UserManagerWSBuilder.getInstance().getUserManager().getUserByUsername(tempId);
if(userRecipient == null) if (userRecipient == null)
userRecipient = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(tempId); userRecipient = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(tempId);
if(userRecipient != null){ if (userRecipient != null) {
GenericItemBean beanUser = new GenericItemBean(userRecipient.getUsername(), userRecipient.getUsername(), userRecipient.getFullname(), userRecipient.getUserAvatarURL()); GenericItemBean beanUser = new GenericItemBean(userRecipient.getUsername(),
userRecipient.getUsername(), userRecipient.getFullname(), userRecipient.getUserAvatarURL());
recipientsBeans.add(beanUser); recipientsBeans.add(beanUser);
recipientsListFiltered.add(userRecipient.getUsername()); recipientsListFiltered.add(userRecipient.getUsername());
} }
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve recipient information for recipient with id " + recipientId, e); logger.error("Unable to retrieve recipient information for recipient with id " + recipientId, e);
} }
} }
if(recipientsListFiltered.isEmpty()){ if (recipientsListFiltered.isEmpty()) {
logger.error("Missing/wrong request parameters"); logger.error("Missing/wrong request parameters");
status = Status.BAD_REQUEST; status = Status.BAD_REQUEST;
responseBean.setMessage(ErrorMessages.MISSING_PARAMETERS); responseBean.setMessage(ErrorMessages.MISSING_PARAMETERS);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
try{ try {
logger.debug("Trying to send message with body " + body + " subject " + subject + " to users " + recipientsIds + " from " + username); logger.debug("Trying to send message with body " + body + " subject " + subject + " to users "
+ recipientsIds + " from " + username);
// send message // send message
MessageManagerClient client = AbstractPlugin.messages().build(); MessageManagerClient client = AbstractPlugin.messages().build();
@ -164,12 +170,13 @@ public class Messages {
// send notification // send notification
logger.debug("Message sent to " + recipientsIds + ". Sending message notification to: " + recipientsIds); logger.debug("Message sent to " + recipientsIds + ". Sending message notification to: " + recipientsIds);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(scope); SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(scope);
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, ScopeProvider.instance.get(), user); NotificationsManager nm = new ApplicationNotificationsManager(
UserManagerWSBuilder.getInstance().getUserManager(), site, ScopeProvider.instance.get(), user);
new Thread(new MessageNotificationsThread(recipientsBeans, messageId, subject, body, nm)).start(); new Thread(new MessageNotificationsThread(recipientsBeans, messageId, subject, body, nm)).start();
responseBean.setSuccess(true); responseBean.setSuccess(true);
responseBean.setResult(messageId); responseBean.setResult(messageId);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to send message.", e); logger.error("Unable to send message.", e);
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
responseBean.setMessage(e.toString()); responseBean.setMessage(e.toString());
@ -180,15 +187,15 @@ public class Messages {
@GET @GET
@Path("get-sent-messages") @Path("get-sent-messages")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successful read of the sent messages, reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
/** /**
* *
* @return the list of sent messages of the user (the token's owner) * @return the list of sent messages of the user (the token's owner)
*/ */
public Response getSentMessages(){ public Response getSentMessages() {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
@ -197,14 +204,14 @@ public class Messages {
logger.debug("Request for retrieving sent messages by " + username); logger.debug("Request for retrieving sent messages by " + username);
try{ try {
MessageManagerClient client = AbstractPlugin.messages().build(); MessageManagerClient client = AbstractPlugin.messages().build();
List<Message> sentMessages = client.getSentMessages(); List<Message> sentMessages = client.getSentMessages();
Collections.reverse(sentMessages); Collections.reverse(sentMessages);
responseBean.setSuccess(true); responseBean.setSuccess(true);
logger.debug("Result is " + sentMessages); logger.debug("Result is " + sentMessages);
responseBean.setResult(sentMessages); responseBean.setResult(sentMessages);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve sent messages", e); logger.error("Unable to retrieve sent messages", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
@ -216,15 +223,15 @@ public class Messages {
@GET @GET
@Path("get-received-messages") @Path("get-received-messages")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successful read of the received messages, reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
/** /**
* *
* @return the list of received messages of the user (the token's owner) * @return the list of received messages of the user (the token's owner)
*/ */
public Response getReceivedMessages(){ public Response getReceivedMessages() {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
@ -232,14 +239,14 @@ public class Messages {
Status status = Status.OK; Status status = Status.OK;
logger.debug("Request for retrieving received messages by " + username); logger.debug("Request for retrieving received messages by " + username);
try{ try {
MessageManagerClient client = AbstractPlugin.messages().build(); MessageManagerClient client = AbstractPlugin.messages().build();
List<Message> getMessages =client.getReceivedMessages(); List<Message> getMessages = client.getReceivedMessages();
Collections.reverse(getMessages); Collections.reverse(getMessages);
responseBean.setSuccess(true); responseBean.setSuccess(true);
responseBean.setResult(getMessages); responseBean.setResult(getMessages);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve sent messages", e); logger.error("Unable to retrieve sent messages", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
@ -247,49 +254,48 @@ public class Messages {
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
/** /**
* Set message read or unread * Set message read or unread
*
* @param messageId the message identifier * @param messageId the message identifier
* @param read true to set read, false to set unread * @param read true to set read, false to set unread
* @return the result of the operation * @return the result of the operation
* @throws ValidationException * @throws ValidationException
*/ */
@POST @POST
@Path("set-message-read/") @Path("set-message-read/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Message set Read or Unread is correctly executed"), @ResponseCode(code = 200, condition = "Message set Read or Unread is correctly executed"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response setMessageRead( public Response setMessageRead(
@NotNull(message="input is missing") @NotNull(message = "input is missing") @FormParam("messageId") String messageId,
@FormParam("messageId") String messageId, @FormParam("read") Boolean read) throws ValidationException {
@FormParam("read") Boolean read) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
String opExecutor = ""; String opExecutor = "";
try{ try {
opExecutor = caller.getClient().getId(); opExecutor = caller.getClient().getId();
MessageManagerClient client = AbstractPlugin.messages().build(); MessageManagerClient client = AbstractPlugin.messages().build();
client.setRead(messageId, read); client.setRead(messageId, read);
String toReturn = "set Message id:" + messageId + (read ? " read" : " unread"); String toReturn = "set Message id:" + messageId + (read ? " read" : " unread");
logger.debug("set Message id:" + messageId + " read?" + read + " for " + opExecutor); logger.debug("set Message id:" + messageId + " read?" + read + " for " + opExecutor);
responseBean.setSuccess(true); responseBean.setSuccess(true);
responseBean.setResult(toReturn); responseBean.setResult(toReturn);
} catch(Exception e){ } catch (Exception e) {
logger.error("Unable to set message read / unread property for user " + opExecutor, e); logger.error("Unable to set message read / unread property for user " + opExecutor, e);
responseBean.setSuccess(false); responseBean.setSuccess(false);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
} }
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
} }

View File

@ -4,7 +4,6 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.ValidationException; import javax.validation.ValidationException;
@ -32,8 +31,6 @@ import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean; import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.portal.databook.shared.Notification; 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.databook.shared.RunningJob;
import org.gcube.portal.notifications.bean.GenericItemBean; import org.gcube.portal.notifications.bean.GenericItemBean;
import org.gcube.portal.notifications.thread.JobStatusNotificationThread; import org.gcube.portal.notifications.thread.JobStatusNotificationThread;
@ -78,12 +75,13 @@ import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/** /**
* REST interface for the social networking library (notifications). * REST interface for the social networking library (notifications).
*
* @author Ahmed Ibrahim ISTI-CNR * @author Ahmed Ibrahim ISTI-CNR
*/ */
@Path("2/notifications") @Path("2/notifications")
@RequestHeaders ({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), @RequestHeader(name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json") @RequestHeader(name = "Content-Type", description = "application/json")
}) })
public class Notifications { public class Notifications {
@ -93,7 +91,8 @@ public class Notifications {
/** /**
* Retrieve notifications of the token's owner * Retrieve notifications of the token's owner
* @param from must be greater or equal to 1, range[0, infinity] *
* @param from must be greater or equal to 1, range[0, infinity]
* @param quantity quantity must be greater or equal to 0 * @param quantity quantity must be greater or equal to 0
* @return notifications up to quantity * @return notifications up to quantity
* @throws ValidationException * @throws ValidationException
@ -101,32 +100,31 @@ public class Notifications {
@GET @GET
@Path("get-range-notifications/") @Path("get-range-notifications/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Notifications retrieved and reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getRangeNotifications( public Response getRangeNotifications(
@DefaultValue("1") @QueryParam("from") @Min(value=1, message="from must be greater or equal to 1") @DefaultValue("1") @QueryParam("from") @Min(value = 1, message = "from must be greater or equal to 1") int from,
int from, @DefaultValue("10") @QueryParam("quantity") @Min(value = 0, message = "quantity must be greater or equal to 0") int quantity)
@DefaultValue("10") @QueryParam("quantity") @Min(value=0, message="quantity must be greater or equal to 0") throws ValidationException {
int quantity
) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
logger.debug("Retrieving " + quantity + " notifications of user = " + username + " from " + from); logger.debug("Retrieving " + quantity + " notifications of user = " + username + " from " + from);
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
List<Notification> notifications = null; List<Notification> notifications = null;
try{ try {
notifications = CassandraConnection.getInstance().getDatabookStore().getRangeNotificationsByUser(username, from, quantity); notifications = CassandraConnection.getInstance().getDatabookStore().getRangeNotificationsByUser(username,
from, quantity);
responseBean.setResult(notifications); responseBean.setResult(notifications);
responseBean.setSuccess(true); responseBean.setSuccess(true);
logger.debug("List of notifications retrieved"); logger.debug("List of notifications retrieved");
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such notifications.", e); logger.error("Unable to retrieve such notifications.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -136,35 +134,37 @@ public class Notifications {
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
/** /**
* Return whether the notifications for this user are enabled or not * Return whether the notifications for this user are enabled or not
*
* @pathExample /is-user-disabled?username=john.smith * @pathExample /is-user-disabled?username=john.smith
* @responseExample application/json { "success": true, "message": null "result": true } * @responseExample application/json { "success": true, "message": null
* "result": true }
* @param username the username you want to check * @param username the username you want to check
* @return true if the notification for the user are disabled (Catalogue and Workspace ones) * @return true if the notification for the user are disabled (Catalogue and
* Workspace ones)
* *
*/ */
@GET @GET
@Path("is-user-disabled/") @Path("is-user-disabled/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @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 = 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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
@AuthorizationControl(allowedRoles={INFRASTRUCTURE_MANAGER_ROLE}, exception=AuthException.class) @AuthorizationControl(allowedRoles = { INFRASTRUCTURE_MANAGER_ROLE }, exception = AuthException.class)
public Response isUserDisabled( public Response isUserDisabled(
@QueryParam("username") @NotNull(message="username cannot be null") @QueryParam("username") @NotNull(message = "username cannot be null") String username)
String username) throws ValidationException{ throws ValidationException {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
try{ try {
Boolean userDisabled= !isNotificationEnabled(username); Boolean userDisabled = !isNotificationEnabled(username);
responseBean.setResult(userDisabled); responseBean.setResult(userDisabled);
responseBean.setSuccess(true); responseBean.setSuccess(true);
logger.debug("are User " + username + " Notifications Disabled?"+userDisabled); logger.debug("are User " + username + " Notifications Disabled?" + userDisabled);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to read whether the notifications for this user are enabled or not.", e); logger.error("Unable to read whether the notifications for this user are enabled or not.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -174,54 +174,59 @@ public class Notifications {
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
// /** // /**
// * Set user notification enabled or disabled // * 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 // * @param disable true if you want to disable the notifications for this user,
// * @return the result of the operation // false if you want to enable them
// * @throws ValidationException // * @return the result of the operation
// */ // * @throws ValidationException
// @POST // */
// @Path("set-user-notifications/") // @POST
// @Consumes(MediaType.APPLICATION_JSON) // @Path("set-user-notifications/")
// @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON)
// @StatusCodes ({ // @Produces(MediaType.APPLICATION_JSON)
// @ResponseCode ( code = 200, condition = "Notification set Off or On correctly executed"), // @StatusCodes ({
// @ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) // @ResponseCode ( code = 200, condition = "Notification set Off or On correctly
// }) // executed"),
// @AuthorizationControl(allowedRoles={INFRASTRUCTURE_MANAGER_ROLE}, exception=AuthException.class) // @ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
// public Response setUserNotifications( // })
// @NotNull(message="input is missing") // @AuthorizationControl(allowedRoles={INFRASTRUCTURE_MANAGER_ROLE},
// @Valid // exception=AuthException.class)
// UserSetNotificationBean setting) throws ValidationException{ // public Response setUserNotifications(
// // @NotNull(message="input is missing")
// Caller caller = AuthorizationProvider.instance.get(); // @Valid
// String context = ScopeProvider.instance.get(); // UserSetNotificationBean setting) throws ValidationException{
// ResponseBean responseBean = new ResponseBean(); //
// Status status = Status.OK; // Caller caller = AuthorizationProvider.instance.get();
// // String context = ScopeProvider.instance.get();
// // ResponseBean responseBean = new ResponseBean();
// try{ // Status status = Status.OK;
// String opExecutor = caller.getClient().getId(); //
// Boolean result = setUserNotificationsOnOff(setting.getUsername(), setting.isDisableNotification(), opExecutor); //
// String toReturn = "Could not set notifications"; // try{
// if (result) { // String opExecutor = caller.getClient().getId();
// toReturn = "Notifications have been set"; // Boolean result = setUserNotificationsOnOff(setting.getUsername(),
// toReturn += setting.isDisableNotification() ? " OFF (for 29 days unless re-enabled manually) ": " ON "; // setting.isDisableNotification(), opExecutor);
// toReturn += "for username=" + setting.getUsername(); // String toReturn = "Could not set notifications";
// } // if (result) {
// responseBean.setSuccess(true); // toReturn = "Notifications have been set";
// responseBean.setResult(toReturn); // toReturn += setting.isDisableNotification() ? " OFF (for 29 days unless
// // re-enabled manually) ": " ON ";
// } catch(Exception e){ // toReturn += "for username=" + setting.getUsername();
// logger.error("Unable to set user notification", e); // }
// responseBean.setSuccess(false); // responseBean.setSuccess(true);
// responseBean.setMessage(e.getMessage()); // responseBean.setResult(toReturn);
// status = Status.INTERNAL_SERVER_ERROR; //
// } // } catch(Exception e){
// // logger.error("Unable to set user notification", e);
// // responseBean.setSuccess(false);
// return Response.status(status).entity(responseBean).build(); // responseBean.setMessage(e.getMessage());
// } // status = Status.INTERNAL_SERVER_ERROR;
// }
//
//
// return Response.status(status).entity(responseBean).build();
// }
/** /**
* @deprecated * @deprecated
@ -230,45 +235,50 @@ public class Notifications {
* @throws IOException * @throws IOException
*/ */
private boolean isNotificationEnabled(String usernameToCheck) throws IOException { private boolean isNotificationEnabled(String usernameToCheck) throws IOException {
// MemcachedClient entries = new DistributedCacheClient().getMemcachedClient(); // MemcachedClient entries = new DistributedCacheClient().getMemcachedClient();
// String key = SocialUtils.DISABLED_USERS_NOTIFICATIONS_NAMESPACE+usernameToCheck; // String key =
// Boolean userEnabled = false; // SocialUtils.DISABLED_USERS_NOTIFICATIONS_NAMESPACE+usernameToCheck;
// if(entries.get(key) == null) // Boolean userEnabled = false;
// userEnabled = true; // if(entries.get(key) == null)
// entries.getConnection().shutdown(); // userEnabled = true;
// return userEnabled; // entries.getConnection().shutdown();
// return userEnabled;
return true; return true;
} }
// /** // /**
// * // *
// * @param username the user you want to disable or enable notifications (max 29 days) // * @param username the user you want to disable or enable notifications (max
// * @param callerId the username or clientid of the operation executor // 29 days)
// * @param disable true if you want to disable the notifications for this user // * @param callerId the username or clientid of the operation executor
// * @return true if the operation was performed // * @param disable true if you want to disable the notifications for this user
// * @throws IOException // * @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(); // private Boolean setUserNotificationsOnOff(String username, boolean disable,
// String key = SocialUtils.DISABLED_USERS_NOTIFICATIONS_NAMESPACE+username; // String callerId) throws IOException {
// OperationFuture<Boolean> result = null; // MemcachedClient entries = new DistributedCacheClient().getMemcachedClient();
// if (disable) { // String key = SocialUtils.DISABLED_USERS_NOTIFICATIONS_NAMESPACE+username;
// result = entries.set(key, SocialUtils.CACHING_TIME_TO_EXPIRATION, "op.ex:" + callerId); //operator executor is who silenced the user // OperationFuture<Boolean> result = null;
// } else { // if (disable) {
// result = entries.delete(key); // result = entries.set(key, SocialUtils.CACHING_TIME_TO_EXPIRATION, "op.ex:" +
// } // callerId); //operator executor is who silenced the user
// try { // } else {
// boolean res = result.getStatus().isSuccess(); // result = entries.delete(key);
// entries.getConnection().shutdown(); // }
// return res; // try {
// } catch (Exception e) { // boolean res = result.getStatus().isSuccess();
// entries.getConnection().shutdown(); // entries.getConnection().shutdown();
// e.printStackTrace(); // return res;
// } // } catch (Exception e) {
// return null; // entries.getConnection().shutdown();
// } // e.printStackTrace();
// }
// return null;
// }
/** /**
* Send a JOB notification to a given recipient * Send a JOB notification to a given recipient
*
* @param job The job bean * @param job The job bean
* @return * @return
* @throws ValidationException * @throws ValidationException
@ -277,34 +287,36 @@ public class Notifications {
@Path("notify-job-status/") @Path("notify-job-status/")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Notification is sent correctly"), @ResponseCode(code = 200, condition = "Notification is sent correctly"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response notifyJobStatus( public Response notifyJobStatus(
@NotNull(message="input is missing") @NotNull(message = "input is missing") @Valid JobNotificationBean job) throws ValidationException {
@Valid
JobNotificationBean job) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get(); String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
String appQualifier = caller.getClient().getId(); String appQualifier = caller.getClient().getId();
logger.debug("Received request from app " + appQualifier + " to notify job status described by bean " + job); logger.debug("Received request from app " + appQualifier + " to notify job status described by bean " + job);
try{ try {
String recipient = job.getRecipient(); String recipient = job.getRecipient();
GCubeUser userRecipient = UserManagerWSBuilder.getInstance().getUserManager().getUserByUsername(recipient); GCubeUser userRecipient = UserManagerWSBuilder.getInstance().getUserManager().getUserByUsername(recipient);
GenericItemBean recipientBean = new GenericItemBean(userRecipient.getUsername(), userRecipient.getUsername(), userRecipient.getFullname(), userRecipient.getUserAvatarURL()); 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 // notifications are sent by using the user allowed to use liferay's json apis
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(context); SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(context);
GCubeUser senderUser = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser()); GCubeUser senderUser = UserManagerWSBuilder.getInstance().getUserManager()
SocialNetworkingUser user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), senderUser.getFullname(), senderUser.getUserAvatarURL()); .getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser());
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, context, user); 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); RunningJob theJob = JobMapper.getJob(job);
@ -312,19 +324,19 @@ public class Notifications {
responseBean.setSuccess(true); responseBean.setSuccess(true);
responseBean.setResult("Notification thread started"); responseBean.setResult("Notification thread started");
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to send job notification", e); logger.error("Unable to send job notification", e);
responseBean.setSuccess(false); responseBean.setSuccess(false);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
} }
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
/** /**
* Send a Catalogue notification to a given user * Send a Catalogue notification to a given user
*
* @param event * @param event
* @return * @return
* @throws ValidationException * @throws ValidationException
@ -333,87 +345,89 @@ public class Notifications {
@Path("catalogue/") @Path("catalogue/")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Catalogue Notification is sent correctly"), @ResponseCode(code = 200, condition = "Catalogue Notification is sent correctly"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response catalogue( public Response catalogue(
@NotNull(message="input is missing") @NotNull(message = "input is missing") @Valid CatalogueEvent event)
@Valid throws ValidationException, UserManagementSystemException, UserRetrievalFault {
CatalogueEvent event) throws ValidationException, UserManagementSystemException, UserRetrievalFault{
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
UserManager um = UserManagerWSBuilder.getInstance().getUserManager(); UserManager um = UserManagerWSBuilder.getInstance().getUserManager();
GCubeUser senderUser = null; GCubeUser senderUser = null;
SocialNetworkingUser user = 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) // 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 username = null;
String fullName = ""; String fullName = "";
logger.debug("Catalogue Notification called by " + caller.getClient().getId() + " isUser?"+TokensUtils.isUserToken(caller)); logger.debug("Catalogue Notification called by " + caller.getClient().getId() + " isUser?"
if(!TokensUtils.isUserToken(caller)){ + TokensUtils.isUserToken(caller));
GCubeUser jarvis = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser()); if (!TokensUtils.isUserToken(caller)) {
GCubeUser jarvis = UserManagerWSBuilder.getInstance().getUserManager()
.getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser());
SecurityTokenProvider.instance.set(LiferayJSONWsCredentials.getSingleton().getNotifierUserToken()); SecurityTokenProvider.instance.set(LiferayJSONWsCredentials.getSingleton().getNotifierUserToken());
username = jarvis.getUsername(); username = jarvis.getUsername();
fullName = caller.getClient().getId().replace("service-account-", ""); // the actual name of the IAM Client fullName = caller.getClient().getId().replace("service-account-", ""); // the actual name of the IAM Client
senderUser = um.getUserByUsername(username); senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName, senderUser.getUserAvatarURL()); user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName,
}else{ senderUser.getUserAvatarURL());
} else {
username = caller.getClient().getId(); username = caller.getClient().getId();
senderUser = um.getUserByUsername(username); senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), senderUser.getFullname(), senderUser.getUserAvatarURL()); user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), senderUser.getFullname(),
senderUser.getUserAvatarURL());
} }
String context = ScopeProvider.instance.get(); String context = ScopeProvider.instance.get();
logger.debug("catalogue notifications from user = " + username); logger.debug("catalogue notifications from user = " + username);
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
boolean deliveryResult = false; boolean deliveryResult = false;
try { try {
//logger.debug("catalogue notifications type is " + event.getType()); // logger.debug("catalogue notifications type is " + event.getType());
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(context); SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(context);
//logger.debug("social networking site is " + site.getName()); // logger.debug("social networking site is " + site.getName());
//logger.debug("context is " + context); // logger.debug("context is " + context);
//logger.debug("user is " + user.getUsername()); // logger.debug("user is " + user.getUsername());
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, context, user); NotificationsManager nm = new ApplicationNotificationsManager(
UserManagerWSBuilder.getInstance().getUserManager(), site, context, user);
String[] idsToNotify = event.getIdsToNotify(); String[] idsToNotify = event.getIdsToNotify();
if (! event.idsAsGroup()) { if (!event.idsAsGroup()) {
for (int i = 0; i < idsToNotify.length; i++) { for (int i = 0; i < idsToNotify.length; i++) {
String userIdToNotify = idsToNotify[i]; String userIdToNotify = idsToNotify[i];
if (isNotificationEnabled(userIdToNotify)) { if (isNotificationEnabled(userIdToNotify)) {
String username2Notify = null; String username2Notify = null;
try { try {
username2Notify = um.getUserByUsername(userIdToNotify).getUsername(); username2Notify = um.getUserByUsername(userIdToNotify).getUsername();
} } catch (Exception e) {
catch (Exception e) {
status = Status.BAD_REQUEST; status = Status.BAD_REQUEST;
logger.error("Username not found", e); logger.error("Username not found", e);
responseBean.setSuccess(false); responseBean.setSuccess(false);
responseBean.setMessage("Username not found, got: " + userIdToNotify); responseBean.setMessage("Username not found, got: " + userIdToNotify);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
//logger.debug("username2notify " + username2Notify); // logger.debug("username2notify " + username2Notify);
//logger.debug("type is " + CatalogueEventTypeMapper.getType(event.getType())); // logger.debug("type is " + CatalogueEventTypeMapper.getType(event.getType()));
//logger.debug("item id is " + event.getItemId()); // logger.debug("item id is " + event.getItemId());
//logger.debug("item text is " + event.getNotifyText()); // logger.debug("item text is " + event.getNotifyText());
//logger.debug("item url is " + event.getItemURL()); // logger.debug("item url is " + event.getItemURL());
deliveryResult = deliveryResult = nm.notifyCatalogueEvent(
nm.notifyCatalogueEvent( CatalogueEventTypeMapper.getType(event.getType()),
CatalogueEventTypeMapper.getType(event.getType()), username2Notify,
username2Notify, event.getItemId(),
event.getItemId(), event.getNotifyText(),
event.getNotifyText(), event.getItemURL());
event.getItemURL()); } else {
} Log.info("Notification disabled (admin) for user " + userIdToNotify + " will not notify");
else {
Log.info("Notification disabled (admin) for user "+userIdToNotify + " will not notify");
} }
} }
} else { //the ids are contexts } else { // the ids are contexts
for (int i = 0; i < idsToNotify.length; i++) { for (int i = 0; i < idsToNotify.length; i++) {
String contextId = idsToNotify[i]; String contextId = idsToNotify[i];
try { try {
@ -425,24 +439,25 @@ public class Notifications {
responseBean.setMessage("Not a VRE Context, only VREs are supported"); responseBean.setMessage("Not a VRE Context, only VREs are supported");
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} else { // it is a context and it is a valid VRE } else { // it is a context and it is a valid VRE
String[] userIdsToNotify = getUsernamesByContext(scope).toArray(new String[0]); //resolve the members String[] userIdsToNotify = getUsernamesByContext(scope).toArray(new String[0]); // resolve
// the
// members
for (int j = 0; j < userIdsToNotify.length; j++) { for (int j = 0; j < userIdsToNotify.length; j++) {
String userIdToNotify = userIdsToNotify[j]; String userIdToNotify = userIdsToNotify[j];
if (isNotificationEnabled(userIdToNotify)) { if (isNotificationEnabled(userIdToNotify)) {
deliveryResult = deliveryResult = nm.notifyCatalogueEvent(
nm.notifyCatalogueEvent( CatalogueEventTypeMapper.getType(event.getType()),
CatalogueEventTypeMapper.getType(event.getType()), userIdToNotify,
userIdToNotify, event.getItemId(),
event.getItemId(), event.getNotifyText(),
event.getNotifyText(), event.getItemURL());
event.getItemURL());
} else { } else {
Log.info("Notification disabled (admin) for user "+userIdToNotify + " will not notify"); Log.info("Notification disabled (admin) for user " + userIdToNotify
+ " will not notify");
} }
} }
} }
} } catch (IllegalArgumentException e) {
catch(IllegalArgumentException e) {
status = Status.BAD_REQUEST; status = Status.BAD_REQUEST;
logger.error("Context not valid", e); logger.error("Context not valid", e);
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -451,7 +466,7 @@ public class Notifications {
} }
} }
} }
} catch(Exception e){ } catch (Exception e) {
logger.error("Unable to send job notification", e); logger.error("Unable to send job notification", e);
responseBean.setSuccess(false); responseBean.setSuccess(false);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
@ -464,7 +479,8 @@ public class Notifications {
responseBean.setResult(new Boolean(true)); responseBean.setResult(new Boolean(true));
} else { } else {
responseBean.setSuccess(false); responseBean.setSuccess(false);
responseBean.setMessage("An error occurred between this service and Cassandra DB, notification not delivered correctly"); responseBean.setMessage(
"An error occurred between this service and Cassandra DB, notification not delivered correctly");
responseBean.setResult(new Boolean(false)); responseBean.setResult(new Boolean(false));
} }
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
@ -472,6 +488,7 @@ public class Notifications {
/** /**
* Send a Workspace notification to a given user * Send a Workspace notification to a given user
*
* @param event * @param event
* @return * @return
* @throws ValidationException * @throws ValidationException
@ -480,17 +497,15 @@ public class Notifications {
@Path("workspace/") @Path("workspace/")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Workspace Notification is sent correctly"), @ResponseCode(code = 200, condition = "Workspace Notification is sent correctly"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response workspace( public Response workspace(
@NotNull(message="input is missing") @NotNull(message = "input is missing") @Valid WorkspaceEvent event) throws ValidationException {
@Valid
WorkspaceEvent event) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get(); String context = ScopeProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
logger.debug("workspace notifications from = " + username); logger.debug("workspace notifications from = " + username);
@ -504,44 +519,48 @@ public class Notifications {
logger.debug("workspace notifications type is " + event.getType()); logger.debug("workspace notifications type is " + event.getType());
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(context); SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(context);
UserManager um = UserManagerWSBuilder.getInstance().getUserManager(); UserManager um = UserManagerWSBuilder.getInstance().getUserManager();
logger.debug("Workspace Notification called by " + caller.getClient().getId() + " isUser?"+TokensUtils.isUserToken(caller)); logger.debug("Workspace Notification called by " + caller.getClient().getId() + " isUser?"
if(!TokensUtils.isUserToken(caller)){ + TokensUtils.isUserToken(caller));
GCubeUser jarvis = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser()); if (!TokensUtils.isUserToken(caller)) {
GCubeUser jarvis = UserManagerWSBuilder.getInstance().getUserManager()
.getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser());
SecurityTokenProvider.instance.set(LiferayJSONWsCredentials.getSingleton().getNotifierUserToken()); SecurityTokenProvider.instance.set(LiferayJSONWsCredentials.getSingleton().getNotifierUserToken());
username = jarvis.getUsername(); username = jarvis.getUsername();
fullName = caller.getClient().getId().replace("service-account-", ""); // the actual name of the IAM Client fullName = caller.getClient().getId().replace("service-account-", ""); // the actual name of the IAM
// Client
senderUser = um.getUserByUsername(username); senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName, senderUser.getUserAvatarURL()); user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName,
}else{ senderUser.getUserAvatarURL());
} else {
username = caller.getClient().getId(); username = caller.getClient().getId();
senderUser = um.getUserByUsername(username); senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), senderUser.getFullname(), senderUser.getUserAvatarURL()); user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(),
senderUser.getFullname(), senderUser.getUserAvatarURL());
} }
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, context, user); NotificationsManager nm = new ApplicationNotificationsManager(
UserManagerWSBuilder.getInstance().getUserManager(), site, context, user);
String[] idsToNotify = event.getIdsToNotify(); String[] idsToNotify = event.getIdsToNotify();
if (! event.idsAsGroup()) { if (!event.idsAsGroup()) {
for (int i = 0; i < idsToNotify.length; i++) { for (int i = 0; i < idsToNotify.length; i++) {
String userIdToNotify = idsToNotify[i]; String userIdToNotify = idsToNotify[i];
if (isNotificationEnabled(userIdToNotify)) { if (isNotificationEnabled(userIdToNotify)) {
String username2Notify = ""; String username2Notify = "";
try { try {
username2Notify = um.getUserByUsername(userIdToNotify).getUsername(); username2Notify = um.getUserByUsername(userIdToNotify).getUsername();
} } catch (Exception e) {
catch (Exception e) {
status = Status.NOT_ACCEPTABLE; status = Status.NOT_ACCEPTABLE;
logger.error("Username not found", e); logger.error("Username not found", e);
responseBean.setSuccess(false); responseBean.setSuccess(false);
responseBean.setMessage("Username not found, received: " + userIdToNotify); responseBean.setMessage("Username not found, received: " + userIdToNotify);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
deliveryResult = notifyWorkspaceEvent(event, nm, username2Notify); deliveryResult = notifyWorkspaceEvent(event, nm, username2Notify);
} } else {
else { Log.info("Notification disabled (admin) for user " + userIdToNotify + " will not notify");
Log.info("Notification disabled (admin) for user "+userIdToNotify + " will not notify");
} }
} }
} else { //the ids are contexts } else { // the ids are contexts
for (int i = 0; i < idsToNotify.length; i++) { for (int i = 0; i < idsToNotify.length; i++) {
String contextId = idsToNotify[i]; String contextId = idsToNotify[i];
try { try {
@ -553,18 +572,20 @@ public class Notifications {
responseBean.setMessage("Not a VRE Context, only VREs are supported"); responseBean.setMessage("Not a VRE Context, only VREs are supported");
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} else { // it is a context and it is a valid VRE } else { // it is a context and it is a valid VRE
String[] userIdsToNotify = getUsernamesByContext(scope).toArray(new String[0]); //resolve the members String[] userIdsToNotify = getUsernamesByContext(scope).toArray(new String[0]); // resolve
// the
// members
for (int j = 0; j < userIdsToNotify.length; j++) { for (int j = 0; j < userIdsToNotify.length; j++) {
String userIdToNotify = userIdsToNotify[j]; String userIdToNotify = userIdsToNotify[j];
if (isNotificationEnabled(userIdToNotify)) if (isNotificationEnabled(userIdToNotify))
deliveryResult = notifyWorkspaceEvent(event, nm, userIdToNotify); deliveryResult = notifyWorkspaceEvent(event, nm, userIdToNotify);
else { else {
Log.info("Notification disabled (admin) for user "+userIdToNotify + " will not notify"); Log.info("Notification disabled (admin) for user " + userIdToNotify
+ " will not notify");
} }
} }
} }
} } catch (IllegalArgumentException e) {
catch(IllegalArgumentException e) {
status = Status.BAD_REQUEST; status = Status.BAD_REQUEST;
logger.error("Context not valid", e); logger.error("Context not valid", e);
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -573,7 +594,7 @@ public class Notifications {
} }
} }
} }
} catch(Exception e){ } catch (Exception e) {
logger.error("Unable to send job notification", e); logger.error("Unable to send job notification", e);
responseBean.setSuccess(false); responseBean.setSuccess(false);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
@ -586,11 +607,13 @@ public class Notifications {
responseBean.setResult(new Boolean(true)); responseBean.setResult(new Boolean(true));
} else { } else {
responseBean.setSuccess(false); responseBean.setSuccess(false);
responseBean.setMessage("An error occurred between this service and Cassandra DB, notification not delivered correctly"); responseBean.setMessage(
"An error occurred between this service and Cassandra DB, notification not delivered correctly");
responseBean.setResult(new Boolean(false)); responseBean.setResult(new Boolean(false));
} }
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
/** /**
* *
* @param event * @param event
@ -603,54 +626,66 @@ public class Notifications {
switch (event.getType()) { switch (event.getType()) {
case ITEM_NEW: { case ITEM_NEW: {
AddedItemEvent itemBean = (AddedItemEvent) event; AddedItemEvent itemBean = (AddedItemEvent) event;
return nm.notifyAddedItem(idToNotify, WorkspaceItemMapper.getFileItem(itemBean.getItem()), WorkspaceItemMapper.getSharedFolder(itemBean.getItem().getParent())); return nm.notifyAddedItem(idToNotify, WorkspaceItemMapper.getFileItem(itemBean.getItem()),
WorkspaceItemMapper.getSharedFolder(itemBean.getItem().getParent()));
} }
case ITEM_UPDATE: { case ITEM_UPDATE: {
UpdatedItemEvent itemBean = (UpdatedItemEvent) event; UpdatedItemEvent itemBean = (UpdatedItemEvent) event;
return nm.notifyUpdatedItem(idToNotify, WorkspaceItemMapper.getFileItem(itemBean.getItem()), WorkspaceItemMapper.getSharedFolder(itemBean.getItem().getParent())); return nm.notifyUpdatedItem(idToNotify, WorkspaceItemMapper.getFileItem(itemBean.getItem()),
WorkspaceItemMapper.getSharedFolder(itemBean.getItem().getParent()));
} }
case ITEM_DELETE: { case ITEM_DELETE: {
DeletedItemEvent itemBean = (DeletedItemEvent) event; DeletedItemEvent itemBean = (DeletedItemEvent) event;
return nm.notifyRemovedItem(idToNotify, itemBean.getItemName(), WorkspaceItemMapper.getSharedFolder(itemBean.getFolder())); return nm.notifyRemovedItem(idToNotify, itemBean.getItemName(),
WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()));
} }
case FOLDER_SHARE: { case FOLDER_SHARE: {
SharedFolderEvent itemBean = (SharedFolderEvent) event; SharedFolderEvent itemBean = (SharedFolderEvent) event;
return nm.notifyFolderSharing(idToNotify, WorkspaceItemMapper.getSharedFolder(itemBean.getFolder())); return nm.notifyFolderSharing(idToNotify,
WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()));
} }
case FOLDER_UNSHARE: { case FOLDER_UNSHARE: {
UnsharedFolderEvent itemBean = (UnsharedFolderEvent) event; UnsharedFolderEvent itemBean = (UnsharedFolderEvent) event;
return nm.notifyFolderUnsharing(idToNotify, itemBean.getUnsharedFolderId(), itemBean.getUnsharedFolderName()); return nm.notifyFolderUnsharing(idToNotify, itemBean.getUnsharedFolderId(),
itemBean.getUnsharedFolderName());
} }
case FOLDER_RENAME: { case FOLDER_RENAME: {
RenamedFolderEvent itemBean = (RenamedFolderEvent) event; RenamedFolderEvent itemBean = (RenamedFolderEvent) event;
return nm.notifyFolderRenaming(idToNotify, itemBean.getPreviousName(), itemBean.getNewName(), itemBean.getRenamedFolderId()); return nm.notifyFolderRenaming(idToNotify, itemBean.getPreviousName(), itemBean.getNewName(),
itemBean.getRenamedFolderId());
} }
case FOLDER_ADMIN_UPGRADE: { case FOLDER_ADMIN_UPGRADE: {
FolderAdminUpgradeEvent itemBean = (FolderAdminUpgradeEvent) event; FolderAdminUpgradeEvent itemBean = (FolderAdminUpgradeEvent) event;
return nm.notifyAdministratorUpgrade(idToNotify, WorkspaceItemMapper.getSharedFolder(itemBean.getFolder())); return nm.notifyAdministratorUpgrade(idToNotify,
WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()));
} }
case FOLDER_ADMIN_DOWNGRADE: { case FOLDER_ADMIN_DOWNGRADE: {
FolderAdminDowngradeEvent itemBean = (FolderAdminDowngradeEvent) event; FolderAdminDowngradeEvent itemBean = (FolderAdminDowngradeEvent) event;
return nm.notifyAdministratorDowngrade(idToNotify, WorkspaceItemMapper.getSharedFolder(itemBean.getFolder())); return nm.notifyAdministratorDowngrade(idToNotify,
WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()));
} }
case FOLDER_ADDEDUSER: { case FOLDER_ADDEDUSER: {
FolderAddedUserEvent itemBean = (FolderAddedUserEvent) event; FolderAddedUserEvent itemBean = (FolderAddedUserEvent) event;
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
return nm.notifyFolderAddedUsers(idToNotify, WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()), itemBean.getNewAddedUserIds(), userManager); return nm.notifyFolderAddedUsers(idToNotify,
WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()), itemBean.getNewAddedUserIds(),
userManager);
} }
case FOLDER_REMOVEDUSER: { case FOLDER_REMOVEDUSER: {
FolderRemovedUserEvent itemBean = (FolderRemovedUserEvent) event; FolderRemovedUserEvent itemBean = (FolderRemovedUserEvent) event;
return nm.notifyFolderRemovedUser(idToNotify, WorkspaceItemMapper.getSharedFolder(itemBean.getFolder())); return nm.notifyFolderRemovedUser(idToNotify,
WorkspaceItemMapper.getSharedFolder(itemBean.getFolder()));
} }
default: default:
break; break;
} }
} catch(Exception e){ } catch (Exception e) {
logger.error("Unable to send job notification", e); logger.error("Unable to send job notification", e);
return false; return false;
} }
return false; return false;
} }
/** /**
* *
* @param context * @param context
@ -670,13 +705,13 @@ public class Notifications {
UsersCache cache = UsersCache.getSingleton(); UsersCache cache = UsersCache.getSingleton();
for (Long userId : userIds) { for (Long userId : userIds) {
if(cache.getUser(userId) == null){ if (cache.getUser(userId) == null) {
GCubeUser theUser = userManager.getUserById(userId); GCubeUser theUser = userManager.getUserById(userId);
if(theUser != null){ if (theUser != null) {
usernames.add(theUser.getUsername()); usernames.add(theUser.getUsername());
cache.pushEntry(userId, theUser); cache.pushEntry(userId, theUser);
} }
}else } else
usernames.add(cache.getUser(userId).getUsername()); usernames.add(cache.getUser(userId).getUsername());
} }
return usernames; return usernames;

View File

@ -33,31 +33,34 @@ import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResponseCode; import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes; import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/** /**
* REST interface for the social service (people). Used by OAUTH 2.0 apps/users. * REST interface for the social service (people). Used by OAUTH 2.0 apps/users.
*/ */
@RequestHeaders ({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), @RequestHeader(name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json") @RequestHeader(name = "Content-Type", description = "application/json")
}) })
@Path("2/people") @Path("2/people")
public class People { public class People {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(People.class); 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" } } * @responseExample application/json { "success" : true, "message" : null,
* @return the user's profile. The user in this case is the one bound to the token * "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) @Produces(MediaType.APPLICATION_JSON)
@GET @GET
@Path("profile") @Path("profile")
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successful retrieval of user's profile, reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getProfile(){ public Response getProfile() {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
@ -66,13 +69,13 @@ public class People {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
if(!TokensUtils.isUserToken(caller)){ if (!TokensUtils.isUserToken(caller)) {
status = Status.FORBIDDEN; status = Status.FORBIDDEN;
responseBean.setMessage("User's information can only be retrieved through a user token"); 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"); logger.warn("Trying to access users method via a token different than 'user-token' is not allowed");
}else{ } else {
try{ try {
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager(); RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager();
GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager(); GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
@ -83,7 +86,8 @@ public class People {
toReturn.put("avatar", user.getUserAvatarURL()); toReturn.put("avatar", user.getUserAvatarURL());
toReturn.put("fullname", user.getFullname()); toReturn.put("fullname", user.getFullname());
toReturn.put("context", scope); toReturn.put("context", scope);
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(user.getUserId(), groupManager.getGroupIdFromInfrastructureScope(scope)); List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(user.getUserId(),
groupManager.getGroupIdFromInfrastructureScope(scope));
List<String> rolesNames = new ArrayList<String>(); List<String> rolesNames = new ArrayList<String>();
for (GCubeRole gCubeRole : roles) { for (GCubeRole gCubeRole : roles) {
rolesNames.add(gCubeRole.getRoleName()); rolesNames.add(gCubeRole.getRoleName());
@ -92,7 +96,7 @@ public class People {
responseBean.setResult(toReturn); responseBean.setResult(toReturn);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve user's profile", e); logger.error("Unable to retrieve user's profile", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;

View File

@ -1,9 +1,7 @@
package org.gcube.portal.social.networking.ws.methods.v2; package org.gcube.portal.social.networking.ws.methods.v2;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.ValidationException; import javax.validation.ValidationException;
@ -19,13 +17,16 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status; 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.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller; import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.server.DatabookStore; import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.portal.databook.shared.*; import org.gcube.portal.databook.shared.ApplicationProfile;
import org.gcube.portal.databook.shared.Attachment;
import org.gcube.portal.databook.shared.Post;
import org.gcube.portal.databook.shared.PostWithAttachment;
import org.gcube.portal.databook.shared.RangePosts;
import org.gcube.portal.databook.shared.ex.ColumnNameNotFoundException; import org.gcube.portal.databook.shared.ex.ColumnNameNotFoundException;
import org.gcube.portal.databook.shared.ex.FeedIDNotFoundException; import org.gcube.portal.databook.shared.ex.FeedIDNotFoundException;
import org.gcube.portal.databook.shared.ex.FeedTypeNotFoundException; import org.gcube.portal.databook.shared.ex.FeedTypeNotFoundException;
@ -45,12 +46,13 @@ import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/** /**
* REST interface for the social networking library (posts). * REST interface for the social networking library (posts).
*
* @author Ahmed Ibrahim ISTI-CNR * @author Ahmed Ibrahim ISTI-CNR
*/ */
@Path("2/posts") @Path("2/posts")
@RequestHeaders ({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), @RequestHeader(name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json") @RequestHeader(name = "Content-Type", description = "application/json")
}) })
public class Posts { public class Posts {
@ -58,7 +60,8 @@ public class Posts {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Posts.class); 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" * Retrieve posts of the auth token's owner, and allow to filter them by time"
*
* @param timeInMillis The reference time since when retrieving posts * @param timeInMillis The reference time since when retrieving posts
* @return the posts * @return the posts
* @throws ValidationException * @throws ValidationException
@ -66,14 +69,13 @@ public class Posts {
@GET @GET
@Path("get-posts-user-since/") @Path("get-posts-user-since/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successful retrieval of posts, reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getRecentPostsByUserAndDate( public Response getRecentPostsByUserAndDate(
@QueryParam("time") @Min(value = 0, message="time cannot be negative") @QueryParam("time") @Min(value = 0, message = "time cannot be negative") long timeInMillis)
long timeInMillis throws ValidationException {
) throws ValidationException{
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
@ -82,16 +84,17 @@ public class Posts {
String username = caller.getClient().getId(); String username = caller.getClient().getId();
List<Post> posts = null; List<Post> posts = null;
try{ try {
logger.debug("Retrieving post for user id " + username + " and reference time " + timeInMillis); logger.debug("Retrieving post for user id " + username + " and reference time " + timeInMillis);
posts = CassandraConnection.getInstance().getDatabookStore().getRecentPostsByUserAndDate(username, timeInMillis); posts = CassandraConnection.getInstance().getDatabookStore().getRecentPostsByUserAndDate(username,
timeInMillis);
Filters.filterPostsPerContext(posts, context); Filters.filterPostsPerContext(posts, context);
Filters.hideSensitiveInformation(posts, caller.getClient().getId()); Filters.hideSensitiveInformation(posts, caller.getClient().getId());
responseBean.setResult(posts); responseBean.setResult(posts);
responseBean.setMessage(""); responseBean.setMessage("");
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such posts.", e); logger.error("Unable to retrieve such posts.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -101,17 +104,18 @@ public class Posts {
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
/** /**
* Retrieve all user's posts * Retrieve all user's posts
* @return all posts of the auth token's owner in the context identified by the token *
* @return all posts of the auth token's owner in the context identified by the
* token
*/ */
@GET @GET
@Path("get-posts-user/") @Path("get-posts-user/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successful retrieval of posts, reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getAllPostsByUser() { public Response getAllPostsByUser() {
@ -121,7 +125,7 @@ public class Posts {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
List<Post> posts = null; List<Post> posts = null;
try{ try {
logger.debug("Retrieving posts for user with id " + username); logger.debug("Retrieving posts for user with id " + username);
posts = CassandraConnection.getInstance().getDatabookStore().getAllPostsByUser(username); posts = CassandraConnection.getInstance().getDatabookStore().getAllPostsByUser(username);
Filters.filterPostsPerContext(posts, context); Filters.filterPostsPerContext(posts, context);
@ -129,7 +133,7 @@ public class Posts {
responseBean.setResult(posts); responseBean.setResult(posts);
responseBean.setMessage(""); responseBean.setMessage("");
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such feeds.", e); logger.error("Unable to retrieve such feeds.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -141,14 +145,16 @@ public class Posts {
/** /**
* Retrieve a post by id * Retrieve a post by id
* @return the post if the post id belongs to a post in the context identified by the token *
* @return the post if the post id belongs to a post in the context identified
* by the token
*/ */
@GET @GET
@Path("get-post/") @Path("get-post/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successful retrieval of posts, reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getPost(@QueryParam("id") String id) { public Response getPost(@QueryParam("id") String id) {
String context = ScopeProvider.instance.get(); String context = ScopeProvider.instance.get();
@ -156,11 +162,11 @@ public class Posts {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
List<Post> posts = new ArrayList<>(); List<Post> posts = new ArrayList<>();
try{ try {
logger.debug("Retrieving post with id " + id); logger.debug("Retrieving post with id " + id);
try { try {
posts.add(CassandraConnection.getInstance().getDatabookStore().readPost(id)); posts.add(CassandraConnection.getInstance().getDatabookStore().readPost(id));
} catch(FeedIDNotFoundException e){ } catch (FeedIDNotFoundException e) {
responseBean.setMessage("The post with id " + id + " does not exist in context " + context); responseBean.setMessage("The post with id " + id + " does not exist in context " + context);
responseBean.setSuccess(false); responseBean.setSuccess(false);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
@ -176,7 +182,7 @@ public class Posts {
responseBean.setResult(posts.get(0)); responseBean.setResult(posts.get(0));
responseBean.setMessage(""); responseBean.setMessage("");
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such post.", e); logger.error("Unable to retrieve such post.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -188,23 +194,23 @@ public class Posts {
/** /**
* Retrieve a given quantity of latest user's posts * Retrieve a given quantity of latest user's posts
*
* @param quantity the number of latest post to get * @param quantity the number of latest post to get
* @pathExample /get-posts-user-quantity?quantity=10 * @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) * @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 * @throws ValidationException
*/ */
@GET @GET
@Path("get-posts-user-quantity/") @Path("get-posts-user-quantity/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successful retrieval of posts, reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getQuantityPostsByUser( public Response getQuantityPostsByUser(
@DefaultValue("10") @DefaultValue("10") @QueryParam("quantity") @Min(value = 0, message = "quantity cannot be negative") int quantity)
@QueryParam("quantity") throws ValidationException {
@Min(value=0, message="quantity cannot be negative")
int quantity) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
@ -215,23 +221,24 @@ public class Posts {
List<Post> posts = new ArrayList<>(); List<Post> posts = new ArrayList<>();
// if quantity is zero, just return an empty list // if quantity is zero, just return an empty list
if(quantity == 0){ if (quantity == 0) {
responseBean.setSuccess(true); responseBean.setSuccess(true);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
try{ try {
logger.debug("getRecentPostsByUser first, posts made by user " + username); logger.debug("getRecentPostsByUser first, posts made by user " + username);
posts = CassandraConnection.getInstance().getDatabookStore().getAllPostsByUser(username); posts = CassandraConnection.getInstance().getDatabookStore().getAllPostsByUser(username);
if (posts != null) if (posts != null)
logger.debug("got " + posts.size() + " posts"); logger.debug("got " + posts.size() + " posts");
logger.debug("Retrieving last " + quantity + " posts made by user " + username + " in context = "+context); logger.debug(
"Retrieving last " + quantity + " posts made by user " + username + " in context = " + context);
Filters.filterPostsPerContext(posts, context); Filters.filterPostsPerContext(posts, context);
quantity = (quantity > posts.size()) ? posts.size() : quantity; quantity = (quantity > posts.size()) ? posts.size() : quantity;
posts = posts.subList(0, quantity); posts = posts.subList(0, quantity);
Filters.hideSensitiveInformation(posts, caller.getClient().getId()); Filters.hideSensitiveInformation(posts, caller.getClient().getId());
responseBean.setResult(posts); responseBean.setResult(posts);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such posts.", e); logger.error("Unable to retrieve such posts.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -242,6 +249,7 @@ public class Posts {
/** /**
* Create a new user post having as owner the auth token's owner * Create a new user post having as owner the auth token's owner
*
* @param post The post to be written * @param post The post to be written
* @return * @return
* @throws ValidationException * @throws ValidationException
@ -250,14 +258,12 @@ public class Posts {
@Path("write-post-user") @Path("write-post-user")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 201, condition = "Successfull created, the new post is reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response writePostUser( public Response writePostUser(
@NotNull(message="Post to write is missing") @NotNull(message = "Post to write is missing") @Valid PostInputBean post) throws ValidationException {
@Valid
PostInputBean post) throws ValidationException{
logger.debug("Request of writing a feed coming from user " + post); logger.debug("Request of writing a feed coming from user " + post);
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
@ -276,12 +282,11 @@ public class Posts {
boolean enableNotification = post.isEnablenotification(); boolean enableNotification = post.isEnablenotification();
// convert enablenotification parameter // convert enablenotification parameter
if(enableNotification) if (enableNotification)
logger.debug("Enable notification for this user post."); logger.debug("Enable notification for this user post.");
else else
logger.debug("Disable notification for this user post."); logger.debug("Disable notification for this user post.");
// try to share // try to share
logger.debug("Trying to share user post..."); logger.debug("Trying to share user post...");
Post res = SocialUtils.shareUserUpdate( Post res = SocialUtils.shareUserUpdate(
@ -293,10 +298,9 @@ public class Posts {
previewHost, previewHost,
previewUrl, previewUrl,
httpImageUrl, httpImageUrl,
enableNotification enableNotification);
);
if(res != null){ if (res != null) {
logger.debug("Post correctly written by user " + username); logger.debug("Post correctly written by user " + username);
responseBean.setResult(res); responseBean.setResult(res);
responseBean.setSuccess(true); responseBean.setSuccess(true);
@ -314,15 +318,17 @@ public class Posts {
/** /**
* Retrieve the application's posts * Retrieve the application's posts
* @return the application (IAM Client) posts belonging to the token's owner (i.e., an application)" *
* @return the application (IAM Client) posts belonging to the token's owner
* (i.e., an application)"
*/ */
@GET @GET
@Path("get-posts-app/") @Path("get-posts-app/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successfull created, the new post is reported in the 'result' field of the returned object"), @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 = 403, condition = "\"There is no application profile with such token"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getAllPostsByApp() { public Response getAllPostsByApp() {
@ -334,7 +340,7 @@ public class Posts {
// check if the token actually matches an application // check if the token actually matches an application
ApplicationProfile appProfile = SocialUtils.getProfileFromInfrastrucure(appId, context); ApplicationProfile appProfile = SocialUtils.getProfileFromInfrastrucure(appId, context);
if(appProfile == null){ if (appProfile == null) {
logger.error("The given token is not belonging to an application!!!"); logger.error("The given token is not belonging to an application!!!");
status = Status.FORBIDDEN; status = Status.FORBIDDEN;
@ -343,7 +349,7 @@ public class Posts {
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
try{ try {
logger.debug("Retrieving posts for app with id " + appId); logger.debug("Retrieving posts for app with id " + appId);
List<Post> feeds = CassandraConnection.getInstance().getDatabookStore().getAllPostsByApp(appId); List<Post> feeds = CassandraConnection.getInstance().getDatabookStore().getAllPostsByApp(appId);
@ -351,7 +357,7 @@ public class Posts {
responseBean.setSuccess(true); responseBean.setSuccess(true);
responseBean.setResult(feeds); responseBean.setResult(feeds);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such feeds.", e); logger.error("Unable to retrieve such feeds.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
@ -364,7 +370,10 @@ public class Posts {
} }
/** /**
* 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 * 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 * @param post The post to be written
* @return * @return
*/ */
@ -372,15 +381,13 @@ public class Posts {
@Path("write-post-app") @Path("write-post-app")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successfull created, the new post is reported in the 'result' field of the returned object"), @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 = 403, condition = "\"There is no application profile with such token"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response writePostApp( public Response writePostApp(
@NotNull(message="Post to write is null") @NotNull(message = "Post to write is null") @Valid PostInputBean post) {
@Valid
PostInputBean post){
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String appId = caller.getClient().getId(); String appId = caller.getClient().getId();
@ -393,7 +400,7 @@ public class Posts {
// check if the token actually matches an application profile // check if the token actually matches an application profile
ApplicationProfile appProfile = SocialUtils.getProfileFromInfrastrucure(appId, context); ApplicationProfile appProfile = SocialUtils.getProfileFromInfrastrucure(appId, context);
if(appProfile == null){ if (appProfile == null) {
logger.error("The given token doesn't belong to an application!!!"); logger.error("The given token doesn't belong to an application!!!");
responseBean.setSuccess(false); responseBean.setSuccess(false);
responseBean.setMessage(ErrorMessages.NOT_APP_TOKEN); responseBean.setMessage(ErrorMessages.NOT_APP_TOKEN);
@ -410,7 +417,7 @@ public class Posts {
String params = post.getParams(); String params = post.getParams();
// convert enablenotification parameter // convert enablenotification parameter
if(enableNotification) if (enableNotification)
logger.debug("Enable notification for this application post."); logger.debug("Enable notification for this application post.");
else else
logger.debug("Disable notification for this application post."); logger.debug("Disable notification for this application post.");
@ -424,10 +431,9 @@ public class Posts {
httpImageUrl, httpImageUrl,
appProfile, appProfile,
caller, caller,
enableNotification enableNotification);
);
if(written != null){ if (written != null) {
responseBean.setResult(written); responseBean.setResult(written);
responseBean.setSuccess(true); responseBean.setSuccess(true);
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
@ -447,9 +453,9 @@ public class Posts {
@GET @GET
@Path("get-posts-vre/") @Path("get-posts-vre/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 201, condition = "Sccessfull retrieved posts, they are reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getAllPostsByVRE() { public Response getAllPostsByVRE() {
@ -458,12 +464,12 @@ public class Posts {
logger.debug("Retrieving all posts coming from vre = " + context); logger.debug("Retrieving all posts coming from vre = " + context);
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
try{ try {
List<Post> posts = CassandraConnection.getInstance().getDatabookStore().getAllPostsByVRE(context); List<Post> posts = CassandraConnection.getInstance().getDatabookStore().getAllPostsByVRE(context);
Filters.hideSensitiveInformation(posts, caller.getClient().getId()); Filters.hideSensitiveInformation(posts, caller.getClient().getId());
responseBean.setResult(posts); responseBean.setResult(posts);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve posts for vre = " + context, e); logger.error("Unable to retrieve posts for vre = " + context, e);
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
responseBean.setMessage(e.toString()); responseBean.setMessage(e.toString());
@ -474,13 +480,18 @@ public class Posts {
} }
/** /**
* return the most recent posts for this vre up to quantity param and the last index of the posts in the timeline * return the most recent posts for this vre up to quantity param and the last
* lastReturnedPostTimelineIndex is useful to know from where to start the range the next time you ask, because there are deletions * 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 from the range start (most recent feeds for this vre) has to be
* @param quantity the number of most recent feeds for this vre starting from "from" param * 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 * @pathExample /get-recent-posts-vre-by-range?from=1&quantity=10
* @return a <class>RangePosts</class> containing of most recent feeds for this vre * @return a <class>RangePosts</class> containing of most recent feeds for this
* vre
* @throws FeedTypeNotFoundException * @throws FeedTypeNotFoundException
* @throws PrivacyLevelTypeNotFoundException * @throws PrivacyLevelTypeNotFoundException
* @throws ColumnNameNotFoundException * @throws ColumnNameNotFoundException
@ -488,29 +499,27 @@ public class Posts {
@GET @GET
@Path("get-recent-posts-vre-by-range/") @Path("get-recent-posts-vre-by-range/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 201, condition = "Sccessfull retrieved posts, they are reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getRecentPostsByVREAndRange( public Response getRecentPostsByVREAndRange(
@QueryParam("from") @QueryParam("from") @Min(value = 1, message = "from cannot be negative") int from,
@Min(value=1, message="from cannot be negative") @QueryParam("quantity") @Min(value = 1, message = "quantity cannot be negative") int quantity)
int from, throws ValidationException {
@QueryParam("quantity")
@Min(value=1, message="quantity cannot be negative")
int quantity) throws ValidationException {
String context = ScopeProvider.instance.get(); String context = ScopeProvider.instance.get();
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
logger.debug("Retrieving all posts coming from vre = " + context); logger.debug("Retrieving all posts coming from vre = " + context);
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
try{ try {
RangePosts rangePosts = CassandraConnection.getInstance().getDatabookStore().getRecentPostsByVREAndRange(context, from, quantity); RangePosts rangePosts = CassandraConnection.getInstance().getDatabookStore()
.getRecentPostsByVREAndRange(context, from, quantity);
Filters.hideSensitiveInformation(rangePosts.getPosts(), caller.getClient().getId()); Filters.hideSensitiveInformation(rangePosts.getPosts(), caller.getClient().getId());
responseBean.setResult(rangePosts); responseBean.setResult(rangePosts);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve posts for vre = " + context, e); logger.error("Unable to retrieve posts for vre = " + context, e);
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
responseBean.setMessage(e.toString()); responseBean.setMessage(e.toString());
@ -522,6 +531,7 @@ public class Posts {
/** /**
* Retrieve posts containing the hashtag in the context bound to the auth token * Retrieve posts containing the hashtag in the context bound to the auth token
*
* @param hashtag he hashtag to be contained within the posts * @param hashtag he hashtag to be contained within the posts
* @pathExample /get-posts-by-hashtag?hashtag=#thehashtag * @pathExample /get-posts-by-hashtag?hashtag=#thehashtag
* @return the posts in the context bound to the auth token matching the hashtag * @return the posts in the context bound to the auth token matching the hashtag
@ -529,30 +539,30 @@ public class Posts {
*/ */
@GET @GET
@Path("get-posts-by-hashtag/") @Path("get-posts-by-hashtag/")
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 201, condition = "Sccessfull retrieved posts, they are reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getPostsByHashTags( public Response getPostsByHashTags(
@QueryParam("hashtag") @QueryParam("hashtag") @NotNull(message = "hashtag cannot be missing") String hashtag)
@NotNull(message="hashtag cannot be missing") throws ValidationException {
String hashtag) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
String context = ScopeProvider.instance.get(); String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
logger.debug("User " + username + " has requested posts containing hashtag " + hashtag + " in context " + context); logger.debug(
try{ "User " + username + " has requested posts containing hashtag " + hashtag + " in context " + context);
try {
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore(); DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
List<Post> posts = datastore.getVREPostsByHashtag(context, hashtag); List<Post> posts = datastore.getVREPostsByHashtag(context, hashtag);
Filters.hideSensitiveInformation(posts, caller.getClient().getId()); Filters.hideSensitiveInformation(posts, caller.getClient().getId());
responseBean.setResult(posts); responseBean.setResult(posts);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Failed to retrieve hashtags", e); logger.error("Failed to retrieve hashtags", e);
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
} }
@ -561,14 +571,16 @@ public class Posts {
/** /**
* Retrieve ids (UUID) of the liked posts by the user * 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 *
* @return ids (UUID) of the liked posts by the user in the context bound to the
* auth token
*/ */
@GET @GET
@Path("get-id-liked-posts/") @Path("get-id-liked-posts/")
@Produces({MediaType.APPLICATION_JSON}) @Produces({ MediaType.APPLICATION_JSON })
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 201, condition = "Sccessfull retrieved ids, they are reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getAllLikedPostIdsByUser() { public Response getAllLikedPostIdsByUser() {
@ -580,7 +592,7 @@ public class Posts {
List<String> retrievedLikedPostsIds = null; List<String> retrievedLikedPostsIds = null;
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
try{ try {
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore(); DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
retrievedLikedPostsIds = datastore.getAllLikedPostIdsByUser(username); retrievedLikedPostsIds = datastore.getAllLikedPostIdsByUser(username);
@ -588,7 +600,7 @@ public class Posts {
responseBean.setResult(retrievedLikedPostsIds); responseBean.setResult(retrievedLikedPostsIds);
responseBean.setSuccess(true); responseBean.setSuccess(true);
logger.debug("Ids of liked posts by " + username + " retrieved"); logger.debug("Ids of liked posts by " + username + " retrieved");
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to read such ids of liked Posts.", e); logger.error("Unable to read such ids of liked Posts.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -600,22 +612,22 @@ public class Posts {
/** /**
* Retrieve posts liked by the user * Retrieve posts liked by the user
*
* @param limit The maximum number of posts to be retrieved * @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 * @return posts liked by the user (up to a given quantity) in the context bound
* to the auth token
* @throws ValidationException * @throws ValidationException
*/ */
@GET @GET
@Path("get-liked-posts/") @Path("get-liked-posts/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successfull retrieved posts, they are reported in the 'result' field of the returned object"), @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) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getAllLikedPostsByUser( public Response getAllLikedPostsByUser(
@DefaultValue("10") @DefaultValue("10") @QueryParam("limit") @Min(message = "limit cannot be negative", value = 0) int limit)
@QueryParam("limit") throws ValidationException {
@Min(message="limit cannot be negative", value = 0)
int limit) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
@ -624,15 +636,17 @@ public class Posts {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
try{ try {
logger.debug("Retrieving " + limit + " liked posts for user with id " + username + " in context " + context); logger.debug(
retrievedLikedPosts = CassandraConnection.getInstance().getDatabookStore().getAllLikedPostsByUser(username, limit); "Retrieving " + limit + " liked posts for user with id " + username + " in context " + context);
retrievedLikedPosts = CassandraConnection.getInstance().getDatabookStore().getAllLikedPostsByUser(username,
limit);
Filters.filterPostsPerContext(retrievedLikedPosts, context); Filters.filterPostsPerContext(retrievedLikedPosts, context);
Filters.hideSensitiveInformation(retrievedLikedPosts, caller.getClient().getId()); Filters.hideSensitiveInformation(retrievedLikedPosts, caller.getClient().getId());
responseBean.setResult(retrievedLikedPosts); responseBean.setResult(retrievedLikedPosts);
responseBean.setSuccess(true); responseBean.setSuccess(true);
logger.debug("Liked posts by " + username + " retrieved"); logger.debug("Liked posts by " + username + " retrieved");
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to read such liked posts.", e); logger.error("Unable to read such liked posts.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -641,29 +655,27 @@ public class Posts {
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
//libapi // libapi
@POST @POST
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("save-user-post-attachments-lib") @Path("save-user-post-attachments-lib")
public Response saveUserPostLib( public Response saveUserPostLib(
@NotNull(message="post to add is missing") @NotNull(message = "post to add is missing") @Valid PostWithAttachment postWithAttachment)
@Valid throws ValidationException {
PostWithAttachment postWithAttachment
) throws ValidationException{
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
try{ try {
Post post = postWithAttachment.getPost(); Post post = postWithAttachment.getPost();
logger.debug("Post is " + post); logger.debug("Post is " + post);
List<Attachment> attachments = postWithAttachment.getAttachments(); List<Attachment> attachments = postWithAttachment.getAttachments();
logger.debug("Attachments are " + attachments); logger.debug("Attachments are " + attachments);
boolean result = CassandraConnection.getInstance().getDatabookStore().saveUserPost(post,attachments); boolean result = CassandraConnection.getInstance().getDatabookStore().saveUserPost(post, attachments);
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setMessage(""); responseBean.setMessage("");
responseBean.setSuccess(result); responseBean.setSuccess(result);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to write comment.", e); logger.error("Unable to write comment.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);
@ -677,20 +689,18 @@ public class Posts {
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("save-app-post-attachments-lib") @Path("save-app-post-attachments-lib")
public Response saveAppPostLib( public Response saveAppPostLib(
@NotNull(message="post to add is missing") @NotNull(message = "post to add is missing") @Valid PostWithAttachment postWithAttachment)
@Valid throws ValidationException {
PostWithAttachment postWithAttachment
) throws ValidationException{
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
try{ try {
Post post = postWithAttachment.getPost(); Post post = postWithAttachment.getPost();
List<Attachment> attachments = postWithAttachment.getAttachments(); List<Attachment> attachments = postWithAttachment.getAttachments();
boolean result = CassandraConnection.getInstance().getDatabookStore().saveAppPost(post,attachments); boolean result = CassandraConnection.getInstance().getDatabookStore().saveAppPost(post, attachments);
responseBean.setResult(result); responseBean.setResult(result);
responseBean.setMessage(""); responseBean.setMessage("");
responseBean.setSuccess(result); responseBean.setSuccess(result);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to write comment.", e); logger.error("Unable to write comment.", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
responseBean.setSuccess(false); responseBean.setSuccess(false);

View File

@ -24,7 +24,6 @@ import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.ResponseCode; import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes; import com.webcohesion.enunciate.metadata.rs.StatusCodes;
/** /**
* REST interface for the social networking library (tokens). * REST interface for the social networking library (tokens).
*/ */
@ -39,21 +38,20 @@ public class Tokens {
@Path("generate-application-token/") @Path("generate-application-token/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 201, condition = "Successful creation of the token, reported in the 'result' field of the returned object"), @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 = 403, condition = "There is no application profile with such id"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
/** /**
* Generate a legacy application auth token for the application with id app_id * Generate a legacy application auth token for the application with id app_id
*
* @param input The bean containing the app_id field * @param input The bean containing the app_id field
* @return the legacy application token * @return the legacy application token
* @throws ValidationException * @throws ValidationException
*/ */
public Response generateApplicationToken( public Response generateApplicationToken(
@NotNull(message="Missing input parameter") @NotNull(message = "Missing input parameter") @Valid ApplicationId input) throws ValidationException {
@Valid
ApplicationId input) throws ValidationException{
logger.debug("Incoming request for app token generation."); logger.debug("Incoming request for app token generation.");
String context = ScopeProvider.instance.get(); String context = ScopeProvider.instance.get();
@ -63,7 +61,7 @@ public class Tokens {
try { try {
// check if the token actually matches an application profile // check if the token actually matches an application profile
ApplicationProfile appProfile = SocialUtils.getProfileFromInfrastrucure(appId, context); ApplicationProfile appProfile = SocialUtils.getProfileFromInfrastrucure(appId, context);
if(appProfile == null){ if (appProfile == null) {
logger.error("The given id doesn't belong to an application!!!"); logger.error("The given id doesn't belong to an application!!!");
responseBean.setSuccess(false); responseBean.setSuccess(false);
responseBean.setMessage(ErrorMessages.NOT_APP_ID); responseBean.setMessage(ErrorMessages.NOT_APP_ID);

View File

@ -52,19 +52,21 @@ import com.webcohesion.enunciate.metadata.rs.StatusCodes;
* REST interface for the social networking library (users). * REST interface for the social networking library (users).
*/ */
@Path("2/users") @Path("2/users")
@RequestHeaders ({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), @RequestHeader(name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json") @RequestHeader(name = "Content-Type", description = "application/json")
}) })
public class Users { public class Users {
// Logger // Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Users.class); private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Users.class);
private static final String NOT_USER_TOKEN_CONTEXT_USED = "User's information can only be retrieved through a user token (not qualified)"; private static final String NOT_USER_TOKEN_CONTEXT_USED = "User's information can only be retrieved through a user token (not qualified)";
private static final List<String> GLOBAL_ROLES_ALLOWED_BY_LOCAL_CALL_METHOD = Arrays.asList("DataMiner-Manager","Quota-Manager"); private static final List<String> GLOBAL_ROLES_ALLOWED_BY_LOCAL_CALL_METHOD = Arrays.asList("DataMiner-Manager",
"Quota-Manager");
/** /**
* Read a user's custom attribute. The user is the one owning the token * Read a user's custom attribute. The user is the one owning the token
*
* @param attributeKey The key of the attribute to be read * @param attributeKey The key of the attribute to be read
* @return the user's custom attribute * @return the user's custom attribute
* @throws ValidationException * @throws ValidationException
@ -72,35 +74,33 @@ public class Users {
@GET @GET
@Path("get-custom-attribute/") @Path("get-custom-attribute/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "Successful read of the attribute, reported in the 'result' field of the returned object"), @ResponseCode(code = 200, condition = "Successful read of the attribute, reported in the 'result' field of the returned object"),
@ResponseCode ( code = 404, condition = "Such an attribute doesn't exist"), @ResponseCode(code = 404, condition = "Such an attribute doesn't exist"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response readCustomAttr( public Response readCustomAttr(
@QueryParam("attribute") @QueryParam("attribute") @NotNull(message = "attribute name is missing") String attributeKey)
@NotNull(message="attribute name is missing") throws ValidationException {
String attributeKey
) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
if(!TokensUtils.isUserTokenDefault(caller)){ if (!TokensUtils.isUserTokenDefault(caller)) {
status = Status.FORBIDDEN; status = Status.FORBIDDEN;
responseBean.setMessage(NOT_USER_TOKEN_CONTEXT_USED); responseBean.setMessage(NOT_USER_TOKEN_CONTEXT_USED);
logger.warn("Trying to access users method via a token different than USER is not allowed"); logger.warn("Trying to access users method via a token different than USER is not allowed");
}else{ } else {
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
try{ try {
GCubeUser user = userManager.getUserByUsername(username); GCubeUser user = userManager.getUserByUsername(username);
String toReturn = (String)userManager.readCustomAttr(user.getUserId(), attributeKey); String toReturn = (String) userManager.readCustomAttr(user.getUserId(), attributeKey);
responseBean.setSuccess(true); responseBean.setSuccess(true);
responseBean.setResult(toReturn); responseBean.setResult(toReturn);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve attribute for user.", e); logger.error("Unable to retrieve attribute for user.", e);
responseBean.setMessage(e.toString()); responseBean.setMessage(e.toString());
@ -114,16 +114,17 @@ public class Users {
/** /**
* Read the user's fullname. The user is the one owning the token * Read the user's fullname. The user is the one owning the token
*
* @return the user's fullname * @return the user's fullname
*/ */
@GET @GET
@Path("get-fullname") @Path("get-fullname")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "The user's fullname is reported in the 'result' field of the returned object"), @ResponseCode(code = 200, condition = "The user's fullname is reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getUserFullname(){ public Response getUserFullname() {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
@ -131,21 +132,21 @@ public class Users {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
if(!TokensUtils.isUserTokenDefault(caller)){ if (!TokensUtils.isUserTokenDefault(caller)) {
status = Status.FORBIDDEN; status = Status.FORBIDDEN;
responseBean.setMessage(NOT_USER_TOKEN_CONTEXT_USED); responseBean.setMessage(NOT_USER_TOKEN_CONTEXT_USED);
logger.warn("Trying to access users method via a token different than USER is not allowed"); logger.warn("Trying to access users method via a token different than USER is not allowed");
}else{ } else {
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
try{ try {
GCubeUser user = userManager.getUserByUsername(username); GCubeUser user = userManager.getUserByUsername(username);
fullName = user.getFullname(); fullName = user.getFullname();
logger.debug("Found fullname " + fullName + " for user " + username); logger.debug("Found fullname " + fullName + " for user " + username);
responseBean.setResult(fullName); responseBean.setResult(fullName);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve attribute for user.", e); logger.error("Unable to retrieve attribute for user.", e);
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
@ -157,36 +158,37 @@ public class Users {
/** /**
* Read the user's email address. The user is the one owning the token * Read the user's email address. The user is the one owning the token
*
* @return rhe user's email address * @return rhe user's email address
*/ */
@GET @GET
@Path("get-email") @Path("get-email")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "The user's email is reported in the 'result' field of the returned object"), @ResponseCode(code = 200, condition = "The user's email is reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getUserEmail(){ public Response getUserEmail() {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
String email = null; String email = null;
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
if(!TokensUtils.isUserTokenDefault(caller)){ if (!TokensUtils.isUserTokenDefault(caller)) {
status = Status.FORBIDDEN; status = Status.FORBIDDEN;
responseBean.setMessage(NOT_USER_TOKEN_CONTEXT_USED); responseBean.setMessage(NOT_USER_TOKEN_CONTEXT_USED);
logger.warn("Trying to access users method via a token different than USER is not allowed"); logger.warn("Trying to access users method via a token different than USER is not allowed");
}else{ } else {
try{ try {
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
GCubeUser user = userManager.getUserByUsername(username); GCubeUser user = userManager.getUserByUsername(username);
email = user.getEmail(); email = user.getEmail();
logger.debug("Found email " + email + " for user " + username); logger.debug("Found email " + email + " for user " + username);
responseBean.setResult(email); responseBean.setResult(email);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve attribute for user.", e); logger.error("Unable to retrieve attribute for user.", e);
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
@ -198,17 +200,27 @@ public class Users {
/** /**
* Get the profile associated to the token * Get the profile associated to the token
* @responseExample application/json { "success" : true, "message" : null, "result" : { "user_id" : 23769487, "username" : "john.smith", "email" : "********", "first_name" : "John", "middle_name" : "", "last_name" : "Smith", "fullname" : "John Smith", "registration_date" : 1475151491415, "user_avatar_url" : "https://******D", "male" : true, "job_title" : "", "location_industry" : "no", "custom_attrs_map" : null, "email_addresses" : [ ], "screen_name" : "john.smith", "user_avatar_id" : "https://****sY%3D" } } *
* @responseExample application/json { "success" : true, "message" : null,
* "result" : { "user_id" : 23769487, "username" :
* "john.smith", "email" : "********", "first_name" : "John",
* "middle_name" : "", "last_name" : "Smith", "fullname" :
* "John Smith", "registration_date" : 1475151491415,
* "user_avatar_url" : "https://******D", "male" : true,
* "job_title" : "", "location_industry" : "no",
* "custom_attrs_map" : null, "email_addresses" : [ ],
* "screen_name" : "john.smith", "user_avatar_id" :
* "https://****sY%3D" } }
* @return the user's profile. The user is the one owning the token * @return the user's profile. The user is the one owning the token
*/ */
@GET @GET
@Path("get-profile") @Path("get-profile")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "The user's profile is reported in the 'result' field of the returned object"), @ResponseCode(code = 200, condition = "The user's profile is reported in the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getUserProfile(){ public Response getUserProfile() {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
@ -216,17 +228,17 @@ public class Users {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
if(!TokensUtils.isUserToken(caller)){ if (!TokensUtils.isUserToken(caller)) {
status = Status.FORBIDDEN; status = Status.FORBIDDEN;
responseBean.setMessage("User's information can only be retrieved through a user Jtoken"); responseBean.setMessage("User's information can only be retrieved through a user Jtoken");
logger.warn("Trying to access users method via a token different than 'user-token' is not allowed"); logger.warn("Trying to access users method via a token different than 'user-token' is not allowed");
}else{ } else {
try{ try {
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
user = userManager.getUserByUsername(username); user = userManager.getUserByUsername(username);
responseBean.setResult(user); responseBean.setResult(user);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve user's profile", e); logger.error("Unable to retrieve user's profile", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
@ -235,16 +247,16 @@ public class Users {
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
private static final Function<GCubeUser, UserProfileExtendedWithVerifiedEmail> GCUBE_TO_EXTENDED_PROFILE_MAP_WITH_VERIFIED_EMAIL private static final Function<GCubeUser, UserProfileExtendedWithVerifiedEmail> GCUBE_TO_EXTENDED_PROFILE_MAP_WITH_VERIFIED_EMAIL = new Function<GCubeUser, UserProfileExtendedWithVerifiedEmail>() {
= new Function<GCubeUser, UserProfileExtendedWithVerifiedEmail>() {
@Override @Override
public UserProfileExtendedWithVerifiedEmail apply(GCubeUser t) { public UserProfileExtendedWithVerifiedEmail apply(GCubeUser t) {
if(t == null) if (t == null)
return null; return null;
UserProfileExtendedWithVerifiedEmail profile = new UserProfileExtendedWithVerifiedEmail(t.getUsername(), null, t.getUserAvatarURL(), t.getFullname()); UserProfileExtendedWithVerifiedEmail profile = new UserProfileExtendedWithVerifiedEmail(t.getUsername(),
null, t.getUserAvatarURL(), t.getFullname());
profile.setEmail(t.getEmail()); profile.setEmail(t.getEmail());
profile.setFirstName(t.getFirstName()); profile.setFirstName(t.getFirstName());
profile.setJobTitle(t.getJobTitle()); profile.setJobTitle(t.getJobTitle());
@ -259,25 +271,25 @@ public class Users {
/** /**
* @responseExample application/json { * @responseExample application/json {
"id": "john.smith", * "id": "john.smith",
"roles": [], * "roles": [],
"picture": "https://***gAJ4uVWTA74xwQ6%2FCA72RRinysY%3D", * "picture": "https://***gAJ4uVWTA74xwQ6%2FCA72RRinysY%3D",
"name": "John Smith", * "name": "John Smith",
"middle_name": "", * "middle_name": "",
"male": true, * "male": true,
"location_industry": "no", * "location_industry": "no",
"given_name": "John", * "given_name": "John",
"email": "******", * "email": "******",
"job_title": "", * "job_title": "",
"family_name": "Smith", * "family_name": "Smith",
"verified_email": true * "verified_email": true
} * }
* @return the user's profile compliant with oauth * @return the user's profile compliant with oauth
*/ */
@GET @GET
@Path("get-oauth-profile") @Path("get-oauth-profile")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response getUserOAuthProfile(){ public Response getUserOAuthProfile() {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
String scope = ScopeProvider.instance.get(); String scope = ScopeProvider.instance.get();
@ -285,62 +297,64 @@ public class Users {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
UserProfileExtendedWithVerifiedEmail userWithEmailVerified = null; UserProfileExtendedWithVerifiedEmail userWithEmailVerified = null;
if(!TokensUtils.isUserToken(caller)){ if (!TokensUtils.isUserToken(caller)) {
status = Status.FORBIDDEN; status = Status.FORBIDDEN;
responseBean.setMessage(NOT_USER_TOKEN_CONTEXT_USED); responseBean.setMessage(NOT_USER_TOKEN_CONTEXT_USED);
logger.warn("Trying to access users method via a token different than USER is not allowed"); logger.warn("Trying to access users method via a token different than USER is not allowed");
}else{ } else {
try{ try {
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager(); RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager();
GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager(); GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
user = userManager.getUserByUsername(username); user = userManager.getUserByUsername(username);
userWithEmailVerified = GCUBE_TO_EXTENDED_PROFILE_MAP_WITH_VERIFIED_EMAIL.apply(user); userWithEmailVerified = GCUBE_TO_EXTENDED_PROFILE_MAP_WITH_VERIFIED_EMAIL.apply(user);
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(user.getUserId(), groupManager.getGroupIdFromInfrastructureScope(scope)); List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(user.getUserId(),
groupManager.getGroupIdFromInfrastructureScope(scope));
List<String> rolesNames = new ArrayList<String>(); List<String> rolesNames = new ArrayList<String>();
for (GCubeRole gCubeRole : roles) { for (GCubeRole gCubeRole : roles) {
rolesNames.add(gCubeRole.getRoleName()); rolesNames.add(gCubeRole.getRoleName());
} }
userWithEmailVerified.setRoles(rolesNames); userWithEmailVerified.setRoles(rolesNames);
//responseBean.setResult(userWithEmailVerified); // responseBean.setResult(userWithEmailVerified);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve user's profile", e); logger.error("Unable to retrieve user's profile", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
} }
} }
logger.debug("returning: "+userWithEmailVerified.toString()); logger.debug("returning: " + userWithEmailVerified.toString());
return Response.status(status).entity(userWithEmailVerified).build(); return Response.status(status).entity(userWithEmailVerified).build();
} }
/** /**
* @responseExample application/json { * @responseExample application/json {
"success": true, * "success": true,
"message": null, * "message": null,
"result": [ * "result": [
"john.smith", * "john.smith",
"marco.polo" * "marco.polo"
] * ]
} * }
* Get the list of usernames belonging to a given context * Get the list of usernames belonging to a given context
* @return the list of usernames for the user belonging to the context linked to the provided auth token * @return the list of usernames for the user belonging to the context linked to
* the provided auth token
*/ */
@GET @GET
@Path("get-all-usernames") @Path("get-all-usernames")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "The list of usernames is put into the 'result' field of the returned object"), @ResponseCode(code = 200, condition = "The list of usernames is put into the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getAllUserNames(){ public Response getAllUserNames() {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
List<String> usernames = new ArrayList<String>(); List<String> usernames = new ArrayList<String>();
try{ try {
GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager(); GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
@ -353,21 +367,21 @@ public class Users {
UsersCache cache = UsersCache.getSingleton(); UsersCache cache = UsersCache.getSingleton();
for (Long userId : userIds) { for (Long userId : userIds) {
if(cache.getUser(userId) == null){ if (cache.getUser(userId) == null) {
GCubeUser user = userManager.getUserById(userId); GCubeUser user = userManager.getUserById(userId);
if(user != null){ if (user != null) {
usernames.add(user.getUsername()); usernames.add(user.getUsername());
cache.pushEntry(userId, user); cache.pushEntry(userId, user);
} }
}else } else
usernames.add(cache.getUser(userId).getUsername()); usernames.add(cache.getUser(userId).getUsername());
} }
responseBean.setResult(usernames); responseBean.setResult(usernames);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve user's usernames", e); logger.error("Unable to retrieve user's usernames", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
} }
@ -375,23 +389,26 @@ public class Users {
} }
/** /**
* Get the map of couples username/fullname of the users belonging to a given context * Get the map of couples username/fullname of the users belonging to a given
* @return the map of couples username/fullname of the users belonging to the context linked to the provided token. * context
*
* @return the map of couples username/fullname of the users belonging to the
* context linked to the provided token.
*/ */
@GET @GET
@Path("get-all-fullnames-and-usernames") @Path("get-all-fullnames-and-usernames")
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "The map is put into the 'result' field of the returned object"), @ResponseCode(code = 200, condition = "The map is put into the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response getFullnamesAndUsernames(){ public Response getFullnamesAndUsernames() {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
Map<String, String> usernamesAndFullnames = new HashMap<String, String>(); Map<String, String> usernamesAndFullnames = new HashMap<String, String>();
try{ try {
GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager(); GroupManager groupManager = GroupManagerWSBuilder.getInstance().getGroupManager();
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
@ -404,21 +421,21 @@ public class Users {
UsersCache cache = UsersCache.getSingleton(); UsersCache cache = UsersCache.getSingleton();
for (Long userId : userIds) { for (Long userId : userIds) {
if(cache.getUser(userId) == null){ if (cache.getUser(userId) == null) {
GCubeUser user = userManager.getUserById(userId); GCubeUser user = userManager.getUserById(userId);
if(user != null){ if (user != null) {
usernamesAndFullnames.put(user.getUsername(), user.getFullname()); usernamesAndFullnames.put(user.getUsername(), user.getFullname());
cache.pushEntry(userId, user); cache.pushEntry(userId, user);
} }
}else } else
usernamesAndFullnames.put(cache.getUser(userId).getUsername(), cache.getUser(userId).getFullname()); usernamesAndFullnames.put(cache.getUser(userId).getUsername(), cache.getUser(userId).getFullname());
} }
responseBean.setResult(usernamesAndFullnames); responseBean.setResult(usernamesAndFullnames);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve user's usernames", e); logger.error("Unable to retrieve user's usernames", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
} }
@ -426,52 +443,55 @@ public class Users {
} }
/** /**
* Get the list of users having a given global-role, e.g. 'Administrator'. (Legacy) * Get the list of users having a given global-role, e.g. 'Administrator'.
* (Legacy)
*
* @param roleName the name of the role to be checked (e.g. Administrator) * @param roleName the name of the role to be checked (e.g. Administrator)
* @return the list of users having a given global-role * @return the list of users having a given global-role
*/ */
@GET @GET
@Path("get-usernames-by-global-role") @Path("get-usernames-by-global-role")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@StatusCodes ({ @StatusCodes({
@ResponseCode ( code = 200, condition = "The list is put into the 'result' field of the returned object"), @ResponseCode(code = 200, condition = "The list is put into the 'result' field of the returned object"),
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT) @ResponseCode(code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
}) })
public Response getUsernamesByGlobalRole( public Response getUsernamesByGlobalRole(
@QueryParam("role-name") String roleName){ @QueryParam("role-name") String roleName) {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
// this method can only be called from IS scope (except for roles in GLOBAL_ROLES_ALLOWED_BY_LOCAL) // this method can only be called from IS scope (except for roles in
// GLOBAL_ROLES_ALLOWED_BY_LOCAL)
ScopeBean scopeInfo = new ScopeBean(ScopeProvider.instance.get()); ScopeBean scopeInfo = new ScopeBean(ScopeProvider.instance.get());
if(!scopeInfo.is(Type.INFRASTRUCTURE)){ if (!scopeInfo.is(Type.INFRASTRUCTURE)) {
status = Status.BAD_REQUEST; status = Status.BAD_REQUEST;
responseBean.setMessage("This method can only be called with an infrastructure token"); responseBean.setMessage("This method can only be called with an infrastructure token");
}else{ } else {
List<String> usernames = new ArrayList<String>(); List<String> usernames = new ArrayList<String>();
try{ try {
RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager(); RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager();
long globalRoleId = roleManager.getRoleIdByName(roleName); long globalRoleId = roleManager.getRoleIdByName(roleName);
if(globalRoleId > 0){ if (globalRoleId > 0) {
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
List<GCubeUser> users = userManager.listUsersByGlobalRole(globalRoleId); List<GCubeUser> users = userManager.listUsersByGlobalRole(globalRoleId);
if(users != null){ if (users != null) {
for (GCubeUser gCubeUser : users) { for (GCubeUser gCubeUser : users) {
usernames.add(gCubeUser.getUsername()); usernames.add(gCubeUser.getUsername());
} }
} }
responseBean.setResult(usernames); responseBean.setResult(usernames);
responseBean.setSuccess(true); responseBean.setSuccess(true);
}else{ } else {
responseBean.setMessage("No global role exists whit such a name"); responseBean.setMessage("No global role exists whit such a name");
status = Status.BAD_REQUEST; status = Status.BAD_REQUEST;
} }
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve user's usernames", e); logger.error("Unable to retrieve user's usernames", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
} }
} }
@ -483,28 +503,27 @@ public class Users {
* @param roleName the role name * @param roleName the role name
* @return the usernames having the role in the VRE * @return the usernames having the role in the VRE
* @responseExample application/json { * @responseExample application/json {
"success": true, * "success": true,
"message": null, * "message": null,
"result": [ * "result": [
"john.smith", * "john.smith",
"marco.polo" * "marco.polo"
] * ]
} * }
*/ */
@GET @GET
@Path("get-usernames-by-role") @Path("get-usernames-by-role")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response getUsernamesByRole( public Response getUsernamesByRole(
@QueryParam("role-name") String roleName){ @QueryParam("role-name") String roleName) {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
String context = ScopeProvider.instance.get(); String context = ScopeProvider.instance.get();
KeycloakAPICredentials apiService = KeycloakAPICredentials.getSingleton(); KeycloakAPICredentials apiService = KeycloakAPICredentials.getSingleton();
Keycloak keycloak; Keycloak keycloak;
keycloak = KeycloakBuilder.builder() keycloak = KeycloakBuilder.builder()
.serverUrl(apiService.getServerURL()) .serverUrl(apiService.getServerURL())
.realm(apiService.getRealm()) .realm(apiService.getRealm())
@ -512,38 +531,38 @@ public class Users {
.clientId(apiService.getClientid()) // .clientId(apiService.getClientid()) //
.clientSecret(apiService.getPassword()).build(); .clientSecret(apiService.getPassword()).build();
List<String> usernames = new ArrayList<String>(); List<String> usernames = new ArrayList<String>();
try { try {
List<UserRepresentation> users = searchByRole(keycloak, apiService.getRealm(), context, roleName); List<UserRepresentation> users = searchByRole(keycloak, apiService.getRealm(), context, roleName);
if(users != null){ if (users != null) {
for (UserRepresentation user : users) { for (UserRepresentation user : users) {
usernames.add(user.getUsername()); usernames.add(user.getUsername());
} }
} }
responseBean.setResult(usernames); responseBean.setResult(usernames);
responseBean.setSuccess(true); responseBean.setSuccess(true);
} catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve user with the requested role", e); logger.error("Unable to retrieve user with the requested role", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
} }
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
private static List<UserRepresentation> searchByRole(Keycloak keycloak, String realmName, String context, String roleName) { private static List<UserRepresentation> searchByRole(Keycloak keycloak, String realmName, String context,
String roleName) {
logger.debug("Searching by role: {}", roleName); logger.debug("Searching by role: {}", roleName);
String clientIdContext = context.replace("/", "%2F") ; String clientIdContext = context.replace("/", "%2F");
List<ClientRepresentation> clients = keycloak.realm(realmName) List<ClientRepresentation> clients = keycloak.realm(realmName)
.clients().findByClientId(clientIdContext); .clients().findByClientId(clientIdContext);
String id = ""; String id = "";
for (ClientRepresentation client : clients) { for (ClientRepresentation client : clients) {
logger.debug("found client ="+client.getClientId()); logger.debug("found client =" + client.getClientId());
logger.debug("found client id="+client.getId()); logger.debug("found client id=" + client.getId());
id =client.getId(); id = client.getId();
} }
List<UserRepresentation> users = keycloak.realm(realmName) List<UserRepresentation> users = keycloak.realm(realmName)
@ -553,12 +572,11 @@ public class Users {
return users; return users;
} }
@GET @GET
@Path("user-exists") @Path("user-exists")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Deprecated @Deprecated
public Response existUser(@QueryParam("username") String username){ public Response existUser(@QueryParam("username") String username) {
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
String messageOnError = "This method can be invoked only by using an application token bound to the root context"; String messageOnError = "This method can be invoked only by using an application token bound to the root context";
@ -567,15 +585,15 @@ public class Users {
responseBean.setSuccess(false); responseBean.setSuccess(false);
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
if(!TokensUtils.isApplicationToken(caller)) if (!TokensUtils.isApplicationToken(caller))
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
ScopeBean scopeInfo = new ScopeBean(ScopeProvider.instance.get()); ScopeBean scopeInfo = new ScopeBean(ScopeProvider.instance.get());
if(!scopeInfo.is(Type.INFRASTRUCTURE)) if (!scopeInfo.is(Type.INFRASTRUCTURE))
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
try{ try {
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
GCubeUser user = userManager.getUserByUsername(username); GCubeUser user = userManager.getUserByUsername(username);
@ -584,9 +602,9 @@ public class Users {
responseBean.setResult(user != null); responseBean.setResult(user != null);
status = Status.OK; status = Status.OK;
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such information", e); logger.error("Unable to retrieve such information", e);
responseBean.setMessage(e.getMessage()); responseBean.setMessage(e.getMessage());
status = Status.INTERNAL_SERVER_ERROR; status = Status.INTERNAL_SERVER_ERROR;
} }

View File

@ -32,15 +32,14 @@ import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader; import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders; import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
/** /**
* REST interface for the social networking library (vres). * REST interface for the social networking library (vres).
*/ */
@Path("2/vres") @Path("2/vres")
@RequestHeaders ({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), @RequestHeader(name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
@RequestHeader( name = "Content-Type", description = "application/json") @RequestHeader(name = "Content-Type", description = "application/json")
}) })
public class VREs { public class VREs {
// Logger // Logger
@ -48,18 +47,18 @@ public class VREs {
/** /**
* @responseExample application/json { * @responseExample application/json {
"success" : true, * "success" : true,
"message" : null, * "message" : null,
"result" : [ { * "result" : [ {
"name" : "NextNext", * "name" : "NextNext",
"context" : "/gcube/devNext/NextNext", * "context" : "/gcube/devNext/NextNext",
"description" : "NextNext description AAA" * "description" : "NextNext description AAA"
}, { * }, {
"name" : "devVRE", * "name" : "devVRE",
"context" : "/gcube/devsec/devVRE", * "context" : "/gcube/devsec/devVRE",
"description" : "devVRE description BBB" * "description" : "devVRE description BBB"
} ] * } ]
} * }
* @pathExample /get-my-vres?getManagers=false * @pathExample /get-my-vres?getManagers=false
* @param getManagers set true if you also want to know the VRE-Managers * @param getManagers set true if you also want to know the VRE-Managers
* @return the list of vres along with some metadata * @return the list of vres along with some metadata
@ -70,23 +69,22 @@ public class VREs {
@Path("get-my-vres/") @Path("get-my-vres/")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response getMyVres( public Response getMyVres(
@DefaultValue("false") @QueryParam("getManagers") boolean getManagers @DefaultValue("false") @QueryParam("getManagers") boolean getManagers) throws ValidationException {
) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get(); Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId(); String username = caller.getClient().getId();
ResponseBean responseBean = new ResponseBean(); ResponseBean responseBean = new ResponseBean();
Status status = Status.OK; Status status = Status.OK;
if(!TokensUtils.isUserToken(caller)){ if (!TokensUtils.isUserToken(caller)) {
status = Status.FORBIDDEN; status = Status.FORBIDDEN;
responseBean.setMessage("This method can only be invoked with a user token!"); 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"); logger.warn("Trying to access get-my-vres method via a token different than USER is not allowed");
}else{ } else {
GroupManager gmManager = GroupManagerWSBuilder.getInstance().getGroupManager(); GroupManager gmManager = GroupManagerWSBuilder.getInstance().getGroupManager();
UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager userManager = UserManagerWSBuilder.getInstance().getUserManager();
RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager(); RoleManager roleManager = RoleManagerWSBuilder.getInstance().getRoleManager();
try{ try {
GCubeUser user = userManager.getUserByUsername(username); GCubeUser user = userManager.getUserByUsername(username);
List<GCubeGroup> vres = gmManager.listVresByUser(user.getUserId()); List<GCubeGroup> vres = gmManager.listVresByUser(user.getUserId());
@ -99,11 +97,11 @@ public class VREs {
obj.put("name", group.getGroupName()); obj.put("name", group.getGroupName());
obj.put("context", gmManager.getInfrastructureScope(group.getGroupId())); obj.put("context", gmManager.getInfrastructureScope(group.getGroupId()));
obj.put("description", group.getDescription()); obj.put("description", group.getDescription());
//obj.put("thumbnail_url", ...); // TODO // obj.put("thumbnail_url", ...); // TODO
JSONArray managers = new JSONArray(); JSONArray managers = new JSONArray();
if(getManagers){ if (getManagers) {
List<GCubeUser> vreManagers = userManager.listUsersByGroupAndRole(group.getGroupId(), List<GCubeUser> vreManagers = userManager.listUsersByGroupAndRole(group.getGroupId(),
roleManager.getRoleIdByName(GatewayRolesNames.VRE_MANAGER.getRoleName())); roleManager.getRoleIdByName(GatewayRolesNames.VRE_MANAGER.getRoleName()));
for (GCubeUser vreManager : vreManagers) { for (GCubeUser vreManager : vreManagers) {
@ -121,7 +119,7 @@ public class VREs {
responseBean.setSuccess(true); responseBean.setSuccess(true);
responseBean.setResult(toReturn); responseBean.setResult(toReturn);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve vres for user.", e); logger.error("Unable to retrieve vres for user.", e);
responseBean.setMessage(e.toString()); responseBean.setMessage(e.toString());
@ -131,5 +129,5 @@ public class VREs {
} }
} }
return Response.status(status).entity(responseBean).build(); return Response.status(status).entity(responseBean).build();
} }
} }

View File

@ -31,7 +31,7 @@ public class ResponseBean implements Serializable {
* @param success * @param success
* @param message * @param message
* @param result * @param result
*/ */
public ResponseBean(boolean success, String message, Object result) { public ResponseBean(boolean success, String message, Object result) {
super(); super();
this.success = success; this.success = success;
@ -39,32 +39,26 @@ public class ResponseBean implements Serializable {
this.result = result; this.result = result;
} }
public boolean isSuccess() { public boolean isSuccess() {
return success; return success;
} }
public void setSuccess(boolean success) { public void setSuccess(boolean success) {
this.success = success; this.success = success;
} }
public String getMessage() { public String getMessage() {
return message; return message;
} }
public void setMessage(String message) { public void setMessage(String message) {
this.message = message; this.message = message;
} }
public Object getResult() { public Object getResult() {
return result; return result;
} }
public void setResult(Object result) { public void setResult(Object result) {
this.result = result; this.result = result;
} }

View File

@ -11,10 +11,14 @@ import com.fasterxml.jackson.databind.SerializationFeature;
@Provider @Provider
/** /**
* Custom mapper with property CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES to perform serialization/deserialization * Custom mapper with property CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES to
* with snake case over camel case for json beans. * perform serialization/deserialization
* TODO check https://github.com/FasterXML/jackson-docs/wiki/JacksonMixInAnnotations for applying such transformation * with snake case over camel case for json beans.
* only to some classes. * 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) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public class CustomObjectMapper implements ContextResolver<ObjectMapper> { public class CustomObjectMapper implements ContextResolver<ObjectMapper> {

View File

@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory;
/** /**
* Cassandra connection class. * Cassandra connection class.
*
* @author Costantino Perciante at ISTI-CNR * @author Costantino Perciante at ISTI-CNR
*/ */
public class CassandraConnection { public class CassandraConnection {
@ -16,35 +17,37 @@ public class CassandraConnection {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CassandraConnection.class); private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CassandraConnection.class);
// databook store (singleton) // databook store (singleton)
private static DatabookStore store; private static DatabookStore store;
private static CassandraConnection singleton = new CassandraConnection(); private static CassandraConnection singleton = new CassandraConnection();
private CassandraConnection(){ private CassandraConnection() {
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
logger.debug("Getting connection to cassandra"); logger.debug("Getting connection to cassandra");
store = new DBCassandraAstyanaxImpl(ctx.container().configuration().infrastructure()); store = new DBCassandraAstyanaxImpl(ctx.container().configuration().infrastructure());
logger.debug("Connection to cassandra created"); logger.debug("Connection to cassandra created");
} }
/** /**
* Returns the object to query the cassandra cluster. * Returns the object to query the cassandra cluster.
*
* @return connection pool to cassandra cluster * @return connection pool to cassandra cluster
*/ */
public DatabookStore getDatabookStore(){ public DatabookStore getDatabookStore() {
return store; return store;
} }
/** /**
* Get the instance * Get the instance
*
* @return * @return
*/ */
public static CassandraConnection getInstance(){ public static CassandraConnection getInstance() {
return singleton; return singleton;
} }
} }

View File

@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory;
/** /**
* The class discovers and offer connections to the elastic search cluster. * The class discovers and offer connections to the elastic search cluster.
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public class ElasticSearchConnection { public class ElasticSearchConnection {
@ -16,12 +17,12 @@ public class ElasticSearchConnection {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ElasticSearchConnection.class); private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ElasticSearchConnection.class);
// databook store (singleton) // databook store (singleton)
private ElasticSearchClient es; private ElasticSearchClient es;
// singleton // singleton
private static ElasticSearchConnection singleton = new ElasticSearchConnection(); private static ElasticSearchConnection singleton = new ElasticSearchConnection();
private ElasticSearchConnection(){ private ElasticSearchConnection() {
try { try {
ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears ApplicationContext ctx = ContextProvider.get(); // get this info from SmartGears
logger.debug("Creating connection to Elasticsearch"); logger.debug("Creating connection to Elasticsearch");
@ -32,7 +33,7 @@ public class ElasticSearchConnection {
} }
} }
public static ElasticSearchConnection getSingleton(){ public static ElasticSearchConnection getSingleton() {
return singleton; return singleton;
@ -40,10 +41,11 @@ public class ElasticSearchConnection {
/** /**
* Returns the object to connect to cassandra cluster. * Returns the object to connect to cassandra cluster.
*
* @return connection pool to cassandra cluster * @return connection pool to cassandra cluster
* @throws Exception * @throws Exception
*/ */
public ElasticSearchClient getElasticSearchClient(){ public ElasticSearchClient getElasticSearchClient() {
return es; return es;

View File

@ -1,8 +1,8 @@
package org.gcube.portal.social.networking.ws.utils; package org.gcube.portal.social.networking.ws.utils;
/** /**
* Class that contains error messages to be returned in the HTTP responses. * Class that contains error messages to be returned in the HTTP responses.
*
* @author Costantino Perciante at ISTI-CNR * @author Costantino Perciante at ISTI-CNR
*/ */
public class ErrorMessages { public class ErrorMessages {
@ -11,7 +11,7 @@ public class ErrorMessages {
public static final String MISSING_PARAMETERS = "Missing request parameters."; public static final String MISSING_PARAMETERS = "Missing request parameters.";
public static final String INVALID_TOKEN = "Invalid token."; public static final String INVALID_TOKEN = "Invalid token.";
public static final String TOKEN_GENERATION_APP_FAILED = "Token generation failed."; 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_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 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 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 BAD_REQUEST = "Please check the parameter you passed, it seems a bad request";

View File

@ -18,6 +18,7 @@ import org.slf4j.LoggerFactory;
/** /**
* Filters to apply to feeds/comments etc * Filters to apply to feeds/comments etc
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public class Filters { public class Filters {
@ -25,39 +26,41 @@ public class Filters {
// Logger // Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Filters.class); private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Filters.class);
private static List<String> getContexts(String context) throws IllegalArgumentException, UserManagementSystemException, GroupRetrievalFault{ private static List<String> getContexts(String context)
throws IllegalArgumentException, UserManagementSystemException, GroupRetrievalFault {
// retrieve group information // retrieve group information
GroupManager gm = GroupManagerWSBuilder.getInstance().getGroupManager(); GroupManager gm = GroupManagerWSBuilder.getInstance().getGroupManager();
GCubeGroup group = gm.getGroup(gm.getGroupIdFromInfrastructureScope(context)); GCubeGroup group = gm.getGroup(gm.getGroupIdFromInfrastructureScope(context));
List<String> contexts = new ArrayList<String>(); List<String> contexts = new ArrayList<String>();
if(gm.isRootVO(group.getGroupId())){ if (gm.isRootVO(group.getGroupId())) {
} } else if (gm.isVO(group.getGroupId())) {
else if(gm.isVO(group.getGroupId())){
List<GCubeGroup> vres = group.getChildren(); List<GCubeGroup> vres = group.getChildren();
for (GCubeGroup gCubeGroup : vres) { for (GCubeGroup gCubeGroup : vres) {
contexts.add(gm.getInfrastructureScope(gCubeGroup.getGroupId())); contexts.add(gm.getInfrastructureScope(gCubeGroup.getGroupId()));
} }
}else{ } else {
contexts.add(gm.getInfrastructureScope(group.getGroupId())); contexts.add(gm.getInfrastructureScope(group.getGroupId()));
} }
return contexts; return contexts;
} }
/** /**
* Given a list of not filtered feeds, the methods remove feeds unaccessible in this scope. * 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 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 VO: feeds for vres within the vo are returned;
* If the initial context is a vre: feeds of the vre are returned; * If the initial context is a vre: feeds of the vre are returned;
*
* @param feedsIds * @param feedsIds
* @param context * @param context
* @throws Exception * @throws Exception
*/ */
public static void filterFeedsPerContextById( public static void filterFeedsPerContextById(
List<String> feedsIds, String context) throws Exception { List<String> feedsIds, String context) throws Exception {
@ -66,10 +69,10 @@ public class Filters {
List<Feed> feeds = new ArrayList<Feed>(); List<Feed> feeds = new ArrayList<Feed>();
for (String feedId : feedsIds) { for (String feedId : feedsIds) {
try{ try {
feeds.add(datastore.readFeed(feedId)); feeds.add(datastore.readFeed(feedId));
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to read feed with id " + feedId, e); logger.error("Unable to read feed with id " + feedId, e);
} }
} }
@ -85,45 +88,50 @@ public class Filters {
} }
/** /**
* Given a list of not filtered feeds, the methods remove feeds unaccessible in this scope. * 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 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 VO: feeds for vres within the vo are returned;
* If the initial context is a vre: feeds of the vre are returned; * If the initial context is a vre: feeds of the vre are returned;
*
* @param feeds * @param feeds
* @param context * @param context
* @throws Exception * @throws Exception
*/ */
@Deprecated @Deprecated
public static void filterFeedsPerContext(List<Feed> feeds, String context) throws Exception { public static void filterFeedsPerContext(List<Feed> feeds, String context) throws Exception {
List<String> contexts = getContexts(context); List<String> contexts = getContexts(context);
// filter // filter
Iterator<Feed> iterator = feeds.iterator(); Iterator<Feed> iterator = feeds.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Feed feed = (Feed) iterator.next(); Feed feed = (Feed) iterator.next();
if(!contexts.contains(feed.getVreid())) if (!contexts.contains(feed.getVreid()))
iterator.remove(); iterator.remove();
} }
} }
/** /**
* Given a list of not filtered posts, the methods remove posts unaccessible in this scope. * 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 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 VO: posts for vres within the vo are returned;
* If the initial context is a vre: posts of the vre are returned; * If the initial context is a vre: posts of the vre are returned;
*
* @param context * @param context
* @throws Exception * @throws Exception
*/ */
public static void filterPostsPerContext(List<Post> posts, String context) throws Exception { public static void filterPostsPerContext(List<Post> posts, String context) throws Exception {
List<String> contexts = getContexts(context); List<String> contexts = getContexts(context);
// filter // filter
Iterator<Post> iterator = posts.iterator(); Iterator<Post> iterator = posts.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Post post = (Post) iterator.next(); Post post = (Post) iterator.next();
if(!contexts.contains(post.getVreid())) if (!contexts.contains(post.getVreid()))
iterator.remove(); iterator.remove();
} }
@ -131,9 +139,10 @@ public class Filters {
/** /**
* Filter comments per context * Filter comments per context
*
* @param comments * @param comments
* @param context * @param context
* @throws Exception * @throws Exception
*/ */
public static void filterCommentsPerContext(List<Comment> comments, String context) throws Exception { public static void filterCommentsPerContext(List<Comment> comments, String context) throws Exception {
@ -145,12 +154,12 @@ public class Filters {
// filter // filter
Iterator<Comment> iterator = comments.iterator(); Iterator<Comment> iterator = comments.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
try{ try {
Comment comment = (Comment) iterator.next(); Comment comment = (Comment) iterator.next();
Feed parent = datastore.readFeed(comment.getFeedid()); Feed parent = datastore.readFeed(comment.getFeedid());
if(!contexts.contains(parent.getVreid())) if (!contexts.contains(parent.getVreid()))
iterator.remove(); iterator.remove();
}catch(Exception e){ } catch (Exception e) {
logger.warn("Failed to analyze this comment", e); logger.warn("Failed to analyze this comment", e);
iterator.remove(); // remove it anyway iterator.remove(); // remove it anyway
} }
@ -159,29 +168,31 @@ public class Filters {
} }
/** /**
* Depending on the type of object provided (e.g. Feed, Comment etc), some information are removed * Depending on the type of object provided (e.g. Feed, Comment etc), some
* information are removed
*
* @param toClear * @param toClear
* @throws Exception * @throws Exception
*/ */
public static <T> void hideSensitiveInformation(List<T> toClear, String usernameCaller){ public static <T> void hideSensitiveInformation(List<T> toClear, String usernameCaller) {
if(toClear == null || toClear.isEmpty() || usernameCaller == null || usernameCaller.isEmpty()) if (toClear == null || toClear.isEmpty() || usernameCaller == null || usernameCaller.isEmpty())
return; return;
else{ else {
// for feeds // for feeds
if(toClear.get(0).getClass().equals(Feed.class)){ if (toClear.get(0).getClass().equals(Feed.class)) {
for (T feed : toClear) { for (T feed : toClear) {
Feed feeded = ((Feed)feed); Feed feeded = ((Feed) feed);
if(!usernameCaller.equals(feeded.getEntityId())) if (!usernameCaller.equals(feeded.getEntityId()))
feeded.setEmail(""); // remove the email field feeded.setEmail(""); // remove the email field
} }
}else if(toClear.get(0).getClass().equals(EnhancedFeed.class)){ } else if (toClear.get(0).getClass().equals(EnhancedFeed.class)) {
for (T enhancedFeed : toClear) { for (T enhancedFeed : toClear) {
Feed feeded = ((EnhancedFeed)enhancedFeed).getFeed(); Feed feeded = ((EnhancedFeed) enhancedFeed).getFeed();
if(!usernameCaller.equals(feeded.getEntityId())) if (!usernameCaller.equals(feeded.getEntityId()))
feeded.setEmail(""); // remove the email field feeded.setEmail(""); // remove the email field
} }
} }

View File

@ -69,7 +69,7 @@ public class SocialUtils {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SocialUtils.class); 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 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 int CACHING_TIME_TO_EXPIRATION = 2506000;// 29 days 6 minutes 40 seconds
public final static String DISABLED_USERS_NOTIFICATIONS_NAMESPACE = "dun:"; public final static String DISABLED_USERS_NOTIFICATIONS_NAMESPACE = "dun:";
// name of the portlet for vre notification // name of the portlet for vre notification
@ -81,18 +81,18 @@ public class SocialUtils {
* @return a list of existing usernames associated with their fullnames * @return a list of existing usernames associated with their fullnames
*/ */
private static ArrayList<GenericItemBean> getUsersFromUsernames(Set<String> mentions) { private static ArrayList<GenericItemBean> getUsersFromUsernames(Set<String> mentions) {
if (mentions.isEmpty()) if (mentions.isEmpty())
return new ArrayList<>(); return new ArrayList<>();
ArrayList<GenericItemBean> toReturn = new ArrayList<>(); ArrayList<GenericItemBean> toReturn = new ArrayList<>();
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
for (String username : mentions) { for (String username : mentions) {
try{ try {
GCubeUser user = uManager.getUserByUsername(username); GCubeUser user = uManager.getUserByUsername(username);
String fullName = user.getFirstName() + " " + user.getLastName(); String fullName = user.getFirstName() + " " + user.getLastName();
toReturn.add(new GenericItemBean(""+user.getUserId(), username, fullName, "")); toReturn.add(new GenericItemBean("" + user.getUserId(), username, fullName, ""));
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to get user informations for username=" + username); logger.error("Unable to get user informations for username=" + username);
} }
} }
return toReturn; return toReturn;
} }
@ -108,6 +108,7 @@ public class SocialUtils {
/** /**
* Method used when an application needs to publish something. * Method used when an application needs to publish something.
*
* @param postText * @param postText
* @param uriParams * @param uriParams
* @param previewTitle * @param previewTitle
@ -116,15 +117,14 @@ public class SocialUtils {
* @return true upon success, false on failure * @return true upon success, false on failure
*/ */
public static Post shareApplicationUpdate( public static Post shareApplicationUpdate(
String postText, String postText,
String uriParams, String uriParams,
String previewTitle, String previewTitle,
String previewDescription, String previewDescription,
String httpImageUrl, String httpImageUrl,
ApplicationProfile applicationProfile, ApplicationProfile applicationProfile,
Caller caller, Caller caller,
boolean notifyGroup boolean notifyGroup) {
){
SocialMessageParser messageParser = new SocialMessageParser(postText); SocialMessageParser messageParser = new SocialMessageParser(postText);
String escapedPostText = messageParser.getParsedMessage(); String escapedPostText = messageParser.getParsedMessage();
@ -132,60 +132,63 @@ public class SocialUtils {
ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(postText)); ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(postText));
ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers); ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get()); SocialNetworkingSite site = SocialNetworkingSiteFinder
.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
escapedPostText = Utils.convertMentionUsernamesAnchorHTML(escapedPostText, mentionedUsersToConvertInHTML, site.getSiteURL(), site.getSiteLandingPagePath()); escapedPostText = Utils.convertMentionUsernamesAnchorHTML(escapedPostText, mentionedUsersToConvertInHTML,
site.getSiteURL(), site.getSiteLandingPagePath());
logger.debug("*** Escaped post text is " + escapedPostText); logger.debug("*** Escaped post text is " + escapedPostText);
String scope = ScopeProvider.instance.get(); String scope = ScopeProvider.instance.get();
String appId = caller.getClient().getId(); String appId = caller.getClient().getId();
Post toWrite = Post toWrite = buildPost(
buildPost( escapedPostText,
escapedPostText, uriParams == null ? "" : uriParams,
uriParams == null ? "" : uriParams, previewTitle == null ? "" : previewTitle,
previewTitle == null ? "" : previewTitle, previewDescription == null ? "" : previewDescription,
previewDescription == null ? "" : previewDescription, httpImageUrl == null ? "" : httpImageUrl,
httpImageUrl == null ? "" : httpImageUrl, applicationProfile,
applicationProfile, scope);
scope);
// try to save it // try to save it
boolean res = CassandraConnection.getInstance().getDatabookStore().saveAppPost(toWrite); boolean res = CassandraConnection.getInstance().getDatabookStore().saveAppPost(toWrite);
if(res){ if (res) {
logger.debug("Feed correctly written by application " + appId); logger.debug("Feed correctly written by application " + appId);
// wait a bit before saving hashtags // wait a bit before saving hashtags
if(hashtags != null && !hashtags.isEmpty()) if (hashtags != null && !hashtags.isEmpty())
new Thread(()->{ new Thread(() -> {
try { try {
Thread.sleep(1000); Thread.sleep(1000);
CassandraConnection.getInstance().getDatabookStore().saveHashTags(toWrite.getKey(), scope, hashtags); CassandraConnection.getInstance().getDatabookStore().saveHashTags(toWrite.getKey(), scope,
hashtags);
} catch (Exception e1) { } catch (Exception e1) {
logger.error("Failed to save hashtags in Cassandra", e1); logger.error("Failed to save hashtags in Cassandra", e1);
} }
}).start(); }).start();
// build the notification manager
// build the notification manager SocialNetworkingUser user = new SocialNetworkingUser(appId, "", applicationProfile.getName(),
applicationProfile.getImageUrl());
SocialNetworkingUser user = new SocialNetworkingUser(appId, "", applicationProfile.getName(), applicationProfile.getImageUrl());
NotificationsManager nm = new ApplicationNotificationsManager( NotificationsManager nm = new ApplicationNotificationsManager(
UserManagerWSBuilder.getInstance().getUserManager(), UserManagerWSBuilder.getInstance().getUserManager(),
site, site,
scope, scope,
user, user,
NEWS_FEED_PORTLET_CLASSNAME); NEWS_FEED_PORTLET_CLASSNAME);
if (!mentionedUsers.isEmpty()) if (!mentionedUsers.isEmpty())
new Thread(new MentionNotificationsThread(toWrite.getKey(), toWrite.getDescription(), nm, null, mentionedUsers)).start(); new Thread(new MentionNotificationsThread(toWrite.getKey(), toWrite.getDescription(), nm, null,
mentionedUsers)).start();
if(notifyGroup){ if (notifyGroup) {
logger.debug("Sending notifications for " + appId + " " + scope); logger.debug("Sending notifications for " + appId + " " + scope);
try{ try {
String name = new ScopeBean(scope).name(); // scope such as devVRE String name = new ScopeBean(scope).name(); // scope such as devVRE
@ -193,28 +196,26 @@ public class SocialUtils {
GroupManager gManager = GroupManagerWSBuilder.getInstance().getGroupManager(); GroupManager gManager = GroupManagerWSBuilder.getInstance().getGroupManager();
long groupId = gManager.getGroupId(name); long groupId = gManager.getGroupId(name);
String groupName = gManager.getGroup(groupId).getGroupName(); String groupName = gManager.getGroup(groupId).getGroupName();
logger.debug("Company id and name " + groupId + " " + groupName); logger.debug("Company id and name " + groupId + " " + groupName);
// start notification thread // start notification thread
new Thread(new PostNotificationsThread( new Thread(new PostNotificationsThread(
UserManagerWSBuilder.getInstance().getUserManager(), UserManagerWSBuilder.getInstance().getUserManager(),
toWrite.getKey(), toWrite.getKey(),
toWrite.getDescription(), toWrite.getDescription(),
""+groupId, "" + groupId,
nm, nm,
new HashSet<String>(hashtags), new HashSet<String>(hashtags),
new HashSet<String>()) new HashSet<String>())).start();
).start(); } catch (Exception e) {
}catch (Exception e) {
logger.debug("Feed succesfully created but unable to send notifications."); logger.debug("Feed succesfully created but unable to send notifications.");
} }
} }
return toWrite; return toWrite;
} } else
else
return null; return null;
} }
@ -222,82 +223,88 @@ public class SocialUtils {
/** /**
* Build an ApplicationProfile Feed. * Build an ApplicationProfile Feed.
* *
* @param description add a description for the update you are sharing * @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 uriParams the additional parameters your applicationProfile
* @param previewTitle the title to show in the preview * needs to open the subject of this update e.g.
* @param previewDescription the description to show in the preview * 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 * @param previewThumbnailUrl the image url to show in the preview
* @return a feed instance ready to be written * @return a feed instance ready to be written
*/ */
private static Post buildPost( private static Post buildPost(
String description, String description,
String uriParams, String uriParams,
String previewTitle, String previewTitle,
String previewDescription, String previewDescription,
String previewThumbnailUrl, String previewThumbnailUrl,
ApplicationProfile applicationProfile, ApplicationProfile applicationProfile,
String scopeApp) { String scopeApp) {
String uri = applicationProfile.getUrl(); String uri = applicationProfile.getUrl();
//add the GET params if necessary // add the GET params if necessary
if (uriParams != null && uriParams.compareTo("") != 0) if (uriParams != null && uriParams.compareTo("") != 0)
uri += "?"+uriParams; uri += "?" + uriParams;
Post toReturn = new Post( Post toReturn = new Post(
UUID.randomUUID().toString(), UUID.randomUUID().toString(),
PostType.PUBLISH, PostType.PUBLISH,
applicationProfile.getKey(), applicationProfile.getKey(),
new Date(), new Date(),
scopeApp, scopeApp,
uri, uri,
previewThumbnailUrl, previewThumbnailUrl,
description, description,
PrivacyLevel.SINGLE_VRE, PrivacyLevel.SINGLE_VRE,
applicationProfile.getName(), applicationProfile.getName(),
"no-email", "no-email",
applicationProfile.getImageUrl(), applicationProfile.getImageUrl(),
previewTitle, previewTitle,
previewDescription, previewDescription,
"", "",
true); true);
return toReturn; return toReturn;
} }
/** /**
* This method looks up the applicationProfile profile among the ones available in the infrastructure * This method looks up the applicationProfile profile among the ones available
* @param idApp as identifier of your application (as reported in the ApplicationProfile) * in the infrastructure
*
* @param idApp as identifier of your application (as reported in the
* ApplicationProfile)
* @param scopeApp the scope of the application * @param scopeApp the scope of the application
*/ */
public static ApplicationProfile getProfileFromInfrastrucure(String idApp, String scopeApp) { public static ApplicationProfile getProfileFromInfrastrucure(String idApp, String scopeApp) {
ScopeBean scope = new ScopeBean(scopeApp); ScopeBean scope = new ScopeBean(scopeApp);
logger.debug("Trying to fetch applicationProfile profile from the infrastructure for " + idApp + " scope: " + scope); logger.debug(
"Trying to fetch applicationProfile profile from the infrastructure for " + idApp + " scope: " + scope);
// set the scope of the root infrastructure // set the scope of the root infrastructure
String rootInfrastructure = scopeApp.split("/")[1]; String rootInfrastructure = scopeApp.split("/")[1];
ScopeProvider.instance.set("/"+rootInfrastructure); ScopeProvider.instance.set("/" + rootInfrastructure);
try { try {
ApplicationProfile toReturn = new ApplicationProfile(); ApplicationProfile toReturn = new ApplicationProfile();
Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource " + 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() " + "where $profile/Profile/SecondaryType/string() eq 'ApplicationProfile' and $profile/Profile/Body/AppId/string() "
+
" eq '" + idApp + "'" + " eq '" + idApp + "'" +
"return $profile"); "return $profile");
DiscoveryClient<String> client = client(); DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q); List<String> appProfile = client.submit(q);
if (appProfile == null || appProfile.size() == 0) if (appProfile == null || appProfile.size() == 0)
throw new Exception("Your applicationProfile is not registered in the infrastructure"); throw new Exception("Your applicationProfile is not registered in the infrastructure");
else { else {
String elem = appProfile.get(0); String elem = appProfile.get(0);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement(); Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
XPathHelper helper = new XPathHelper(node); XPathHelper helper = new XPathHelper(node);
@ -307,16 +314,17 @@ public class SocialUtils {
toReturn.setName(currValue.get(0)); toReturn.setName(currValue.get(0));
} } else
else throw new ApplicationProfileNotFoundException("Your applicationProfile NAME was not found in the profile"); throw new ApplicationProfileNotFoundException(
"Your applicationProfile NAME was not found in the profile");
currValue = helper.evaluate("/Resource/Profile/Description/text()"); currValue = helper.evaluate("/Resource/Profile/Description/text()");
if (currValue != null && currValue.size() > 0) { if (currValue != null && currValue.size() > 0) {
toReturn.setDescription(currValue.get(0)); toReturn.setDescription(currValue.get(0));
} } else
else logger.warn("No Description exists for " + toReturn.getName()); logger.warn("No Description exists for " + toReturn.getName());
currValue = helper.evaluate("/Resource/Profile/Body/AppId/text()"); currValue = helper.evaluate("/Resource/Profile/Body/AppId/text()");
@ -324,35 +332,41 @@ public class SocialUtils {
toReturn.setKey(currValue.get(0)); toReturn.setKey(currValue.get(0));
} } else
else throw new ApplicationProfileNotFoundException("Your applicationProfile ID n was not found in the profile, consider adding <AppId> element in <Body>"); 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()"); currValue = helper.evaluate("/Resource/Profile/Body/ThumbnailURL/text()");
if (currValue != null && currValue.size() > 0) { if (currValue != null && currValue.size() > 0) {
toReturn.setImageUrl(currValue.get(0)); toReturn.setImageUrl(currValue.get(0));
} } else
else throw new Exception("Your applicationProfile Image Url was not found in the profile, consider adding <ThumbnailURL> element in <Body>"); 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()"); currValue = helper.evaluate("/Resource/Profile/Body/EndPoint/Scope/text()");
if (currValue != null && currValue.size() > 0) { if (currValue != null && currValue.size() > 0) {
List<String> scopes = currValue; List<String> scopes = currValue;
boolean foundUrl = false; boolean foundUrl = false;
for (int i = 0; i < scopes.size(); i++) { for (int i = 0; i < scopes.size(); i++) {
if (currValue.get(i).trim().compareTo(scope.toString()) == 0) { if (currValue.get(i).trim().compareTo(scope.toString()) == 0) {
toReturn.setUrl(helper.evaluate("/Resource/Profile/Body/EndPoint/URL/text()").get(i)); toReturn.setUrl(helper.evaluate("/Resource/Profile/Body/EndPoint/URL/text()").get(i));
toReturn.setScope(scope.toString()); toReturn.setScope(scope.toString());
foundUrl = true; foundUrl = true;
break; break;
} }
} }
if (! foundUrl) if (!foundUrl)
throw new ApplicationProfileNotFoundException("Your applicationProfile URL was not found in the profile for Scope: " + scope.toString()); 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>"); else
throw new ApplicationProfileNotFoundException(
"Your applicationProfile EndPoint was not found in the profile, consider adding <EndPoint><Scope> element in <Body>");
logger.debug("Returning " + toReturn); logger.debug("Returning " + toReturn);
return toReturn; return toReturn;
} }
@ -361,7 +375,7 @@ public class SocialUtils {
logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", e); logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", e);
} finally{ } finally {
// set the scope back // set the scope back
ScopeProvider.instance.set(scopeApp); ScopeProvider.instance.set(scopeApp);
@ -374,6 +388,7 @@ public class SocialUtils {
/** /**
* Allows user to post a feed in a certain vre. * Allows user to post a feed in a certain vre.
*
* @param userId * @param userId
* @param postText * @param postText
* @param vreId * @param vreId
@ -388,24 +403,26 @@ public class SocialUtils {
public static Post shareUserUpdate( public static Post shareUserUpdate(
String userId, String userId,
String postText, String postText,
String vreId, String vreId,
String previewTitle, String previewTitle,
String previewDescription, String previewDescription,
String previewHost, String previewHost,
String previewUrl, String previewUrl,
String urlThumbnail, String urlThumbnail,
boolean notifyGroup) { boolean notifyGroup) {
SocialMessageParser messageParser = new SocialMessageParser(postText); SocialMessageParser messageParser = new SocialMessageParser(postText);
String escapedPostText = messageParser.getParsedMessage(); String escapedPostText = messageParser.getParsedMessage();
List<String> hashtags = messageParser.getHashtags(); List<String> hashtags = messageParser.getHashtags();
//check if any mention exists // check if any mention exists
ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(postText)); ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(postText));
ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers); ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get()); SocialNetworkingSite site = SocialNetworkingSiteFinder
.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
escapedPostText = Utils.convertMentionUsernamesAnchorHTML(escapedPostText, mentionedUsersToConvertInHTML, site.getSiteURL(), site.getSiteLandingPagePath()); escapedPostText = Utils.convertMentionUsernamesAnchorHTML(escapedPostText, mentionedUsersToConvertInHTML,
site.getSiteURL(), site.getSiteLandingPagePath());
GCubeUser user; GCubeUser user;
@ -413,7 +430,7 @@ public class SocialUtils {
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
try { try {
user = uManager.getUserByUsername(userId); user = uManager.getUserByUsername(userId);
} catch(Exception e){ } catch (Exception e) {
logger.error("Unable to get user informations, post write fails.", e); logger.error("Unable to get user informations, post write fails.", e);
return null; return null;
} }
@ -428,7 +445,7 @@ public class SocialUtils {
if (urlThumbnail == null) if (urlThumbnail == null)
urlThumbnail = "null"; urlThumbnail = "null";
//this means the user has shared a file without text in it. // this means the user has shared a file without text in it.
String textToPost = ""; String textToPost = "";
if (escapedPostText.trim().compareTo(NO_TEXT_FILE_SHARE) == 0) { if (escapedPostText.trim().compareTo(NO_TEXT_FILE_SHARE) == 0) {
textToPost = org.gcube.social_networking.socialutillibrary.Utils.convertFileNameAnchorHTML(url); textToPost = org.gcube.social_networking.socialutillibrary.Utils.convertFileNameAnchorHTML(url);
@ -437,23 +454,25 @@ public class SocialUtils {
} }
Post toShare = new Post(UUID.randomUUID().toString(), PostType.PUBLISH, userId, new Date(), 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); 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); logger.debug("Attempting to save Post with text: " + textToPost + " Level = " + PrivacyLevel.SINGLE_VRE
+ " Timeline = " + vreId);
boolean result = CassandraConnection.getInstance().getDatabookStore().saveUserPost(toShare); boolean result = CassandraConnection.getInstance().getDatabookStore().saveUserPost(toShare);
if(vreId != null && vreId.compareTo("") != 0 && result) { if (vreId != null && vreId.compareTo("") != 0 && result) {
logger.trace("Attempting to write onto " + vreId); logger.trace("Attempting to write onto " + vreId);
try { try {
try{ try {
logger.debug("Sleeping waiting for cassandra's update"); logger.debug("Sleeping waiting for cassandra's update");
Thread.sleep(1000); Thread.sleep(1000);
}catch(Exception e){ } catch (Exception e) {
logger.error(e.toString()); logger.error(e.toString());
@ -461,27 +480,31 @@ public class SocialUtils {
CassandraConnection.getInstance().getDatabookStore().saveFeedToVRETimeline(toShare.getKey(), vreId); CassandraConnection.getInstance().getDatabookStore().saveFeedToVRETimeline(toShare.getKey(), vreId);
if (hashtags != null && !hashtags.isEmpty()) if (hashtags != null && !hashtags.isEmpty())
CassandraConnection.getInstance().getDatabookStore().saveHashTags(toShare.getKey(), vreId, hashtags); CassandraConnection.getInstance().getDatabookStore().saveHashTags(toShare.getKey(), vreId,
hashtags);
} catch (FeedIDNotFoundException e) { } catch (FeedIDNotFoundException e) {
logger.error("Error writing onto VRES Time Line" + vreId); logger.error("Error writing onto VRES Time Line" + vreId);
} }
logger.trace("Success writing onto " + vreId); logger.trace("Success writing onto " + vreId);
} }
if (!result) if (!result)
return null; return null;
SocialNetworkingUser socialUser = SocialNetworkingUser socialUser = new SocialNetworkingUser(userId, email, fullName, thumbnailURL);
new SocialNetworkingUser(userId, email, fullName, thumbnailURL); NotificationsManager nm = new ApplicationNotificationsManager(
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, vreId, socialUser, NEWS_FEED_PORTLET_CLASSNAME); UserManagerWSBuilder.getInstance().getUserManager(), site, vreId, socialUser,
NEWS_FEED_PORTLET_CLASSNAME);
if (!mentionedUsers.isEmpty()) if (!mentionedUsers.isEmpty())
new Thread(new MentionNotificationsThread(toShare.getKey(), toShare.getDescription(), nm, null, mentionedUsers)).start(); 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 // send the notification about this posts to everyone in the group if
// notifyGroup is true
if (vreId != null && vreId.compareTo("") != 0 && notifyGroup) { if (vreId != null && vreId.compareTo("") != 0 && notifyGroup) {
try{ try {
// retrieve group information // retrieve group information
GroupManager gManager = GroupManagerWSBuilder.getInstance().getGroupManager(); GroupManager gManager = GroupManagerWSBuilder.getInstance().getGroupManager();
// handle the scope // handle the scope
@ -493,51 +516,56 @@ public class SocialUtils {
new Thread( new Thread(
new PostNotificationsThread( new PostNotificationsThread(
UserManagerWSBuilder.getInstance().getUserManager(), UserManagerWSBuilder.getInstance().getUserManager(),
toShare.getKey(), toShare.getKey(),
toShare.getDescription(), toShare.getDescription(),
""+groupId, "" + groupId,
nm, nm,
new HashSet<String>(), new HashSet<String>(),
new HashSet<String>(hashtags)) new HashSet<String>(hashtags)))
).start(); .start();
logger.debug("Start sending notifications for post written by " + userId); logger.debug("Start sending notifications for post written by " + userId);
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to notify users", e); logger.error("Unable to notify users", e);
} }
} }
return toShare; return toShare;
} }
/** /**
* Allows to comment post in a certain vre. * Allows to comment post in a certain vre.
*
* @param userid the username * @param userid the username
* @param time the date and time of the comment * @param time the date and time of the comment
* @param postId the key of the post that was commented * @param postId the key of the post that was commented
* @param commentText the text as it is, it will be parsed * @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 postOwnerId the username of the user who created the post that was
* @param context the VRE context * commented
* @param context the VRE context
* *
* @return the Comment instance if ok, null if somwthign went KO * @return the Comment instance if ok, null if somwthign went KO
* @throws FeedIDNotFoundException * @throws FeedIDNotFoundException
*/ */
public static Comment commentPost(String userid, Date time, String postId, String commentText, String postOwnerId, String context) 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); SocialMessageParser messageParser = new SocialMessageParser(commentText);
String escapedCommentText = messageParser.getParsedMessage(); String escapedCommentText = messageParser.getParsedMessage();
//check if any mention exists // check if any mention exists
ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(commentText)); ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(commentText));
ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers); ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get()); SocialNetworkingSite site = SocialNetworkingSiteFinder
.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
escapedCommentText = Utils.convertMentionUsernamesAnchorHTML(escapedCommentText, mentionedUsersToConvertInHTML, site.getSiteURL(), site.getSiteLandingPagePath()); escapedCommentText = Utils.convertMentionUsernamesAnchorHTML(escapedCommentText, mentionedUsersToConvertInHTML,
site.getSiteURL(), site.getSiteLandingPagePath());
// retrieve user information // retrieve user information
GCubeUser user; GCubeUser user;
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
try { try {
user = uManager.getUserByUsername(userid); user = uManager.getUserByUsername(userid);
} catch(Exception e){ } catch (Exception e) {
logger.error("Unable to get user informations, comment write fails.", e); logger.error("Unable to get user informations, comment write fails.", e);
return null; return null;
} }
@ -546,57 +574,62 @@ public class SocialUtils {
String fullName = user.getFirstName() + " " + user.getLastName(); String fullName = user.getFirstName() + " " + user.getLastName();
String thumbnailURL = user.getUserAvatarURL(); String thumbnailURL = user.getUserAvatarURL();
Comment theComment = new Comment(commentKey, userid, time, postId, escapedCommentText, fullName, thumbnailURL); Comment theComment = new Comment(commentKey, userid, time, postId, escapedCommentText, fullName, thumbnailURL);
logger.debug("Attempting to save Comment with text: " + commentText + " postid="+postId); logger.debug("Attempting to save Comment with text: " + commentText + " postid=" + postId);
boolean result = CassandraConnection.getInstance().getDatabookStore().addComment(theComment); boolean result = CassandraConnection.getInstance().getDatabookStore().addComment(theComment);
logger.debug("Added comment? " + theComment.toString() + " Result is " +result); logger.debug("Added comment? " + theComment.toString() + " Result is " + result);
if (!result) if (!result)
return null; return null;
//if the comment was correctly delivered notify users involved // if the comment was correctly delivered notify users involved
SocialNetworkingUser socialUser = new SocialNetworkingUser(userid, email, fullName, thumbnailURL); SocialNetworkingUser socialUser = new SocialNetworkingUser(userid, email, fullName, thumbnailURL);
NotificationsManager nm = new ApplicationNotificationsManager(uManager, site, context, socialUser, NEWS_FEED_PORTLET_CLASSNAME); 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) // 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); logger.debug("The post creator is " + postOwnerId);
if (! user.getUsername().equals(postOwnerId)) { if (!user.getUsername().equals(postOwnerId)) {
boolean resultNotifyOwnComment = nm.notifyOwnCommentReply(postOwnerId, postId, escapedCommentText, theComment.getKey()); boolean resultNotifyOwnComment = nm.notifyOwnCommentReply(postOwnerId, postId, escapedCommentText,
theComment.getKey());
logger.debug("Comment Notification to post creator added? " + resultNotifyOwnComment); logger.debug("Comment Notification to post creator added? " + resultNotifyOwnComment);
} }
//if there are users who liked this post they get notified, asynchronously with this thread // if there are users who liked this post they get notified, asynchronously with
// this thread
ArrayList<Like> likes = getAllLikesByPost(postId); ArrayList<Like> likes = getAllLikesByPost(postId);
Thread likesThread = new Thread(new LikeNotificationsThread(escapedCommentText, nm, likes, postOwnerId, theComment.getKey())); Thread likesThread = new Thread(
new LikeNotificationsThread(escapedCommentText, nm, likes, postOwnerId, theComment.getKey()));
likesThread.start(); likesThread.start();
//notify the other users who commented this post (excluding the ones above) // notify the other users who commented this post (excluding the ones above)
Thread commentsNotificationthread = new Thread(new CommentNotificationsThread( Thread commentsNotificationthread = new Thread(new CommentNotificationsThread(
CassandraConnection.getInstance().getDatabookStore(), CassandraConnection.getInstance().getDatabookStore(),
uManager, user.getUsername(), theComment.getFeedid(), escapedCommentText, nm, postOwnerId, theComment.getKey(), likes)); uManager, user.getUsername(), theComment.getFeedid(), escapedCommentText, nm, postOwnerId,
commentsNotificationthread.start(); theComment.getKey(), likes));
commentsNotificationthread.start();
//send the notification to the mentioned users, if any // send the notification to the mentioned users, if any
if (mentionedUsers != null && mentionedUsers.size() > 0) { if (mentionedUsers != null && mentionedUsers.size() > 0) {
ArrayList<GenericItemBean> toPass = new ArrayList<GenericItemBean>(); ArrayList<GenericItemBean> toPass = new ArrayList<GenericItemBean>();
// among the mentionedUsers there could be groups of people // among the mentionedUsers there could be groups of people
Map<String, ItemBean> uniqueUsersToNotify = new HashMap<>(); Map<String, ItemBean> uniqueUsersToNotify = new HashMap<>();
UserManager um = new LiferayUserManager(); UserManager um = new LiferayUserManager();
for (ItemBean bean : mentionedUsersToConvertInHTML) { for (ItemBean bean : mentionedUsersToConvertInHTML) {
if(bean.isItemGroup()){ if (bean.isItemGroup()) {
// retrieve the users of this group // retrieve the users of this group
try { try {
List<GCubeUser> teamUsers = um.listUsersByTeam(Long.parseLong(bean.getId())); List<GCubeUser> teamUsers = um.listUsersByTeam(Long.parseLong(bean.getId()));
for (GCubeUser userTeam : teamUsers) { for (GCubeUser userTeam : teamUsers) {
if(!uniqueUsersToNotify.containsKey(userTeam.getUsername())) if (!uniqueUsersToNotify.containsKey(userTeam.getUsername()))
uniqueUsersToNotify.put(userTeam.getUsername(), new ItemBean(userTeam.getUserId()+"", uniqueUsersToNotify.put(userTeam.getUsername(), new ItemBean(userTeam.getUserId() + "",
userTeam.getUsername(), userTeam.getFullname(), userTeam.getUserAvatarURL())); userTeam.getUsername(), userTeam.getFullname(), userTeam.getUserAvatarURL()));
} }
@ -606,9 +639,9 @@ public class SocialUtils {
logger.error("Unable to retrieve team information", e); logger.error("Unable to retrieve team information", e);
} }
}else{ } else {
// it is a user, just add to the hashmap // it is a user, just add to the hashmap
if(!uniqueUsersToNotify.containsKey(bean.getName())) if (!uniqueUsersToNotify.containsKey(bean.getName()))
uniqueUsersToNotify.put(bean.getName(), bean); uniqueUsersToNotify.put(bean.getName(), bean);
} }
@ -620,17 +653,20 @@ public class SocialUtils {
Map.Entry<String, ItemBean> userEntry = (Map.Entry<String, ItemBean>) userMapIterator Map.Entry<String, ItemBean> userEntry = (Map.Entry<String, ItemBean>) userMapIterator
.next(); .next();
ItemBean userBean = userEntry.getValue(); ItemBean userBean = userEntry.getValue();
toPass.add(new GenericItemBean(userBean.getId(), userBean.getName(), userBean.getAlternativeName(), userBean.getThumbnailURL())); 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 thread = new Thread(
new MentionNotificationsThread(theComment.getFeedid(), escapedCommentText, nm, null, toPass));
thread.start(); thread.start();
} }
return theComment; return theComment;
} }
private static ArrayList<Like> getAllLikesByPost(String postid) { private static ArrayList<Like> getAllLikesByPost(String postid) {
ArrayList<Like> toReturn = (ArrayList<Like>) CassandraConnection.getInstance().getDatabookStore().getAllLikesByPost(postid); ArrayList<Like> toReturn = (ArrayList<Like>) CassandraConnection.getInstance().getDatabookStore()
.getAllLikesByPost(postid);
logger.debug("Asking likes for " + postid); logger.debug("Asking likes for " + postid);
for (Like like : toReturn) { for (Like like : toReturn) {
// retrieve user information // retrieve user information
@ -638,7 +674,7 @@ public class SocialUtils {
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
try { try {
user = uManager.getUserByUsername(like.getUserid()); user = uManager.getUserByUsername(like.getUserid());
} catch(Exception e){ } catch (Exception e) {
logger.error("Unable to get user informations, comment write fails.", e); logger.error("Unable to get user informations, comment write fails.", e);
return null; return null;
} }
@ -656,7 +692,7 @@ public class SocialUtils {
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
try { try {
user = uManager.getUserByUsername(username); user = uManager.getUserByUsername(username);
} catch(Exception e){ } catch (Exception e) {
logger.error("Unable to get user informations, like write fails.", e); logger.error("Unable to get user informations, like write fails.", e);
return false; return false;
} }
@ -664,40 +700,44 @@ public class SocialUtils {
String fullName = user.getFirstName() + " " + user.getLastName(); String fullName = user.getFirstName() + " " + user.getLastName();
String thumbnailURL = user.getUserAvatarURL(); String thumbnailURL = user.getUserAvatarURL();
SocialNetworkingUser socialUser = new SocialNetworkingUser(user.getUsername(), email, fullName, thumbnailURL); SocialNetworkingUser socialUser = new SocialNetworkingUser(user.getUsername(), email, fullName, thumbnailURL);
Like toLike = new Like(UUID.randomUUID().toString(), user.getUsername(), Like toLike = new Like(UUID.randomUUID().toString(), user.getUsername(),
new Date(), postid, user.getFullname(), user.getUserAvatarURL()); new Date(), postid, user.getFullname(), user.getUserAvatarURL());
Post thePost = null; Post thePost = null;
try { try {
logger.debug("Attempting to read post with id: " +postid); logger.debug("Attempting to read post with id: " + postid);
thePost = CassandraConnection.getInstance().getDatabookStore().readPost(postid); thePost = CassandraConnection.getInstance().getDatabookStore().readPost(postid);
likeCommitResult = CassandraConnection.getInstance().getDatabookStore().like(toLike); likeCommitResult = CassandraConnection.getInstance().getDatabookStore().like(toLike);
} catch (Exception e) { } catch (Exception e) {
logger.error("Post not found for this like ot could not like the post " + e.getMessage()); logger.error("Post not found for this like ot could not like the post " + e.getMessage());
return false; return false;
} }
//if the like was correctly delivered notify the user who made the post // if the like was correctly delivered notify the user who made the post
boolean resultNotifyLike =false; boolean resultNotifyLike = false;
if (likeCommitResult) { if (likeCommitResult) {
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get()); SocialNetworkingSite site = SocialNetworkingSiteFinder
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, context, socialUser, NEWS_FEED_PORTLET_CLASSNAME); .getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
NotificationsManager nm = new ApplicationNotificationsManager(
UserManagerWSBuilder.getInstance().getUserManager(), site, context, socialUser,
NEWS_FEED_PORTLET_CLASSNAME);
String postText = thePost.getDescription(); String postText = thePost.getDescription();
String postOwnerId = thePost.getEntityId(); String postOwnerId = thePost.getEntityId();
SocialMessageParser messageParser = new SocialMessageParser(postText); SocialMessageParser messageParser = new SocialMessageParser(postText);
String escapedPostText = messageParser.getParsedMessage(); String escapedPostText = messageParser.getParsedMessage();
//if the user who liked this post is not the user who posted it notify the poster user (Post owner) // if the user who liked this post is not the user who posted it notify the
logger.debug("The post creator is " + postOwnerId); // poster user (Post owner)
if (! user.getUsername().equals(postOwnerId)) { logger.debug("The post creator is " + postOwnerId);
if (!user.getUsername().equals(postOwnerId)) {
resultNotifyLike = nm.notifyLikedPost(postOwnerId, postid, escapedPostText); resultNotifyLike = nm.notifyLikedPost(postOwnerId, postid, escapedPostText);
logger.debug("Like Notification to post creator added? " + resultNotifyLike); logger.debug("Like Notification to post creator added? " + resultNotifyLike);
} }
} }
return likeCommitResult && resultNotifyLike; return likeCommitResult && resultNotifyLike;
} }
public static boolean unlike(String username, String likeid, String postid) { public static boolean unlike(String username, String likeid, String postid) {
boolean unlikeCommitResult = false; boolean unlikeCommitResult = false;
// retrieve user information // retrieve user information
@ -705,20 +745,20 @@ public class SocialUtils {
UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager(); UserManager uManager = UserManagerWSBuilder.getInstance().getUserManager();
try { try {
user = uManager.getUserByUsername(username); user = uManager.getUserByUsername(username);
} catch(Exception e){ } catch (Exception e) {
logger.error("Unable to get user informations, unlike write fails.", e); logger.error("Unable to get user informations, unlike write fails.", e);
return false; return false;
} }
String fullName = user.getFirstName() + " " + user.getLastName(); String fullName = user.getFirstName() + " " + user.getLastName();
String thumbnailURL = user.getUserAvatarURL(); String thumbnailURL = user.getUserAvatarURL();
try { try {
unlikeCommitResult = CassandraConnection.getInstance().getDatabookStore().unlike(username, likeid, postid); unlikeCommitResult = CassandraConnection.getInstance().getDatabookStore().unlike(username, likeid, postid);
} catch (Exception e) { } catch (Exception e) {
logger.error("Post not Found for this like ot could not unlike the post " + e.getMessage()); logger.error("Post not Found for this like ot could not unlike the post " + e.getMessage());
return false; return false;
} }
return unlikeCommitResult; return unlikeCommitResult;
} }

View File

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

View File

@ -19,7 +19,7 @@ public class UserProfileExtendedWithVerifiedEmail {
@JsonProperty("name") @JsonProperty("name")
private String fullname; private String fullname;
@JsonProperty("middle_name") @JsonProperty("middle_name")
private String middleName; private String middleName;
@ -188,7 +188,4 @@ public class UserProfileExtendedWithVerifiedEmail {
return builder.toString(); return builder.toString();
} }
} }

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <web-app xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"> version="3.0">
<display-name>Restful Web Application</display-name> <display-name>Restful Web Application</display-name>
@ -39,4 +39,4 @@
<welcome-file-list> <welcome-file-list>
<welcome-file>index.jsp</welcome-file> <welcome-file>index.jsp</welcome-file>
</welcome-file-list> </welcome-file-list>
</web-app> </web-app>

View File

@ -34,36 +34,41 @@ public class GcoreEndpointReader {
String currentScope = ScopeProvider.instance.get(); String currentScope = ScopeProvider.instance.get();
try{ try {
logger.info("set scope "+scope); logger.info("set scope " + scope);
ScopeProvider.instance.set(scope); ScopeProvider.instance.set(scope);
SimpleQuery query = queryFor(GCoreEndpoint.class); SimpleQuery query = queryFor(GCoreEndpoint.class);
query.addCondition(String.format("$resource/Profile/ServiceClass/text() eq '%s'",serviceClass)); query.addCondition(String.format("$resource/Profile/ServiceClass/text() eq '%s'", serviceClass));
query.addCondition("$resource/Profile/DeploymentData/Status/text() eq 'ready'"); query.addCondition("$resource/Profile/DeploymentData/Status/text() eq 'ready'");
query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'",serviceName)); query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'", serviceName));
query.setResult("$resource/Profile/AccessPoint/RunningInstanceInterfaces//Endpoint[@EntryName/string() eq \""+resource+"\"]/text()"); query.setResult(
"$resource/Profile/AccessPoint/RunningInstanceInterfaces//Endpoint[@EntryName/string() eq \""
+ resource + "\"]/text()");
logger.debug("submitting quey "+query.toString()); logger.debug("submitting quey " + query.toString());
DiscoveryClient<String> client = client(); DiscoveryClient<String> client = client();
List<String> endpoints = client.submit(query); 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); if (endpoints == null || endpoints.isEmpty())
throw new Exception("Cannot retrieve the GCoreEndpoint serviceName: " + serviceName + ", serviceClass: "
+ serviceClass + ", in scope: " + scope);
this.resourceEntyName = endpoints.get(0); this.resourceEntyName = endpoints.get(0);
if(resourceEntyName==null) if (resourceEntyName == null)
throw new Exception("Endpoint:"+resource+", is null for serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+scope); throw new Exception("Endpoint:" + resource + ", is null for serviceName: " + serviceName
+ ", serviceClass: " + serviceClass + ", in scope: " + scope);
logger.info("found entyname "+resourceEntyName+" for ckanResource: "+resource); logger.info("found entyname " + resourceEntyName + " for ckanResource: " + resource);
}catch(Exception e){ } catch (Exception e) {
String error = "An error occurred during GCoreEndpoint discovery, serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+scope +"."; String error = "An error occurred during GCoreEndpoint discovery, serviceName: " + serviceName
+ ", serviceClass: " + serviceClass + ", in scope: " + scope + ".";
logger.error(error, e); logger.error(error, e);
throw new Exception(error); throw new Exception(error);
}finally{ } finally {
if(currentScope != null) if (currentScope != null)
ScopeProvider.instance.set(currentScope); ScopeProvider.instance.set(currentScope);
} }
} }

View File

@ -16,6 +16,7 @@ import org.slf4j.LoggerFactory;
/** /**
* Retrieves the base url of the social-networking service in the scope provided * Retrieves the base url of the social-networking service in the scope provided
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public class ServiceEndPointReaderSocial { public class ServiceEndPointReaderSocial {
@ -26,23 +27,23 @@ public class ServiceEndPointReaderSocial {
private final static String RUNTIME_RESOURCE_NAME = "SocialNetworking"; private final static String RUNTIME_RESOURCE_NAME = "SocialNetworking";
private final static String CATEGORY = "Portal"; private final static String CATEGORY = "Portal";
public ServiceEndPointReaderSocial(String context){ public ServiceEndPointReaderSocial(String context) {
if(context == null || context.isEmpty()) if (context == null || context.isEmpty())
throw new IllegalArgumentException("A valid context is needed to discover the service"); throw new IllegalArgumentException("A valid context is needed to discover the service");
String oldContext = ScopeProvider.instance.get(); String oldContext = ScopeProvider.instance.get();
ScopeProvider.instance.set(context); ScopeProvider.instance.set(context);
try{ try {
List<ServiceEndpoint> resources = getConfigurationFromIS(); List<ServiceEndpoint> resources = getConfigurationFromIS();
if (resources.size() == 0){ if (resources.size() == 0) {
logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope."); logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME + " and Category "
throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope."); + CATEGORY + " in this scope.");
} throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME
else { + " and Category " + CATEGORY + " in this scope.");
} else {
for (ServiceEndpoint res : resources) { for (ServiceEndpoint res : resources) {
@ -62,13 +63,13 @@ public class ServiceEndPointReaderSocial {
} }
}catch(Exception e){ } catch (Exception e) {
logger.error("Unable to retrieve such service endpoint information!", e); logger.error("Unable to retrieve such service endpoint information!", e);
}finally{ } finally {
if(oldContext != null && !oldContext.equals(context)) if (oldContext != null && !oldContext.equals(context))
ScopeProvider.instance.set(oldContext); ScopeProvider.instance.set(oldContext);
} }
@ -79,14 +80,15 @@ public class ServiceEndPointReaderSocial {
/** /**
* 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;
@ -95,6 +97,7 @@ public class ServiceEndPointReaderSocial {
/** /**
* Get the base path of the social networking service * Get the base path of the social networking service
*
* @return * @return
*/ */
public String getBasePath() { public String getBasePath() {