Social Networking Service

From Gcube Wiki
Revision as of 11:26, 24 July 2017 by Costantino.perciante (Talk | contribs) (Get usernames by global role)

Jump to: navigation, search

Contents

The Social Networking Service is a RESTful application which exposes operations coming from both the gCube Social-Networking-Library and the User Management components. The former is the bridge between the Cassandra Cluster (on which social data are stored) and the social applications, whereas the latter is the abstraction layer over the enabling technology of the Infrastructure portals, Liferay, in terms of: roles, users and organizations and how they are mapped to gCube concepts (VREs, Teams, and so on).

The web services exposes a subset of such functionalities over https in a standard, reliable and secure way.

See the vailable REST-API at a glance here.

Discover the Web Service

For gCube releases older than 4.3, a Service Endpoint that has

Name = SocialNetworking
Category = Portal

mantains the base path of the service. Starting from gCube 4.3 version, the service runs on SmartGears, thus a gCore Endpoint needs to be searched having

Service Name = SocialNetworking
Service Class = Portal

The base path is the entry point of the web service. In the development environment, its current value is

 https://socialnetworking-d-d4s.d4science.org/social-networking-library-ws/rest

In the production environment, its current value is

 https://socialnetworking1.d4science.org/social-networking-library-ws/rest

This url is referred as BASE_URL.

Service versions

Starting from gCube 4.3, the service exposes its methods using a more standard naming approach. Moreover, they accept (in case of http POST/PUT methods) JSON objects. The result of all methods is always a JSON object of this kind

{"success": false/true,
"message": ...,
"result": ...,
}

Where

  • success reports if the request succeeded or failed;
  • message is a status/error message that can be checked in case of errors (success equals false);
  • result is the current result object (it can be a list, a single object and so on depending on the invoked method).

Inputs are automatically validated before the request is served.

The older version (Version 1) instead has some limitation thus you are kindly suggested to no longer use it. However, in the following, its methods are going to be reported as well. The older version will be removed starting from the next gCube releases.

Authorization

No matter the version number of the service, every call to one of its method require a gcube-token. See here for more information about this token. This secret token needs to be valid in the current context. It can be put as query parameter of the http request or within the header. Both approaches are valid. If the token is missing, the operation will be rejected and an http forbidden code will be returned.

Usage

The methods of the Web Service can be called by writing your own REST client application or by using (a lot of) already existent rest client plugins. In the following, we will use the RESTClient plugin for Firefox for POST methods. Your browser can be used for GET methods. The return value of each method is an HTTP Response object that has an HTTP CODE (200, 201, 400, 500, ...) and, optionally, a JSON or text object that represents the created/retrieved resource or better specifies the occurred error. In case of errors, please refer to the Troubleshooting section for more details.

Service methods (Version 2)

The list of sub-services available in the new version is going to be reported next. The name convention is different. For instance, to read user's posts, the method to be called is

BASE_PATH/2/posts/get-posts-user/

The real result of the method, if the request succeeded, is contained into the 'result' field of the json object

