added (partial) implementations for Users and Groups that exploit liferay's json web services

git-svn-id: http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/vo-management/usermanagement-core@141545 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Costantino Perciante 2017-01-13 10:02:08 +00:00
parent b072b22511
commit 8079834438
6 changed files with 1332 additions and 2 deletions

View File

@ -1,4 +1,9 @@
<ReleaseNotes>
<Changeset component="org.gcube.vo-management.usermanagement-core.2-3-0"
date="2017-02-01">
<Change>Added partial support to Liferay's JSON apis.
</Change>
</Changeset>
<Changeset component="org.gcube.vo-management.usermanagement-core.2-2-0"
date="2016-12-06">
<Change>Added method to read VirtualGroups associated to sites

17
pom.xml
View File

@ -10,7 +10,7 @@
<groupId>org.gcube.dvos</groupId>
<artifactId>usermanagement-core</artifactId>
<version>2.2.0-SNAPSHOT</version>
<version>2.3.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>User Management API</name>
@ -29,6 +29,8 @@
<maven.compiler.target>1.7</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<json.simple.version>1.1.1</json.simple.version>
<apache.http.version>4.3</apache.http.version>
</properties>
<dependencyManagement>
<dependencies>
@ -49,7 +51,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<version>4.8</version>
<scope>test</scope>
</dependency>
<dependency>
@ -60,6 +62,17 @@
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<!-- For JSON ws implementations -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${apache.http.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>${json.simple.version}</version>
</dependency>
</dependencies>
<build>
<resources>

View File

@ -0,0 +1,599 @@
package org.gcube.vomanagement.usermanagement.impl.ws;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.UserManagementNameException;
import org.gcube.vomanagement.usermanagement.exception.UserManagementPortalException;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.VirtualGroupNotExistingException;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GroupMembershipType;
import org.gcube.vomanagement.usermanagement.model.VirtualGroup;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.LoggerFactory;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
/**
* Exploit Liferay JSON Web Service to perform GroupManager's operations.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class LiferayWSGroupManager implements GroupManager {
// These properties are needed to save authentication credentials once.
private HttpClientContext localContext;
private CredentialsProvider credsProvider;
private HttpHost target;
// Several JSON calls use this property, so it will be discovered once (at init)
private Long companyId;
// the base path of the JSONWS apis
private static final String API_BASE_URL = "/api/jsonws";
// get methods paths
private static final String GET_COMPANY_ID = "/company/get-company-by-web-id/web-id/liferay.com";
private static final String GET_GROUP_BY_NAME = "/group/get-group/company-id/$COMPANY_ID/name/$GROUP_NAME";
private static final String GET_GROUP_BY_ID = "/group/get-group/group-id/$GROUP_ID";
private static final String GET_GROUPS_BY_PARENT_ID = "/group/get-groups/company-id/$COMPANY_ID/parent-group-id/$GROUP_PARENT_ID/site/$SITE";
private static final String GET_GROUPS_BY_USERID = "/group/get-user-sites-groups/user-id/$USER_ID/class-names/%5B%22com.liferay.portal.model.Group%22%5D/max/$MAX_GROUP";
// logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(LiferayWSGroupManager.class);
/**
* In order to contact the json ws of Liferay, user and password are needed. The host in which the current JVM
* machine runs needs to be authorized.
* @param user
* @param password
* @param host the host to contact
* @param port the port number
* @throws Exception
* @schema the schema (http/https) https is suggested!
*/
public LiferayWSGroupManager(String user, String password, String host, String schema, int port) throws Exception{
target = new HttpHost(host, port, schema);
credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(target.getHostName(), target.getPort()),
new UsernamePasswordCredentials(user, password));
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(target, basicAuth);
// Add AuthCache to the execution context
localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
// retrieve the company-id which will used later on
retrieveCompanyId();
}
/**
* Retrieve the company id value, which will be used later on for the other calls
* @throws Exception
*/
private void retrieveCompanyId() throws Exception {
String json = executeHTTPGETRequest(API_BASE_URL + GET_COMPANY_ID, credsProvider, localContext, target);
if(json != null){
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject)parser.parse(json);
companyId = (Long)jsonObject.get("companyId");
logger.info("Company id retrieved is " + companyId);
}else
throw new Exception("Failed to retrieve the company-id. The following calls will fail!");
}
/**
* Execute an http GET request and returns the JSON response
* @param requestPath
* @return a JSON string on success, null otherwise
*/
private static String executeHTTPGETRequest(String requestPath, CredentialsProvider credsProvider, HttpClientContext localContext, HttpHost target){
try{
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
HttpGet httpget = new HttpGet(requestPath);
logger.debug("Executing request " + httpget.getRequestLine() + " to target " + target);
CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
try {
String result = EntityUtils.toString(response.getEntity());
logger.debug("Request result is " + result);
return result;
} finally {
response.close();
}
}catch(Exception e){
logger.error("Exception while performing GET request", e);
}
return null;
}
/**
* Map a json object representing a group to a GCubeGroup object
* @param jsonGroup
* @return
* @throws PortalException
* @throws SystemException
* @throws UserManagementSystemException
* @throws GroupRetrievalFault
*/
private GCubeGroup mapLRGroup(String jsonGroup) throws PortalException, SystemException, UserManagementSystemException, GroupRetrievalFault {
try{
if (jsonGroup != null) {
JSONParser parser = new JSONParser();
JSONObject jsonGroupObject = (JSONObject)parser.parse(jsonGroup);
long logoId = 0; // TODO
long groupId = (long)jsonGroupObject.get("groupId");
if (isVRE(groupId)) {
logger.debug("********** IS VRE");
return new GCubeGroup(
groupId,
(long)jsonGroupObject.get("parentGroupId"),
(String)jsonGroupObject.get("name"),
(String)jsonGroupObject.get("description"),
(String)jsonGroupObject.get("friendlyURL"),
logoId,
null,
getMappedGroupMembershipType(((Long)jsonGroupObject.get("type")).intValue()));
}
else if (isVO(groupId)) {
logger.debug("********** IS VO");
List<GCubeGroup> vres = new ArrayList<GCubeGroup>();
List<String> vreInJson = getChildren(groupId);
if(vreInJson != null)
for (String vreJson : vreInJson) {
vres.add(mapLRGroup(vreJson));
}
return new GCubeGroup(
groupId,
(long)jsonGroupObject.get("parentGroupId"),
(String)jsonGroupObject.get("name"),
(String)jsonGroupObject.get("description"),
(String)jsonGroupObject.get("friendlyURL"),
logoId,
vres,
getMappedGroupMembershipType(((Long)jsonGroupObject.get("type")).intValue()));
} else if (isRootVO(groupId)) {
logger.debug("********** IS ROOT VO");
List<GCubeGroup> vos = new ArrayList<GCubeGroup>();
List<String> vosInJson = getChildren(groupId);
if(vosInJson != null)
for (String voInJson : vosInJson)
vos.add(mapLRGroup(voInJson));
return new GCubeGroup(
groupId,
(long)jsonGroupObject.get("parentGroupId"), // it is 0
(String)jsonGroupObject.get("name"),
(String)jsonGroupObject.get("description"),
(String)jsonGroupObject.get("friendlyURL"),
logoId,
vos,
getMappedGroupMembershipType(((Long)jsonGroupObject.get("type")).intValue()));
} else{
logger.warn("This groupId does not correspond to a (root-)VO ora VRE");
return null;
}
}
}catch(Exception e){
logger.error("There was an error while trying to map the group with json " + jsonGroup + " to the GcubeGroup class", e);
}
return null;
}
/**
* Retrieve the group children of the group having id groupId
* @param groupId
* @return Json representions of groups
*/
private List<String> getChildren(long groupId) {
List<String> jsonChildren = new ArrayList<String>();
try{
String jsonGroups =
executeHTTPGETRequest(API_BASE_URL + GET_GROUPS_BY_PARENT_ID.replace("$COMPANY_ID", String.valueOf(companyId)).replace("$GROUP_PARENT_ID", String.valueOf(groupId))
.replace("$SITE", Boolean.toString(true)),
credsProvider, localContext, target);
if(jsonGroups != null){
logger.debug("***** CHILDREN GROUP SET IS " + jsonGroups);
JSONParser parser = new JSONParser();
JSONArray array = (JSONArray)parser.parse(jsonGroups);
for (int i = 0; i < array.size(); i++) {
jsonChildren.add(((JSONObject)array.get(i)).toJSONString());
}
return jsonChildren;
}
}catch(Exception e){
logger.error("Error while returning the children of the group with id " + groupId, e);
}
return null;
}
/**
*
* @param type
* @return the correspondent mapping to the gcube model
*/
private GroupMembershipType getMappedGroupMembershipType(int type) {
switch (type) {
case 2:
return GroupMembershipType.RESTRICTED;
case 1:
return GroupMembershipType.OPEN;
default:
return GroupMembershipType.PRIVATE;
}
}
@Override
public GCubeGroup createRootVO(String rootVOName, String description)
throws UserManagementNameException, UserManagementSystemException,
UserRetrievalFault, GroupRetrievalFault,
UserManagementPortalException {
// TODO Auto-generated method stub
return null;
}
@Override
public GCubeGroup createVO(String virtualOrgName, long rootVOGroupId,
String description) throws UserManagementNameException,
UserManagementSystemException, UserRetrievalFault,
GroupRetrievalFault, UserManagementPortalException {
// TODO Auto-generated method stub
return null;
}
@Override
public GCubeGroup createVRE(String virtualResearchEnvName,
long virtualOrgGroupId, String description)
throws UserManagementNameException, UserManagementSystemException,
UserRetrievalFault, GroupRetrievalFault,
UserManagementPortalException {
// TODO Auto-generated method stub
return null;
}
@Override
public long getGroupParentId(long groupId)
throws UserManagementSystemException, GroupRetrievalFault {
try {
String jsonGroup =
executeHTTPGETRequest(API_BASE_URL + GET_GROUP_BY_ID.replace("$GROUP_ID", String.valueOf(groupId)),
credsProvider, localContext, target);
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject)parser.parse(jsonGroup);
return (long)obj.get("parentGroupId");
}catch (Exception e) {
logger.error("Unable to determine the parent group id of the group with id " + groupId);
}
return -1;
}
@Override
public long getGroupId(String groupName)
throws UserManagementSystemException, GroupRetrievalFault {
try{
String jsonGroup =
executeHTTPGETRequest(API_BASE_URL + GET_GROUP_BY_NAME.replace("$COMPANY_ID", String.valueOf(companyId)).replace("$GROUP_NAME", groupName),
credsProvider, localContext, target);
if(jsonGroup != null){
logger.debug("Trying to parse json group object");
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject)parser.parse(jsonGroup);
return (Long)obj.get("groupId");
}else
return -1;
}catch(Exception e){
logger.error("Error while retrieving the group id, returning -1", e);
}
return -1;
}
@Override
public GCubeGroup getGroup(long groupId)
throws UserManagementSystemException, GroupRetrievalFault {
try{
String jsonGroup =
executeHTTPGETRequest(API_BASE_URL + GET_GROUP_BY_ID.replace("$GROUP_ID", String.valueOf(groupId)),
credsProvider, localContext, target);
if(jsonGroup != null){
return mapLRGroup(jsonGroup);
}else
return null;
}catch(Exception e){
logger.error("Error while retrieving the group id, returning null", e);
}
return null;
}
@Override
public List<VirtualGroup> getVirtualGroups()
throws VirtualGroupNotExistingException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<VirtualGroup> getVirtualGroups(long actualGroupId)
throws GroupRetrievalFault, VirtualGroupNotExistingException {
// TODO Auto-generated method stub
return null;
}
@Override
public long getGroupIdFromInfrastructureScope(String scope)
throws IllegalArgumentException, UserManagementSystemException,
GroupRetrievalFault {
logger.debug("called getGroupIdFromInfrastructureScope on " + scope);
if(!scope.startsWith("/")){
throw new IllegalArgumentException("Scope should start with '/' ->" + scope);
}
if(scope.endsWith("/")){
throw new IllegalArgumentException("Scope should not end with '/' ->" + scope);
}
// splits this scope
String[] splits = scope.split("/");
if (splits.length > 4)
throw new IllegalArgumentException("Scope is invalid, too many '/' ->" + scope);
if (splits.length == 2) //is a root VO
return getGroupId(splits[1]);
else if (splits.length == 3) {//is a VO
try {
long parentGroupId = getGroupId(splits[1]); // get the root
List<String> vosInJson = null;
vosInJson = getChildren(parentGroupId); // get the vos
return checkChildrenAndReturnId(vosInJson, splits[2]);
} catch (Exception e) {
logger.error("Failed to retrieve the group id for this context", e);
}
}
else if (splits.length == 4) {//is a VRE
try {
logger.debug("is a VRE scope " + scope);
long parentGroupId = getGroupId(splits[2]); // get the vo
List<String> vresInJson = null;
vresInJson = getChildren(parentGroupId); // get the vres
return checkChildrenAndReturnId(vresInJson ,splits[3]);
} catch (Exception e) {
logger.error("Failed to retrieve the group id for this context", e);
}
}
return -1;
}
/**
* Among the groups, find -if any- the one that has the name nameToFind and return its id.
* @param groups
* @param nameToFind
* @return
* @throws ParseException
*/
private long checkChildrenAndReturnId(List<String> groups, String nameToFind) throws ParseException {
JSONParser parser = new JSONParser();
for (String group : groups) {
JSONObject obj = (JSONObject)parser.parse(group);
if(obj.get("name").equals(nameToFind))
return (long) obj.get("groupId");
}
return -1;
}
@Override
public GCubeGroup getRootVO() throws UserManagementSystemException,
GroupRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public String getRootVOName() throws UserManagementSystemException,
GroupRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public String getInfrastructureScope(long groupId)
throws UserManagementSystemException, GroupRetrievalFault {
try {
GCubeGroup group = getGroup(groupId);
if (isVRE(groupId)){
long voId = group.getParentGroupId();
GCubeGroup voGroup = getGroup(voId);
long rootVoId = voGroup.getParentGroupId();
String rootGroupName = getGroup(rootVoId).getGroupName();
return "/" + rootGroupName + "/" + voGroup.getGroupName() + "/" + group.getGroupName();
}
if (isVO(groupId)){
String rootVoName = getGroup(group.getParentGroupId()).getGroupName();
return "/" + rootVoName + "/" + group.getGroupName();
}
if (isRootVO(groupId))
return "/"+group.getGroupName();
}catch (Exception e) {
logger.error("Unable to retrieve the Infrastructure scope for group id " + groupId);
}
return null;
}
@Override
public String getScope(long groupId) throws UserManagementSystemException,
GroupRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public List<GCubeGroup> listGroups() throws UserManagementSystemException,
GroupRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public List<GCubeGroup> listGroupsByUser(long userId)
throws UserRetrievalFault, UserManagementSystemException,
GroupRetrievalFault {
List<GCubeGroup> toReturn = new ArrayList<GCubeGroup>();
try{
String jsonGroups = // TODO evaluate the max number of groups to return before, somehow
executeHTTPGETRequest(API_BASE_URL + GET_GROUPS_BY_USERID.replace("$USER_ID", String.valueOf(userId)).replace("$MAX_GROUP", String.valueOf(1000)),
credsProvider, localContext, target);
if(jsonGroups != null){
logger.debug("Trying to parse json object");
JSONParser parser = new JSONParser();
JSONArray array = (JSONArray)parser.parse(jsonGroups);
for (int i = 0; i < array.size(); i++) {
toReturn.add(mapLRGroup(((JSONObject)array.get(i)).toJSONString()));
}
}else
return null;
}catch(Exception e){
logger.error("Error while retrieving the group id, returning -1", e);
}
return toReturn;
}
@Override
public Set<GCubeGroup> listGroupsByUserAndSite(long userId,
String serverName) throws UserRetrievalFault,
UserManagementSystemException, GroupRetrievalFault,
VirtualGroupNotExistingException {
// TODO Auto-generated method stub
return null;
}
@Override
public Set<GCubeGroup> listGroupsByUserAndSiteGroupId(long userId,
long siteGroupId) throws UserRetrievalFault,
UserManagementSystemException, GroupRetrievalFault,
VirtualGroupNotExistingException {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<GCubeGroup, List<GCubeRole>> listGroupsAndRolesByUser(long userId)
throws UserManagementSystemException {
// TODO Auto-generated method stub
return null;
}
@Override
public Boolean isRootVO(long groupId) throws UserManagementSystemException,
GroupRetrievalFault {
try {
long groupParentId = getGroupParentId(groupId);
return (groupParentId == 0);
} catch (Exception e) {
logger.error("Error while checking if group with id " + groupId + " is the root VO");
}
return false;
}
@Override
public Boolean isVO(long groupId) throws UserManagementSystemException,
GroupRetrievalFault {
try {
long groupParentId = getGroupParentId(groupId);
if (groupParentId != 0) {
return !isVRE(groupId);
}
} catch (Exception e) {
logger.error("Error while checking if group with id " + groupId + " is a VO");
}
return false;
}
@Override
public Boolean isVRE(long groupId) throws UserManagementSystemException,
GroupRetrievalFault {
try {
long groupParentId = getGroupParentId(groupId);
if (groupParentId != 0) {
return getGroupParentId(groupParentId) != 0;
}
} catch (Exception e) {
logger.error("Error while checking if group with id " + groupId + " is a VRE");
}
return false;
}
@Override
public Serializable readCustomAttr(long groupId, String attributeKey)
throws GroupRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public void saveCustomAttr(long groupId, String attributeKey,
Serializable value) throws GroupRetrievalFault {
// TODO Auto-generated method stub
}
@Override
public String updateGroupDescription(long groupId, String description)
throws GroupRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public String getGroupLogoURL(long logoId) {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -0,0 +1,561 @@
package org.gcube.vomanagement.usermanagement.impl.ws;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.RoleRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.TeamRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.UserManagementPortalException;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault;
import org.gcube.vomanagement.usermanagement.model.Email;
import org.gcube.vomanagement.usermanagement.model.GCubeMembershipRequest;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.gcube.vomanagement.usermanagement.model.MembershipRequestStatus;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.LoggerFactory;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
/**
* Exploit Liferay JSON Web Service to perform UserManager's operations.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class LiferayWSUserManager implements UserManager{
// These properties are needed to save authentication credentials once.
private HttpClientContext localContext;
private CredentialsProvider credsProvider;
private HttpHost target;
// Several JSON calls use this property, so it will be discovered once (at init)
private Long companyId;
// the base path of the JSONWS apis
private static final String API_BASE_URL = "/api/jsonws";
// get methods paths
private static final String GET_COMPANY_ID = "/company/get-company-by-web-id/web-id/liferay.com";
private static final String GET_USER_BY_USERNAME = "/user/get-user-by-screen-name/company-id/$COMPANY_ID/screen-name/$USER_ID";
private static final String GET_USERS_BY_GROUP = "/user/get-group-users/group-id/$GROUP_ID";
private static final String GET_USER_CUSTOM_FIELD_BY_KEY = "/expandovalue/get-json-data/company-id/$COMPANY_ID/class-name/com.liferay.portal.model.User/table-name/CUSTOM_FIELDS/column-name/$CUSTOM_FIELD_KEY/class-pk/$USER_ID";
private static final String GET_CONTACT_BY_USER_ID = "/contact/get-contact/contact-id/$CONTACT_ID";
// logger
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(LiferayWSUserManager.class);
// some pre-defined constants
private static final String USER_LOCATION_INDUSTRY_KEY = "industry";
/**
* In order to contact the json ws of Liferay, user and password are needed. The host in which the current JVM
* machine runs needs to be authorized.
* @param user
* @param password
* @param host the host to contact
* @param port the port number
* @throws Exception
* @schema the schema (http/https) https is suggested!
*/
public LiferayWSUserManager(String user, String password, String host, String schema, int port) throws Exception{
target = new HttpHost(host, port, schema);
credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(target.getHostName(), target.getPort()),
new UsernamePasswordCredentials(user, password));
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(target, basicAuth);
// Add AuthCache to the execution context
localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
// retrieve the company-id which will used later on
retrieveCompanyId();
}
/**
* Retrieve the company id value, which will be used later on for the other calls
* @throws Exception
*/
private void retrieveCompanyId() throws Exception {
String json = executeHTTPGETRequest(API_BASE_URL + GET_COMPANY_ID, credsProvider, localContext, target);
if(json != null){
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject)parser.parse(json);
companyId = (Long)jsonObject.get("companyId");
logger.info("Company id retrieved is " + companyId);
}else
throw new Exception("Failed to retrieve the company-id. The following calls will fail!");
}
/**
* Execute an http GET request and returns the JSON response
* @param requestPath
* @return a JSON string on success, null otherwise
*/
private static String executeHTTPGETRequest(String requestPath, CredentialsProvider credsProvider, HttpClientContext localContext, HttpHost target){
try{
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
HttpGet httpget = new HttpGet(requestPath);
logger.debug("Executing request " + httpget.getRequestLine() + " to target " + target);
CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
try {
String result = EntityUtils.toString(response.getEntity());
logger.debug("Request result is " + result);
return result;
} finally {
response.close();
}
}catch(Exception e){
logger.error("Exception while performing GET request with path " + requestPath, e);
}
return null;
}
/**
* Maps the JSON user to the GCubeUser.class object
* @param json
* @return
*/
private GCubeUser mapLRUser(String json){
try{
if (json != null) {
JSONParser parser = new JSONParser();
JSONObject userJSON = (JSONObject)parser.parse(json);
// TODO skip for now
List<Email> emails = new ArrayList<Email>();
// for (EmailAddress e : u.getEmailAddresses()) {
// emails.add(new Email(e.getAddress(), e.getType().toString(), e.isPrimary()));
// }
String locationIndustry = "";
try {
locationIndustry = (String) readCustomAttr((long)userJSON.get("userId"), USER_LOCATION_INDUSTRY_KEY);
} catch (Exception e1) {
logger.warn("Failed to retrieve property " + USER_LOCATION_INDUSTRY_KEY, e1);
}
// retrieve the contact id information (it is into the user json)
long contactId = (long)userJSON.get("contactId");
// retrieve contact json obj from contactId
String jsonContact = getContactJson(contactId);
JSONObject contactJSON = (JSONObject)parser.parse(jsonContact);
return new GCubeUser(
(long)userJSON.get("userId"),
(String)userJSON.get("screenName"),
(String)userJSON.get("emailAddress"),
(String)userJSON.get("firstName"),
(String)userJSON.get("middleName"),
(String)userJSON.get("lastName"),
(String)userJSON.get("fullName"),
(long)userJSON.get("createDate"),
null, // skip for now TODO getUserAvatarAbsoluteURL(u)
(boolean)contactJSON.get("male"),
(String)userJSON.get("jobTitle"),
locationIndustry,
emails);
}
}catch(Exception e){
logger.error("Exception while mapping the json user object to the GCubeUser java object", e);
}
return null;
}
/**
* Given the contactId value, retrieves the json object releted to this information
* @param contactId
* @return
*/
private String getContactJson(long contactId) {
return executeHTTPGETRequest(API_BASE_URL + GET_CONTACT_BY_USER_ID.replace("$CONTACT_ID", String.valueOf(contactId)),
credsProvider, localContext, target);
}
@Override
public GCubeUser createUser(boolean autoScreenName, String username,
String email, String firstName, String middleName, String lastName,
String jobTitle, String location_industry,
String backgroundSummary, boolean male, String reminderQuestion,
String reminderAnswer) throws UserManagementSystemException {
// TODO Auto-generated method stub
return null;
}
@Override
public GCubeUser createUser(boolean autoScreenName, String username,
String email, String firstName, String middleName, String lastName,
String jobTitle, String location_industry,
String backgroundSummary, boolean male, String reminderQuestion,
String reminderAnswer, boolean sendEmail, boolean forcePasswordReset)
throws UserManagementSystemException {
// TODO Auto-generated method stub
return null;
}
@Override
public GCubeUser createUser(boolean autoScreenName, String username,
String email, String firstName, String middleName, String lastName,
String jobTitle, String location_industry,
String backgroundSummary, boolean male, String reminderQuestion,
String reminderAnswer, boolean sendEmail,
boolean forcePasswordReset, byte[] portraitBytes)
throws UserManagementSystemException {
// TODO Auto-generated method stub
return null;
}
@Override
public GCubeUser createUser(boolean autoScreenName, String username,
String email, String firstName, String middleName, String lastName,
String jobTitle, String location_industry,
String backgroundSummary, boolean male, String reminderQuestion,
String reminderAnswer, boolean sendEmail,
boolean forcePasswordReset, byte[] portraitBytes, String mySpacesn,
String twittersn, String facebooksn, String skypesn,
String jabbersn, String aimsn) throws UserManagementSystemException {
// TODO Auto-generated method stub
return null;
}
@Override
public GCubeUser getUserByUsername(String username)
throws UserManagementSystemException, UserRetrievalFault {
String jsonUser =
executeHTTPGETRequest(API_BASE_URL + GET_USER_BY_USERNAME.replace("$COMPANY_ID", String.valueOf(companyId)).replace("$USER_ID", username),
credsProvider, localContext, target);
if(jsonUser != null){
logger.debug("Json user retrieved");
return mapLRUser(jsonUser);
}else
return null;
}
@Override
public GCubeUser getUserByScreenName(String username)
throws UserManagementSystemException, UserRetrievalFault {
return getUserByUsername(username);
}
@Override
public GCubeUser getUserByEmail(String email)
throws UserManagementSystemException, UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public GCubeUser getUserById(long userId)
throws UserManagementSystemException, UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public long getUserId(String username)
throws UserManagementSystemException, UserRetrievalFault {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getUserProfessionalBackground(long userId)
throws UserManagementSystemException, UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public void setUserProfessionalBackground(long userId, String summary)
throws UserManagementSystemException, UserRetrievalFault {
// TODO Auto-generated method stub
}
@Override
public List<GCubeUser> listUsers() throws UserManagementSystemException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<GCubeUser> listUsers(boolean indexed)
throws UserManagementSystemException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<GCubeUser> listUsersByGroup(long groupId)
throws UserManagementSystemException, GroupRetrievalFault,
UserRetrievalFault {
try{
List<GCubeUser> toReturn = new ArrayList<GCubeUser>();
String jsonUsers =
executeHTTPGETRequest(API_BASE_URL + GET_USERS_BY_GROUP.replace("$GROUP_ID", String.valueOf(groupId)),
credsProvider, localContext, target);
if(jsonUsers != null){
logger.debug("Trying to parse json users array ");
JSONParser parser = new JSONParser();
JSONArray array = (JSONArray)parser.parse(jsonUsers);
for (int i = 0; i < array.size(); i++) {
toReturn.add(mapLRUser(((JSONObject)array.get(i)).toJSONString()));
}
}else
return null;
return toReturn;
}catch(Exception e){
logger.error("Something went wrong, sorry", e);
return null;
}
}
@Override
public List<GCubeUser> listUsersByGroup(long groupId, boolean indexed)
throws UserManagementSystemException, GroupRetrievalFault,
UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public List<GCubeUser> listUsersByGroupName(String name)
throws UserManagementSystemException, GroupRetrievalFault,
UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public Set<GCubeUser> getUserContactsByGroup(long userId, long scopeGroupId)
throws UserManagementSystemException, GroupRetrievalFault,
UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public List<GCubeMembershipRequest> listMembershipRequestsByGroup(
long groupId) throws UserManagementSystemException,
GroupRetrievalFault, UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public GCubeMembershipRequest getMembershipRequestsById(
long membershipRequestId) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<GCubeMembershipRequest> getMembershipRequests(long userId,
long groupId, MembershipRequestStatus status)
throws UserManagementSystemException, GroupRetrievalFault,
UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public GCubeMembershipRequest requestMembership(long userId, long groupId,
String comment) throws UserManagementSystemException,
GroupRetrievalFault, UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public GCubeMembershipRequest acceptMembershipRequest(long requestUserId,
long groupId, boolean addUserToGroup, String replyUsername,
String replyComment) throws UserManagementSystemException,
GroupRetrievalFault, UserManagementPortalException {
// TODO Auto-generated method stub
return null;
}
@Override
public GCubeMembershipRequest rejectMembershipRequest(long userId,
long groupId, String replyUsername, String replyComment)
throws UserManagementSystemException, GroupRetrievalFault,
UserManagementPortalException {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<GCubeUser, List<GCubeRole>> listUsersAndRolesByGroup(long groupId)
throws GroupRetrievalFault, UserManagementSystemException,
UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public List<GCubeUser> listUsersByGroupAndRole(long groupId, long roleId)
throws UserManagementSystemException, RoleRetrievalFault,
GroupRetrievalFault, UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public List<GCubeUser> listUsersByTeam(long teamId)
throws UserManagementSystemException, TeamRetrievalFault,
UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public void assignUserToGroup(long groupId, long userId)
throws UserManagementSystemException, GroupRetrievalFault,
UserRetrievalFault, UserManagementPortalException {
// TODO Auto-generated method stub
}
@Override
public void dismissUserFromGroup(long groupId, long userId)
throws UserManagementSystemException, GroupRetrievalFault,
UserRetrievalFault {
// TODO Auto-generated method stub
}
@Override
public List<GCubeUser> listUnregisteredUsersByGroup(long groupId)
throws UserManagementSystemException, GroupRetrievalFault,
UserRetrievalFault {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isPasswordChanged(String email) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean userExistsByEmail(String email) {
// TODO Auto-generated method stub
return false;
}
@Override
public String getFullNameFromEmail(String email) {
// TODO Auto-generated method stub
return null;
}
@Override
public void deleteUserByEMail(String email)
throws UserManagementSystemException,
UserManagementPortalException, PortalException, SystemException {
// TODO Auto-generated method stub
}
@Override
public byte[] getUserAvatarBytes(String screenName) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getUserOpenId(String screenName) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean updateContactInformation(String screenName,
String mySpacesn, String twittersn, String facebooksn,
String skypesn, String jabbersn, String aimsn) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean updateJobTitle(long userId, String theJob) {
// TODO Auto-generated method stub
return false;
}
@Override
public Serializable readCustomAttr(long userId, String attributeKey)
throws UserRetrievalFault {
String toReturn = null;
try{
String jsonCustomField =
executeHTTPGETRequest(API_BASE_URL + GET_USER_CUSTOM_FIELD_BY_KEY.replace("$COMPANY_ID", String.valueOf(companyId)).replace("$CUSTOM_FIELD_KEY", attributeKey).replace("$USER_ID", String.valueOf(userId)),
credsProvider, localContext, target);
if(jsonCustomField != null){
logger.debug("Trying to parse custom field in json object");
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject)parser.parse(jsonCustomField);
toReturn = (String)obj.get("data");
}
}catch(Exception e){
logger.error("Something went wrong, sorry", e);
return null;
}
return toReturn;
}
@Override
public void saveCustomAttr(long userId, String attributeKey,
Serializable value) throws UserRetrievalFault {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,79 @@
package org.gcube.vomanagement.usermanagement.test;
import java.util.List;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault;
import org.gcube.vomanagement.usermanagement.impl.ws.LiferayWSGroupManager;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.slf4j.LoggerFactory;
/**
* Test class for Liferay Group WS
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class LiferayWSGroupTest {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(LiferayWSGroupTest.class);
private GroupManager groupManager = null;
private String user = "";
private String password = ""; // Put a valid password here
private String host = "";
private String schema = "";
private int port = -1;
//@Before
public void init() throws Exception{
logger.info("Init method, building LiferayWSGroupManager");
groupManager = new LiferayWSGroupManager(user, password, host, schema, port);
}
//@Test
public void getGroupParentId() throws UserManagementSystemException, GroupRetrievalFault{
long id = groupManager.getGroupParentId(-1);
logger.debug("Retrieved parent id " + id);
}
//@Test
public void getGroupId() throws UserManagementSystemException, GroupRetrievalFault{
long id = groupManager.getGroupId("devNext");
logger.debug("Retrieved id " + id);
}
//@Test
public void getGroup() throws UserManagementSystemException, GroupRetrievalFault{
GCubeGroup group = groupManager.getGroup(-1);
logger.debug("Retrieved group " + group);
}
//@Test
public void getGroupIdFromInfrastructureScope() throws IllegalArgumentException, UserManagementSystemException, GroupRetrievalFault{
long id = groupManager.getGroupIdFromInfrastructureScope("/gcube/devNext/NextNext");
logger.debug("Retrieved group " + id);
}
//@Test
public void getInfrastructureScope() throws IllegalArgumentException, UserManagementSystemException, GroupRetrievalFault{
String scope = groupManager.getInfrastructureScope(-1);
logger.debug("Retrieved scope " + scope);
}
//@Test
public void listGroupsByUser() throws IllegalArgumentException, UserManagementSystemException, GroupRetrievalFault, UserRetrievalFault{
List<GCubeGroup> groups = groupManager.listGroupsByUser(-1);
logger.debug("Retrieved groups " + groups);
}
}

View File

@ -0,0 +1,73 @@
package org.gcube.vomanagement.usermanagement.test;
import java.util.List;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault;
import org.gcube.vomanagement.usermanagement.impl.ws.LiferayWSUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.slf4j.LoggerFactory;
/**
* Test class for Liferay User WS
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class LiferayWSUserTest{
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(LiferayWSUserTest.class);
private UserManager userManager = null;
private String user = "";
private String password = ""; // Put a valid password here
private String host = "";
private String schema = "";
private int port = -1;
//@Before
public void init() throws Exception{
logger.info("Init method, building LiferayWSUserManager");
userManager = new LiferayWSUserManager(user, password, host, schema, port);
}
//@Test
public void getUserByUsername() throws UserManagementSystemException, UserRetrievalFault{
String username = "costantino.perciante";
GCubeUser gcubeUser = userManager.getUserByUsername(username);
logger.debug("Retrieved user object " + gcubeUser);
}
//@Test
@SuppressWarnings("deprecation")
public void getUserByScreenName() throws UserManagementSystemException, UserRetrievalFault{
String username = "costantino.perciante";
GCubeUser gcubeUser = userManager.getUserByScreenName(username);
logger.debug("Retrieved user object " + gcubeUser);
}
//@Test
public void listUsersByGroup() throws UserManagementSystemException, UserRetrievalFault, GroupRetrievalFault{
List<GCubeUser> gcubeUsers = userManager.listUsersByGroup(21660);
logger.debug("Retrieved user object " + gcubeUsers);
}
//@Test
public void readCustomAttr() throws UserRetrievalFault{
long userId = 21325;
String value = (String) userManager.readCustomAttr(userId, "industry");
logger.debug("Retrieved custom field value " + value);
}
}