Costantino Perciante 2018-02-16 18:22:14 +00:00
parent e6c711f5d8
commit 1272ecae18
15 changed files with 235 additions and 136 deletions

29
pom.xml
View File

@ -24,12 +24,20 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-portal-bom</artifactId>
<version>LATEST</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<java-version>1.7</java-version>
<version.jersey>2.25.1</version.jersey>
<version.jersey>2.9</version.jersey>
<jaxrs.version>2.0.1</jaxrs.version>
<distroDirectory>${project.basedir}/distro</distroDirectory>
<gCubeSubsystem>social-networking</gCubeSubsystem>
<webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory>
@ -48,19 +56,16 @@
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>home-library</artifactId>
<version>[2.0.0-SNAPSHOT, 3.0.0-SNAPSHOT)</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>home-library-jcr</artifactId>
<version>[2.0.0-SNAPSHOT, 3.0.0-SNAPSHOT)</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.portal</groupId>
<artifactId>social-networking-library</artifactId>
<version>[1.0.0-SNAPSHOT,)</version>
<scope>compile</scope>
</dependency>
<dependency>
@ -73,23 +78,22 @@
<artifactId>social-networking-service-model</artifactId>
<version>[1.0.0-SNAPSHOT,)</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-bean-validation</artifactId>
<version>${version.jersey}</version>
<scope>provided</scope>
</dependency>
<!-- <dependency> -->
<!-- <groupId>javax.ws.rs</groupId> -->
<!-- <artifactId>javax.ws.rs-api</artifactId> -->
<!-- <version>${jaxrs.version}</version> -->
<!-- </dependency> -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${version.jersey}</version>
<scope>provided</scope>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${version.jersey}</version>
<scope>provided</scope>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
@ -99,7 +103,6 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
<scope>provided</scope>
</dependency>
<dependency>

View File

