in progress

This commit is contained in:
Francesco Mangiacrapa 2024-03-22 16:26:40 +01:00
parent 3913019df3
commit d8838a176b
10 changed files with 380 additions and 241 deletions

View File

@ -60,6 +60,11 @@
<artifactId>social-service-client</artifactId> <artifactId>social-service-client</artifactId>
<version>[1.0.0, 2.0.0-SNAPSHOT)</version> <version>[1.0.0, 2.0.0-SNAPSHOT)</version>
</dependency> </dependency>
<dependency>
<groupId>org.gcube.portlets.user</groupId>
<artifactId>uri-resolver-manager</artifactId>
<version>[1.0.0,2.0.0-SNAPSHOT)</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId> <artifactId>commons-text</artifactId>

View File

@ -10,7 +10,6 @@ import java.util.stream.Collectors;
import org.bson.Document; import org.bson.Document;
import org.gcube.application.cms.implementations.utils.UserUtils; import org.gcube.application.cms.implementations.utils.UserUtils;
import org.gcube.application.cms.notifications.config.NotificationFor;
import org.gcube.application.cms.notifications.config.SubscribeNotificationEvent; import org.gcube.application.cms.notifications.config.SubscribeNotificationEvent;
import org.gcube.application.cms.notifications.manage.ManageDoActionNotification; import org.gcube.application.cms.notifications.manage.ManageDoActionNotification;
import org.gcube.application.cms.notifications.substitutor.NMessagesPlaceholdersSubstitutorUtil; import org.gcube.application.cms.notifications.substitutor.NMessagesPlaceholdersSubstitutorUtil;
@ -76,7 +75,7 @@ public class NotificationsPlugin extends AbstractPlugin implements EventListener
@Override @Override
public void updated(ItemObserved<Project> observerd) { public void updated(ItemObserved<Project> observerd) {
log.info("listenerCreated fired on item: {} " + observerd); log.info("listenerCreated fired on item: {} ", observerd);
boolean subscribed = checkIfSubscribedEvent(observerd); boolean subscribed = checkIfSubscribedEvent(observerd);
@ -91,7 +90,7 @@ public class NotificationsPlugin extends AbstractPlugin implements EventListener
@Override @Override
public void updated(ItemObserved<Project> observerd) { public void updated(ItemObserved<Project> observerd) {
log.info("listenerUpdated fired on item: {} " + observerd); log.info("listenerUpdated fired on item: {} ", observerd);
boolean subscribed = checkIfSubscribedEvent(observerd); boolean subscribed = checkIfSubscribedEvent(observerd);
if (subscribed) { if (subscribed) {
@ -105,7 +104,7 @@ public class NotificationsPlugin extends AbstractPlugin implements EventListener
@Override @Override
public void updated(ItemObserved<Project> observerd) { public void updated(ItemObserved<Project> observerd) {
log.info("listenerDeleted fired on item: {} " + observerd); log.info("listenerDeleted fired on item: {} ", observerd);
boolean subscribed = checkIfSubscribedEvent(observerd); boolean subscribed = checkIfSubscribedEvent(observerd);
if (subscribed) { if (subscribed) {
@ -118,7 +117,7 @@ public class NotificationsPlugin extends AbstractPlugin implements EventListener
@Override @Override
public void updated(ItemObserved<Project> observerd) { public void updated(ItemObserved<Project> observerd) {
log.info("listenerLCStepPerformed fired on item: {} " + observerd); log.info("listenerLCStepPerformed fired on item: {} ", observerd);
boolean subscribed = checkIfSubscribedEvent(observerd); boolean subscribed = checkIfSubscribedEvent(observerd);
if (subscribed) { if (subscribed) {

View File

@ -14,6 +14,7 @@ import lombok.Data;
public class NotificationWhen { public class NotificationWhen {
List<String> target_phase; List<String> target_phase;
String last_invoked_step;
List<Notify> notify; List<Notify> notify;
} }

View File

@ -19,7 +19,11 @@ import org.gcube.application.cms.notifications.substitutor.SubstitutorMessagesMa
import org.gcube.application.cms.plugins.events.ItemObserved; import org.gcube.application.cms.plugins.events.ItemObserved;
import org.gcube.application.geoportal.common.model.document.Project; import org.gcube.application.geoportal.common.model.document.Project;
import org.gcube.application.geoportal.common.model.document.accounting.User; import org.gcube.application.geoportal.common.model.document.accounting.User;
import org.gcube.application.geoportal.common.model.document.lifecycle.LifecycleInformation;
import org.gcube.common.authorization.utils.manager.SecretManager;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.portlets.user.uriresolvermanager.resolvers.query.GeoportalResolverQueryStringBuilder.RESOLVE_AS; import org.gcube.portlets.user.uriresolvermanager.resolvers.query.GeoportalResolverQueryStringBuilder.RESOLVE_AS;
import org.gcube.social_networking.socialnetworking.model.beans.catalogue.CatalogueEventType;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -35,8 +39,7 @@ public class ManageDoActionNotification {
private List<SubscribeNotificationEvent> listSubscribedNotification; private List<SubscribeNotificationEvent> listSubscribedNotification;
private ItemObserved<Project> itemObserved; private ItemObserved<Project> itemObserved;
private NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersSUtil; private NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersS;
private SubstitutorMessagesMap placeholderMapValues;
/** /**
* Instantiates a new manage do action notification. * Instantiates a new manage do action notification.
@ -48,21 +51,22 @@ public class ManageDoActionNotification {
public ManageDoActionNotification(ItemObserved<Project> itemObserved, public ManageDoActionNotification(ItemObserved<Project> itemObserved,
NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersSUtil, List<SubscribeNotificationEvent> filterList) { NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersSUtil, List<SubscribeNotificationEvent> filterList) {
this.listSubscribedNotification = filterList; this.listSubscribedNotification = filterList;
this.nMPlaceholdersSUtil = nMPlaceholdersSUtil; this.nMPlaceholdersS = nMPlaceholdersSUtil;
this.itemObserved = itemObserved; this.itemObserved = itemObserved;
// Creating the map for replacing the placeholders with their values // Creating the map for replacing the placeholder with their values
placeholderMapValues = new SubstitutorMessagesMap(); SubstitutorMessagesMap placeholderMapValues = new SubstitutorMessagesMap();
String gisLink = GisClient.gisLink(RESOLVE_AS.PRIVATE, itemObserved.getUCD_Id(), itemObserved.getProjectId(), String gisLink = GisClient.gisLink(RESOLVE_AS.PRIVATE, itemObserved.getUCD_Id(), itemObserved.getProjectId(),
itemObserved.getContext().getName(), true); itemObserved.getContext().getId(), true);
placeholderMapValues.putGisLink(gisLink); placeholderMapValues.putGisLink(gisLink);
placeholderMapValues.putProjectId(itemObserved.getProjectId()); placeholderMapValues.putProjectId(itemObserved.getProjectId());
LinkedHashMap<String, Object> docAsMap = itemObserved.getDocumentEntries(1); LinkedHashMap<String, Object> docAsMap = itemObserved.getDocumentEntries(1);
String projectName = docAsMap.size() > 1 ? docAsMap.values().stream().findFirst().get() + "" String projectName = docAsMap.size() > 0 ? docAsMap.values().stream().findFirst().get() + ""
: itemObserved.getProjectId(); : itemObserved.getProjectId();
placeholderMapValues.putProjectName(projectName); placeholderMapValues.putProjectName(projectName);
placeholderMapValues.putUser(itemObserved.getUserCaller().getUsername());
nMPlaceholdersSUtil.setPlaceholderMapValues(placeholderMapValues); nMPlaceholdersS.setPlaceholderMapValues(placeholderMapValues);
} }
@ -79,33 +83,57 @@ public class ManageDoActionNotification {
List<NotificationFor> listNotificationFor = subscribeNotificationEvent.getNotificationFor(); List<NotificationFor> listNotificationFor = subscribeNotificationEvent.getNotificationFor();
// Reading 'phase' property from itemObserved // Reading 'phase' property from itemObserved
String itemPhase = itemObserved.getProject().getLifecycleInformation().getPhase(); LifecycleInformation lInfo = itemObserved.getProject().getLifecycleInformation();
log.debug("ItemObserved 'phase' is: {}", itemPhase); String itemPhase = lInfo.getPhase();
String lastInvokedStep = lInfo.getLastInvokedStep();
log.debug("ItemObserved phase is: {}, lastInvokedStep is: {}", itemPhase, lastInvokedStep);
final SecretManager cm = SecretManagerProvider.instance.get();
for (final NotificationFor notificationFor : listNotificationFor) { for (final NotificationFor notificationFor : listNotificationFor) {
// Filtering notifications on 'phase' according to item itemObserved 'phase' // Filtering notifications on 'phase' and 'lastInvokedStep' according to item
List<NotificationWhen> notificationsCompliantToPhase = notificationFor.getWhen().stream() // itemObserved 'phase'
.filter(when -> when.getTarget_phase().contains(itemPhase)).collect(Collectors.toList()); List<NotificationWhen> notificationsCompliantToPhase = matchNotificationsAccordingItemStatus(
notificationFor, itemPhase, lastInvokedStep);
log.debug("Filtered notification on phase {} are: {}", itemPhase, notificationsCompliantToPhase); // log.debug("Filtered notifications on phase {} and lastInvokedStep {} are: {}", itemPhase, lastInvokedStep,
// notificationsCompliantToPhase);
if (notificationsCompliantToPhase != null && notificationsCompliantToPhase.size() > 0) { if (notificationsCompliantToPhase != null && notificationsCompliantToPhase.size() > 0) {
// GET LIST USER COMPLIANT TO ROLES // GET LIST USER COMPLIANT TO ROLES
List<User> notifyUsers = getListUserCompliantToRoles(notificationFor, itemObserved); List<User> notifyUsers = getListUserCompliantToRoles(notificationFor, itemObserved);
final SocialClients socialClients = new SocialClients();
if (notifyUsers.size() > 0) { if (notifyUsers.size() > 0) {
for (final User user : notifyUsers) { log.info("Users compliant to role are: {}", notifyUsers.size());
if (log.isDebugEnabled()) {
Thread notificationT = new Thread() { notifyUsers.stream().forEach(u -> log.debug("user: " + u));
public void run() {
new ManageNotifyUser(notificationFor, nMPlaceholdersSUtil, user);
};
};
notificationT.run();
} }
for (final User user : notifyUsers) {
try {
NotifyUser mnu = new NotifyUser(socialClients, notificationsCompliantToPhase,
nMPlaceholdersS, user);
mnu.send();
} catch (Exception e) {
log.error("Error occurred when send notify: ", e);
}
}
/*
* for (final User user : notifyUsers) { Thread notificationT = new Thread() {
* public void run() { SecretManagerProvider.instance.set(cm); NotifyUser mnu =
* new NotifyUser(socialClients, notificationsCompliantToPhase, nMPlaceholdersS,
* user); try { mnu.send(); } catch (Exception e) {
* log.error("Error occurred when send notify: ", e); } };
*
* };
*
* notificationT.start(); }
*/
} }
} }
} }
@ -113,6 +141,40 @@ public class ManageDoActionNotification {
} }
public static List<NotificationWhen> matchNotificationsAccordingItemStatus(NotificationFor notificationFor,
String itemPhase, String lastInvokedStep) {
log.info("Filtering notifications according to phase: {}, lastInvokedStep: {}", itemPhase, lastInvokedStep);
List<NotificationWhen> filteredList = new ArrayList<NotificationWhen>();
int i = 0;
for (NotificationWhen notificationWhen : notificationFor.getWhen()) {
log.info(++i + ") notificationWhen target phases: {} and last_invoked_step: {}",
notificationWhen.getTarget_phase(), notificationWhen.getLast_invoked_step());
if (notificationWhen.getTarget_phase().contains(itemPhase)) {
if (notificationWhen.getLast_invoked_step() == null) {
// no filtering on lastInvokedStep
filteredList.add(notificationWhen);
} else if (notificationWhen.getLast_invoked_step().compareToIgnoreCase(lastInvokedStep) == 0) {
// matching the lastInvokedStep
filteredList.add(notificationWhen);
}
}
}
log.info("returning filtered list with {} object {}", filteredList.size(),
NotificationWhen.class.getSimpleName());
return filteredList;
}
public static CatalogueEventType toCatalogueEventType(String itemPhase, String lastInvokedStep) {
return null;
}
/** /**
* Gets the list user compliant to roles. * Gets the list user compliant to roles.
* *
@ -152,6 +214,7 @@ public class ManageDoActionNotification {
.getUsername(); .getUsername();
notifyUsers.add( notifyUsers.add(
new User(creatorUsername, Stream.of(role).collect(Collectors.toCollection(HashSet::new)))); new User(creatorUsername, Stream.of(role).collect(Collectors.toCollection(HashSet::new))));
log.info("added {} user for role {}", notifyUsers.size(), role);
} catch (Exception e) { } catch (Exception e) {
log.error("Error on reading user {} from scope {}: ", itemCreatorRole, log.error("Error on reading user {} from scope {}: ", itemCreatorRole,
UserUtils.getCurrent().getContext(), e); UserUtils.getCurrent().getContext(), e);
@ -163,6 +226,7 @@ public class ManageDoActionNotification {
.map(username -> new User(username, .map(username -> new User(username,
Stream.of(role).collect(Collectors.toCollection(HashSet::new)))) Stream.of(role).collect(Collectors.toCollection(HashSet::new))))
.collect(Collectors.toList())); .collect(Collectors.toList()));
log.info("added {} users for role {}", notifyUsers.size(), role);
} catch (Exception e) { } catch (Exception e) {
log.error("Error on reading users from scope {}: ", UserUtils.getCurrent().getContext(), e); log.error("Error on reading users from scope {}: ", UserUtils.getCurrent().getContext(), e);
} }
@ -171,7 +235,7 @@ public class ManageDoActionNotification {
} }
// return the list of users that must be notified; // return the list of users that must be notified;
log.error("returing {} users to be notified: ", notifyUsers.size()); log.info("returing {} users to be notified: ", notifyUsers.size());
return notifyUsers; return notifyUsers;
} }

View File

@ -1,91 +0,0 @@
package org.gcube.application.cms.notifications.manage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.gcube.application.cms.notifications.NotificationGenericConstants.NOTIFICATION_TYPE;
import org.gcube.application.cms.notifications.config.NotificationFor;
import org.gcube.application.cms.notifications.config.NotificationWhen;
import org.gcube.application.cms.notifications.config.Notify;
import org.gcube.application.cms.notifications.social.SocialClients;
import org.gcube.application.cms.notifications.substitutor.NMessagesPlaceholdersSubstitutorUtil;
import org.gcube.application.geoportal.common.model.document.accounting.User;
import org.gcube.portal.databook.shared.Post;
import org.gcube.social_networking.socialnetworking.model.beans.MessageInputBean;
import org.gcube.social_networking.socialnetworking.model.beans.PostInputBean;
import org.gcube.social_networking.socialnetworking.model.beans.Recipient;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ManageNotifyUser {
private NotificationFor notificationFor;
private User recipientUser;
private NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersSUtil;
public ManageNotifyUser(NotificationFor notificationFor, NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersSUtil,
User recipientUser) {
this.notificationFor = notificationFor;
this.recipientUser = recipientUser;
this.nMPlaceholdersSUtil = nMPlaceholdersSUtil;
}
public void send() throws Exception {
SocialClients socialClients = new SocialClients();
List<Notify> listNotifies = toNotify();
// TODO
// NotificationClient client = new NotificationClient();
// client.send ??????
for (Notify notify : listNotifies) {
switch (notify.getType()) {
case USER_MESSAGE:
log.info("Notification type {}, send: {}", notify.getType(), notify.getSend());
if (notify.getSend()) {
log.info("Sending message...");
String subject = "Message";
String body = null;
subject = nMPlaceholdersSUtil.replacePlaceholder(notify.getPlaceholder_title());
body = nMPlaceholdersSUtil.replacePlaceholder(notify.getPlaceholder_msg());
log.debug("Sending subject: {}", subject);
log.debug("Sending body: {}", body);
List<Recipient> rec = Arrays.asList(new Recipient(recipientUser.getUsername()));
log.info("Sending message...");
MessageInputBean message = new MessageInputBean(subject, body, new ArrayList<Recipient>(rec));
String idMessage = socialClients.writeMessage(message);
log.info("Message sent with id: {}", idMessage);
}
break;
case VRE_POST:
log.info("Notification type {}, send: {}", notify.getType(), notify.getSend());
PostInputBean toWrite = null;
Post thePost = socialClients.writeUserPost(toWrite);
log.info("{} post created: {} ", notify.getType(), thePost);
break;
case EMAIL:
break;
default:
break;
}
}
}
private List<Notify> toNotify() {
List<Notify> listNotifies = new ArrayList<Notify>();
List<NotificationWhen> listWhen = notificationFor.getWhen();
for (NotificationWhen notificationWhen : listWhen) {
listNotifies.addAll(notificationWhen.getNotify().stream().filter(n -> n.getSend() == true)
.collect(Collectors.toList()));
}
return listNotifies;
}
}

View File

@ -0,0 +1,134 @@
package org.gcube.application.cms.notifications.manage;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.gcube.application.cms.notifications.config.NotificationWhen;
import org.gcube.application.cms.notifications.config.Notify;
import org.gcube.application.cms.notifications.social.SocialClients;
import org.gcube.application.cms.notifications.substitutor.NMessagesPlaceholdersSubstitutorUtil;
import org.gcube.application.geoportal.common.model.document.accounting.User;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.portal.databook.shared.Post;
import org.gcube.social_networking.social_networking_client_library.NotificationClient;
import org.gcube.social_networking.socialnetworking.model.beans.PostInputBean;
import org.gcube.social_networking.socialnetworking.model.beans.Recipient;
import org.gcube.social_networking.socialnetworking.model.beans.catalogue.CatalogueEvent;
import org.gcube.social_networking.socialnetworking.model.beans.catalogue.CatalogueEventType;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class NotifyUser {
private User recipientUser;
private NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersSUtil;
private List<NotificationWhen> listNotificationWhen;
private SocialClients socialClients;
public NotifyUser(SocialClients socialClients, List<NotificationWhen> listWhen,
NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersSUtil, User recipientUser) {
this.socialClients = socialClients;
this.listNotificationWhen = listWhen;
this.recipientUser = recipientUser;
this.nMPlaceholdersSUtil = nMPlaceholdersSUtil;
}
public void send() throws Exception {
log.info("send call...");
List<Notify> listNotifies = toNotify();
// TODO
// NotificationClient client = new NotificationClient();
// client.send ??????
for (Notify notify : listNotifies) {
switch (notify.getType()) {
case USER_MESSAGE:
log.info("Notification type {}, send: {}", notify.getType(), notify.getSend());
if (notify.getSend()) {
log.debug("Building message...");
String subject = "Message";
String body = null;
// PostClient postClient = socialClients.getPostClient();
// PostInputBean postInputBean = new PostInputBean();
// postInputBean.setEnablenotification(true);
// postInputBean.setText(message);
//
// socialClients.writeUserPost(null)
subject = nMPlaceholdersSUtil.replacePlaceholder(notify.getPlaceholder_title());
body = nMPlaceholdersSUtil.replacePlaceholder(notify.getPlaceholder_msg());
log.debug("subject: {}", subject);
log.debug("body: {}", body);
List<Recipient> rec = Arrays.asList(new Recipient(recipientUser.getUsername()));
log.info("Sending message to users: {}", rec);
// sendNotification(null);
// MessageInputBean message = new MessageInputBean(subject, body, new ArrayList<Recipient>(rec));
// String idMessage = socialClients.writeMessage(message);
// log.info("Message sent with id: {}", idMessage);
}
break;
case VRE_POST:
if (notify.getSend()) {
log.info("Notification type {}, send: {}", notify.getType(), notify.getSend());
PostInputBean toWrite = null;
Post thePost = socialClients.writeUserPost(toWrite);
log.info("{} post created: {} ", notify.getType(), thePost);
}
break;
case EMAIL:
break;
default:
break;
}
}
}
protected void sendNotification(CatalogueEvent catalogueEvent) throws Exception {
Thread thread = new Thread() {
public void run() {
try {
log.trace("{} is going to send the following notification {}", SecretManagerProvider.instance.get().getUser().getUsername(), catalogueEvent);
NotificationClient nc = new NotificationClient();
nc.sendCatalogueEvent(catalogueEvent);
} catch(Exception e) {
log.error("Error while sending notification.", e);
}
}
};
// thread.run();
thread.start();
}
protected CatalogueEvent toCatalogueEvent(CatalogueEventType catalogueEventType, String messageString, String subject, String itemURL, List<String> users) throws Exception {
CatalogueEvent catalogueEvent = new CatalogueEvent();
catalogueEvent.setType(catalogueEventType);
catalogueEvent.setNotifyText(messageString);
catalogueEvent.setItemId(subject);
if(itemURL!=null) {
catalogueEvent.setItemURL(new URL(itemURL));
}
catalogueEvent.setIdsToNotify(users.toArray(new String[users.size()]));
catalogueEvent.setIdsAsGroup(false);
return catalogueEvent;
}
private List<Notify> toNotify() {
List<Notify> listNotifies = new ArrayList<Notify>();
for (NotificationWhen notificationWhen : listNotificationWhen) {
listNotifies.addAll(notificationWhen.getNotify().stream().filter(n -> n.getSend() == true)
.collect(Collectors.toList()));
}
return listNotifies;
}
}

View File

@ -91,4 +91,20 @@ public class SocialClients {
return postClient.writeUserPost(toWrite); return postClient.writeUserPost(toWrite);
} }
public static org.slf4j.Logger getLog() {
return log;
}
public PostClient getPostClient() {
return postClient;
}
public MessageClient getMessagesClient() {
return messagesClient;
}
public UserClient getUserClient() {
return userClient;
}
} }

View File

@ -3,7 +3,6 @@ package org.gcube.application.cms.notifications.substitutor;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.util.HashMap;
import java.util.Properties; import java.util.Properties;
import org.apache.commons.text.StringSubstitutor; import org.apache.commons.text.StringSubstitutor;
@ -50,14 +49,16 @@ public class NMessagesPlaceholdersSubstitutorUtil {
if (notificationPlaceholder == null || notificationPlaceholder.isEmpty()) if (notificationPlaceholder == null || notificationPlaceholder.isEmpty())
return notificationPlaceholder; return notificationPlaceholder;
log.trace("stringSub is {}",stringSub);
if (stringSub != null) { if (stringSub != null) {
log.info("notificationPlaceholder: {}", notificationPlaceholder); log.debug("notificationPlaceholder: {}", notificationPlaceholder);
String templateString = notificationMessagesProperties.getProperty(notificationPlaceholder); String templateString = notificationMessagesProperties.getProperty(notificationPlaceholder);
log.debug("templateString: {}", templateString); log.debug("templateString: {}", templateString);
// Replace // Replace
String resolvedString = stringSub.replace(templateString); String resolvedString = stringSub.replace(templateString);
log.info("resolvedString: {}", resolvedString); log.debug("resolvedString: {}", resolvedString);
return resolvedString; return resolvedString;
} }
log.info("placeholderMapValues is null, returning source: {}", notificationPlaceholder); log.info("placeholderMapValues is null, returning source: {}", notificationPlaceholder);

View File

@ -4,6 +4,8 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.bson.Document;
import org.gcube.application.cms.implementations.utils.UserUtils;
import org.gcube.application.cms.notifications.NotificationEventsSubscribedConfig; import org.gcube.application.cms.notifications.NotificationEventsSubscribedConfig;
import org.gcube.application.cms.notifications.NotificationGenericConstants.NOTIFICATION_TYPE; import org.gcube.application.cms.notifications.NotificationGenericConstants.NOTIFICATION_TYPE;
import org.gcube.application.cms.notifications.NotificationsPlugin; import org.gcube.application.cms.notifications.NotificationsPlugin;
@ -12,23 +14,33 @@ import org.gcube.application.cms.notifications.config.NotificationFor;
import org.gcube.application.cms.notifications.config.NotificationWhen; import org.gcube.application.cms.notifications.config.NotificationWhen;
import org.gcube.application.cms.notifications.config.Notify; import org.gcube.application.cms.notifications.config.Notify;
import org.gcube.application.cms.notifications.config.SubscribeNotificationEvent; import org.gcube.application.cms.notifications.config.SubscribeNotificationEvent;
import org.gcube.application.cms.notifications.manage.ManageDoActionNotification;
import org.gcube.application.cms.plugins.events.EventManager;
import org.gcube.application.cms.plugins.events.EventManager.Event; import org.gcube.application.cms.plugins.events.EventManager.Event;
import org.gcube.application.cms.plugins.events.ItemObserved;
import org.gcube.application.cms.plugins.faults.InitializationException; import org.gcube.application.cms.plugins.faults.InitializationException;
import org.gcube.application.cms.serialization.Serialization; import org.gcube.application.cms.serialization.Serialization;
import org.gcube.application.cms.tests.TestProfiles; import org.gcube.application.cms.tests.TestProfiles;
import org.gcube.application.cms.tests.plugins.BasicPluginTest; import org.gcube.application.cms.tests.plugins.BasicPluginTest;
import org.gcube.application.geoportal.common.model.document.Project;
import org.gcube.application.geoportal.common.model.document.accounting.AccountingInfo;
import org.gcube.application.geoportal.common.model.document.accounting.PublicationInfo;
import org.gcube.application.geoportal.common.model.document.lifecycle.LifecycleInformation;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor; import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor;
import org.gcube.application.geoportal.common.utils.tests.GCubeTest; import org.gcube.application.geoportal.common.utils.tests.GCubeTest;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
public class CatalogueBindingPluginTest extends BasicPluginTest { public class CatalogueBindingPluginTest extends BasicPluginTest {
// @Test NotificationsPlugin plugin;
@Before
public void checkPlugin() { public void checkPlugin() {
org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled()); org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled());
NotificationsPlugin plugin = (NotificationsPlugin) plugins.get(NotificationsPlugin.DESCRIPTOR.getId()); plugin = (NotificationsPlugin) plugins.get(NotificationsPlugin.DESCRIPTOR.getId());
try { try {
plugin.init(); plugin.init();
@ -45,23 +57,10 @@ public class CatalogueBindingPluginTest extends BasicPluginTest {
} }
@Test //@Test
public void checkPluginConfig() { public void checkPluginConfig() {
org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled()); org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled());
NotificationsPlugin plugin = (NotificationsPlugin) plugins.get(NotificationsPlugin.DESCRIPTOR.getId());
UseCaseDescriptor descriptor = TestProfiles.profiles.get("profiledConcessioni"); UseCaseDescriptor descriptor = TestProfiles.profiles.get("profiledConcessioni");
try {
plugin.init();
} catch (InitializationException e1) {
e1.printStackTrace();
}
try {
plugin.initInContext();
} catch (InitializationException e1) {
e1.printStackTrace();
}
NotificationEventsSubscribedConfig notificationEventsSubs; NotificationEventsSubscribedConfig notificationEventsSubs;
try { try {
System.out.println(NotificationEventsSubscribedConfig.class.getSimpleName() + ": "); System.out.println(NotificationEventsSubscribedConfig.class.getSimpleName() + ": ");
@ -76,13 +75,68 @@ public class CatalogueBindingPluginTest extends BasicPluginTest {
} }
@Test
public void checkNotifications() {
org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled());
// NotificationsPlugin plugin = (NotificationsPlugin)
// plugins.get(NotificationsPlugin.DESCRIPTOR.getId());
UseCaseDescriptor descriptor = TestProfiles.profiles.get("profiledConcessioni");
NotificationEventsSubscribedConfig notificationEventsSubs;
try {
System.out.println(NotificationEventsSubscribedConfig.class.getSimpleName() + ": ");
notificationEventsSubs = plugin.readNotificationsSubscribedFromConfigurationInTheUCD(descriptor);
List<SubscribeNotificationEvent> events = notificationEventsSubs.getListNotificationEventSubscribed();
for (SubscribeNotificationEvent subscribeNotificationEvent : events) {
sysOut(subscribeNotificationEvent);
}
} catch (Exception e) {
e.printStackTrace();
}
// notifying the Event.PROJECT_CREATED;
ItemObserved<Project> item = new ItemObserved<Project>();
EventManager.Event event = Event.LIFECYCLE_STEP_PERFORMED;
AccountingInfo user = UserUtils.getCurrent().asInfo();
// System.out.println(user.getUser());
// sysOut(user);
System.out.println("User is: " + user.getUser());
System.out.println("Context is: " + user.getContext());
item.setUserCaller(user.getUser());
item.setContext(user.getContext());
item.setEvent(event);
item.setUseCaseDescriptor(descriptor);
// MOCK PROJECT
Project testProject = new Project();
testProject.setId("63bda06581b811167f6a0769");
testProject.setProfileID(descriptor.getId());
PublicationInfo info = new PublicationInfo(descriptor.getCreationInfo(), null, null);
testProject.setInfo(info);
Document theDocument = new Document();
theDocument.append("name", "My Best Project");
testProject.setTheDocument(theDocument);
LifecycleInformation lifecycleInfo = new LifecycleInformation();
lifecycleInfo.setPhase("Pending Approval");
lifecycleInfo.setLastInvokedStep("SUBMIT-FOR-REVIEW");
testProject.setLifecycleInformation(lifecycleInfo);
item.setProject(testProject);
System.out.println("By notifying event " + event + " project " + item.getProjectId());
EventManager.getInstance().notify(event, item);
}
private void sysOut(SubscribeNotificationEvent subscribeNotificationEvent) { private void sysOut(SubscribeNotificationEvent subscribeNotificationEvent) {
System.out.println("\n#SubscribeNotificationEvent - Event: " + subscribeNotificationEvent.getEvent()); System.out.println("\n#SubscribeNotificationEvent - Event: " + subscribeNotificationEvent.getEvent());
List<NotificationFor> listNotificationFor = subscribeNotificationEvent.getNotificationFor(); List<NotificationFor> listNotificationFor = subscribeNotificationEvent.getNotificationFor();
for (NotificationFor notificationFor : listNotificationFor) { for (NotificationFor notificationFor : listNotificationFor) {
System.out.println("\tNotificationFor - roles: " + notificationFor.getRoles()); System.out.println("\tNotificationFor - roles: " + notificationFor.getRoles());
for (NotificationWhen notificationWhen : notificationFor.getWhen()) { for (NotificationWhen notificationWhen : notificationFor.getWhen()) {
System.out.println("\t\tNotificationWhen - Target_phase: " + notificationWhen.getTarget_phase()); System.out.println("\t\tNotificationWhen - Target_phase: " + notificationWhen.getTarget_phase()
+ ", Last_invoked_step: " + notificationWhen.getLast_invoked_step());
for (Notify notify : notificationWhen.getNotify()) { for (Notify notify : notificationWhen.getNotify()) {
System.out.println("\t\t\tNotify type : " + notify.getType()); System.out.println("\t\t\tNotify type : " + notify.getType());
System.out.println("\t\t\tNotify send : " + notify.getSend()); System.out.println("\t\t\tNotify send : " + notify.getSend());
@ -95,10 +149,50 @@ public class CatalogueBindingPluginTest extends BasicPluginTest {
} }
} }
//@Test
public void matchingNotificationTest() {
org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled());
String itemPhase = "Pending Approval";
String lastInvokedStep = "SUBMIT-FOR-REVIEW";
List<NotificationWhen> listWhen = new ArrayList<NotificationWhen>();
SubscribeNotificationEvent sne = mockSubscribeNotificationEvent();
for (NotificationFor notificationFor : sne.getNotificationFor()) {
listWhen.addAll(ManageDoActionNotification.matchNotificationsAccordingItemStatus(notificationFor, itemPhase, lastInvokedStep));
}
System.out.println("Filtered notifications: "+listWhen);
}
// @Test // @Test
public void checkSerializeDeserialize() { public void checkSerializeDeserialize() {
org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled()); org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled());
SubscribeNotificationEvent sne = mockSubscribeNotificationEvent();
try {
String serializeTOJSON = Serialization.write(sne);
System.out.println("Serialized toJSON :" + serializeTOJSON);
SubscribeNotificationEvent deserializeToJSON = Serialization.read(serializeTOJSON,
SubscribeNotificationEvent.class);
System.out.println("Deserialized from JSON :" + deserializeToJSON);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SubscribeNotificationEvent mockSubscribeNotificationEvent() {
SubscribeNotificationEvent sne = new SubscribeNotificationEvent(); SubscribeNotificationEvent sne = new SubscribeNotificationEvent();
sne.setEvent(Event.LIFECYCLE_STEP_PERFORMED); sne.setEvent(Event.LIFECYCLE_STEP_PERFORMED);
@ -110,6 +204,7 @@ public class CatalogueBindingPluginTest extends BasicPluginTest {
List<NotificationWhen> listWhen = new ArrayList<NotificationWhen>(); List<NotificationWhen> listWhen = new ArrayList<NotificationWhen>();
NotificationWhen notificationWhen = new NotificationWhen(); NotificationWhen notificationWhen = new NotificationWhen();
notificationWhen.setTarget_phase(Arrays.asList("Pending Approval")); notificationWhen.setTarget_phase(Arrays.asList("Pending Approval"));
notificationWhen.setLast_invoked_step("SUBMIT-FOR-REVIEW");
Notify notify = new Notify(); Notify notify = new Notify();
notify.setType(NOTIFICATION_TYPE.EMAIL); notify.setType(NOTIFICATION_TYPE.EMAIL);
@ -129,96 +224,7 @@ public class CatalogueBindingPluginTest extends BasicPluginTest {
sne.setNotificationFor(listNotificationFor); sne.setNotificationFor(listNotificationFor);
try { return sne;
String serializeTOJSON = Serialization.write(sne);
System.out.println("Serialized toJSON :" + serializeTOJSON);
SubscribeNotificationEvent deserializeToJSON = Serialization.read(serializeTOJSON,
SubscribeNotificationEvent.class);
System.out.println("Deserialized from JSON :" + deserializeToJSON);
// Test Notify
/*
* String testNotify = "{\n" + " \"type\": \"EMAIL\",\n" +
* " \"send\": true,\n" + " \"attach_pdf_document\": false,\n" +
* " \"message\": \"The project ${project_name} has just been rejected by ${user}\"\n"
* + "}";
*
* System.out.println("String :"+testNotify); Notify serialize =
* Serialization.read(testNotify, Notify.class);
* System.out.println("Ser from JSON :"+serialize);
*/
// Test NotificationFor
/*
* String testNotificationFor = "{ \"when\": [\n" + " {\n" +
* " \"target_phase\": [\n" +
* " \"Rejected\"\n" + " ],\n" +
* " \"notify\": {\n" +
* " \"send_personal_nofitication\": false,\n" +
* " \"send_email\": true,\n" +
* " \"send_pdf_document\": false,\n" +
* " \"post_on_vre\": false,\n" +
* " \"message\": \"The project ${project_name} has just been rejected. You are kindly requested to review it\"\n"
* + " }\n" + " },\n" +
* " {\n" + " \"target_phase\": [\n" +
* " \"Published\"\n" + " ],\n" +
* " \"notify\": {\n" +
* " \"send_personal_nofitication\": false,\n" +
* " \"send_email\": true,\n" +
* " \"send_pdf_document\": true,\n" +
* " \"post_on_vre\": true,\n" +
* " \"message\": \"The project ${project_name} has just been published. See it at @link\"\n"
* + " }\n" + " }\n" + " ]}";
*
* System.out.println("String :"+testNotificationFor); NotificationFor
* serializeNotificationWhen = Serialization.read(testNotificationFor,
* NotificationFor.class);
* System.out.println("Ser from JSON :"+serializeNotificationWhen);
*/
// String testSubribeNotifications = "{\n" + " \"event\": \"LIFECYCLE_STEP_PERFORMED\",\n"
// + " \"notificationFor\": [\n" + " {\n" + " \"roles\": [\n" + " \"Data-Manager\"\n"
// + " ],\n" + " \"when\": [\n" + " {\n" + " \"target_phase\": [\n"
// + " \"Pending Approval\"\n" + " ],\n" + " \"notify\": [\n"
// + " {\n" + " \"type\": \"SOCIAL_POST\",\n"
// + " \"send\": true,\n" + " \"attach_pdf_document\": false,\n"
// + " \"message\": \"${user} created the project ${project_name}. You are kindly requested to review it and decide either to APPROVE or REJECT it. See it at @link\"\n"
// + " }\n" + " ]\n" + " },\n" + " {\n"
// + " \"target_phase\": [\n" + " \"Rejected\"\n" + " ],\n"
// + " \"notify\": [\n" + " {\n" + " \"type\": \"SOCIAL_POST\",\n"
// + " \"send\": true,\n" + " \"attach_pdf_document\": false,\n"
// + " \"message\": \"The project ${project_name} has just been rejected by ${user}\"\n"
// + " }\n" + " ]\n" + " }\n" + " ]\n" + " },\n" + " {\n"
// + " \"roles\": [\n" + " \"Item_Creator\"\n" + " ],\n" + " \"when\": [\n"
// + " {\n" + " \"target_phase\": [\n" + " \"Rejected\"\n"
// + " ],\n" + " \"notify\": [\n" + " {\n"
// + " \"type\": \"EMAIL\",\n" + " \"send\": true,\n"
// + " \"attach_pdf_document\": false,\n"
// + " \"message\": \"The project ${project_name} has just been rejected. You are kindly requested to review it\"\n"
// + " }\n" + " ]\n" + " },\n" + " {\n"
// + " \"target_phase\": [\n" + " \"Published\"\n" + " ],\n"
// + " \"notify\": [\n" + " {\n" + " \"type\": \"EMAIL\",\n"
// + " \"send\": true,\n" + " \"attach_pdf_document\": false,\n"
// + " \"message\": \"The project ${project_name} has just been published. See it at @link\"\n"
// + " }\n" + " ]\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + "}";
//
// testSubribeNotifications = "{event=LIFECYCLE_STEP_PERFORMED, notificationFor=[{roles=[Data-Manager], when=[{target_phase=[Pending Approval], notify=[{type=EMAIL, send=true, attach_pdf_document=false, message=${user} created the project ${project_name}. You are kindly requested to review it and decide either to APPROVE or REJECT it. See it at @link}]}, {target_phase=[Rejected], notify=[{type=EMAIL, send=true, attach_pdf_document=false, message=The project ${project_name} has just been rejected by ${user}}]}]}, {roles=[Item_Creator], when=[{target_phase=[Rejected], notify=[{type=EMAIL, send=true, attach_pdf_document=false, message=The project ${project_name} has just been rejected. You are kindly requested to review it}]}, {target_phase=[Published], notify=[{type=EMAIL, send=true, attach_pdf_document=false, message=The project ${project_name} has just been published. See it at @link}]}]}]}";
//
// System.out.println("String :" + testSubribeNotifications);
// SubscribeNotificationEvent serializeSubscribeNotificationEvent = Serialization
// .convert(testSubribeNotifications, SubscribeNotificationEvent.class);
// System.out.println("Ser from JSON :" + serializeSubscribeNotificationEvent);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
} }

View File

@ -1,8 +1,5 @@
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.net.URL; import java.net.URL;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -38,13 +35,20 @@ public class StringReplacerTest {
public void checkReplace() { public void checkReplace() {
org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled()); org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled());
Map<String, String> valuesMap = new HashMap<>(); // Map<String, String> valuesMap = new HashMap<>();
valuesMap.put(SubstitutorMessagesMap.USER, USERNAME); // valuesMap.put(SubstitutorMessagesMap.USER, USERNAME);
valuesMap.put(SubstitutorMessagesMap.PROJECT_NAME, PROJECT_NAME); // valuesMap.put(SubstitutorMessagesMap.PROJECT_NAME, PROJECT_NAME);
valuesMap.put(SubstitutorMessagesMap.GIS_LINK, GIS_LINK); // valuesMap.put(SubstitutorMessagesMap.GIS_LINK, GIS_LINK);
valuesMap.put(SubstitutorMessagesMap.PROJECT_ID, PROJECT_ID); // valuesMap.put(SubstitutorMessagesMap.PROJECT_ID, PROJECT_ID);
SubstitutorMessagesMap smp = new SubstitutorMessagesMap();
smp.putUser(USERNAME);
smp.putGisLink(GIS_LINK);
smp.putProjectId(PROJECT_ID);
smp.putProjectName(PROJECT_NAME);
// Build StringSubstitutor // Build StringSubstitutor
StringSubstitutor sub = new StringSubstitutor(valuesMap); StringSubstitutor sub = new StringSubstitutor(smp);
try (BufferedInputStream in = new BufferedInputStream(new URL(FILE_URL).openStream())) { try (BufferedInputStream in = new BufferedInputStream(new URL(FILE_URL).openStream())) {