Switched user info retrieving to authorization utils library

This commit is contained in:
Luca Frosini 2021-12-06 17:45:15 +01:00
parent 58674cec7a
commit dd6bf694b4
13 changed files with 108 additions and 303 deletions

View File

@ -52,7 +52,7 @@ public abstract class ModerationThread {
public void postItemCreated() throws Exception{ public void postItemCreated() throws Exception{
createModerationThread(); createModerationThread();
String username = ckanUser.getPortalUser().getNameSurname(); String username = ckanUser.getNameSurname();
CMItemStatus cmItemStatus = CMItemStatus.PENDING; CMItemStatus cmItemStatus = CMItemStatus.PENDING;
String message = String.format("@**%s** has created the item with name '%s' (id='%s'). The item is now in **%s** state and must be moderated.", String message = String.format("@**%s** has created the item with name '%s' (id='%s'). The item is now in **%s** state and must be moderated.",
username, itemName, itemID, cmItemStatus.getFancyValue()); username, itemName, itemID, cmItemStatus.getFancyValue());
@ -60,7 +60,7 @@ public abstract class ModerationThread {
} }
public void postItemUpdated() throws Exception { public void postItemUpdated() throws Exception {
String username = ckanUser.getPortalUser().getNameSurname(); String username = ckanUser.getNameSurname();
CMItemStatus cmItemStatus = CMItemStatus.PENDING; CMItemStatus cmItemStatus = CMItemStatus.PENDING;
String message = String.format("@**%s** has updated the item with name '%s' (id='%s'). The item is now in **%s** state and must be moderated.", String message = String.format("@**%s** has updated the item with name '%s' (id='%s'). The item is now in **%s** state and must be moderated.",
username, itemName, itemID, cmItemStatus.getFancyValue()); username, itemName, itemID, cmItemStatus.getFancyValue());
@ -68,7 +68,7 @@ public abstract class ModerationThread {
} }
public void postItemRejected(String userMessage) throws Exception { public void postItemRejected(String userMessage) throws Exception {
String username = ckanUser.getPortalUser().getNameSurname(); String username = ckanUser.getNameSurname();
CMItemStatus cmItemStatus = CMItemStatus.REJECTED; CMItemStatus cmItemStatus = CMItemStatus.REJECTED;
String message = String.format("@**%s** has **%s** the item with name '%s' (id='%s'). The author can delete the item or update it to try to meet moderators requests if any.", String message = String.format("@**%s** has **%s** the item with name '%s' (id='%s'). The author can delete the item or update it to try to meet moderators requests if any.",
username, cmItemStatus.getFancyValue(), itemName, itemID); username, cmItemStatus.getFancyValue(), itemName, itemID);
@ -77,7 +77,7 @@ public abstract class ModerationThread {
} }
public void postItemApproved(String userMessage) throws Exception{ public void postItemApproved(String userMessage) throws Exception{
String username = ckanUser.getPortalUser().getNameSurname(); String username = ckanUser.getNameSurname();
CMItemStatus cmItemStatus = CMItemStatus.APPROVED; CMItemStatus cmItemStatus = CMItemStatus.APPROVED;
String message = String.format("@**%s** has **%s** the item with name '%s' (id='%s'). The item is now available in the catalogue.", String message = String.format("@**%s** has **%s** the item with name '%s' (id='%s'). The item is now available in the catalogue.",
username, cmItemStatus.getFancyValue(), itemName, itemID); username, cmItemStatus.getFancyValue(), itemName, itemID);

View File

@ -110,7 +110,7 @@ public class ZulipStream extends ModerationThread {
ArrayNode principalsArrayNode = objectMapper.createArrayNode(); ArrayNode principalsArrayNode = objectMapper.createArrayNode();
// Going to add the item creator // Going to add the item creator
String itemCreatorEmail = ckanUser.getPortalUser().getEMail(); String itemCreatorEmail = ckanUser.getEMail();
principalsArrayNode.add(itemCreatorEmail); principalsArrayNode.add(itemCreatorEmail);
getGCatZulipRestExecutor(); getGCatZulipRestExecutor();

View File

@ -33,7 +33,6 @@ import org.gcube.gcat.api.roles.Role;
import org.gcube.gcat.moderation.thread.ModerationThread; import org.gcube.gcat.moderation.thread.ModerationThread;
import org.gcube.gcat.oldutils.Validator; import org.gcube.gcat.oldutils.Validator;
import org.gcube.gcat.profile.MetadataUtility; import org.gcube.gcat.profile.MetadataUtility;
import org.gcube.gcat.social.PortalUser;
import org.gcube.gcat.social.SocialPost; import org.gcube.gcat.social.SocialPost;
import org.gcube.gcat.utils.URIResolver; import org.gcube.gcat.utils.URIResolver;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -287,13 +286,12 @@ public class CKANPackage extends CKAN implements Moderated {
objectNode.remove(CAPACITY_KEY); objectNode.remove(CAPACITY_KEY);
} }
PortalUser portalUser = ckanUser.getPortalUser(); String authorName = ckanUser.getSurnameName();
String authorName = String.format("%s %s", portalUser.getSurname(), portalUser.getName());
if(authorName==null || authorName.compareTo("")==0) { if(authorName==null || authorName.compareTo("")==0) {
authorName = ckanUser.getName(); authorName = ckanUser.getName();
} }
objectNode.put(AUTHOR_KEY, authorName); objectNode.put(AUTHOR_KEY, authorName);
String authorEmail = portalUser.getEMail(); String authorEmail = ckanUser.getEMail();
objectNode.put(AUTHOR_EMAIL_KEY, authorEmail); objectNode.put(AUTHOR_EMAIL_KEY, authorEmail);
@ -575,7 +573,7 @@ public class CKANPackage extends CKAN implements Moderated {
if(queryParameters.containsKey(GCatConstants.OWN_ONLY_QUERY_PARAMETER)) { if(queryParameters.containsKey(GCatConstants.OWN_ONLY_QUERY_PARAMETER)) {
if(!queryParameters.get(GCatConstants.OWN_ONLY_QUERY_PARAMETER).isEmpty() && Boolean.parseBoolean(queryParameters.get(GCatConstants.OWN_ONLY_QUERY_PARAMETER).get(0))) { if(!queryParameters.get(GCatConstants.OWN_ONLY_QUERY_PARAMETER).isEmpty() && Boolean.parseBoolean(queryParameters.get(GCatConstants.OWN_ONLY_QUERY_PARAMETER).get(0))) {
String filter = String.format("%s:%s", AUTHOR_EMAIL_KEY, ckanUser.getPortalUser().getEMail()); String filter = String.format("%s:%s", AUTHOR_EMAIL_KEY, ckanUser.getEMail());
q = String.format("%s AND %s", q, filter); q = String.format("%s AND %s", q, filter);
} }
} }
@ -707,7 +705,7 @@ public class CKANPackage extends CKAN implements Moderated {
} }
protected boolean isItemCreator() { protected boolean isItemCreator() {
return result.get(AUTHOR_EMAIL_KEY).asText().compareTo(ckanUser.getPortalUser().getEMail())==0; return result.get(AUTHOR_EMAIL_KEY).asText().compareTo(ckanUser.getEMail())==0;
} }
protected void readItem() throws Exception { protected void readItem() throws Exception {
@ -1057,7 +1055,7 @@ public class CKANPackage extends CKAN implements Moderated {
CMItemStatus cmItemStatus = getRequestedCMItemStatus(); CMItemStatus cmItemStatus = getRequestedCMItemStatus();
if(!ckanUser.getPortalUser().isCatalogueModerator()) { if(!ckanUser.isCatalogueModerator()) {
switch (ckanUser.getRole()) { switch (ckanUser.getRole()) {
case ADMIN: case ADMIN:
@ -1065,7 +1063,7 @@ public class CKANPackage extends CKAN implements Moderated {
case EDITOR: case EDITOR:
if(cmItemStatus!=null && cmItemStatus!=CMItemStatus.APPROVED) { if(cmItemStatus!=null && cmItemStatus!=CMItemStatus.APPROVED) {
q = String.format("%s AND %s:%s", q, AUTHOR_EMAIL_KEY, ckanUser.getPortalUser().getEMail()); q = String.format("%s AND %s:%s", q, AUTHOR_EMAIL_KEY, ckanUser.getEMail());
}else{ }else{
cmItemStatus = CMItemStatus.APPROVED; cmItemStatus = CMItemStatus.APPROVED;
} }
@ -1110,13 +1108,12 @@ public class CKANPackage extends CKAN implements Moderated {
return; return;
} }
PortalUser portalUser = ckanUser.getPortalUser();
if(isItemCreator()) { if(isItemCreator()) {
// The author is entitled to read its own items independently from the status // The author is entitled to read its own items independently from the status
return; return;
} }
if(ckanUser.getRole() == Role.ADMIN || portalUser.isCatalogueModerator()) { if(ckanUser.getRole() == Role.ADMIN || ckanUser.isCatalogueModerator()) {
// Catalogue-Admin and Catalogue-Moderator are entitled to read items with any statues // Catalogue-Admin and Catalogue-Moderator are entitled to read items with any statues
return; return;
} }
@ -1131,8 +1128,6 @@ public class CKANPackage extends CKAN implements Moderated {
boolean setToPending = true; boolean setToPending = true;
PortalUser portalUser = ckanUser.getPortalUser();
switch (cmItemStatus) { switch (cmItemStatus) {
case APPROVED: case APPROVED:
if(ckanUser.getRole() != Role.ADMIN && !isItemCreator()) { if(ckanUser.getRole() != Role.ADMIN && !isItemCreator()) {
@ -1148,7 +1143,7 @@ public class CKANPackage extends CKAN implements Moderated {
if(isItemCreator()) { if(isItemCreator()) {
break; break;
} }
if(portalUser.isCatalogueModerator()) { if(ckanUser.isCatalogueModerator()) {
break; break;
} }
throw new ForbiddenException("You are not entitled to update a " + cmItemStatus.getValue() + " item"); throw new ForbiddenException("You are not entitled to update a " + cmItemStatus.getValue() + " item");
@ -1157,7 +1152,7 @@ public class CKANPackage extends CKAN implements Moderated {
if(isItemCreator()) { if(isItemCreator()) {
break; break;
} }
if(portalUser.isCatalogueModerator()) { if(ckanUser.isCatalogueModerator()) {
break; break;
} }
throw new ForbiddenException("You are not entitled to update a " + cmItemStatus.getValue() + " item"); throw new ForbiddenException("You are not entitled to update a " + cmItemStatus.getValue() + " item");
@ -1180,8 +1175,6 @@ public class CKANPackage extends CKAN implements Moderated {
if(isModerationEnabled()) { if(isModerationEnabled()) {
readItem(); readItem();
PortalUser portalUser = ckanUser.getPortalUser();
if(ckanUser.getRole() == Role.ADMIN) { if(ckanUser.getRole() == Role.ADMIN) {
// Ad Admin can delete any item independently from the status // Ad Admin can delete any item independently from the status
return; return;
@ -1200,7 +1193,7 @@ public class CKANPackage extends CKAN implements Moderated {
if(isItemCreator()) { if(isItemCreator()) {
break; break;
} }
if(portalUser.isCatalogueModerator()) { if(ckanUser.isCatalogueModerator()) {
break; break;
} }
throw new ForbiddenException("You are not entitled to delete a " + cmItemStatus.getValue() + " item"); throw new ForbiddenException("You are not entitled to delete a " + cmItemStatus.getValue() + " item");
@ -1209,7 +1202,7 @@ public class CKANPackage extends CKAN implements Moderated {
if(isItemCreator()) { if(isItemCreator()) {
break; break;
} }
if(portalUser.isCatalogueModerator()) { if(ckanUser.isCatalogueModerator()) {
break; break;
} }
throw new ForbiddenException("You are not entitled to update a " + cmItemStatus.getValue() + " item"); throw new ForbiddenException("You are not entitled to update a " + cmItemStatus.getValue() + " item");
@ -1310,7 +1303,6 @@ public class CKANPackage extends CKAN implements Moderated {
try { try {
if(isModerationEnabled()) { if(isModerationEnabled()) {
readItem(); readItem();
PortalUser portalUser = ckanUser.getPortalUser();
CMItemStatus cmItemStatus = getCMItemStatus(); CMItemStatus cmItemStatus = getCMItemStatus();
switch (cmItemStatus) { switch (cmItemStatus) {
case APPROVED: case APPROVED:
@ -1321,7 +1313,7 @@ public class CKANPackage extends CKAN implements Moderated {
throw new MethodNotSupportedException("You can't approve a rejected item. The item must be updated first. The update will set the item in pending, than it can be approved/rejected."); throw new MethodNotSupportedException("You can't approve a rejected item. The item must be updated first. The update will set the item in pending, than it can be approved/rejected.");
case PENDING: case PENDING:
if(!portalUser.isCatalogueModerator()) { if(!ckanUser.isCatalogueModerator()) {
throw new MethodNotSupportedException("Only catalogue moderator can approve a pending item."); throw new MethodNotSupportedException("Only catalogue moderator can approve a pending item.");
} }
setToApproved(result); setToApproved(result);
@ -1368,8 +1360,7 @@ public class CKANPackage extends CKAN implements Moderated {
break; break;
case PENDING: case PENDING:
PortalUser portalUser = ckanUser.getPortalUser(); if(!ckanUser.isCatalogueModerator()) {
if(!portalUser.isCatalogueModerator()) {
throw new MethodNotSupportedException("Only catalogue moderator can reject a pending item."); throw new MethodNotSupportedException("Only catalogue moderator can reject a pending item.");
} }
@ -1405,7 +1396,7 @@ public class CKANPackage extends CKAN implements Moderated {
readItem(); readItem();
// Catalogue Moderators are allowed to post message to the dedicated Stream // Catalogue Moderators are allowed to post message to the dedicated Stream
if(!ckanUser.getPortalUser().isCatalogueModerator()) { if(!ckanUser.isCatalogueModerator()) {
// Users that are not // Users that are not
if(!isItemCreator()) { if(!isItemCreator()) {
throw new NotAllowedException("Only item creator and " + Moderated.CATALOGUE_MODERATOR + "s are entitled to partecipate to the moderation discussion thread."); throw new NotAllowedException("Only item creator and " + Moderated.CATALOGUE_MODERATOR + "s are entitled to partecipate to the moderation discussion thread.");

View File

@ -1,6 +1,6 @@
package org.gcube.gcat.persistence.ckan; package org.gcube.gcat.persistence.ckan;
import java.util.List; import java.util.Collection;
import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.WebApplicationException; import javax.ws.rs.WebApplicationException;
@ -8,8 +8,8 @@ import javax.ws.rs.core.Response.Status;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode; import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.common.authorization.utils.manager.SecretManager; import org.gcube.common.authorization.utils.manager.SecretManager;
import org.gcube.gcat.api.moderation.Moderated;
import org.gcube.gcat.api.roles.Role; import org.gcube.gcat.api.roles.Role;
import org.gcube.gcat.social.PortalUser;
import org.gcube.gcat.utils.RandomString; import org.gcube.gcat.utils.RandomString;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -44,8 +44,8 @@ public class CKANUser extends CKAN {
private static final String API_KEY = "apikey"; private static final String API_KEY = "apikey";
protected PortalUser portalUser;
protected Role role; protected Role role;
protected Boolean catalogueModerator;
public CKANUser() { public CKANUser() {
super(); super();
@ -56,6 +56,7 @@ public class CKANUser extends CKAN {
PATCH = null; PATCH = null;
DELETE = USER_DELETE; DELETE = USER_DELETE;
PURGE = null; PURGE = null;
catalogueModerator = null;
} }
public String create() { public String create() {
@ -80,14 +81,14 @@ public class CKANUser extends CKAN {
* @return true if the display name and the full name has been updated in objectNode * @return true if the display name and the full name has been updated in objectNode
*/ */
private boolean checkAndSetJobTitle(ObjectNode objectNode) { private boolean checkAndSetJobTitle(ObjectNode objectNode) {
String portalJobTitle = getPortalUser().getJobTitle(); String jobTitle = SecretManager.instance.get().getTitle();
String ckanJobTitle = ""; String ckanJobTitle = "";
if(objectNode.has(ABOUT)) { if(objectNode.has(ABOUT)) {
ckanJobTitle = objectNode.get(ABOUT).asText(); ckanJobTitle = objectNode.get(ABOUT).asText();
} }
if(portalJobTitle.compareTo(ckanJobTitle) != 0) { if(jobTitle.compareTo(ckanJobTitle) != 0) {
objectNode.put(ABOUT, portalJobTitle); objectNode.put(ABOUT, jobTitle);
return true; return true;
} }
return false; return false;
@ -99,7 +100,7 @@ public class CKANUser extends CKAN {
* @return true if the display name and the full name has been updated in objectNode * @return true if the display name and the full name has been updated in objectNode
*/ */
private boolean checkAndSetFullName(ObjectNode objectNode) { private boolean checkAndSetFullName(ObjectNode objectNode) {
String portalFullname = getPortalUser().getSurnameName(); String portalFullname = getSurnameName();
String ckanFullname = ""; String ckanFullname = "";
if(objectNode.has(FULL_NAME)) { if(objectNode.has(FULL_NAME)) {
@ -119,7 +120,7 @@ public class CKANUser extends CKAN {
* @return true if the display name and the full name has been updated * @return true if the display name and the full name has been updated
*/ */
private boolean checkAndSetEMail(ObjectNode objectNode) { private boolean checkAndSetEMail(ObjectNode objectNode) {
String portalEmail = getPortalUser().getEMail(); String portalEmail = SecretManager.instance.get().getEMail();
String ckanEmail = ""; String ckanEmail = "";
if(objectNode.has(EMAIL)) { if(objectNode.has(EMAIL)) {
@ -213,7 +214,7 @@ public class CKANUser extends CKAN {
public Role getRole() { public Role getRole() {
if(role == null) { if(role == null) {
role = Role.MEMBER; role = Role.MEMBER;
List<String> roles = getPortalUser().getRoles(); Collection<String> roles = SecretManager.instance.get().getRoles();
for(String portalRole : roles) { for(String portalRole : roles) {
Role gotRole = Role.getRoleFromPortalRole(portalRole); Role gotRole = Role.getRoleFromPortalRole(portalRole);
if(gotRole != null && gotRole.ordinal() > role.ordinal()) { if(gotRole != null && gotRole.ordinal() > role.ordinal()) {
@ -247,12 +248,26 @@ public class CKANUser extends CKAN {
throw new InternalServerErrorException(e); throw new InternalServerErrorException(e);
} }
} }
public PortalUser getPortalUser() { public boolean isCatalogueModerator() {
if(portalUser == null) { if(catalogueModerator == null) {
portalUser = new PortalUser(); catalogueModerator = SecretManager.instance.get().getRoles().contains(Moderated.CATALOGUE_MODERATOR);
} }
return portalUser; return catalogueModerator;
}
public String getSurnameName(){
SecretManager sm = SecretManager.instance.get();
return String.format("%s %s", sm.getSurname(), sm.getName()).trim();
}
public String getNameSurname() {
SecretManager sm = SecretManager.instance.get();
return String.format("%s %s", sm.getName(), sm.getSurname()).trim();
}
public String getEMail() {
return SecretManager.instance.get().getEMail();
} }
} }

View File

@ -1,138 +0,0 @@
package org.gcube.gcat.social;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.ws.rs.InternalServerErrorException;
import org.gcube.common.gxhttp.request.GXHTTPStringRequest;
import org.gcube.gcat.api.moderation.Moderated;
import org.gcube.gcat.utils.HTTPUtility;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class PortalUser {
protected static final String RESPONSE_SUCCESS_KEY = "success";
protected static final String RESPONSE_MESSAGE_KEY = "message";
protected static final String RESPONSE_RESULT_KEY = "result";
protected static final String SOCIAL_SERVICE_GET_OAUTH_USER_PROFILE_PATH = "2/users/get-oauth-profile";
// This key contains the fullname
//protected static final String OAUTH_USER_PROFILE_FULLNAME_KEY = "name";
protected static final String OAUTH_USER_PROFILE_NAME_KEY = "given_name";
protected static final String OAUTH_USER_PROFILE_SURNAME_KEY = "family_name";
protected static final String OAUTH_USER_PROFILE_EMAIL_KEY = "email";
protected static final String OAUTH_USER_PROFILE_JOB_TITLE_KEY = "job_title";
protected static final String OAUTH_USER_PROFILE_ROLES_KEY = "roles";
protected final ObjectMapper objectMapper;
// private JsonNode gCubeUserProfile;
protected JsonNode oAuthUserProfile;
protected String name;
protected String surname;
protected String eMail;
protected String jobTitle;
protected List<String> roles;
protected Boolean catalogueModerator;
public PortalUser() {
this.objectMapper = new ObjectMapper();
}
public JsonNode getOAuthUserProfile() {
if(oAuthUserProfile == null) {
try {
String socialServiceBasePath = SocialService.getSocialService().getServiceBasePath();
GXHTTPStringRequest gxhttpStringRequest = HTTPUtility.createGXHTTPStringRequest(socialServiceBasePath,
SOCIAL_SERVICE_GET_OAUTH_USER_PROFILE_PATH, false);
HttpURLConnection httpURLConnection = gxhttpStringRequest.get();
String ret = HTTPUtility.getResultAsString(httpURLConnection);
oAuthUserProfile = objectMapper.readTree(ret);
} catch(Exception e) {
throw new InternalServerErrorException("Unable to retrive Infrastructure User Information from Social Service", e);
}
}
return oAuthUserProfile;
}
public String getSurnameName() {
return String.format("%s %s", getSurname(), getName());
}
public String getNameSurname() {
return String.format("%s %s", getName(), getSurname());
}
public String getName() {
if(name == null) {
name = getOAuthUserProfile().get(OAUTH_USER_PROFILE_NAME_KEY).asText();
}
return name;
}
public String getSurname() {
if(surname == null) {
surname = getOAuthUserProfile().get(OAUTH_USER_PROFILE_SURNAME_KEY).asText();
}
return surname;
}
public String getEMail() {
if(eMail == null) {
eMail = getOAuthUserProfile().get(OAUTH_USER_PROFILE_EMAIL_KEY).asText();
}
return eMail;
}
public List<String> getRoles() {
if(roles == null) {
JsonNode jsonNode = getOAuthUserProfile().get(OAUTH_USER_PROFILE_ROLES_KEY);
roles = new ArrayList<String>();
if(jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
if(arrayNode.size() > 0) {
Iterator<JsonNode> iterator = arrayNode.iterator();
while(iterator.hasNext()) {
roles.add(iterator.next().asText());
}
}
}
}
return roles;
}
public boolean isCatalogueModerator() {
if(catalogueModerator == null) {
catalogueModerator = getRoles().contains(Moderated.CATALOGUE_MODERATOR);
}
return catalogueModerator;
}
public String getJobTitle() {
if(jobTitle == null) {
jobTitle = getOAuthUserProfile().get(OAUTH_USER_PROFILE_JOB_TITLE_KEY).asText();
}
return jobTitle;
}
}

View File

@ -13,6 +13,7 @@ import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode; import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode; import org.gcube.com.fasterxml.jackson.databind.node.ObjectNode;
import org.gcube.common.authorization.utils.manager.SecretManager; import org.gcube.common.authorization.utils.manager.SecretManager;
import org.gcube.common.authorization.utils.socialservice.SocialService;
import org.gcube.common.gxhttp.request.GXHTTPStringRequest; import org.gcube.common.gxhttp.request.GXHTTPStringRequest;
import org.gcube.gcat.persistence.ckan.CKANInstance; import org.gcube.gcat.persistence.ckan.CKANInstance;
import org.gcube.gcat.persistence.ckan.CKANUserCache; import org.gcube.gcat.persistence.ckan.CKANUserCache;
@ -145,8 +146,7 @@ public class SocialPost extends Thread {
public void sendSocialPost(boolean notifyUsers) { public void sendSocialPost(boolean notifyUsers) {
try { try {
PortalUser portalUser = CKANUserCache.getCurrrentCKANUser().getPortalUser(); String fullName = CKANUserCache.getCurrrentCKANUser().getNameSurname();
String fullName = portalUser.getNameSurname();
String basePath = SocialService.getSocialService().getServiceBasePath(); String basePath = SocialService.getSocialService().getServiceBasePath();
if(basePath == null) { if(basePath == null) {

View File

@ -1,95 +0,0 @@
package org.gcube.gcat.social;
import static org.gcube.resources.discovery.icclient.ICFactory.client;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.gcube.common.authorization.utils.manager.SecretManager;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Discover the Social Networking Service in the Infrastructure.
* @author Luca Frosini (ISTI - CNR)
*/
public class SocialService {
private static final String RESOURCE = "jersey-servlet";
private static final String SERVICE_NAME = "SocialNetworking";
private static final String SERVICE_CLASSE = "Portal";
private static Logger logger = LoggerFactory.getLogger(SocialService.class);
private String serviceBasePath;
// Map<String contextFullName, SocialService socialService>
private static Map<String,SocialService> socialServicePerContext;
static {
socialServicePerContext = new HashMap<>();
}
public static SocialService getSocialService() throws Exception {
String contex = SecretManager.instance.get().getContext();
SocialService socialService = socialServicePerContext.get(contex);
if(socialService == null) {
socialService = new SocialService();
socialServicePerContext.put(contex, socialService);
}
return socialService;
}
/**
* Discover the gcore endpoint for the social networking service.
* @throws Exception the exception
*/
private SocialService() throws Exception {
getServiceBasePathViaGCoreEndpoint();
}
protected void getServiceBasePathViaGCoreEndpoint() throws Exception {
try {
SimpleQuery query = queryFor(GCoreEndpoint.class);
query.addCondition(String.format("$resource/Profile/ServiceClass/text() eq '%s'", SERVICE_CLASSE));
query.addCondition("$resource/Profile/DeploymentData/Status/text() eq 'ready'");
query.addCondition(String.format("$resource/Profile/ServiceName/text() eq '%s'", SERVICE_NAME));
query.setResult(
"$resource/Profile/AccessPoint/RunningInstanceInterfaces//Endpoint[@EntryName/string() eq \""
+ RESOURCE + "\"]/text()");
DiscoveryClient<String> client = client();
List<String> endpoints = client.submit(query);
if(endpoints == null || endpoints.isEmpty()) {
throw new Exception("Cannot retrieve the GCoreEndpoint SERVICE_NAME: " + SERVICE_NAME
+ ", SERVICE_CLASSE: " + SERVICE_CLASSE + ", in scope: " + SecretManager.instance.get().getContext());
}
this.serviceBasePath = endpoints.get(0);
if(serviceBasePath == null)
throw new Exception("Endpoint:" + RESOURCE + ", is null for SERVICE_NAME: " + SERVICE_NAME
+ ", SERVICE_CLASSE: " + SERVICE_CLASSE + ", in scope: " + SecretManager.instance.get().getContext());
serviceBasePath = serviceBasePath.endsWith("/") ? serviceBasePath : serviceBasePath + "/";
} catch(Exception e) {
String error = "An error occurred during GCoreEndpoint discovery, SERVICE_NAME: " + SERVICE_NAME
+ ", SERVICE_CLASSE: " + SERVICE_CLASSE + ", in scope: " + SecretManager.instance.get().getContext() + ".";
logger.error(error, e);
throw new Exception(error);
}
}
/**
* @return the base path of the service
*/
public String getServiceBasePath() {
return serviceBasePath;
}
}

View File

@ -9,6 +9,7 @@ import java.util.Set;
import org.gcube.com.fasterxml.jackson.databind.JsonNode; import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper; import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode; import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.common.authorization.utils.socialservice.SocialService;
import org.gcube.common.gxhttp.request.GXHTTPStringRequest; import org.gcube.common.gxhttp.request.GXHTTPStringRequest;
import org.gcube.gcat.utils.HTTPUtility; import org.gcube.gcat.utils.HTTPUtility;

View File

@ -74,13 +74,13 @@ public class CKANGroupTest extends ContextTest {
// @Test // @Test
public void deleteAllGroups() throws Exception { public void deleteAllGroups() throws Exception {
//ContextTest.setContextByName(""); ContextTest.setContextByName("/gcube");
CKANGroup ckanGroup = new CKANGroup(); CKANGroup ckanGroup = new CKANGroup();
ckanGroup.setApiKey(CKANUtility.getSysAdminAPI()); ckanGroup.setApiKey(CKANUtility.getSysAdminAPI());
List<String> groups = listGroup(); List<String> groups = listGroup();
for(String name : groups) { for(String name : groups) {
ckanGroup.setName(name); ckanGroup.setName(name);
ckanGroup.delete(true); // ckanGroup.delete(true);
} }
} }

View File

@ -1,6 +1,10 @@
package org.gcube.gcat.persistence.ckan; package org.gcube.gcat.persistence.ckan;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.gcat.ContextTest; import org.gcube.gcat.ContextTest;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -35,4 +39,37 @@ public class CKANOrganizationTest extends ContextTest {
String ret = ckanOrganization.list(1000, 0); String ret = ckanOrganization.list(1000, 0);
logger.debug("{}", ret); logger.debug("{}", ret);
} }
@Ignore
@Test
public void deleteOrganization() throws Exception {
ContextTest.setContextByName("/gcube");
CKANOrganization ckanOrganization = new CKANOrganization();
ckanOrganization.setApiKey(CKANUtility.getSysAdminAPI());
String name = "aquamaps1";
ckanOrganization.setName(name);
logger.debug("Going to delete {}", name);
// ckanOrganization.delete(true);
}
@Ignore
@Test
public void deleteAllOrganizations() throws Exception {
ContextTest.setContextByName("/gcube");
CKANOrganization ckanOrganization = new CKANOrganization();
ckanOrganization.setApiKey(CKANUtility.getSysAdminAPI());
String ret = ckanOrganization.list(1000, 0);
logger.debug("{}", ret);
ObjectMapper mapper = new ObjectMapper();
JsonNode organizations = (ArrayNode) mapper.readTree(ret);
for(JsonNode jn : organizations) {
ckanOrganization.setName(jn.asText());
logger.debug("Going to delete {}", jn.asText());
try {
// ckanOrganization.delete(true);
}catch (Exception e) {
// A not empty organization cannot be deleted
}
}
}
} }

View File

@ -35,6 +35,7 @@ import org.gcube.gcat.api.moderation.Moderated;
import org.gcube.informationsystem.publisher.RegistryPublisher; import org.gcube.informationsystem.publisher.RegistryPublisher;
import org.gcube.informationsystem.publisher.RegistryPublisherFactory; import org.gcube.informationsystem.publisher.RegistryPublisherFactory;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -626,16 +627,29 @@ public class CKANPackageTest extends ContextTest {
ckanPackage.purge(); ckanPackage.purge();
} }
@Ignore
@Test @Test
public void deleteAllTest() { public void deleteAllTest() {
CKANPackage ckanPackage = new CKANPackage(); CKANPackage ckanPackage = new CKANPackage();
MultivaluedMap<String, String> mvm = new MultivaluedHashMap<String,String>(); MultivaluedMap<String, String> mvm = new MultivaluedHashMap<String,String>();
mvm.add(GCatConstants.Q_KEY, "organization:eosc-pillar-f2ds"); mvm.add(GCatConstants.Q_KEY, "organization:devvre");
mvm.add(GCatConstants.OWN_ONLY_QUERY_PARAMETER, "false"); mvm.add(GCatConstants.OWN_ONLY_QUERY_PARAMETER, "false");
UriInfo uriInfo = getUriInfo(mvm); UriInfo uriInfo = getUriInfo(mvm);
ckanPackage.setUriInfo(uriInfo); ckanPackage.setUriInfo(uriInfo);
String res = ckanPackage.deleteAll(true); // String res = ckanPackage.deleteAll(true);
logger.debug("{}", res); // logger.debug("{}", res);
}
@Ignore
@Test
public void deleteAllItemsInAllOrganizations() {
CKANPackage ckanPackage = new CKANPackage();
MultivaluedMap<String, String> mvm = new MultivaluedHashMap<String,String>();
mvm.add(GCatConstants.OWN_ONLY_QUERY_PARAMETER, "false");
UriInfo uriInfo = getUriInfo(mvm);
ckanPackage.setUriInfo(uriInfo);
// String res = ckanPackage.deleteAll(true);
// logger.debug("{}", res);
} }
@Test @Test

View File

@ -1,21 +0,0 @@
package org.gcube.gcat.social;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
public class PortalUserTest {
private static final Logger logger = LoggerFactory.getLogger(PortalUserTest.class);
@Test
public void testGetUserProfile() throws Exception {
PortalUser portalUser = new PortalUser();
JsonNode jsonNode = portalUser.getOAuthUserProfile();
ObjectMapper objectMapper = new ObjectMapper();
logger.debug("OAuth User Profile is {}", objectMapper.writeValueAsString(jsonNode));
}
}

View File

@ -1,5 +1,6 @@
package org.gcube.gcat.social; package org.gcube.gcat.social;
import org.gcube.common.authorization.utils.socialservice.SocialService;
import org.gcube.gcat.ContextTest; import org.gcube.gcat.ContextTest;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;