@ -1,6 +1,8 @@
package org.gcube.portal.social_networking_client_library;
import org.gcube.portal.social_networking_client_library.utils.ServiceDiscoverer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base client service.
@ -8,13 +10,16 @@ import org.gcube.portal.social_networking_client_library.utils.ServiceDiscoverer
*/
public abstract class BaseClient {
private static Logger logger = LoggerFactory.getLogger(BaseClient.class);
private String serviceEndpoint;
public BaseClient(String subPath) throws Exception {
ServiceDiscoverer discover = new ServiceDiscoverer();
serviceEndpoint = discover.getEntryPoint();
ServiceDiscoverer discoverer = new ServiceDiscoverer();
logger.debug("Discovering service...");
serviceEndpoint = discoverer.getEntryPoint();
serviceEndpoint = serviceEndpoint.endsWith("/") ? serviceEndpoint + subPath :
serviceEndpoint + "/" + subPath;
logger.debug("Discovered service " + serviceEndpoint);
}
public String getServiceEndpoint() {

View File

@ -3,12 +3,14 @@ package org.gcube.portal.social_networking_client_library;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.GenericType;
import org.apache.commons.lang.Validate;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.portal.databook.shared.EnhancedFeed;
import org.gcube.portal.social_networking_client_library.utils.HttpClient;
import org.gcube.portal.socialnetworking.model.output.ResponseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -20,12 +22,11 @@ public class FullTextSearchClient extends BaseClient{
private static final String SUB_SERVICE_PATH = "2/full-text-search/";
private static Logger logger = LoggerFactory.getLogger(FullTextSearchClient.class);
public FullTextSearchClient() throws Exception {
super(SUB_SERVICE_PATH);
}
/**
* Perform a search query over social data
* @param query
@ -34,18 +35,17 @@ public class FullTextSearchClient extends BaseClient{
* @return a list of matching posts
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("unchecked")
public List<EnhancedFeed> search(String query, int from, int quantity) throws UnsupportedEncodingException{
public ArrayList<EnhancedFeed> search(String query, int from, int quantity) throws UnsupportedEncodingException{
Validate.isTrue(query != null, "Query cannot be null");
Validate.isTrue(from >= 0, "From needs to be greater or equal to zero");
Validate.isTrue(quantity >= 0, "Quantity needs to be greater or equal to zero");
logger.debug("Request for query " + query + " and from " + from + " and quantity is " + quantity);
String thisMethodSignature = "search-by-query";
String request = getServiceEndpoint() + thisMethodSignature + "?" + "query=" + URLEncoder.encode(query, "UTF-8") + "&from=" + from + "&quantity=" + quantity;
return HttpClient.get(new ArrayList<EnhancedFeed>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<EnhancedFeed>>>(){}, request, SecurityTokenProvider.instance.get());
}
}

View File

@ -3,8 +3,11 @@ package org.gcube.portal.social_networking_client_library;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.core.GenericType;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.portal.social_networking_client_library.utils.HttpClient;
import org.gcube.portal.socialnetworking.model.output.ResponseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -26,14 +29,11 @@ public class HashTagsClient extends BaseClient{
* Get hashtags and their count
* @return a map of type hashtag -> number
*/
@SuppressWarnings("unchecked")
public Map<String, Integer> getHashtagsCount(){
logger.debug("Request for hastags");
String thisMethodSignature = "get-hashtags-and-occurrences";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(new HashMap<String, Integer>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<HashMap<String, Integer>>>(){}, request, SecurityTokenProvider.instance.get());
}

View File

@ -3,11 +3,14 @@ package org.gcube.portal.social_networking_client_library;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.GenericType;
import org.apache.commons.lang.Validate;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.homelibrary.home.workspace.sharing.WorkspaceMessage;
import org.gcube.portal.social_networking_client_library.utils.HttpClient;
import org.gcube.portal.socialnetworking.model.input.MessageInputBean;
import org.gcube.portal.socialnetworking.model.output.ResponseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -29,13 +32,12 @@ public class MessagesClient extends BaseClient{
* Get sent messages
* @return
*/
@SuppressWarnings("unchecked")
public List<WorkspaceMessage> getSentMessages(){
logger.debug("Request for sent messages");
String thisMethodSignature = "get-sent-messages";
String request = getServiceEndpoint() + thisMethodSignature + "?";
return HttpClient.get(new ArrayList<WorkspaceMessage>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<WorkspaceMessage>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -43,13 +45,12 @@ public class MessagesClient extends BaseClient{
* Get received messages
* @return
*/
@SuppressWarnings("unchecked")
public List<WorkspaceMessage> getReceivedMessages(){
logger.debug("Request for received messages");
String thisMethodSignature = "get-received-messages";
String request = getServiceEndpoint() + thisMethodSignature + "?";
return HttpClient.get(new ArrayList<WorkspaceMessage>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<WorkspaceMessage>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -64,7 +65,7 @@ public class MessagesClient extends BaseClient{
logger.debug("Request for writing new message");
String thisMethodSignature = "write-message";
String request = getServiceEndpoint() + thisMethodSignature + "?";
return HttpClient.post(String.class, request, SecurityTokenProvider.instance.get(), m);
return HttpClient.post(new GenericType<ResponseBean<String>>(){}, request, SecurityTokenProvider.instance.get(), m);
}
}

View File

@ -3,11 +3,14 @@ package org.gcube.portal.social_networking_client_library;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.GenericType;
import org.apache.commons.lang.Validate;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.portal.databook.shared.Notification;
import org.gcube.portal.social_networking_client_library.utils.HttpClient;
import org.gcube.portal.socialnetworking.model.input.JobNotificationBean;
import org.gcube.portal.socialnetworking.model.output.ResponseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -27,20 +30,19 @@ public class NotificationsClient extends BaseClient{
/**
* Get range notifications
* @param from
* @param from greater or equal to one
* @param quantity
* @return
*/
@SuppressWarnings("unchecked")
public List<Notification> getNotifications(int from, int quantity){
Validate.isTrue(from >= 0, "From cannot be negative");
Validate.isTrue(from >= 1, "From cannot be negative");
Validate.isTrue(from >= 0, "Quantity cannot be negative");
logger.debug("Request for getting notifications");
String thisMethodSignature = "get-range-notifications";
String request = getServiceEndpoint() + thisMethodSignature + "?from=" + from + "&quantity=" +quantity;
return HttpClient.get(new ArrayList<Notification>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<Notification>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -52,11 +54,10 @@ public class NotificationsClient extends BaseClient{
public void sendJobNotification(JobNotificationBean notification){
Validate.isTrue(notification != null, "Notification cannot be null");
logger.debug("Request for getting notifications");
String thisMethodSignature = "notify-job-status";
String request = getServiceEndpoint() + thisMethodSignature;
HttpClient.post(Void.class, request, SecurityTokenProvider.instance.get(), notification);
HttpClient.post(new GenericType<ResponseBean<String>>(){}, request, SecurityTokenProvider.instance.get(), notification);
}

View File

@ -1,7 +1,10 @@
package org.gcube.portal.social_networking_client_library;
import javax.ws.rs.core.GenericType;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.portal.social_networking_client_library.utils.HttpClient;
import org.gcube.portal.socialnetworking.model.output.ResponseBean;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -29,8 +32,7 @@ public class PeopleClient extends BaseClient{
logger.debug("Request for getting profile");
String thisMethodSignature = "profile";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(JSONObject.class, request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<JSONObject>>(){}, request, SecurityTokenProvider.instance.get());
}
}

View File

@ -3,11 +3,14 @@ package org.gcube.portal.social_networking_client_library;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.GenericType;
import org.apache.commons.lang.Validate;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.portal.databook.shared.Feed;
import org.gcube.portal.social_networking_client_library.utils.HttpClient;
import org.gcube.portal.socialnetworking.model.input.PostInputBean;
import org.gcube.portal.socialnetworking.model.output.ResponseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -29,7 +32,6 @@ public class PostsClient extends BaseClient{
* Get posts since date
* @return
*/
@SuppressWarnings("unchecked")
public List<Feed> getPostsSinceDate(long timeInMillis){
Validate.isTrue(timeInMillis >= 0, "time cannot be negative");
@ -37,7 +39,7 @@ public class PostsClient extends BaseClient{
logger.debug("Request for getting posts");
String thisMethodSignature = "get-posts-user-since";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(new ArrayList<Feed>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<Feed>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -45,7 +47,6 @@ public class PostsClient extends BaseClient{
* Get all posts
* @return
*/
@SuppressWarnings("unchecked")
public List<Feed> getAllPosts(long timeInMillis){
Validate.isTrue(timeInMillis >= 0, "time cannot be negative");
@ -53,7 +54,7 @@ public class PostsClient extends BaseClient{
logger.debug("Request for getting posts");
String thisMethodSignature = "get-posts-user";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(new ArrayList<Feed>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<Feed>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -61,7 +62,6 @@ public class PostsClient extends BaseClient{
* Get posts quantity
* @return
*/
@SuppressWarnings("unchecked")
public List<Feed> getPostsQuantity(int quantity){
Validate.isTrue(quantity >= 0, "quantity cannot be negative");
@ -69,7 +69,7 @@ public class PostsClient extends BaseClient{
logger.debug("Request for getting posts");
String thisMethodSignature = "get-posts-user-quantity";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(new ArrayList<Feed>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<Feed>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -84,7 +84,7 @@ public class PostsClient extends BaseClient{
logger.debug("Request for writing post");
String thisMethodSignature = "write-post-user";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.post(Feed.class, request, SecurityTokenProvider.instance.get(), toWrite);
return HttpClient.post(new GenericType<ResponseBean<Feed>>(){}, request, SecurityTokenProvider.instance.get(), toWrite);
}
@ -92,13 +92,12 @@ public class PostsClient extends BaseClient{
* Get posts application (token set must belong to the application)
* @return
*/
@SuppressWarnings("unchecked")
public List<Feed> getAllApplicationPosts(){
logger.debug("Request for getting posts");
String thisMethodSignature = "get-posts-app";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(new ArrayList<Feed>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<Feed>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -113,7 +112,7 @@ public class PostsClient extends BaseClient{
logger.debug("Request for writing application post");
String thisMethodSignature = "write-post-app";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.post(Feed.class, request, SecurityTokenProvider.instance.get(), toWrite);
return HttpClient.post(new GenericType<ResponseBean<Feed>>(){}, request, SecurityTokenProvider.instance.get(), toWrite);
}
@ -121,13 +120,12 @@ public class PostsClient extends BaseClient{
* Get posts vre
* @return
*/
@SuppressWarnings("unchecked")
public List<Feed> getPostsVRE(){
logger.debug("Request for getting posts vre");
String thisMethodSignature = "get-posts-vre";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(new ArrayList<Feed>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<Feed>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -135,7 +133,6 @@ public class PostsClient extends BaseClient{
* Get posts hashtag
* @return
*/
@SuppressWarnings("unchecked")
public List<Feed> getHashtagPosts(String hashtag){
Validate.isTrue(hashtag != null, "hashtag cannot be null");
@ -143,21 +140,20 @@ public class PostsClient extends BaseClient{
logger.debug("Request for getting posts with hashtag " + hashtag);
String thisMethodSignature = "get-posts-by-hashtag";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(new ArrayList<Feed>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<Feed>>>(){}, request, SecurityTokenProvider.instance.get());
}
/**
* Get liked posts
* @return
*/
@SuppressWarnings("unchecked")
public List<Feed> getLikedPost(){
logger.debug("Request for getting posts liked");
String thisMethodSignature = "get-liked-posts";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(new ArrayList<String>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<Feed>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -165,13 +161,12 @@ public class PostsClient extends BaseClient{
* Get liked posts ids
* @return
*/
@SuppressWarnings("unchecked")
public List<String> getLikedPostIds(){
logger.debug("Request for getting posts liked");
String thisMethodSignature = "get-id-liked-posts";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(new ArrayList<String>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<String>>>(){}, request, SecurityTokenProvider.instance.get());
}

View File

@ -1,9 +1,12 @@
package org.gcube.portal.social_networking_client_library;
import javax.ws.rs.core.GenericType;
import org.apache.commons.lang.Validate;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.portal.social_networking_client_library.utils.HttpClient;
import org.gcube.portal.socialnetworking.model.input.ApplicationId;
import org.gcube.portal.socialnetworking.model.output.ResponseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -32,7 +35,7 @@ public class TokensClient extends BaseClient{
logger.debug("Request for writing new message");
String thisMethodSignature = "generate-application-token";
String request = getServiceEndpoint() + thisMethodSignature + "?";
return HttpClient.post(String.class, request, SecurityTokenProvider.instance.get(), appId);
return HttpClient.post(new GenericType<ResponseBean<String>>(){}, request, SecurityTokenProvider.instance.get(), appId);
}

View File

@ -5,9 +5,12 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.GenericType;
import org.apache.commons.lang.Validate;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.portal.social_networking_client_library.utils.HttpClient;
import org.gcube.portal.socialnetworking.model.output.ResponseBean;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -37,7 +40,7 @@ public class UsersClient extends BaseClient{
logger.debug("Request for attribute value");
String thisMethodSignature = "get-custom-attribute";
String request = getServiceEndpoint() + thisMethodSignature + "?attribute=" + attributeKey;
return HttpClient.get(String.class, request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<String>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -50,7 +53,7 @@ public class UsersClient extends BaseClient{
logger.debug("Request for fullname");
String thisMethodSignature = "get-fullname";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(String.class, request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<String>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -63,7 +66,7 @@ public class UsersClient extends BaseClient{
logger.debug("Request for email");
String thisMethodSignature = "get-email";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(String.class, request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<String>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -76,7 +79,7 @@ public class UsersClient extends BaseClient{
logger.debug("Request for getting profile");
String thisMethodSignature = "get-profile";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(JSONObject.class, request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<JSONObject>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -84,13 +87,12 @@ public class UsersClient extends BaseClient{
* Get all usernames in this context
* @return
*/
@SuppressWarnings("unchecked")
public List<String> getAllUsernamesContext(){
logger.debug("Request for getting usernames in this context");
String thisMethodSignature = "get-all-usernames";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(new ArrayList<String>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<String>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -98,13 +100,12 @@ public class UsersClient extends BaseClient{
* Get all usernames and fullnames in this context
* @return
*/
@SuppressWarnings("unchecked")
public Map<String, String> getAllUsernamesFullnamesContext(){
logger.debug("Request for getting usernames and fullnames in this context");
String thisMethodSignature = "get-all-fullnames-and-usernames";
String request = getServiceEndpoint() + thisMethodSignature;
return HttpClient.get(new HashMap<String, String>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<HashMap<String, String>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -112,7 +113,6 @@ public class UsersClient extends BaseClient{
* Get usernames by global role
* @return
*/
@SuppressWarnings("unchecked")
public List<String> getAllUsernamesByGlobalRole(String globalRole){
Validate.isTrue(globalRole != null, "role cannot be null");
@ -120,7 +120,7 @@ public class UsersClient extends BaseClient{
logger.debug("Request for getting usernames with global role");
String thisMethodSignature = "get-usernames-by-global-role";
String request = getServiceEndpoint() + thisMethodSignature + "?role-name=" + globalRole;
return HttpClient.get(new ArrayList<String>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<String>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -128,7 +128,6 @@ public class UsersClient extends BaseClient{
* Get usernames by local role
* @return
*/
@SuppressWarnings("unchecked")
public List<String> getAllUsernamesByLocalRole(String localRole){
Validate.isTrue(localRole != null, "role cannot be null");
@ -136,7 +135,7 @@ public class UsersClient extends BaseClient{
logger.debug("Request for getting usernames with global role");
String thisMethodSignature = "get-usernames-by-role";
String request = getServiceEndpoint() + thisMethodSignature + "?role-name=" + localRole;
return HttpClient.get(new ArrayList<String>(0).getClass(), request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<ArrayList<String>>>(){}, request, SecurityTokenProvider.instance.get());
}
@ -151,7 +150,7 @@ public class UsersClient extends BaseClient{
logger.debug("Request for getting usernames with global role");
String thisMethodSignature = "user-exists";
String request = getServiceEndpoint() + thisMethodSignature + "?username=" + username;
return HttpClient.get(Boolean.class, request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<Boolean>>(){}, request, SecurityTokenProvider.instance.get());
}

View File

@ -1,7 +1,10 @@
package org.gcube.portal.social_networking_client_library;
import javax.ws.rs.core.GenericType;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.portal.social_networking_client_library.utils.HttpClient;
import org.gcube.portal.socialnetworking.model.output.ResponseBean;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -29,7 +32,7 @@ public class VREsClient extends BaseClient{
logger.debug("Request for writing new message");
String thisMethodSignature = "get-my-vres";
String request = getServiceEndpoint() + thisMethodSignature + "?";
return HttpClient.get(JSONArray.class, request, SecurityTokenProvider.instance.get());
return HttpClient.get(new GenericType<ResponseBean<JSONArray>>(){}, request, SecurityTokenProvider.instance.get());
}

View File

@ -0,0 +1,15 @@
package org.gcube.portal.social_networking_client_library.exceptions;
/**
* No social service available in the infrastructure.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class NoSocialServiceAvailable extends Exception {
public NoSocialServiceAvailable(String errorMsg) {
super(errorMsg);
}
private static final long serialVersionUID = 5927949225149691036L;
}

View File

@ -5,73 +5,111 @@ import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.gcube.portal.socialnetworking.model.output.ResponseBean;
import org.glassfish.jersey.client.ClientResponse;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
/**
* Http client with post and get methods (jersey is used)
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
@SuppressWarnings("unchecked")
public class HttpClient {
public class HttpClient{
private static Logger logger = LoggerFactory.getLogger(HttpClient.class);
public static <R extends Object> R get(Class<R> returnType, String requestUrl, String token){
/**
* Executes a get request
* @param genericType
* @param genericType
* @param genericType
* @param returnType
* @param requestUrl
* @param token
* @return
*/
public static <R> R get(GenericType<ResponseBean<R>> returnType, String requestUrl, String token){
logger.debug("Executing get request at url " + requestUrl + " and token is " + maskedToken(token));
// Create Jersey client
Client client = ClientBuilder.newClient();
ClientConfig cc = new ClientConfig().register(new JacksonFeature());//.register(new JacksonJsonProvider(getMapper()));
Client client = ClientBuilder.newClient(cc);
WebTarget webResourceGet = client.target(requestUrl).queryParam("gcube-token", token);
ClientResponse response = webResourceGet.request(MediaType.APPLICATION_JSON).get(ClientResponse.class);
ResponseBean<R> response = webResourceGet.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).get(returnType);
if (response.getStatus() < 200 || response.getStatus() > 205) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
if(response == null)
throw new WebApplicationException("Response returned by the service is null");
ResponseBean responseEntity = (ResponseBean) response.getEntity();
if (responseEntity.getMessage() != null && !responseEntity.getMessage().isEmpty()) {
if (response.getMessage() != null && !response.getMessage().isEmpty())
throw new WebApplicationException(
"Response has status code " + response.getStatus() + " and message " +
responseEntity.getMessage());
}
"Error message is " + response.getMessage());
return (R) responseEntity.getResult();
return response.getResult();
}
public static <R extends Object> R post(Class<R> returnType, String requestUrl, String token, Object body){
// public static ObjectMapper getMapper(){
//
// ObjectMapper mapper = new ObjectMapper();
// mapper.enable(SerializationFeature.INDENT_OUTPUT);
// mapper.addMixIn(WorkspaceMessage.class, MessageOutputBeanMixIn.class);
// mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
// return mapper;
// }
logger.debug("Executing get request at url " + requestUrl + " and token is " + maskedToken(token));
/**
* Executes a post request
* @param returnType
* @param requestUrl
* @param token
* @param body
* @return
* @throws JsonProcessingException
*/
public static <R> R post(GenericType<ResponseBean<R>> returnType, String requestUrl, String token, Object obj){
// Create Jersey client
Client client = ClientBuilder.newClient();
logger.debug("Executing post request at url " + requestUrl + " and token is " + maskedToken(token));
ClientConfig cc = new ClientConfig().register(new JacksonFeature());
Client client = ClientBuilder.newClient(cc);
WebTarget webResourceGet = client.target(requestUrl).queryParam("gcube-token", token);
Response response = webResourceGet.request(MediaType.APPLICATION_JSON).post(Entity.json(body));
//
// String asJson = null;
// try{
// ObjectMapper mapper = new ObjectMapper();
// mapper.enable(SerializationFeature.INDENT_OUTPUT);
// mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
// mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
// asJson = mapper.writeValueAsString(obj);
// logger.debug("Request body looks like\n"+asJson);
// }catch(Exception e){
// logger.error("Failed to parse data", e);
// }
if (response.getStatus() < 200 || response.getStatus() > 205) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
logger.debug("Entity looks like " + Entity.json(obj));
ResponseBean responseEntity = (ResponseBean) response.getEntity();
ResponseBean<R> response = webResourceGet.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(Entity.json(obj), returnType);
if (responseEntity.getMessage() != null && !responseEntity.getMessage().isEmpty()) {
if(response == null)
throw new WebApplicationException("Response returned by the service is null");
if (response.getMessage() != null && !response.getMessage().isEmpty())
throw new WebApplicationException(
"Response has status code " + response.getStatus() + " and message " +
responseEntity.getMessage());
}
"Error message is " + response.getMessage());
return (R) responseEntity.getResult();
return response.getResult();
}
/**
* Avoid to show the token
* @param token
* @return
*/
private static String maskedToken(String token){
if(token == null)

View File

@ -10,6 +10,7 @@ import java.util.List;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portal.social_networking_client_library.exceptions.NoSocialServiceAvailable;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.slf4j.Logger;
@ -31,6 +32,9 @@ public class ServiceDiscoverer {
public ServiceDiscoverer() throws Exception {
String currentScope = ScopeProvider.instance.get();
if(currentScope == null || currentScope.isEmpty())
throw new RuntimeException("Scope is not set");
try{
@ -47,12 +51,12 @@ public class ServiceDiscoverer {
DiscoveryClient<String> client = client();
List<String> endpoints = client.submit(query);
if (endpoints == null || endpoints.isEmpty())
throw new Exception("Cannot retrieve the GCoreEndpoint serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+currentScope);
throw new NoSocialServiceAvailable("Cannot retrieve the GCoreEndpoint serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+currentScope);
this.entryPoint = endpoints.get(0);
if(entryPoint==null)
throw new Exception("Endpoint:"+resource+", is null for serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+currentScope);
throw new NoSocialServiceAvailable("Endpoint:"+resource+", is null for serviceName: "+serviceName +", serviceClass: " +serviceClass +", in scope: "+currentScope);
logger.info("found entryPoint "+entryPoint+" for social service: "+resource);

View File

@ -15,78 +15,108 @@ import org.gcube.portal.databook.shared.Notification;
import org.gcube.portal.socialnetworking.model.input.JobNotificationBean;
import org.gcube.portal.socialnetworking.model.input.MessageInputBean;
import org.gcube.portal.socialnetworking.model.input.Recipient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestClientServices {
private static Logger logger = LoggerFactory.getLogger(TestClientServices.class);
@Before
public void setContextAndToken(){
ScopeProvider.instance.set("/gcube/devNext/NextNext");
SecurityTokenProvider.instance.set("d423aed7-e9e2-424a-b9e7-2bbbd151d9c4-98187548");
}
@Test
//@Test
public void testSearch() throws Exception {
FullTextSearchClient search = new FullTextSearchClient();
List<EnhancedFeed> result = search.search("looking for test", 0, 10);
ArrayList<EnhancedFeed> result = search.search("looking for test", 0, 10);
for (EnhancedFeed enhancedFeed : result) {
logger.debug("Returned feed " + enhancedFeed);
}
}
@Test
//@Test
public void testSearchEmptyList() throws Exception {
FullTextSearchClient search = new FullTextSearchClient();
ArrayList<EnhancedFeed> result = search.search("tipiterotipirè", 0, 10);
for (EnhancedFeed enhancedFeed : result) {
logger.debug("Returned feed " + enhancedFeed);
}
}
//@Test
public void testHashTags() throws Exception {
HashTagsClient hashtags = new HashTagsClient();
Map<String, Integer> hashtagsCount = hashtags.getHashtagsCount();
logger.debug("Returned tags " + hashtagsCount);
logger.debug("Returned tags " + hashtagsCount);
}
@Test
public void testMessages() throws Exception {
public void testMessagesReceived() throws Exception {
MessagesClient messagesClient = new MessagesClient();
List<WorkspaceMessage> receivedMessages = messagesClient.getReceivedMessages();
for (WorkspaceMessage workspaceMessage : receivedMessages) {
logger.debug("Received message " + workspaceMessage.toString());
}
}
//@Test
public void testMessagesSent() throws Exception {
MessagesClient messagesClient = new MessagesClient();
List<WorkspaceMessage> sentMessages = messagesClient.getSentMessages();
for (WorkspaceMessage workspaceMessage : sentMessages) {
logger.debug("Sent message was " + workspaceMessage);
}
}
//@Test
public void sendMessage() throws Exception{
logger.debug("Sending message ");
MessagesClient messagesClient = new MessagesClient();
List<Recipient> rec = Arrays.asList(new Recipient("andrea.rossi"));
MessageInputBean input = new MessageInputBean("Test message",
MessageInputBean message = new MessageInputBean(
"Test message",
"Sending message via client " + System.currentTimeMillis(),
new ArrayList<Recipient>(rec));
String idMessage = messagesClient.writeMessage(input);
String idMessage = messagesClient.writeMessage(message);
assert(idMessage != null);
}
@Test
//@Test
public void testNotifications() throws Exception {
NotificationsClient notificationsClient = new NotificationsClient();
List<Notification> latestNotifications = notificationsClient.getNotifications(0, 2000);
List<Notification> latestNotifications = notificationsClient.getNotifications(1, 2);
for (Notification notification : latestNotifications) {
logger.debug("Notification is " + notification);
}
}
@Test
//@Test
public void sendJobNotification() throws Exception {
NotificationsClient notificationsClient = new NotificationsClient();
JobNotificationBean notification = new JobNotificationBean("costantino.perciante", UUID.randomUUID().toString(), "SmartExecutor Social Indexer", "SmartExecutor",
JobStatusType.SUCCEEDED, "");
JobNotificationBean notification = new JobNotificationBean(
"costantino.perciante",
UUID.randomUUID().toString(),
"SmartExecutor Social Indexer",
"SmartExecutor",
JobStatusType.SUCCEEDED,
"all ok");
notificationsClient.sendJobNotification(notification);
logger.debug("Sent job notification and received ");
logger.debug("Sent job notification ");
}
@After
public void reset(){
ScopeProvider.instance.reset();
SecurityTokenProvider.instance.reset();
}
}