From d8838a176bde6a7d90d81d0d9382f7c8c119f7bb Mon Sep 17 00:00:00 2001 From: "francesco.mangiacrapa" Date: Fri, 22 Mar 2024 16:26:40 +0100 Subject: [PATCH] in progress --- notifications-plugins/pom.xml | 5 + .../notifications/NotificationsPlugin.java | 9 +- .../config/NotificationWhen.java | 1 + .../manage/ManageDoActionNotification.java | 116 ++++++--- .../manage/ManageNotifyUser.java | 91 -------- .../cms/notifications/manage/NotifyUser.java | 134 +++++++++++ .../notifications/social/SocialClients.java | 16 ++ .../NMessagesPlaceholdersSubstitutorUtil.java | 7 +- .../test/java/CatalogueBindingPluginTest.java | 220 +++++++++--------- .../src/test/java/StringReplacerTest.java | 22 +- 10 files changed, 380 insertions(+), 241 deletions(-) delete mode 100644 notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/ManageNotifyUser.java create mode 100644 notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/NotifyUser.java diff --git a/notifications-plugins/pom.xml b/notifications-plugins/pom.xml index 240bccf..bb75347 100644 --- a/notifications-plugins/pom.xml +++ b/notifications-plugins/pom.xml @@ -60,6 +60,11 @@ social-service-client [1.0.0, 2.0.0-SNAPSHOT) + + org.gcube.portlets.user + uri-resolver-manager + [1.0.0,2.0.0-SNAPSHOT) + org.apache.commons commons-text diff --git a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/NotificationsPlugin.java b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/NotificationsPlugin.java index 5e382e5..4a3eaa8 100644 --- a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/NotificationsPlugin.java +++ b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/NotificationsPlugin.java @@ -10,7 +10,6 @@ import java.util.stream.Collectors; import org.bson.Document; 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.manage.ManageDoActionNotification; import org.gcube.application.cms.notifications.substitutor.NMessagesPlaceholdersSubstitutorUtil; @@ -76,7 +75,7 @@ public class NotificationsPlugin extends AbstractPlugin implements EventListener @Override public void updated(ItemObserved observerd) { - log.info("listenerCreated fired on item: {} " + observerd); + log.info("listenerCreated fired on item: {} ", observerd); boolean subscribed = checkIfSubscribedEvent(observerd); @@ -91,7 +90,7 @@ public class NotificationsPlugin extends AbstractPlugin implements EventListener @Override public void updated(ItemObserved observerd) { - log.info("listenerUpdated fired on item: {} " + observerd); + log.info("listenerUpdated fired on item: {} ", observerd); boolean subscribed = checkIfSubscribedEvent(observerd); if (subscribed) { @@ -105,7 +104,7 @@ public class NotificationsPlugin extends AbstractPlugin implements EventListener @Override public void updated(ItemObserved observerd) { - log.info("listenerDeleted fired on item: {} " + observerd); + log.info("listenerDeleted fired on item: {} ", observerd); boolean subscribed = checkIfSubscribedEvent(observerd); if (subscribed) { @@ -118,7 +117,7 @@ public class NotificationsPlugin extends AbstractPlugin implements EventListener @Override public void updated(ItemObserved observerd) { - log.info("listenerLCStepPerformed fired on item: {} " + observerd); + log.info("listenerLCStepPerformed fired on item: {} ", observerd); boolean subscribed = checkIfSubscribedEvent(observerd); if (subscribed) { diff --git a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/config/NotificationWhen.java b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/config/NotificationWhen.java index ead85b9..094c419 100644 --- a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/config/NotificationWhen.java +++ b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/config/NotificationWhen.java @@ -14,6 +14,7 @@ import lombok.Data; public class NotificationWhen { List target_phase; + String last_invoked_step; List notify; } diff --git a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/ManageDoActionNotification.java b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/ManageDoActionNotification.java index b823553..ece1d24 100644 --- a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/ManageDoActionNotification.java +++ b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/ManageDoActionNotification.java @@ -19,7 +19,11 @@ import org.gcube.application.cms.notifications.substitutor.SubstitutorMessagesMa 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.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.social_networking.socialnetworking.model.beans.catalogue.CatalogueEventType; import lombok.extern.slf4j.Slf4j; @@ -35,8 +39,7 @@ public class ManageDoActionNotification { private List listSubscribedNotification; private ItemObserved itemObserved; - private NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersSUtil; - private SubstitutorMessagesMap placeholderMapValues; + private NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersS; /** * Instantiates a new manage do action notification. @@ -48,21 +51,22 @@ public class ManageDoActionNotification { public ManageDoActionNotification(ItemObserved itemObserved, NMessagesPlaceholdersSubstitutorUtil nMPlaceholdersSUtil, List filterList) { this.listSubscribedNotification = filterList; - this.nMPlaceholdersSUtil = nMPlaceholdersSUtil; + this.nMPlaceholdersS = nMPlaceholdersSUtil; this.itemObserved = itemObserved; - // Creating the map for replacing the placeholders with their values - placeholderMapValues = new SubstitutorMessagesMap(); + // Creating the map for replacing the placeholder with their values + SubstitutorMessagesMap placeholderMapValues = new SubstitutorMessagesMap(); String gisLink = GisClient.gisLink(RESOLVE_AS.PRIVATE, itemObserved.getUCD_Id(), itemObserved.getProjectId(), - itemObserved.getContext().getName(), true); + itemObserved.getContext().getId(), true); placeholderMapValues.putGisLink(gisLink); placeholderMapValues.putProjectId(itemObserved.getProjectId()); LinkedHashMap 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(); placeholderMapValues.putProjectName(projectName); + placeholderMapValues.putUser(itemObserved.getUserCaller().getUsername()); - nMPlaceholdersSUtil.setPlaceholderMapValues(placeholderMapValues); + nMPlaceholdersS.setPlaceholderMapValues(placeholderMapValues); } @@ -79,33 +83,57 @@ public class ManageDoActionNotification { List listNotificationFor = subscribeNotificationEvent.getNotificationFor(); // Reading 'phase' property from itemObserved - String itemPhase = itemObserved.getProject().getLifecycleInformation().getPhase(); - log.debug("ItemObserved 'phase' is: {}", itemPhase); + LifecycleInformation lInfo = itemObserved.getProject().getLifecycleInformation(); + 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) { - // Filtering notifications on 'phase' according to item itemObserved 'phase' - List notificationsCompliantToPhase = notificationFor.getWhen().stream() - .filter(when -> when.getTarget_phase().contains(itemPhase)).collect(Collectors.toList()); + // Filtering notifications on 'phase' and 'lastInvokedStep' according to item + // itemObserved 'phase' + List 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) { // GET LIST USER COMPLIANT TO ROLES List notifyUsers = getListUserCompliantToRoles(notificationFor, itemObserved); + final SocialClients socialClients = new SocialClients(); + if (notifyUsers.size() > 0) { - for (final User user : notifyUsers) { - - Thread notificationT = new Thread() { - - public void run() { - new ManageNotifyUser(notificationFor, nMPlaceholdersSUtil, user); - }; - - }; - - notificationT.run(); + log.info("Users compliant to role are: {}", notifyUsers.size()); + if (log.isDebugEnabled()) { + notifyUsers.stream().forEach(u -> log.debug("user: " + u)); } + 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 matchNotificationsAccordingItemStatus(NotificationFor notificationFor, + String itemPhase, String lastInvokedStep) { + log.info("Filtering notifications according to phase: {}, lastInvokedStep: {}", itemPhase, lastInvokedStep); + + List filteredList = new ArrayList(); + + 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. * @@ -152,6 +214,7 @@ public class ManageDoActionNotification { .getUsername(); notifyUsers.add( new User(creatorUsername, Stream.of(role).collect(Collectors.toCollection(HashSet::new)))); + log.info("added {} user for role {}", notifyUsers.size(), role); } catch (Exception e) { log.error("Error on reading user {} from scope {}: ", itemCreatorRole, UserUtils.getCurrent().getContext(), e); @@ -163,6 +226,7 @@ public class ManageDoActionNotification { .map(username -> new User(username, Stream.of(role).collect(Collectors.toCollection(HashSet::new)))) .collect(Collectors.toList())); + log.info("added {} users for role {}", notifyUsers.size(), role); } catch (Exception 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; - log.error("returing {} users to be notified: ", notifyUsers.size()); + log.info("returing {} users to be notified: ", notifyUsers.size()); return notifyUsers; } diff --git a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/ManageNotifyUser.java b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/ManageNotifyUser.java deleted file mode 100644 index 3e1bc6f..0000000 --- a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/ManageNotifyUser.java +++ /dev/null @@ -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 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 rec = Arrays.asList(new Recipient(recipientUser.getUsername())); - log.info("Sending message..."); - MessageInputBean message = new MessageInputBean(subject, body, new ArrayList(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 toNotify() { - List listNotifies = new ArrayList(); - List listWhen = notificationFor.getWhen(); - for (NotificationWhen notificationWhen : listWhen) { - listNotifies.addAll(notificationWhen.getNotify().stream().filter(n -> n.getSend() == true) - .collect(Collectors.toList())); - } - return listNotifies; - } - -} diff --git a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/NotifyUser.java b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/NotifyUser.java new file mode 100644 index 0000000..d5d97fc --- /dev/null +++ b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/manage/NotifyUser.java @@ -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 listNotificationWhen; + private SocialClients socialClients; + + public NotifyUser(SocialClients socialClients, List 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 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 rec = Arrays.asList(new Recipient(recipientUser.getUsername())); + log.info("Sending message to users: {}", rec); + +// sendNotification(null); +// MessageInputBean message = new MessageInputBean(subject, body, new ArrayList(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 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 toNotify() { + List listNotifies = new ArrayList(); + for (NotificationWhen notificationWhen : listNotificationWhen) { + listNotifies.addAll(notificationWhen.getNotify().stream().filter(n -> n.getSend() == true) + .collect(Collectors.toList())); + } + return listNotifies; + } + +} diff --git a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/social/SocialClients.java b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/social/SocialClients.java index bf2dcf2..2589a9d 100644 --- a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/social/SocialClients.java +++ b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/social/SocialClients.java @@ -91,4 +91,20 @@ public class SocialClients { 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; + } + } diff --git a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/substitutor/NMessagesPlaceholdersSubstitutorUtil.java b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/substitutor/NMessagesPlaceholdersSubstitutorUtil.java index e4f6b8e..50f1c04 100644 --- a/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/substitutor/NMessagesPlaceholdersSubstitutorUtil.java +++ b/notifications-plugins/src/main/java/org/gcube/application/cms/notifications/substitutor/NMessagesPlaceholdersSubstitutorUtil.java @@ -3,7 +3,6 @@ package org.gcube.application.cms.notifications.substitutor; import java.io.BufferedInputStream; import java.io.IOException; import java.net.URL; -import java.util.HashMap; import java.util.Properties; import org.apache.commons.text.StringSubstitutor; @@ -49,15 +48,17 @@ public class NMessagesPlaceholdersSubstitutorUtil { if (notificationPlaceholder == null || notificationPlaceholder.isEmpty()) return notificationPlaceholder; + + log.trace("stringSub is {}",stringSub); if (stringSub != null) { - log.info("notificationPlaceholder: {}", notificationPlaceholder); + log.debug("notificationPlaceholder: {}", notificationPlaceholder); String templateString = notificationMessagesProperties.getProperty(notificationPlaceholder); log.debug("templateString: {}", templateString); // Replace String resolvedString = stringSub.replace(templateString); - log.info("resolvedString: {}", resolvedString); + log.debug("resolvedString: {}", resolvedString); return resolvedString; } log.info("placeholderMapValues is null, returning source: {}", notificationPlaceholder); diff --git a/notifications-plugins/src/test/java/CatalogueBindingPluginTest.java b/notifications-plugins/src/test/java/CatalogueBindingPluginTest.java index 9ad211e..e2f6c45 100644 --- a/notifications-plugins/src/test/java/CatalogueBindingPluginTest.java +++ b/notifications-plugins/src/test/java/CatalogueBindingPluginTest.java @@ -4,6 +4,8 @@ import java.util.ArrayList; import java.util.Arrays; 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.NotificationGenericConstants.NOTIFICATION_TYPE; 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.Notify; 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.ItemObserved; import org.gcube.application.cms.plugins.faults.InitializationException; import org.gcube.application.cms.serialization.Serialization; import org.gcube.application.cms.tests.TestProfiles; 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.utils.tests.GCubeTest; +import org.junit.Before; import org.junit.Test; import com.fasterxml.jackson.core.JsonProcessingException; public class CatalogueBindingPluginTest extends BasicPluginTest { - // @Test + NotificationsPlugin plugin; + + @Before public void checkPlugin() { org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled()); - NotificationsPlugin plugin = (NotificationsPlugin) plugins.get(NotificationsPlugin.DESCRIPTOR.getId()); + plugin = (NotificationsPlugin) plugins.get(NotificationsPlugin.DESCRIPTOR.getId()); try { plugin.init(); @@ -45,23 +57,10 @@ public class CatalogueBindingPluginTest extends BasicPluginTest { } - @Test + //@Test public void checkPluginConfig() { org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled()); - NotificationsPlugin plugin = (NotificationsPlugin) plugins.get(NotificationsPlugin.DESCRIPTOR.getId()); UseCaseDescriptor descriptor = TestProfiles.profiles.get("profiledConcessioni"); - - try { - plugin.init(); - } catch (InitializationException e1) { - e1.printStackTrace(); - } - try { - plugin.initInContext(); - } catch (InitializationException e1) { - e1.printStackTrace(); - } - NotificationEventsSubscribedConfig notificationEventsSubs; try { 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 events = notificationEventsSubs.getListNotificationEventSubscribed(); + for (SubscribeNotificationEvent subscribeNotificationEvent : events) { + sysOut(subscribeNotificationEvent); + } + } catch (Exception e) { + e.printStackTrace(); + } + + // notifying the Event.PROJECT_CREATED; + ItemObserved item = new ItemObserved(); + 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) { System.out.println("\n#SubscribeNotificationEvent - Event: " + subscribeNotificationEvent.getEvent()); List listNotificationFor = subscribeNotificationEvent.getNotificationFor(); for (NotificationFor notificationFor : listNotificationFor) { System.out.println("\tNotificationFor - roles: " + notificationFor.getRoles()); 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()) { System.out.println("\t\t\tNotify type : " + notify.getType()); 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 listWhen = new ArrayList(); + SubscribeNotificationEvent sne = mockSubscribeNotificationEvent(); + for (NotificationFor notificationFor : sne.getNotificationFor()) { + listWhen.addAll(ManageDoActionNotification.matchNotificationsAccordingItemStatus(notificationFor, itemPhase, lastInvokedStep)); + } + + System.out.println("Filtered notifications: "+listWhen); + + + } + // @Test public void checkSerializeDeserialize() { 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(); sne.setEvent(Event.LIFECYCLE_STEP_PERFORMED); @@ -110,6 +204,7 @@ public class CatalogueBindingPluginTest extends BasicPluginTest { List listWhen = new ArrayList(); NotificationWhen notificationWhen = new NotificationWhen(); notificationWhen.setTarget_phase(Arrays.asList("Pending Approval")); + notificationWhen.setLast_invoked_step("SUBMIT-FOR-REVIEW"); Notify notify = new Notify(); notify.setType(NOTIFICATION_TYPE.EMAIL); @@ -129,96 +224,7 @@ public class CatalogueBindingPluginTest extends BasicPluginTest { sne.setNotificationFor(listNotificationFor); - 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); - - // 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(); - } - + return sne; } } diff --git a/notifications-plugins/src/test/java/StringReplacerTest.java b/notifications-plugins/src/test/java/StringReplacerTest.java index 377d7d1..497afc2 100644 --- a/notifications-plugins/src/test/java/StringReplacerTest.java +++ b/notifications-plugins/src/test/java/StringReplacerTest.java @@ -1,8 +1,5 @@ import java.io.BufferedInputStream; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.HashMap; @@ -38,13 +35,20 @@ public class StringReplacerTest { public void checkReplace() { org.junit.Assume.assumeTrue(GCubeTest.isTestInfrastructureEnabled()); - Map valuesMap = new HashMap<>(); - valuesMap.put(SubstitutorMessagesMap.USER, USERNAME); - valuesMap.put(SubstitutorMessagesMap.PROJECT_NAME, PROJECT_NAME); - valuesMap.put(SubstitutorMessagesMap.GIS_LINK, GIS_LINK); - valuesMap.put(SubstitutorMessagesMap.PROJECT_ID, PROJECT_ID); +// Map valuesMap = new HashMap<>(); +// valuesMap.put(SubstitutorMessagesMap.USER, USERNAME); +// valuesMap.put(SubstitutorMessagesMap.PROJECT_NAME, PROJECT_NAME); +// valuesMap.put(SubstitutorMessagesMap.GIS_LINK, GIS_LINK); +// 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 - StringSubstitutor sub = new StringSubstitutor(valuesMap); + StringSubstitutor sub = new StringSubstitutor(smp); try (BufferedInputStream in = new BufferedInputStream(new URL(FILE_URL).openStream())) {