{"success": ..., "message": ..., "result": "[{first post}, {second post}, ...}

In the following, the list of available sub-services available under the newest version, its methods and the parameters they need in order to be called are reported. Again, you can use your preferred REST client so examples won't be reported.

List of Available Sub-Services and methods

Tokens

Generate application token

The link to append to Base_URL is the following:

2/tokens/generate-application-token

First of all, you need to have a user gcube-token for authentication purposes. You can get it using the Token Generator portlet available on the VRE you are interesting the app will post in. Then, to get an application gcube-token you can invoke the method. It is an HTTP/POST method that accepts as parameter:

  • a json object of this kind {"app_id": "your-app-id-goes-here"}.

User profile and roles

To retrieve user's profile user profile info (and roles) the subservice to call, once the social networking service endpoint has been retrieved, is this one:

/2/people/profile

further details: get member information

Full text search

Search by query

Social data are indexed into an ElasticSearch engine and are querable using a full-text approach. You can retrieve more information about this index [1]. The link to append to Base_URL is the following

2/full-text-search/search-by-query

The query can be submitted also to the service, by using the following parameters

  • query: the query to perform against the index [mandatory];
  • from : the result set should be returned by starting from the n-th result [default is zero, optional];
  • quantity: how many enhanced posts need to be returned [default is 10, optional].

Hashtags

Get hashtags and occurrences in a context

The link to append to Base_URL is the following

2/hashtags/get-hashtags-and-occurrences

The result is of the kind {"success": true, "message": null, "result":{{"hashtag1" : x}, {"hashtag2" : y}, ...} }

Posts

Write application post

The link to append to Base_URL is the following:

2/posts/write-post-app

By means of the application token requested with the above method, the app can write on the VRE for which the token has been previously requested. Just invoke this method, that accepts these parameters in a JSON object

  • text: text of the post;
  • params: additional parameters if your application supports the direct opening of of this update's object e.g. id=12345&type=foo [optional];
  • preview_title: a title for the preview of the post [optional];
  • preview_host: a host for the preview of the post [optional];
  • preview_description: a description for the preview of the post [optional];
  • preview_url: the preview url [optional];
  • image_url: if you want to put an image, pass its url [optional];
  • enable_notification: a boolean value to enable notifications [optional, default is false].

Write user post

The link to append to Base_URL is the following:

2/posts/write-post-user

By means of a valid user token, he/she can write on the VRE for which the token has been previously requested. Just invoke this method, that accepts these parameters in a JSON object:

  • text: text of the post;
  • preview_title: a title for the preview of the post [optional];
  • preview_description: a description for the preview of the post [optional];
  • preview_host: a host for the preview of the post [optional];
  • preview_url: the preview url [optional];
  • image_url: if you want to put an image, pass its url [optional];
  • enable_notification: a boolean value to enable notifications [optional].

Retrieve all application posts

The link to append to Base_URL is the following:

2/posts/get-posts-app

In order to retrieve all the posts the application wrote (in every VRE it is allowed to write in) you can invoke this HTTP/GET method.

Retrieve all user posts

The link to append to Base_URL is the following:

2/posts/get-posts-user

Retrieve all user posts since a given date

The link to append to Base_URL is the following:

2/posts/get-posts-user-since

If you are interested in retrieving user's posts whose timestamps are greater than a given date you can invoke this method. This HTTP/GET method accepts as parameter:

  • time: the time of the oldest post to retrieve converted in milliseconds.

Retrieve all user posts up to a given quantity

The link to append to Base_URL is the following:

2/posts/get-posts-user-quantity

If you are interested in retrieving user's posts, starting from the newest up to a given quantity you can invoke this method. This HTTP/GET method accepts as parameter:

  • quantity: a value greater than zero (the default value is 10).

Retrieve the identifiers of the posts a user liked

The link to append to Base_URL is the following:

2/posts/get-id-liked-posts

By means of this method a user can retrieve the identifiers of the posts he/she liked.

Retrieve the posts a user liked

The link to append to Base_URL is the following:

2/posts/get-liked-posts

By means of this method a user can retrieve the posts he/she liked.

Retrieve all vre posts

The link to append to Base_URL is the following:

2/posts/get-posts-vre

By means of this method a user that has a token valid for a certain VRE, can retrieve all the posts of that VRE.

Get posts by hashtag

The link to append to Base_URL is the following:

2/posts/get-posts-by-hashtag

The method requires as parameter:

  • hashtag: the hashtag to be contained in the returned posts[mandatory].

Comments

Retrieve comments by user

The link to append to Base_URL is the following:

2/comments/get-comments-user

It is an http GET method.

Retrieve comments by user and time

The link to append to Base_URL is the following:

2/comments/get-comments-user-by-time

It is an http GET method. It requires:

  • time: the time (in milliseconds) since when the comments need to be retrieved [default is zero, optional];

Notifications

Retrieve user's notifications in a given range

The link to append to Base_URL is the following:

2/notifications/get-range-notifications

By means of this method a user can retrieve his/her last notifications in the range [a, b]. The method requires:

  • from: an integer greater than zero;
  • quantity: an integer equal or greater than zero.

The final range is evaluated as [from, from + quantity].

Notify job status

The link to append to Base_URL is the following:

2/notifications/notify-job-status

By means of this method a user can be notified about the status of a job in the infrastructure. Jobs are, for instance, SmartExecutor's plugins or DataMiner's algorithms. The method requires the following parameters in a JSON object via HTTP POST

  • recipient: the username of the user to be alerted [mandatory];
  • job_id: the identifier of the job (e.g, a uuid) [mandatory];
  • job_name: the name of the running job (e.g., Social-data-indexer-plugin)[mandatory];
  • service_name: the name of the service that launched the job (e.g., SmartExecutor) [mandatory];
  • status: the status reached by the job, that is any among CANCELLED, CANCELLING, DELETED, DELETING, EXECUTING, FAILED, SUCCEEDED, SUBMITTED, TIMED_OUT, WAITING [mandatory];
  • status_message: a detailed message about the status [optional].

Messages

Send a message

It is an HTTP POST method.

The link to append to BASE_URL is

2/messages/write-message

By default, the sender of the message is the owner of the gcube-token. According to the recipients' notifications preferences, they could receive a portal notification, an email notification and so on.

Parameters, to be put in a JSON object are:

  • subject: the subject of the message to send;
  • body: the body of the message;
  • recipients: a list of valid comma separated users' ids (e.g., andrea.rossi, mario.rossi) or users' emails (e.g., andrea.rossi@isti.cnr.it, mario.rossi@isti.cnr.it);

Get received messages

The link to append to BASE_URL is

2/messages/get-received-messages

It is an http GET method.

Get sent messages

The link to append to BASE_URL is

2/messages/get-sent-messages

It is an http GET method.

Users

User exists

The link to append to BASE_URL is

2/users/user-exists

The method requires

  • username: the username of the user which has to be checked.

Note The method can be only invoked with a root-context application token.

Read user's custom fields

The link to append to BASE_URL is

2/users/get-custom-attribute

The method requires

  • attribute: that is the name of a valid attribute to be read.

Get user's email

The link to append to BASE_URL is

2/users/get-email

The method returns the email associated to the owner of the security token used.

Get user's profile

The link to append to BASE_URL is

2/users/get-profile

The method returns the profile of the owner of the security token used.

Get user's fullname

The link to append to BASE_URL is

2/users/get-fullname

The method returns the fullname associated to the owner of the security token used.

Get all users' usernames in VRE

The link to append to BASE_URL is

2/users/get-usernames

The method returns the usernames of the context associated to the security token.

Get usernames by global role

The link to append to BASE_URL is

2/users/get-usernames-by-global-role

The method requires

  • role-name: that is the name of the role to consider.

This method can be only invoked with an Infrastructure Token.

Troubleshooting

There could be many reasons for a failed request. Please always check the HTTP CODE and the message within the response.

HTTP Error Code

This table tries to help you:

HTTP CODE Meaning
400 - BAD_REQUEST Please check the parameters you are passing
403 - FORBIDDEN Is the token valid? / Does it belong to an application? [In case of application request]
404 - NOT_FOUND The object(s) you are asking for is(are) not available
500 - INTERNAL_SERVER_ERROR There was an error while serving your request (retry later)


Always manage HTTP Redirects on POST requests (i.e. 30X codes)

The service accepts both incoming http and https client requests, which are automatically redirect to https protocol by the reverse proxy nginx. This redirect mechanism must be taken into account when POST calls are performed, because it is not (always) supported and transparent by clients. In order to be sure, please check if you get a 30X error and extract the redirection urls within the response header. The following is a working java code that extract such information. It uses the apache-client library to perform http calls.

// build the client and the request
String path = ... ; 
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
CloseableHttpClient httpClient = clientBuilder.build();
HttpPost request = new HttpPost(path);
JSONObject obj = new JSONObject();
 
... // build the json object
 
// set header properties
request.addHeader("gcube-token", ...);
request.addHeader("Content-type", ContentType.APPLICATION_JSON.toString());
StringEntity params = new StringEntity(obj.toJSONString(), ContentType.APPLICATION_JSON);
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
logger.info(" " + response.getStatusLine().getStatusCode() + " and response message is " + response.getStatusLine().getReasonPhrase());
 
int status = response.getStatusLine().getStatusCode();
 
// check the response status and look if it was a redirect problem
if (status != HttpURLConnection.HTTP_OK && (status == HttpURLConnection.HTTP_MOVED_TEMP ||
        status == HttpURLConnection.HTTP_MOVED_PERM ||
        status == HttpURLConnection.HTTP_SEE_OTHER)) {
 
    // redirect -> fetch new location
    Header[] locations = response.getHeaders("Location");
    Header lastLocation = locations[locations.length - 1];
    String realLocation = lastLocation.getValue();
    logger.debug("New location is " + realLocation);
 
    // perform again the same request
    request = new HttpPost(realLocation);
    request.addHeader("gcube-token", ...);
    request.addHeader("Content-type", ContentType.APPLICATION_JSON.toString());
    params = new StringEntity(obj.toJSONString(), ContentType.APPLICATION_JSON);
    request.setEntity(params);
    response = httpClient.execute(request);
    logger.info(" " + response.getStatusLine().getStatusCode() + " and response message is " + response.getStatusLine().getReasonPhrase());
} else
    logger.debug(" " + response.getStatusLine().getStatusCode() + " and response message is " + response.getStatusLine().getReasonPhrase());

Service methods (Version 1) - DEPRECATED

In the following, the list of available sub-services available under the first version, its methods and the parameters they need in order to be called are reported. The gcube-token is always required so it won't be reported as parameter.

This version has been replaced by version 2, please do not use this version and update your code asap.

List of available Sub-Services and methods

Tokens

Generate application token

The link to append to Base_URL is the following:

tokens/generateApplicationToken

First of all, you need to have a user gcube-token for authentication purposes. You can get it using the Token Generator portlet available on the VRE you are interesting the app will post in. Now, to get an application gcube-token you can invoke the method. It is an HTTP/POST method that accepts as parameters:

  • appid: the identifier of the application as reported in the Application Profile.

For example, using the RESTClient plugin for Firefox you will have something like this for requiring a new application token:

GenerateApplicationToken.png

Push on the SEND button and if all it's ok, your application gcube-token will be generated and returned as plain text in the response within the HTTP response having code 201.

Posts

Write application post

The link to append to Base_URL is the following:

posts/writePostApplication

By means of the application token requested with the above method, the app can write on the VRE for which the token has been previously requested. Just invoke this method, that accepts these parameters:

  • text: text of the post;
  • params: additional parameters if your application supports the direct opening of of this update's object e.g. id=12345&type=foo [optional];
  • previewtitle: a title for the preview of the post [optional];
  • previewdescription: a description for the preview of the post [optional];
  • httpimageurl: if you want to put an image, pass its url [optional];
  • enablenotification: a boolean value to enable notifications [optional].

For example:

WriteApplicationPost.png

Push on SEND and check the code associated to the returned response (201 in case of success).

Retrieve all application posts

The link to append to Base_URL is the following:

posts/getAllPostsByApp

In order to retrieve all the posts the application wrote (in every VRE it is allowed to write in) you can invoke this HTTP/GET method.

For example, using your browser:

BASE_URL/posts/getAllPostsByApp?gcube-token=yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyy

If all goes ok, the response object has status code 200 and the posts are returned in JSON format.

Retrieve all user posts

The link to append to Base_URL is the following:

posts/getAllPostsByUser

For example, using your browser:

BASE_URL/posts/getAllPostsByUser?gcube-token=yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyy

If all goes ok, the response object has status code 200 and the posts are returned in JSON format.

Retrieve all user posts since a given date

The link to append to Base_URL is the following:

posts/getRecentPostsByUserAndDate

If you are interested in retrieving user's posts whose timestamps are greater than a given date you can invoke this method. This HTTP/GET method accepts this parameter:

  • time: the time of the oldest post to retrieve converted in milliseconds.

For example, using your browser:

BASE_URL/posts/getRecentPostsByUserAndDate?gcube-token=yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyy&time=xxxxx

If all goes ok, the response object has status code 200 and the posts are returned in JSON format.

Retrieve all user posts up to a given quantity

The link to append to Base_URL is the following:

posts/getRecentPostsByUser

If you are interested in retrieving user's posts, starting from the newest up to a given quantity you can invoke this method. This HTTP/GET method accepts two parameter:

  • quantity: a value greater than zero (the default value is 10).

For example, using your browser:

BASE_URL/posts/getRecentPostsByUser?gcube-token=yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyy&quantity=20


If all goes ok, the response object has status code 200 and the posts are returned in JSON format.

Write user post

The link to append to Base_URL is the following:

posts/writePostUser

By means of a valid user token, he/she can write on the VRE for which the token has been previously requested. Just invoke this method, that accepts these parameters:

  • text: text of the post;
  • previewtitle: a title for the preview of the post [optional];
  • previewdescription: a description for the preview of the post [optional];
  • previewHost: [optional];
  • previewUrl: [optional];
  • httpimageurl: if you want to put an image, pass its url [optional];
  • enablenotification: a boolean value to enable notifications [optional];

For example:

Userpost.png

Push on SEND and check the code associated to the returned response (201 in case of success).

Retrieve the identifiers of the posts a user liked

The link to append to Base_URL is the following:

posts/getAllLikedPostIdsByUser

By means of this method a user can retrieve the identifiers of the posts he/she liked.

For example, using your browser:

BASE_URL/posts/getAllLikedPostIdsByUser?gcube-token=yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyy

If all goes ok, the response object has status code 200 and the identifiers of the posts are returned in JSON format.

Retrieve the posts a user liked

The link to append to Base_URL is the following:

posts/getAllLikedPostsByUser

By means of this method a user can retrieve the posts he/she liked.

For example, using your browser:

BASE_URL/posts/getAllLikedPostsByUser?gcube-token=yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyy

If all goes ok, the response object has status code 200 and the posts are returned in JSON format.

Retrieve all vre posts

The link to append to Base_URL is the following:

posts/getAllPostsByVRE

By means of this method a user that has a token valid for a certain VRE, can retrieve all the posts of that VRE. For example, using your browser:

BASE_URL/posts/getAllPostsByVRE?gcube-token=yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyy

If all goes ok, the response object has status code 200 and the posts are returned in JSON format.

Notifications

Retrieve user's notifications in a given range

The link to append to Base_URL is the following:

notifications/getRangeNotificationsByUser

By means of this method a user can retrieve his/her last notifications in the range [a, b]. The method requires:

  • from: an integer greater than zero;
  • quantity: an integer equal or greater than zero.

The final range is evaluated as [from, from + quantity]

For example, using your browser:

BASE_URL/notifications/getRangeNotificationsByUser?gcube-token=yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyy&from=from&quantity=quantity

If all goes ok, the response object has status code 200 and the posts are returned in JSON format.

Messages

Send a message

You can send a message via the web service by using the following POST method:

  • writeMessageToUsers

The link to append to BASE_URL is

messages/writeMessageToUsers

By default, the sender of the message is the owner of the gcube-token. If you need to specify a different "sender", you can do that by specifying the parameter sender. Furthermore, according to the recipients' notifications preferences, they could receive a portal notification, a mail notification and so on.

Parameters are:

  • subject: the subject of the message to send;
  • body: the body of the message;
  • recipients: a list of valid comma separated users' ids (e.g., andrea.rossi, mario.rossi).
  • sender: a valid sender's id [optional]

An example usage of the method is reported in the picture below (without specifying the sender):

Send message example.png

Users

Read user's custom fields

You can read user's custom attributes using the following method

  • readCustomAttr

The link to append to BASE_URL is

users/readCustomAttr

The read method requires

  • attribute: that is the name of a valid attribute to be read.

For example, using your browser:

BASE_URL/users/readCustomAttr?gcube-token=yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyy&attribute=attributeX