secret instead of caller, used socialdbdriver

This commit is contained in:
Ahmed Salah Tawfik Ibrahim 2024-06-06 20:02:51 +02:00
parent d560078141
commit adfb010f61
18 changed files with 182 additions and 509 deletions

View File

@ -7,6 +7,7 @@ import org.gcube.idm.common.is.IsServerConfig;
import org.gcube.smartgears.ApplicationManager;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.social_networking.server.CassandraConnection;
import org.gcube.social_networking.utils.InfrastructureUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -41,6 +42,9 @@ public class SocialServiceApplicationManager implements ApplicationManager {
logger.debug("init called in null context");
}
}
//setting cassandra connection
CassandraConnection conn = CassandraConnection.getInstance();
}
/**

View File

@ -3,7 +3,6 @@ package org.gcube.social_networking.ws.methods.v2;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.validation.Valid;
import javax.validation.ValidationException;
@ -19,26 +18,22 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.smartgears.utils.InnerMethodName;
import org.gcube.social_networking.socialnetworking.model.shared.Comment;
import org.gcube.social_networking.socialnetworking.model.shared.Post;
import org.gcube.social_networking.socialnetworking.model.shared.exceptions.PostIDNotFoundException;
import org.gcube.social_networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.social_networking.ws.inputs.CommentInputBean;
import org.gcube.social_networking.ws.inputs.PostInputBean;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.server.CassandraConnection;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.Filters;
import org.gcube.social_networking.ws.utils.SocialUtils;
import org.gcube.socialnetworking.socialtoken.SocialMessageParser;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.slf4j.LoggerFactory;
import com.liferay.portlet.journal.FeedIdException;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
@ -78,9 +73,12 @@ public class Comments {
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
String username = caller.getClient().getId();
InnerMethodName.set("get-comments-by-post-id");
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
List<Comment> comments = null;
try{
@ -113,9 +111,10 @@ public class Comments {
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
String username = caller.getClient().getId();
InnerMethodName.set("get-comments-user");
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
List<Comment> comments = null;
try{
@ -148,9 +147,9 @@ public class Comments {
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
String username = caller.getClient().getId();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
List<Comment> comments = null;
try{
@ -187,10 +186,10 @@ public class Comments {
@NotNull(message="Comment to write is missing")
@Valid
CommentInputBean comment) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
logger.debug("Request of writing a comment coming from user " + username);
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
@ -201,7 +200,7 @@ public class Comments {
Date time = new Date();
String postOwnerId = CassandraConnection.getInstance().getDatabookStore().readPost(postId).getEntityId();
Comment theComment = SocialUtils.commentPost(userid, time, postId, commentText, postOwnerId, context);
Comment theComment = SocialUtils.commentPost(userid, time, postId, commentText, postOwnerId, context, secret);
if (theComment != null)
logger.debug("Added comment " + theComment.toString());
else {

View File

@ -22,14 +22,15 @@ import javax.ws.rs.core.Response.Status;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.social_networking.socialnetworking.model.shared.EnhancedPost;
import org.gcube.social_networking.socialnetworking.model.shared.Post;
import org.gcube.social_networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.social_networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.server.CassandraConnection;
import org.gcube.social_networking.server.SocialDBDriver;
import org.gcube.social_networking.ws.utils.ElasticSearchConnection;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.Filters;
@ -38,6 +39,7 @@ import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.glassfish.jersey.message.filtering.spi.ScopeProvider;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
@ -84,14 +86,15 @@ public class FullTextSearch {
int quantity
) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.BAD_REQUEST;
responseBean.setMessage("This method can be only invoked by using a user token.");
if(!TokensUtils.isUserToken(caller))
if(!TokensUtils.isUserToken(secret))
return Response.status(status).entity(responseBean).build();
status = Status.OK;
@ -129,8 +132,8 @@ public class FullTextSearch {
// query elastic search
List<EnhancedPost> enhancedPosts = ElasticSearchConnection.getSingleton().getElasticSearchClient().search(query, vres, from, quantity);
Filters.hideSensitiveInformation(enhancedPosts, caller.getClient().getId());
DatabookStore store = CassandraConnection.getInstance().getDatabookStore();
Filters.hideSensitiveInformation(enhancedPosts, secret.getOwner().getId());
SocialDBDriver store = CassandraConnection.getInstance().getDatabookStore();
// retrieve the ids of liked Posts by the user
List<String> likedPosts = store.getAllLikedPostIdsByUser(username);

View File

@ -1,25 +1,19 @@
package org.gcube.social_networking.ws.methods.v2;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.ValidationException;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.social_networking.socialnetworking.model.shared.Post;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.social_networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.server.CassandraConnection;
import org.gcube.social_networking.server.SocialDBDriver;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.slf4j.LoggerFactory;
@ -54,16 +48,17 @@ public class HashTags {
*/
public Response getHashTagsAndOccurrences(){
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
logger.debug("User " + username + " has requested hashtags of context " + context);
try{
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
SocialDBDriver datastore = CassandraConnection.getInstance().getDatabookStore();
// TODO handle the case of VO and ROOT
boolean isVRE = GroupManagerWSBuilder.getInstance().getGroupManager().isVRE(GroupManagerWSBuilder.getInstance().getGroupManager().getGroupIdFromInfrastructureScope(context));
if(isVRE){

View File

@ -8,7 +8,7 @@ import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import org.gcube.social_networking.socialnetworking.model.shared.*;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.server.CassandraConnection;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.slf4j.LoggerFactory;
@ -1360,7 +1360,7 @@ public class Lib {
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
try{
List<Attachment> result = CassandraConnection.getInstance().getDatabookStore().getAttachmentsByFeedId(postid);
List<Attachment> result = CassandraConnection.getInstance().getDatabookStore().getAttachmentsByPostId(postid);
responseBean.setResult(result);
responseBean.setMessage("");
responseBean.setSuccess(true);

View File

@ -16,14 +16,13 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.shared.Like;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.social_networking.socialnetworking.model.shared.Like;
import org.gcube.social_networking.ws.inputs.LikeInputBean;
import org.gcube.social_networking.ws.inputs.PostId;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.server.CassandraConnection;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.SocialUtils;
import org.slf4j.LoggerFactory;
@ -67,9 +66,8 @@ public class Likes {
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
String username = caller.getClient().getId();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
List<Like> likes = null;
try{
@ -105,10 +103,10 @@ public class Likes {
@NotNull(message="Post to like is missing")
@Valid
PostId post) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
logger.debug("Request of like coming from user " + username);
String context = ScopeProvider.instance.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
boolean likeResultOperation = SocialUtils.like(username, post.getPostId(), context);
@ -145,8 +143,8 @@ public class Likes {
@NotNull(message="Post to unlike is missing")
@Valid
LikeInputBean likeInputBean) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
logger.debug("Request of unlike coming from user " + username);
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;

View File

@ -24,15 +24,15 @@ import org.gcube.applicationsupportlayer.social.NotificationsManager;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingUser;
import org.gcube.common.authorization.control.annotations.AuthorizationControl;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.common.storagehub.client.plugins.AbstractPlugin;
import org.gcube.common.storagehub.client.proxies.MessageManagerClient;
import org.gcube.common.storagehub.model.messages.Message;
import org.gcube.portal.notifications.bean.GenericItemBean;
import org.gcube.portal.notifications.thread.MessageNotificationsThread;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.gcube.social_networking.caches.SocialNetworkingSiteFinder;
import org.gcube.social_networking.liferay.ws.LiferayJSONWsCredentials;
import org.gcube.social_networking.liferay.ws.UserManagerWSBuilder;
@ -47,6 +47,7 @@ import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.glassfish.jersey.message.filtering.spi.ScopeProvider;
import org.slf4j.LoggerFactory;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
@ -95,28 +96,30 @@ public class Messages {
logger.debug("Incoming message bean is " + input);
Caller caller = AuthorizationProvider.instance.get();
Secret secret = SecretManagerProvider.get();
UserManager um = UserManagerWSBuilder.getInstance().getUserManager();
GCubeUser senderUser = null;
SocialNetworkingUser user = null;
// check if the token belongs to an application token. In this case use J.A.R.V.I.S (the username used to communicate with Liferay)
String username = null;
String fullName = "";
logger.debug("Catalogue Notification called by " + caller.getClient().getId() + " isUser?"+TokensUtils.isUserToken(caller));
logger.debug("Catalogue Notification called by " + secret.getOwner().getId() + " isUser?"+TokensUtils.isUserToken(caller));
if(!TokensUtils.isUserToken(caller)){
GCubeUser jarvis = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser());
SecurityTokenProvider.instance.set(LiferayJSONWsCredentials.getSingleton().getNotifierUserToken());
username = jarvis.getUsername();
fullName = caller.getClient().getId().replace("service-account-", ""); // the actual name of the IAM Client
fullName = secret.getOwner().getId().replace("service-account-", ""); // the actual name of the IAM Client
senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName, senderUser.getUserAvatarURL());
}else{
username = caller.getClient().getId();
username = secret.getOwner().getId();
senderUser = um.getUserByUsername(username);
fullName = senderUser.getFullname();
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName, senderUser.getUserAvatarURL());
}
String scope = ScopeProvider.instance.get();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.CREATED;
String body = input.getBody();
@ -163,8 +166,8 @@ public class Messages {
// send notification
logger.debug("Message sent to " + recipientsIds + ". Sending message notification to: " + recipientsIds);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(scope);
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, ScopeProvider.instance.get(), user);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(context);
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, secret.getContext(), user);
new Thread(new MessageNotificationsThread(recipientsBeans, messageId, subject, body, nm)).start();
responseBean.setSuccess(true);
responseBean.setResult(messageId);
@ -190,8 +193,9 @@ public class Messages {
*/
public Response getSentMessages(){
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
@ -226,8 +230,8 @@ public class Messages {
*/
public Response getReceivedMessages(){
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
@ -267,13 +271,14 @@ public class Messages {
@FormParam("messageId") String messageId,
@FormParam("read") Boolean read) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
Secret secret = SecretManagerProvider.get();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
String opExecutor = "";
try{
opExecutor = caller.getClient().getId();
opExecutor = secret.getOwner().getId();
MessageManagerClient client = AbstractPlugin.messages().build();
client.setRead(messageId, read);
String toReturn = "set Message id:" + messageId + (read ? " read" : " unread");

View File

@ -31,6 +31,8 @@ import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.social_networking.socialnetworking.model.shared.Notification;
import org.gcube.social_networking.socialnetworking.model.shared.NotificationChannelType;
import org.gcube.social_networking.socialnetworking.model.shared.NotificationType;
@ -47,7 +49,7 @@ import org.gcube.social_networking.ws.mappers.CatalogueEventTypeMapper;
import org.gcube.social_networking.ws.mappers.JobMapper;
import org.gcube.social_networking.ws.mappers.WorkspaceItemMapper;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.server.CassandraConnection;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.TokensUtils;
import org.gcube.social_networking.socialnetworking.model.beans.JobNotificationBean;
@ -112,8 +114,9 @@ public class Notifications {
int quantity
) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
logger.debug("Retrieving " + quantity + " notifications of user = " + username + " from " + from);
@ -286,12 +289,12 @@ public class Notifications {
@Valid
JobNotificationBean job) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
String appQualifier = caller.getClient().getId();
String appQualifier = secret.getOwner().getId();
logger.debug("Received request from app " + appQualifier + " to notify job status described by bean " + job);
try{
@ -342,14 +345,15 @@ public class Notifications {
@Valid
CatalogueEvent event) throws ValidationException, UserManagementSystemException, UserRetrievalFault{
Caller caller = AuthorizationProvider.instance.get();
Secret secret = SecretManagerProvider.get();
UserManager um = UserManagerWSBuilder.getInstance().getUserManager();
GCubeUser senderUser = null;
SocialNetworkingUser user = null;
// check if the token belongs to an application token. In this case use J.A.R.V.I.S (the username used to communicate with Liferay)
String username = null;
String fullName = "";
logger.debug("Catalogue Notification called by " + caller.getClient().getId() + " isUser?"+TokensUtils.isUserToken(caller));
logger.debug("Catalogue Notification called by " + secret.getOwner().getId() + " isUser?"+TokensUtils.isUserToken(caller));
if(!TokensUtils.isUserToken(caller)){
GCubeUser jarvis = UserManagerWSBuilder.getInstance().getUserManager().getUserByEmail(LiferayJSONWsCredentials.getSingleton().getUser());
SecurityTokenProvider.instance.set(LiferayJSONWsCredentials.getSingleton().getNotifierUserToken());
@ -358,12 +362,12 @@ public class Notifications {
senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), fullName, senderUser.getUserAvatarURL());
}else{
username = caller.getClient().getId();
username = secret.getOwner().getId();
senderUser = um.getUserByUsername(username);
user = new SocialNetworkingUser(senderUser.getUsername(), senderUser.getEmail(), senderUser.getFullname(), senderUser.getUserAvatarURL());
}
String context = ScopeProvider.instance.get();
String context = secret.getContext();
logger.debug("catalogue notifications from user = " + username);
ResponseBean responseBean = new ResponseBean();

View File

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

View File

@ -3,7 +3,6 @@ package org.gcube.social_networking.ws.methods.v2;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.ValidationException;
@ -19,12 +18,9 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.social_networking.socialnetworking.model.shared.PostWithAttachment;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.social_networking.socialnetworking.model.shared.*;
import org.gcube.social_networking.socialnetworking.model.shared.exceptions.ColumnNameNotFoundException;
import org.gcube.social_networking.socialnetworking.model.shared.exceptions.PostIDNotFoundException;
@ -32,7 +28,8 @@ import org.gcube.social_networking.socialnetworking.model.shared.exceptions.Post
import org.gcube.social_networking.socialnetworking.model.shared.exceptions.PrivacyLevelTypeNotFoundException;
import org.gcube.social_networking.ws.inputs.PostInputBean;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.CassandraConnection;
import org.gcube.social_networking.server.CassandraConnection;
import org.gcube.social_networking.server.SocialDBDriver;
import org.gcube.social_networking.ws.utils.ErrorMessages;
import org.gcube.social_networking.ws.utils.Filters;
import org.gcube.social_networking.ws.utils.SocialUtils;
@ -77,16 +74,16 @@ public class Posts {
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
Caller caller = AuthorizationProvider.instance.get();
String context = ScopeProvider.instance.get();
String username = caller.getClient().getId();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
List<Post> posts = null;
try{
logger.debug("Retrieving post for user id " + username + " and reference time " + timeInMillis);
posts = CassandraConnection.getInstance().getDatabookStore().getRecentPostsByUserAndDate(username, timeInMillis);
Filters.filterPostsPerContext(posts, context);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
Filters.hideSensitiveInformation(posts, secret.getOwner().getId());
responseBean.setResult(posts);
responseBean.setMessage("");
responseBean.setSuccess(true);
@ -115,9 +112,9 @@ public class Posts {
})
public Response getAllPostsByUser() {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
List<Post> posts = null;
@ -125,7 +122,7 @@ public class Posts {
logger.debug("Retrieving posts for user with id " + username);
posts = CassandraConnection.getInstance().getDatabookStore().getAllPostsByUser(username);
Filters.filterPostsPerContext(posts, context);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
Filters.hideSensitiveInformation(posts, secret.getOwner().getId());
responseBean.setResult(posts);
responseBean.setMessage("");
responseBean.setSuccess(true);
@ -151,8 +148,9 @@ public class Posts {
@ResponseCode ( code = 500, condition = ErrorMessages.ERROR_IN_API_RESULT)
})
public Response getPost(@QueryParam("id") String id) {
String context = ScopeProvider.instance.get();
Caller caller = AuthorizationProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
List<Post> posts = new ArrayList<>();
@ -166,7 +164,7 @@ public class Posts {
return Response.status(status).entity(responseBean).build();
}
Filters.filterPostsPerContext(posts, context);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
Filters.hideSensitiveInformation(posts, secret.getOwner().getId());
if (posts.isEmpty()) {
responseBean.setMessage("The post with id " + id + " does not belong to this context " + context);
responseBean.setSuccess(false);
@ -206,9 +204,9 @@ public class Posts {
@Min(value=0, message="quantity cannot be negative")
int quantity) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
@ -228,7 +226,7 @@ public class Posts {
Filters.filterPostsPerContext(posts, context);
quantity = (quantity > posts.size()) ? posts.size() : quantity;
posts = posts.subList(0, quantity);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
Filters.hideSensitiveInformation(posts, secret.getOwner().getId());
responseBean.setResult(posts);
responseBean.setSuccess(true);
}catch(Exception e){
@ -260,9 +258,9 @@ public class Posts {
PostInputBean post) throws ValidationException{
logger.debug("Request of writing a Post coming from user " + post);
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.CREATED;
@ -326,9 +324,9 @@ public class Posts {
})
public Response getAllPostsByApp() {
Caller caller = AuthorizationProvider.instance.get();
String appId = caller.getClient().getId();
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String appId = secret.getOwner().getId();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
@ -382,9 +380,9 @@ public class Posts {
@Valid
PostInputBean post){
Caller caller = AuthorizationProvider.instance.get();
String appId = caller.getClient().getId();
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String appId = secret.getOwner().getId();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.CREATED;
@ -423,7 +421,7 @@ public class Posts {
previewDescription,
httpImageUrl,
appProfile,
caller,
secret,
enableNotification
);
@ -453,14 +451,15 @@ public class Posts {
})
public Response getAllPostsByVRE() {
String context = ScopeProvider.instance.get();
Caller caller = AuthorizationProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
logger.debug("Retrieving all posts coming from vre = " + context);
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
try{
List<Post> posts = CassandraConnection.getInstance().getDatabookStore().getAllPostsByVRE(context);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
Filters.hideSensitiveInformation(posts, secret.getOwner().getId());
responseBean.setResult(posts);
responseBean.setSuccess(true);
}catch(Exception e){
@ -500,14 +499,14 @@ public class Posts {
@Min(value=1, message="quantity cannot be negative")
int quantity) throws ValidationException {
String context = ScopeProvider.instance.get();
Caller caller = AuthorizationProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String context = secret.getContext();
logger.debug("Retrieving all posts coming from vre = " + context);
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
try{
RangePosts rangePosts = CassandraConnection.getInstance().getDatabookStore().getRecentPostsByVREAndRange(context, from, quantity);
Filters.hideSensitiveInformation(rangePosts.getPosts(), caller.getClient().getId());
Filters.hideSensitiveInformation(rangePosts.getPosts(), secret.getOwner().getId());
responseBean.setResult(rangePosts);
responseBean.setSuccess(true);
}catch(Exception e){
@ -539,16 +538,16 @@ public class Posts {
@NotNull(message="hashtag cannot be missing")
String hashtag) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
logger.debug("User " + username + " has requested posts containing hashtag " + hashtag + " in context " + context);
try{
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
SocialDBDriver datastore = CassandraConnection.getInstance().getDatabookStore();
List<Post> posts = datastore.getVREPostsByHashtag(context, hashtag);
Filters.hideSensitiveInformation(posts, caller.getClient().getId());
Filters.hideSensitiveInformation(posts, secret.getOwner().getId());
responseBean.setResult(posts);
responseBean.setSuccess(true);
@ -572,9 +571,9 @@ public class Posts {
})
public Response getAllLikedPostIdsByUser() {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
logger.debug("Retrieving all liked posts for user with id " + username + " in context " + context);
List<String> retrievedLikedPostsIds = null;
@ -582,7 +581,7 @@ public class Posts {
Status status = Status.OK;
try{
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
SocialDBDriver datastore = CassandraConnection.getInstance().getDatabookStore();
retrievedLikedPostsIds = datastore.getAllLikedPostIdsByUser(username);
Filters.filterPostsPerContextById(retrievedLikedPostsIds, context);
responseBean.setResult(retrievedLikedPostsIds);
@ -617,9 +616,9 @@ public class Posts {
@Min(message="limit cannot be negative", value = 0)
int limit) throws ValidationException{
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
String context = secret.getContext();
List<Post> retrievedLikedPosts = null;
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
@ -628,7 +627,7 @@ public class Posts {
logger.debug("Retrieving " + limit + " liked posts for user with id " + username + " in context " + context);
retrievedLikedPosts = CassandraConnection.getInstance().getDatabookStore().getAllLikedPostsByUser(username, limit);
Filters.filterPostsPerContext(retrievedLikedPosts, context);
Filters.hideSensitiveInformation(retrievedLikedPosts, caller.getClient().getId());
Filters.hideSensitiveInformation(retrievedLikedPosts, secret.getOwner().getId());
responseBean.setResult(retrievedLikedPosts);
responseBean.setSuccess(true);
logger.debug("Liked posts by " + username + " retrieved");

View File

@ -13,7 +13,8 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.social_networking.socialnetworking.model.shared.ApplicationProfile;
import org.gcube.social_networking.ws.inputs.ApplicationId;
import org.gcube.social_networking.ws.outputs.ResponseBean;
@ -56,7 +57,8 @@ public class Tokens {
ApplicationId input) throws ValidationException{
logger.debug("Incoming request for app token generation.");
String context = ScopeProvider.instance.get();
Secret secret = SecretManagerProvider.get();
String context = secret.getContext();
ResponseBean responseBean = new ResponseBean();
Status status = Status.CREATED;
String appId = input.getAppId();

View File

@ -12,19 +12,19 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.policies.Users;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.social_networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.social_networking.liferay.ws.RoleManagerWSBuilder;
import org.gcube.social_networking.liferay.ws.UserManagerWSBuilder;
import org.gcube.social_networking.ws.outputs.ResponseBean;
import org.gcube.social_networking.ws.utils.TokensUtils;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.gcube.vomanagement.usermanagement.model.GatewayRolesNames;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.LoggerFactory;
@ -73,11 +73,12 @@ public class VREs {
@DefaultValue("false") @QueryParam("getManagers") boolean getManagers
) throws ValidationException {
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
Secret secret = SecretManagerProvider.get();
String username = secret.getOwner().getId();
ResponseBean responseBean = new ResponseBean();
Status status = Status.OK;
if(!TokensUtils.isUserToken(caller)){
status = Status.FORBIDDEN;
responseBean.setMessage("This method can only be invoked with a user token!");

View File

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

View File

@ -11,6 +11,7 @@ import org.slf4j.LoggerFactory;
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class ElasticSearchConnection {
// Logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ElasticSearchConnection.class);

View File

@ -18,4 +18,5 @@ public class ErrorMessages {
public static final String ERROR_IN_API_RESULT = "The error is reported into the 'message' field of the returned object";
public static final String POST_OUTSIDE_VRE = "A post cannot be written into a context that is not a VRE";
public static final String DEPRECATED_METHOD = "This method is deprecated, must use version 2";
}

View File

@ -4,11 +4,12 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.gcube.portal.databook.server.DatabookStore;
import org.gcube.social_networking.socialnetworking.model.shared.Comment;
import org.gcube.social_networking.socialnetworking.model.shared.EnhancedPost;
import org.gcube.social_networking.socialnetworking.model.shared.Post;
import org.gcube.social_networking.liferay.ws.GroupManagerWSBuilder;
import org.gcube.social_networking.server.SocialDBDriver;
import org.gcube.social_networking.server.CassandraConnection;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
@ -61,7 +62,7 @@ public class Filters {
public static void filterPostsPerContextById(
List<String> postsIds, String context) throws Exception {
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
SocialDBDriver datastore = CassandraConnection.getInstance().getDatabookStore();
List<Post> posts = new ArrayList<Post>();
for (String postId : postsIds) {
@ -118,7 +119,7 @@ public class Filters {
List<String> contexts = getContexts(context);
// get cassandra store
DatabookStore datastore = CassandraConnection.getInstance().getDatabookStore();
SocialDBDriver datastore = CassandraConnection.getInstance().getDatabookStore();
// filter
Iterator<Comment> iterator = comments.iterator();

View File

@ -25,8 +25,9 @@ import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingSite;
import org.gcube.applicationsupportlayer.social.shared.SocialNetworkingUser;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.resources.gcore.utils.XPathHelper;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.security.secrets.Secret;
import org.gcube.social_networking.server.CassandraConnection;
//import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.social_networking.socialnetworking.model.shared.ApplicationProfile;
import org.gcube.social_networking.socialnetworking.model.shared.Comment;
import org.gcube.social_networking.socialnetworking.model.shared.Like;
@ -122,7 +123,7 @@ public class SocialUtils {
String previewDescription,
String httpImageUrl,
ApplicationProfile applicationProfile,
Caller caller,
Secret secret,
boolean notifyGroup
){
@ -132,13 +133,13 @@ public class SocialUtils {
ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(postText));
ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(secret.getContext());
escapedPostText = Utils.convertMentionUsernamesAnchorHTML(escapedPostText, mentionedUsersToConvertInHTML, site.getSiteURL(), site.getSiteLandingPagePath());
logger.debug("*** Escaped post text is " + escapedPostText);
String scope = ScopeProvider.instance.get();
String appId = caller.getClient().getId();
String scope = secret.getContext();
String appId = secret.getOwner().getId();
Post toWrite =
buildPost(
@ -187,7 +188,7 @@ public class SocialUtils {
try{
String name = new ScopeBean(scope).name(); // scope such as devVRE
String name = scope;//new ScopeBean(scope).name(); // scope such as devVRE // need to fix
// retrieve group information
GroupManager gManager = GroupManagerWSBuilder.getInstance().getGroupManager();
@ -265,112 +266,7 @@ public class SocialUtils {
return toReturn;
}
/**
* This method looks up the applicationProfile profile among the ones available in the infrastructure
* @param idApp as identifier of your application (as reported in the ApplicationProfile)
* @param scopeApp the scope of the application
*/
public static ApplicationProfile getProfileFromInfrastrucure(String idApp, String scopeApp) {
ScopeBean scope = new ScopeBean(scopeApp);
logger.debug("Trying to fetch applicationProfile profile from the infrastructure for " + idApp + " scope: " + scope);
// set the scope of the root infrastructure
String rootInfrastructure = scopeApp.split("/")[1];
ScopeProvider.instance.set("/"+rootInfrastructure);
try {
ApplicationProfile toReturn = new ApplicationProfile();
Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource " +
"where $profile/Profile/SecondaryType/string() eq 'ApplicationProfile' and $profile/Profile/Body/AppId/string() " +
" eq '" + idApp + "'" +
"return $profile");
DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q);
if (appProfile == null || appProfile.size() == 0)
throw new Exception("Your applicationProfile is not registered in the infrastructure");
else {
String elem = appProfile.get(0);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
XPathHelper helper = new XPathHelper(node);
List<String> currValue = null;
currValue = helper.evaluate("/Resource/Profile/Name/text()");
if (currValue != null && currValue.size() > 0) {
toReturn.setName(currValue.get(0));
}
else throw new ApplicationProfileNotFoundException("Your applicationProfile NAME was not found in the profile");
currValue = helper.evaluate("/Resource/Profile/Description/text()");
if (currValue != null && currValue.size() > 0) {
toReturn.setDescription(currValue.get(0));
}
else logger.warn("No Description exists for " + toReturn.getName());
currValue = helper.evaluate("/Resource/Profile/Body/AppId/text()");
if (currValue != null && currValue.size() > 0) {
toReturn.setKey(currValue.get(0));
}
else throw new ApplicationProfileNotFoundException("Your applicationProfile ID n was not found in the profile, consider adding <AppId> element in <Body>");
currValue = helper.evaluate("/Resource/Profile/Body/ThumbnailURL/text()");
if (currValue != null && currValue.size() > 0) {
toReturn.setImageUrl(currValue.get(0));
}
else throw new Exception("Your applicationProfile Image Url was not found in the profile, consider adding <ThumbnailURL> element in <Body>");
currValue = helper.evaluate("/Resource/Profile/Body/EndPoint/Scope/text()");
if (currValue != null && currValue.size() > 0) {
List<String> scopes = currValue;
boolean foundUrl = false;
for (int i = 0; i < scopes.size(); i++) {
if (currValue.get(i).trim().compareTo(scope.toString()) == 0) {
toReturn.setUrl(helper.evaluate("/Resource/Profile/Body/EndPoint/URL/text()").get(i));
toReturn.setScope(scope.toString());
foundUrl = true;
break;
}
}
if (! foundUrl)
throw new ApplicationProfileNotFoundException("Your applicationProfile URL was not found in the profile for Scope: " + scope.toString());
}
else throw new ApplicationProfileNotFoundException("Your applicationProfile EndPoint was not found in the profile, consider adding <EndPoint><Scope> element in <Body>");
logger.debug("Returning " + toReturn);
return toReturn;
}
} catch (Exception e) {
logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", e);
} finally{
// set the scope back
ScopeProvider.instance.set(scopeApp);
}
return null;
}
//removed getprofilefrominfrastructure
/**
* Allows user to post a post in a certain vre.
@ -394,7 +290,8 @@ public class SocialUtils {
String previewHost,
String previewUrl,
String urlThumbnail,
boolean notifyGroup) {
boolean notifyGroup,
Secret secret) {
SocialMessageParser messageParser = new SocialMessageParser(postText);
String escapedPostText = messageParser.getParsedMessage();
@ -403,7 +300,7 @@ public class SocialUtils {
ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(postText));
ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(secret.getContext());
escapedPostText = Utils.convertMentionUsernamesAnchorHTML(escapedPostText, mentionedUsersToConvertInHTML, site.getSiteURL(), site.getSiteLandingPagePath());
@ -485,7 +382,7 @@ public class SocialUtils {
// retrieve group information
GroupManager gManager = GroupManagerWSBuilder.getInstance().getGroupManager();
// handle the scope
String name = new ScopeBean(vreId).name(); // scope such as devVR
String name = vreId; //new ScopeBean(vreId).name(); // scope such as devVR // need to fix
long groupId = gManager.getGroupId(name);
String groupName = gManager.getGroup(groupId).getGroupName();
@ -521,14 +418,14 @@ public class SocialUtils {
* @return the Comment instance if ok, null if somwthign went KO
* @throws PostIDNotFoundException
*/
public static Comment commentPost(String userid, Date time, String postId, String commentText, String postOwnerId, String context) throws PostIDNotFoundException {
public static Comment commentPost(String userid, Date time, String postId, String commentText, String postOwnerId, String context, Secret secret) throws PostIDNotFoundException {
SocialMessageParser messageParser = new SocialMessageParser(commentText);
String escapedCommentText = messageParser.getParsedMessage();
//check if any mention exists
ArrayList<GenericItemBean> mentionedUsers = getUsersFromUsernames(Utils.getMentionedUsernames(commentText));
ArrayList<ItemBean> mentionedUsersToConvertInHTML = convertToItemBean(mentionedUsers);
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(secret.getContext());
escapedCommentText = Utils.convertMentionUsernamesAnchorHTML(escapedCommentText, mentionedUsersToConvertInHTML, site.getSiteURL(), site.getSiteLandingPagePath());
@ -649,7 +546,7 @@ public class SocialUtils {
return toReturn;
}
public static boolean like(String username, String postid, String context) {
public static boolean like(String username, String postid, String context, Secret secret) {
boolean likeCommitResult = false;
// retrieve user information
GCubeUser user;
@ -680,7 +577,7 @@ public class SocialUtils {
boolean resultNotifyLike =false;
if (likeCommitResult) {
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(ScopeProvider.instance.get());
SocialNetworkingSite site = SocialNetworkingSiteFinder.getSocialNetworkingSiteFromScope(secret.getContext());
NotificationsManager nm = new ApplicationNotificationsManager(UserManagerWSBuilder.getInstance().getUserManager(), site, context, socialUser, NEWS_FEED_PORTLET_CLASSNAME);
String postText = thePost.getDescription();

View File

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