From 28fad3ccc453b4792d64475a2e0d31f60c4a694b Mon Sep 17 00:00:00 2001 From: amentis Date: Mon, 11 Dec 2023 18:47:35 +0200 Subject: [PATCH] remove mail service --- .../notification/NotificationContactType.java | 32 +++ .../notification/NotificationNotifyState.java | 33 +++ .../NotificationTrackingProcess.java | 32 +++ .../NotificationTrackingState.java | 35 +++ .../types/notification/Attachment.java | 36 +++ .../types/notification/ContactPair.java | 33 +++ .../commons/types/notification/DataType.java | 42 +++ .../commons/types/notification/FieldInfo.java | 40 +++ .../types/notification/InAppTrackingData.java | 31 +++ .../notification/NotificationContactData.java | 39 +++ .../notification/NotificationFieldData.java | 32 +++ .../types/notification/RouteTrackingData.java | 30 +++ .../types/notification/TrackingTrace.java | 30 +++ .../NotificationContactTypeConverter.java | 12 + .../NotificationNotifyStateConverter.java | 12 + .../NotificationTrackingProcessConverter.java | 12 + .../NotificationTrackingStateConverter.java | 13 + .../data/notification/NotificationEntity.java | 225 ++++++++++++++++ .../NotificationIntegrationEvent.java | 74 ++++++ .../NotificationIntegrationEventHandler.java | 7 + ...tificationIntegrationEventHandlerImpl.java | 106 ++++++++ .../notification/NotificationPersist.java | 169 ++++++++++++ .../DescriptionTemplateServiceImpl.java | 54 ++-- .../eu/eudat/service/lock/LockService.java | 4 +- .../eudat/service/lock/LockServiceImpl.java | 47 ++-- .../eu/eudat/service/mail/MailService.java | 12 - .../eudat/service/mail/MailServiceImpl.java | 140 ---------- .../eu/eudat/service/mail/SimpleMail.java | 51 ---- .../notification/NotificationService.java | 16 ++ .../notification/NotificationServiceImpl.java | 106 ++++++++ .../main/resources/config/notification.yml | 8 +- .../target/classes/config/notification.yml | 8 +- .../eudat/controllers/v2/LockController.java | 17 +- .../logic/managers/ContactEmailManager.java | 39 ++- .../managers/EmailConfirmationManager.java | 7 +- .../logic/managers/NotificationManager.java | 46 ++-- .../UnlinkEmailConfirmationManager.java | 5 +- .../utilities/ConfirmationEmailService.java | 17 +- .../ConfirmationEmailServiceImpl.java | 245 ++++++++---------- .../services/utilities/InvitationService.java | 7 +- .../utilities/InvitationServiceImpl.java | 73 +++--- .../services/utilities/UtilitiesService.java | 4 +- .../utilities/UtilitiesServiceImpl.java | 11 +- 43 files changed, 1469 insertions(+), 523 deletions(-) create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationContactType.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationNotifyState.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationTrackingProcess.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationTrackingState.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/Attachment.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/ContactPair.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/DataType.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/FieldInfo.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/InAppTrackingData.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/NotificationContactData.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/NotificationFieldData.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/RouteTrackingData.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/TrackingTrace.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationContactTypeConverter.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationNotifyStateConverter.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationTrackingProcessConverter.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationTrackingStateConverter.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/data/notification/NotificationEntity.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEvent.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEventHandler.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEventHandlerImpl.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/model/persist/notification/NotificationPersist.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/mail/MailService.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/mail/MailServiceImpl.java delete mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/mail/SimpleMail.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/notification/NotificationService.java create mode 100644 dmp-backend/core/src/main/java/eu/eudat/service/notification/NotificationServiceImpl.java diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationContactType.java b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationContactType.java new file mode 100644 index 000000000..904fea9b3 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationContactType.java @@ -0,0 +1,32 @@ +package eu.eudat.commons.enums.notification; + +import com.fasterxml.jackson.annotation.JsonValue; +import eu.eudat.commons.enums.EnumUtils; +import eu.eudat.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum NotificationContactType implements DatabaseEnum { + EMAIL((short)0), + SLACK_BROADCAST((short)1), + SMS((short)2), + IN_APP((short)3); + + private final Short value; + + NotificationContactType(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(NotificationContactType.class); + + public static NotificationContactType of(Short i) { + return map.get(i); + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationNotifyState.java b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationNotifyState.java new file mode 100644 index 000000000..dfc25879f --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationNotifyState.java @@ -0,0 +1,33 @@ +package eu.eudat.commons.enums.notification; + +import com.fasterxml.jackson.annotation.JsonValue; +import eu.eudat.commons.enums.EnumUtils; +import eu.eudat.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum NotificationNotifyState implements DatabaseEnum { + PENDING((short)0), + PROCESSING((short)1), + SUCCESSFUL((short)2), + ERROR((short)3), + OMITTED((short)4); + + private final Short value; + + NotificationNotifyState(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(NotificationNotifyState.class); + + public static NotificationNotifyState of(Short i) { + return map.get(i); + } + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationTrackingProcess.java b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationTrackingProcess.java new file mode 100644 index 000000000..145f2f85d --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationTrackingProcess.java @@ -0,0 +1,32 @@ +package eu.eudat.commons.enums.notification; + +import com.fasterxml.jackson.annotation.JsonValue; +import eu.eudat.commons.enums.EnumUtils; +import eu.eudat.data.converters.enums.DatabaseEnum; + +import java.util.Map; + +public enum NotificationTrackingProcess implements DatabaseEnum { + PENDING((short)0), + PROCESSING((short)1), + COMPLETED((short)2), + ERROR((short)3), + OMITTED((short)4); + + private final Short value; + + NotificationTrackingProcess(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(NotificationTrackingProcess.class); + + public static NotificationTrackingProcess of(Short i) { + return map.get(i); + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationTrackingState.java b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationTrackingState.java new file mode 100644 index 000000000..6b06c1edf --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/enums/notification/NotificationTrackingState.java @@ -0,0 +1,35 @@ +package eu.eudat.commons.enums.notification; + +import com.fasterxml.jackson.annotation.JsonValue; +import eu.eudat.data.converters.enums.DatabaseEnum; +import eu.eudat.commons.enums.EnumUtils; + +import java.util.Map; + +public enum NotificationTrackingState implements DatabaseEnum { + UNDEFINED((short)0), + NA((short)1), + QUEUED((short)2), + SENT((short)3), + DELIVERED((short)4), + UNDELIVERED((short)5), + FAILED((short)6), + UNSENT((short)7); + + private final Short value; + + NotificationTrackingState(Short value) { + this.value = value; + } + + @JsonValue + public Short getValue() { + return value; + } + + private static final Map map = EnumUtils.getEnumValueMap(NotificationTrackingState.class); + + public static NotificationTrackingState of(Short i) { + return map.get(i); + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/Attachment.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/Attachment.java new file mode 100644 index 000000000..d133aa09a --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/Attachment.java @@ -0,0 +1,36 @@ +package eu.eudat.commons.types.notification; + +public class Attachment { + + private String fileRef, fileName, mimeType; + + public Attachment(String fileRef, String fileName, String mimeType) { + this.fileRef = fileRef; + this.fileName = fileName; + this.mimeType = mimeType; + } + + public String getFileRef() { + return fileRef; + } + + public void setFileRef(String fileRef) { + this.fileRef = fileRef; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getMimeType() { + return mimeType; + } + + public void setMimeType(String mimeType) { + this.mimeType = mimeType; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/ContactPair.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/ContactPair.java new file mode 100644 index 000000000..f20701af4 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/ContactPair.java @@ -0,0 +1,33 @@ +package eu.eudat.commons.types.notification; + + +import eu.eudat.commons.enums.ContactInfoType; + +public class ContactPair { + private ContactInfoType type; + private String Contact; + + public ContactPair(ContactInfoType type, String contact) { + this.type = type; + Contact = contact; + } + + public ContactPair() { + } + + public ContactInfoType getType() { + return type; + } + + public void setType(ContactInfoType type) { + this.type = type; + } + + public String getContact() { + return Contact; + } + + public void setContact(String contact) { + Contact = contact; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/DataType.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/DataType.java new file mode 100644 index 000000000..2cfde8ed7 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/DataType.java @@ -0,0 +1,42 @@ +package eu.eudat.commons.types.notification; + +import com.fasterxml.jackson.annotation.JsonValue; + +import java.util.HashMap; +import java.util.Map; + +public enum DataType { + Integer(0), + Decimal(1), + Double(2), + DateTime(3), + TimeSpan(4), + String(5); + private static final Map values = new HashMap<>(); + + private final Integer mappedName; + + //For jackson parsing (used by MVC) + @JsonValue + public Integer getMappedName() { + return mappedName; + } + + static { + for (DataType e : values()) { + values.put(e.asInt(), e); + } + } + + private DataType(int mappedName) { + this.mappedName = mappedName; + } + + public Integer asInt() { + return this.mappedName; + } + + public static DataType fromString(Integer value) { + return values.getOrDefault(value, Integer); + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/FieldInfo.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/FieldInfo.java new file mode 100644 index 000000000..c93a55261 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/FieldInfo.java @@ -0,0 +1,40 @@ +package eu.eudat.commons.types.notification; + +public class FieldInfo { + private String key; + private DataType type; + private String value; + + public FieldInfo(String key, DataType type, String value) { + this.key = key; + this.type = type; + this.value = value; + } + + public FieldInfo() { + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public DataType getType() { + return type; + } + + public void setType(DataType type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/InAppTrackingData.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/InAppTrackingData.java new file mode 100644 index 000000000..c2abd1f8d --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/InAppTrackingData.java @@ -0,0 +1,31 @@ +package eu.eudat.commons.types.notification; + +import java.util.List; +import java.util.UUID; + +public class InAppTrackingData { + + private UUID inAppNotificationId; + private List traces; + + public InAppTrackingData(UUID inAppNotificationId, List traces) { + this.inAppNotificationId = inAppNotificationId; + this.traces = traces; + } + + public UUID getInAppNotificationId() { + return inAppNotificationId; + } + + public void setInAppNotificationId(UUID inAppNotificationId) { + this.inAppNotificationId = inAppNotificationId; + } + + public List getTraces() { + return traces; + } + + public void setTraces(List traces) { + this.traces = traces; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/NotificationContactData.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/NotificationContactData.java new file mode 100644 index 000000000..a6d50efc5 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/NotificationContactData.java @@ -0,0 +1,39 @@ +package eu.eudat.commons.types.notification; + +import java.util.List; + +public class NotificationContactData { + private List contacts; + private List BCC; + private List CC; + + public NotificationContactData(List contacts, List BCC, List CC) { + this.contacts = contacts; + this.BCC = BCC; + this.CC = CC; + } + + public List getContacts() { + return contacts; + } + + public void setContacts(List contacts) { + this.contacts = contacts; + } + + public List getBCC() { + return BCC; + } + + public void setBCC(List BCC) { + this.BCC = BCC; + } + + public List getCC() { + return CC; + } + + public void setCC(List CC) { + this.CC = CC; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/NotificationFieldData.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/NotificationFieldData.java new file mode 100644 index 000000000..024f3aee7 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/NotificationFieldData.java @@ -0,0 +1,32 @@ +package eu.eudat.commons.types.notification; + +import java.util.List; + +public class NotificationFieldData { + private List fields; + private List attachments; + + public NotificationFieldData(List fields, List attachments) { + this.fields = fields; + this.attachments = attachments; + } + + public NotificationFieldData() { + } + + public List getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } + + public List getAttachments() { + return attachments; + } + + public void setAttachments(List attachments) { + this.attachments = attachments; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/RouteTrackingData.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/RouteTrackingData.java new file mode 100644 index 000000000..4b3a7003c --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/RouteTrackingData.java @@ -0,0 +1,30 @@ +package eu.eudat.commons.types.notification; + +import java.util.List; + +public class RouteTrackingData { + + private String trackingId; + private List traces; + + public RouteTrackingData(String trackingId, List traces) { + this.trackingId = trackingId; + this.traces = traces; + } + + public String getTrackingId() { + return trackingId; + } + + public void setTrackingId(String trackingId) { + this.trackingId = trackingId; + } + + public List getTraces() { + return traces; + } + + public void setTraces(List traces) { + this.traces = traces; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/TrackingTrace.java b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/TrackingTrace.java new file mode 100644 index 000000000..c0ed7eb2e --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/commons/types/notification/TrackingTrace.java @@ -0,0 +1,30 @@ +package eu.eudat.commons.types.notification; + +import java.time.Instant; + +public class TrackingTrace { + + private Instant at; + private String data; + + public TrackingTrace(Instant at, String data) { + this.at = at; + this.data = data; + } + + public Instant getAt() { + return at; + } + + public void setAt(Instant at) { + this.at = at; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationContactTypeConverter.java b/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationContactTypeConverter.java new file mode 100644 index 000000000..18eef5b44 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationContactTypeConverter.java @@ -0,0 +1,12 @@ +package eu.eudat.data.converters.enums.notification; + +import eu.eudat.commons.enums.notification.NotificationContactType; +import eu.eudat.data.converters.enums.DatabaseEnumConverter; +import jakarta.persistence.Converter; + +@Converter +public class NotificationContactTypeConverter extends DatabaseEnumConverter { + public NotificationContactType of(Short i) { + return NotificationContactType.of(i); + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationNotifyStateConverter.java b/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationNotifyStateConverter.java new file mode 100644 index 000000000..c1d8932af --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationNotifyStateConverter.java @@ -0,0 +1,12 @@ +package eu.eudat.data.converters.enums.notification; + +import eu.eudat.commons.enums.notification.NotificationNotifyState; +import eu.eudat.data.converters.enums.DatabaseEnumConverter; +import jakarta.persistence.Converter; + +@Converter +public class NotificationNotifyStateConverter extends DatabaseEnumConverter { + public NotificationNotifyState of(Short i) { + return NotificationNotifyState.of(i); + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationTrackingProcessConverter.java b/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationTrackingProcessConverter.java new file mode 100644 index 000000000..fd12ffcd7 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationTrackingProcessConverter.java @@ -0,0 +1,12 @@ +package eu.eudat.data.converters.enums.notification; + +import eu.eudat.commons.enums.notification.NotificationTrackingProcess; +import eu.eudat.data.converters.enums.DatabaseEnumConverter; +import jakarta.persistence.Converter; + +@Converter +public class NotificationTrackingProcessConverter extends DatabaseEnumConverter { + public NotificationTrackingProcess of(Short i) { + return NotificationTrackingProcess.of(i); + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationTrackingStateConverter.java b/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationTrackingStateConverter.java new file mode 100644 index 000000000..149e565df --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/data/converters/enums/notification/NotificationTrackingStateConverter.java @@ -0,0 +1,13 @@ +package eu.eudat.data.converters.enums.notification; + + +import eu.eudat.commons.enums.notification.NotificationTrackingState; +import eu.eudat.data.converters.enums.DatabaseEnumConverter; +import jakarta.persistence.Converter; + +@Converter +public class NotificationTrackingStateConverter extends DatabaseEnumConverter { + public NotificationTrackingState of(Short i) { + return NotificationTrackingState.of(i); + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/data/notification/NotificationEntity.java b/dmp-backend/core/src/main/java/eu/eudat/data/notification/NotificationEntity.java new file mode 100644 index 000000000..a4815efc0 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/data/notification/NotificationEntity.java @@ -0,0 +1,225 @@ +package eu.eudat.data.notification; + + +import eu.eudat.commons.enums.IsActive; +import eu.eudat.commons.enums.notification.NotificationContactType; +import eu.eudat.commons.enums.notification.NotificationNotifyState; +import eu.eudat.commons.enums.notification.NotificationTrackingProcess; +import eu.eudat.commons.enums.notification.NotificationTrackingState; +import eu.eudat.data.converters.enums.IsActiveConverter; +import eu.eudat.data.converters.enums.notification.NotificationContactTypeConverter; +import eu.eudat.data.converters.enums.notification.NotificationNotifyStateConverter; +import eu.eudat.data.converters.enums.notification.NotificationTrackingProcessConverter; +import eu.eudat.data.converters.enums.notification.NotificationTrackingStateConverter; +import eu.eudat.data.tenant.TenantScopedBaseEntity; +import jakarta.persistence.*; +import jakarta.persistence.Table; + +import java.time.Instant; +import java.util.UUID; + +@Entity +@Table(name = "\"ntf_Notification\"") +public class NotificationEntity extends TenantScopedBaseEntity { + + public static class Field { + public final static String _id = "id"; + public static final String _userId = "userId"; + public static final String _type = "type"; + public static final String _contactTypeHint = "contactTypeHint"; + public static final String _contactHint = "contactHint"; + public final static String _notifiedAt = "notifiedAt"; + public final static String _isActive = "isActive"; + public final static String _createdAt = "createdAt"; + public final static String _updatedAt = "updatedAt"; + public final static String _data = "data"; + public final static String _retryCount = "retryCount"; + public final static String _notifyState = "notifyState"; + public final static String _notifiedWith = "notifiedWith"; + public final static String _trackingState = "trackingState"; + public final static String _trackingProcess = "trackingProcess"; + public final static String _trackingData = "trackingData"; + } + + @Id + @Column(name = "\"id\"", columnDefinition = "uuid", updatable = false, nullable = false) + private UUID id; + + @Column(name = "\"user\"", columnDefinition = "uuid") + private UUID userId; + + @Column(name = "\"type\"", columnDefinition = "uuid", nullable = false) + private UUID type; + + @Column(name = "\"contact_type_hint\"") + @Convert(converter = NotificationContactTypeConverter.class) + private NotificationContactType contactTypeHint; + + @Column(name = "\"contact_hint\"") + private String contactHint; + + @Column(name = "\"notify_state\"", nullable = false) + @Convert(converter = NotificationNotifyStateConverter.class) + private NotificationNotifyState notifyState; + + @Column(name = "\"notified_with\"") + @Convert(converter = NotificationContactTypeConverter.class) + private NotificationContactType notifiedWith; + @Column(name = "\"notified_at\"") + private Instant notifiedAt; + + @Column(name = "\"data\"") + private String data; + + @Column(name = "\"retry_count\"") + private Integer retryCount; + + @Column(name = "\"is_active\"", length = 20, nullable = false) + @Convert(converter = IsActiveConverter.class) + private IsActive isActive; + + @Column(name = "\"created_at\"", nullable = false) + private Instant createdAt; + + @Column(name = "\"updated_at\"", nullable = false) + private Instant updatedAt; + + @Column(name = "\"tracking_state\"", nullable = false) + @Convert(converter = NotificationTrackingStateConverter.class) + private NotificationTrackingState trackingState; + + @Column(name = "\"tracking_process\"", nullable = false) + @Convert(converter = NotificationTrackingProcessConverter.class) + private NotificationTrackingProcess trackingProcess; + + @Column(name = "\"tracking_data\"") + private String trackingData; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public UUID getType() { + return type; + } + + public void setType(UUID type) { + this.type = type; + } + + public NotificationContactType getContactTypeHint() { + return contactTypeHint; + } + + public void setContactTypeHint(NotificationContactType contactTypeHint) { + this.contactTypeHint = contactTypeHint; + } + + public String getContactHint() { + return contactHint; + } + + public void setContactHint(String contactHint) { + this.contactHint = contactHint; + } + + public NotificationContactType getNotifiedWith() { + return notifiedWith; + } + + public void setNotifiedWith(NotificationContactType notifiedWith) { + this.notifiedWith = notifiedWith; + } + + public NotificationNotifyState getNotifyState() { + return notifyState; + } + + public void setNotifyState(NotificationNotifyState notifyState) { + this.notifyState = notifyState; + } + + public Instant getNotifiedAt() { + return notifiedAt; + } + + public void setNotifiedAt(Instant notifiedAt) { + this.notifiedAt = notifiedAt; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public Integer getRetryCount() { + return retryCount; + } + + public void setRetryCount(Integer retryCount) { + this.retryCount = retryCount; + } + + public IsActive getIsActive() { + return isActive; + } + + public void setIsActive(IsActive isActive) { + this.isActive = isActive; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public NotificationTrackingState getTrackingState() { + return trackingState; + } + + public void setTrackingState(NotificationTrackingState trackingState) { + this.trackingState = trackingState; + } + + public NotificationTrackingProcess getTrackingProcess() { + return trackingProcess; + } + + public void setTrackingProcess(NotificationTrackingProcess trackingProcess) { + this.trackingProcess = trackingProcess; + } + + public String getTrackingData() { + return trackingData; + } + + public void setTrackingData(String trackingData) { + this.trackingData = trackingData; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEvent.java b/dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEvent.java new file mode 100644 index 000000000..e39375d9a --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEvent.java @@ -0,0 +1,74 @@ +package eu.eudat.integrationevent.outbox.notification; + +import eu.eudat.commons.enums.notification.NotificationContactType; +import eu.eudat.commons.enums.old.notification.NotificationType; +import eu.eudat.integrationevent.TrackedEvent; + +import java.util.UUID; + +public class NotificationIntegrationEvent extends TrackedEvent { + + private UUID userId; + private UUID tenant; + private UUID notificationType; + private NotificationContactType contactTypeHint; + private String contactHint; + private String data; + private String provenanceRef; + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public UUID getTenant() { + return tenant; + } + + public void setTenant(UUID tenant) { + this.tenant = tenant; + } + + public UUID getNotificationType() { + return notificationType; + } + + public void setNotificationType(UUID notificationType) { + this.notificationType = notificationType; + } + + public NotificationContactType getContactTypeHint() { + return contactTypeHint; + } + + public void setContactTypeHint(NotificationContactType contactTypeHint) { + this.contactTypeHint = contactTypeHint; + } + + public String getContactHint() { + return contactHint; + } + + public void setContactHint(String contactHint) { + this.contactHint = contactHint; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public String getProvenanceRef() { + return provenanceRef; + } + + public void setProvenanceRef(String provenanceRef) { + this.provenanceRef = provenanceRef; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEventHandler.java b/dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEventHandler.java new file mode 100644 index 000000000..656aba6e7 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEventHandler.java @@ -0,0 +1,7 @@ +package eu.eudat.integrationevent.outbox.notification; + +import javax.management.InvalidApplicationException; + +public interface NotificationIntegrationEventHandler { + void handle(NotificationIntegrationEvent event) throws InvalidApplicationException; +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEventHandlerImpl.java b/dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEventHandlerImpl.java new file mode 100644 index 000000000..130d6b20d --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/integrationevent/outbox/notification/NotificationIntegrationEventHandlerImpl.java @@ -0,0 +1,106 @@ +package eu.eudat.integrationevent.outbox.notification; + + +import eu.eudat.audit.AuditableAction; +import eu.eudat.commons.enums.ContactInfoType; +import eu.eudat.commons.enums.notification.NotificationContactType; +import eu.eudat.commons.enums.notification.NotificationNotifyState; +import eu.eudat.commons.enums.notification.NotificationTrackingProcess; +import eu.eudat.commons.enums.notification.NotificationTrackingState; +import eu.eudat.data.UserContactInfoEntity; +import eu.eudat.data.UserEntity; +import eu.eudat.integrationevent.outbox.OutboxIntegrationEvent; +import eu.eudat.integrationevent.outbox.OutboxService; +import eu.eudat.model.persist.notification.NotificationPersist; +import eu.eudat.query.UserContactInfoQuery; +import eu.eudat.query.UserQuery; +import eu.eudat.service.notification.NotificationService; +import gr.cite.tools.auditing.AuditService; +import gr.cite.tools.data.query.QueryFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.validation.ValidationService; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.context.annotation.RequestScope; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +@Component +@RequestScope +public class NotificationIntegrationEventHandlerImpl implements NotificationIntegrationEventHandler { + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationIntegrationEventHandlerImpl.class)); + private final NotificationService notificationService; + private final ValidationService validationService; + private final QueryFactory queryFactory; + private final AuditService auditService; + private final OutboxService outboxService; + + @Autowired + public NotificationIntegrationEventHandlerImpl( + OutboxService outboxService, + NotificationService notificationService, + ValidationService validationService, + QueryFactory queryFactory, + AuditService auditService) { + this.outboxService = outboxService; + this.notificationService = notificationService; + this.validationService = validationService; + this.queryFactory = queryFactory; + this.auditService = auditService; + } + + @Override + public void handle(NotificationIntegrationEvent event) throws InvalidApplicationException { +// OutboxIntegrationEvent message = new OutboxIntegrationEvent(); +// message.setMessageId(UUID.randomUUID()); +// message.setType(OutboxIntegrationEvent.NOTIFY); +// message.setEvent(event); +// this.outboxService.publish(message); + NotificationPersist persist = new NotificationPersist(); + persist.setType(event.getNotificationType()); + persist.setUserId(event.getUserId()); + persist.setContactHint(event.getContactHint()); + persist.setContactTypeHint(event.getContactTypeHint()); + persist.setData(event.getData()); + persist.setNotifyState(NotificationNotifyState.PENDING); + persist.setNotifiedWith(NotificationContactType.EMAIL); + persist.setRetryCount(0); + persist.setTrackingState(NotificationTrackingState.UNDEFINED); + persist.setTrackingProcess(NotificationTrackingProcess.PENDING); + persist.setTrackingData(null); + persist.setProvenanceRef(event.getProvenanceRef()); + persist.setNotifiedAt(Instant.now()); + //validationService.validateForce(persist); + if (isNotificationConsistent(persist)) { + notificationService.persist(persist, null); + auditService.track(AuditableAction.Notification_Persist, "notification_event", event); + } + } + + private boolean isNotificationConsistent(NotificationPersist notification) { + switch (notification.getContactTypeHint()){ + case IN_APP:{ + if (notification.getUserId() == null) return false; + + List users = this.queryFactory.query(UserQuery.class).ids(notification.getUserId()).collect(); + return users.size() > 0; + } + case EMAIL:{ + if (notification.getContactHint() != null && !notification.getContactHint().isBlank()) return true; + + if (notification.getUserId() == null) return false; + + List userContactInfoEntities = this.queryFactory.query(UserContactInfoQuery.class).types(ContactInfoType.Email).userIds(notification.getUserId()).collect(); + return userContactInfoEntities.size() > 0; + } + default: + throw new MyApplicationException("invalid type " + notification.getContactTypeHint()); + + } + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/model/persist/notification/NotificationPersist.java b/dmp-backend/core/src/main/java/eu/eudat/model/persist/notification/NotificationPersist.java new file mode 100644 index 000000000..358556800 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/model/persist/notification/NotificationPersist.java @@ -0,0 +1,169 @@ +package eu.eudat.model.persist.notification; + +import eu.eudat.commons.enums.notification.NotificationContactType; +import eu.eudat.commons.enums.notification.NotificationNotifyState; +import eu.eudat.commons.enums.notification.NotificationTrackingProcess; +import eu.eudat.commons.enums.notification.NotificationTrackingState; +import eu.eudat.commons.validation.FieldNotNullIfOtherSet; +import eu.eudat.commons.validation.ValidId; +import jakarta.validation.constraints.NotNull; + + +import java.time.Instant; +import java.util.UUID; + +@FieldNotNullIfOtherSet(message = "{validation.hashempty}") +public class NotificationPersist { + + @ValidId(message = "{validation.invalidid}") + private UUID id; + + @NotNull(message = "{validation.empty}") + private UUID userId; + + private UUID type; + + private NotificationContactType contactTypeHint; + + private String contactHint; + + private String data; + + private NotificationNotifyState notifyState; + + private NotificationContactType notifiedWith; + + private Integer retryCount; + + private NotificationTrackingState trackingState; + + private NotificationTrackingProcess trackingProcess; + + private String trackingData; + + private String provenanceRef; + + private Instant notifiedAt; + + private String hash; + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + public UUID getUserId() { + return userId; + } + + public void setUserId(UUID userId) { + this.userId = userId; + } + + public UUID getType() { + return type; + } + + public void setType(UUID type) { + this.type = type; + } + + public NotificationContactType getContactTypeHint() { + return contactTypeHint; + } + + public void setContactTypeHint(NotificationContactType contactTypeHint) { + this.contactTypeHint = contactTypeHint; + } + + public String getContactHint() { + return contactHint; + } + + public void setContactHint(String contactHint) { + this.contactHint = contactHint; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public NotificationNotifyState getNotifyState() { + return notifyState; + } + + public void setNotifyState(NotificationNotifyState notifyState) { + this.notifyState = notifyState; + } + + public NotificationContactType getNotifiedWith() { + return notifiedWith; + } + + public void setNotifiedWith(NotificationContactType notifiedWith) { + this.notifiedWith = notifiedWith; + } + + public Integer getRetryCount() { + return retryCount; + } + + public void setRetryCount(Integer retryCount) { + this.retryCount = retryCount; + } + + public NotificationTrackingState getTrackingState() { + return trackingState; + } + + public void setTrackingState(NotificationTrackingState trackingState) { + this.trackingState = trackingState; + } + + public NotificationTrackingProcess getTrackingProcess() { + return trackingProcess; + } + + public void setTrackingProcess(NotificationTrackingProcess trackingProcess) { + this.trackingProcess = trackingProcess; + } + + public String getTrackingData() { + return trackingData; + } + + public void setTrackingData(String trackingData) { + this.trackingData = trackingData; + } + + public String getProvenanceRef() { + return provenanceRef; + } + + public void setProvenanceRef(String provenanceRef) { + this.provenanceRef = provenanceRef; + } + + public Instant getNotifiedAt() { + return notifiedAt; + } + + public void setNotifiedAt(Instant notifiedAt) { + this.notifiedAt = notifiedAt; + } + + public String getHash() { + return hash; + } + + public void setHash(String hash) { + this.hash = hash; + } +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/descriptiontemplate/DescriptionTemplateServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/descriptiontemplate/DescriptionTemplateServiceImpl.java index 8a55703a6..0fba396ff 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/descriptiontemplate/DescriptionTemplateServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/descriptiontemplate/DescriptionTemplateServiceImpl.java @@ -6,15 +6,20 @@ import eu.eudat.authorization.Permission; import eu.eudat.commons.JsonHandlingService; import eu.eudat.commons.XmlHandlingService; import eu.eudat.commons.enums.*; +import eu.eudat.commons.enums.notification.NotificationContactType; +import eu.eudat.commons.scope.tenant.TenantScope; import eu.eudat.commons.scope.user.UserScope; import eu.eudat.commons.types.descriptiontemplate.*; import eu.eudat.commons.types.descriptiontemplate.fielddata.BaseFieldDataEntity; import eu.eudat.commons.types.descriptiontemplate.importexport.*; +import eu.eudat.commons.types.notification.*; import eu.eudat.convention.ConventionService; import eu.eudat.data.DescriptionTemplateEntity; import eu.eudat.data.UserDescriptionTemplateEntity; import eu.eudat.data.UserEntity; import eu.eudat.errorcode.ErrorThesaurusProperties; +import eu.eudat.integrationevent.outbox.notification.NotificationIntegrationEvent; +import eu.eudat.integrationevent.outbox.notification.NotificationIntegrationEventHandler; import eu.eudat.model.DescriptionTemplate; import eu.eudat.model.UserContactInfo; import eu.eudat.model.builder.DescriptionTemplateBuilder; @@ -34,8 +39,6 @@ import eu.eudat.query.UserContactInfoQuery; import eu.eudat.query.UserDescriptionTemplateQuery; import eu.eudat.service.fielddatahelper.FieldDataHelperService; import eu.eudat.service.fielddatahelper.FieldDataHelperServiceProvider; -import eu.eudat.service.mail.MailService; -import eu.eudat.service.mail.SimpleMail; import eu.eudat.service.responseutils.ResponseUtilsService; import eu.eudat.service.storage.StorageFileService; import gr.cite.commons.web.authz.service.AuthorizationService; @@ -67,10 +70,7 @@ import org.xml.sax.SAXException; import javax.management.InvalidApplicationException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; -import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.ArrayList; @@ -100,11 +100,12 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic private final QueryFactory queryFactory; private final ErrorThesaurusProperties errors; private final ValidationService validationService; - private final MailService mailService; + private final TenantScope tenantScope; private final Environment environment; private final ResponseUtilsService responseUtilsService; private final StorageFileService storageFileService; private final JsonHandlingService jsonHandlingService; + private final NotificationIntegrationEventHandler eventHandler; @Autowired public DescriptionTemplateServiceImpl( @@ -115,7 +116,7 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic ConventionService conventionService, MessageSource messageSource, XmlHandlingService xmlHandlingService, - FieldDataHelperServiceProvider fieldDataHelperServiceProvider, QueryFactory queryFactory, ErrorThesaurusProperties errors, ValidationService validationService, MailService mailService, Environment environment, ResponseUtilsService responseUtilsService, StorageFileService storageFileService, JsonHandlingService jsonHandlingService) { + FieldDataHelperServiceProvider fieldDataHelperServiceProvider, QueryFactory queryFactory, ErrorThesaurusProperties errors, ValidationService validationService, TenantScope tenantScope, Environment environment, ResponseUtilsService responseUtilsService, StorageFileService storageFileService, JsonHandlingService jsonHandlingService, NotificationIntegrationEventHandler eventHandler) { this.entityManager = entityManager; this.userScope = userScope; this.authorizationService = authorizationService; @@ -128,11 +129,12 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic this.queryFactory = queryFactory; this.errors = errors; this.validationService = validationService; - this.mailService = mailService; + this.tenantScope = tenantScope; this.environment = environment; this.responseUtilsService = responseUtilsService; this.storageFileService = storageFileService; this.jsonHandlingService = jsonHandlingService; + this.eventHandler = eventHandler; } //region Persist @@ -204,26 +206,32 @@ public class DescriptionTemplateServiceImpl implements DescriptionTemplateServic this.deleterFactory.deleter(UserDescriptionTemplateDeleter.class).delete(toDelete); } - private void sendJoinMail(UserDescriptionTemplateEntity userDatasetProfile) { - SimpleMail mail = new SimpleMail(); + private void sendJoinMail(UserDescriptionTemplateEntity userDatasetProfile) throws InvalidApplicationException { + NotificationIntegrationEvent event = new NotificationIntegrationEvent(); + event.setTenant(tenantScope.getTenant()); + event.setUserId(userScope.getUserIdSafe()); + UserEntity user = this.entityManager.find(UserEntity.class, userDatasetProfile.getUserId()); DescriptionTemplateEntity descriptionTemplate = this.queryFactory.query(DescriptionTemplateQuery.class).isActive(IsActive.Active).ids(userDatasetProfile.getDescriptionTemplateId()).first(); - mail.setSubject(environment.getProperty("admin.mail.subject").replace( "{templateName}", descriptionTemplate.getLabel())); - String content = this.mailService.getMailTemplateContent(environment.getProperty("email.dataset.template")); - content = content.replace("{recipient}", user.getName()); - content = content.replace("{templateName}", descriptionTemplate.getLabel()); - content = content.replace("{host}", this.environment.getProperty("dmp.domain")); - content = content.replace("{templateID}", descriptionTemplate.getId().toString()); - mail.setContent(content); UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); - mail.setTo(query.first().getValue()); - try { - this.mailService.sendSimpleMail(mail); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } + + List contactPairs = new ArrayList<>(); + contactPairs.add(new ContactPair(ContactInfoType.Email, query.first().getValue())); + NotificationContactData contactData = new NotificationContactData(contactPairs, null, null); + event.setContactHint(jsonHandlingService.toJsonSafe(contactData)); + event.setContactTypeHint(NotificationContactType.EMAIL); + event.setNotificationType(UUID.fromString("223BB607-EFA1-4CE7-99EC-4BEABFEF9A8B")); + NotificationFieldData data = new NotificationFieldData(); + List fieldInfoList = new ArrayList<>(); + fieldInfoList.add(new FieldInfo("{recipient}", DataType.String, user.getName())); + fieldInfoList.add(new FieldInfo("{templateName}", DataType.String, descriptionTemplate.getLabel())); + fieldInfoList.add(new FieldInfo("{host}", DataType.String, this.environment.getProperty("dmp.domain"))); + fieldInfoList.add(new FieldInfo("{templateID}", DataType.String, descriptionTemplate.getId().toString())); + data.setFields(fieldInfoList); + event.setData(jsonHandlingService.toJsonSafe(data)); + eventHandler.handle(event); } private void addOwner(DescriptionTemplateEntity descriptionTemplateEntity) throws InvalidApplicationException { diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/lock/LockService.java b/dmp-backend/core/src/main/java/eu/eudat/service/lock/LockService.java index 48d2591a6..32e603ad8 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/lock/LockService.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/lock/LockService.java @@ -16,9 +16,9 @@ public interface LockService { Lock persist(LockPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException; - boolean isLocked(LockLookup lookup) throws InvalidApplicationException; + boolean isLocked(UUID target) throws InvalidApplicationException; - void unlock(LockLookup lookup) throws InvalidApplicationException; + void unlock(UUID target) throws InvalidApplicationException; void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException; } diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/lock/LockServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/lock/LockServiceImpl.java index 8d4327940..db83d6bad 100644 --- a/dmp-backend/core/src/main/java/eu/eudat/service/lock/LockServiceImpl.java +++ b/dmp-backend/core/src/main/java/eu/eudat/service/lock/LockServiceImpl.java @@ -107,35 +107,32 @@ public class LockServiceImpl implements LockService { return this.builderFactory.builder(LockBuilder.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).build(BaseFieldSet.build(fields, Lock._id), data); } - public boolean isLocked(LockLookup lookup) throws InvalidApplicationException { - if (lookup !=null && lookup.getTargetIds() != null && lookup.getTargetIds().size() > 0){ - LockQuery query = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).targetIds(lookup.getTargetIds()); - if (query.count() == 1) { - LockEntity lock = query.firstAs(lookup.getProject()); - if (lock.getLockedBy().equals(this.userScope.getUserId())) { - lock.setTouchedAt(Instant.now()); - this.entityManager.merge(lock); - this.entityManager.flush(); - return false; - } - return this.forceUnlock(lookup) > 0; - } else if (query.count() > 1) { - this.forceUnlock(lookup); - return this.isLocked(lookup); + public boolean isLocked(UUID target) throws InvalidApplicationException { + LockQuery query = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).targetIds(target); + if (query.count() == 1) { + LockEntity lock = query.first(); + if (lock.getLockedBy().equals(this.userScope.getUserId())) { + lock.setTouchedAt(Instant.now()); + this.entityManager.merge(lock); + this.entityManager.flush(); + return false; } - return false; - } else{ - throw new InvalidApplicationException("Wrong LockLookup"); + return this.forceUnlock(target) > 0; + } else if (query.count() > 1) { + this.forceUnlock(target); + return this.isLocked(target); } + return false; + } - private Long forceUnlock(LockLookup lookup) throws InvalidApplicationException { + private Long forceUnlock(UUID target) throws InvalidApplicationException { - LockQuery query = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).targetIds(lookup.getTargetIds()); + LockQuery query = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).targetIds(target); Long availableLocks = query.count(); long deletedLocks = 0L; if (availableLocks > 0) { - List locks = query.collectAs(lookup.getProject()); + List locks = query.collect(); for (LockEntity lock : locks) { if (new Date().getTime() - Date.from(lock.getTouchedAt()).getTime() > 120000) { this.deleteAndSave(lock.getId()); @@ -155,17 +152,17 @@ public class LockServiceImpl implements LockService { return availableLocks - deletedLocks; } - public void unlock(LockLookup lookup) throws InvalidApplicationException { + public void unlock(UUID target) throws InvalidApplicationException { - LockQuery query = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).targetIds(lookup.getTargetIds()); + LockQuery query = this.queryFactory.query(LockQuery.class).authorize(AuthorizationFlags.OwnerOrDmpAssociatedOrPermissionOrPublic).targetIds(target); if (query.count() == 1) { - LockEntity lock = query.firstAs(lookup.getProject()); + LockEntity lock = query.first(); if (!lock.getLockedBy().equals(this.userScope.getUserId())) { throw new InvalidApplicationException("Only the user who created that lock can delete it"); } this.deleteAndSave(lock.getId()); } else if (query.count() > 1) { - List locks = query.collectAs(lookup.getProject()); + List locks = query.collect(); locks.stream().filter(lock -> lock.getLockedBy().equals(this.userScope.getUserIdSafe())).forEach(lock -> { try { this.deleteAndSave(lock.getId()); diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/mail/MailService.java b/dmp-backend/core/src/main/java/eu/eudat/service/mail/MailService.java deleted file mode 100644 index aa6c087a3..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/mail/MailService.java +++ /dev/null @@ -1,12 +0,0 @@ -package eu.eudat.service.mail; - -import jakarta.mail.MessagingException; - - -public interface MailService { - void sendSimpleMail(SimpleMail mail) throws MessagingException; - - String getMailTemplateContent(String resourceTemplate); - - String getMailTemplateSubject(); -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/mail/MailServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/mail/MailServiceImpl.java deleted file mode 100644 index db652f312..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/mail/MailServiceImpl.java +++ /dev/null @@ -1,140 +0,0 @@ -package eu.eudat.service.mail; - -import jakarta.mail.BodyPart; -import jakarta.mail.Message; -import jakarta.mail.MessagingException; -import jakarta.mail.internet.MimeBodyPart; -import jakarta.mail.internet.MimeMessage; -import jakarta.mail.internet.MimeMultipart; -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.core.env.Environment; -import org.springframework.core.io.Resource; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.stereotype.Service; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - - -@Service("mailService") -public class MailServiceImpl implements MailService { - private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class); - - private Environment env; - - private JavaMailSender emailSender; - - private ApplicationContext applicationContext; - - @Autowired - public MailServiceImpl(Environment env, JavaMailSender emailSender, ApplicationContext applicationContext) { - this.env = env; - this.emailSender = emailSender; - this.applicationContext = applicationContext; - } - - @Override - public void sendSimpleMail(SimpleMail mail) throws MessagingException { - List imageSources = parseImages(mail.getContent()); - List cids = new ArrayList<>(); - if (!imageSources.isEmpty()) { - for (int i = 0; i < imageSources.size(); i++) { - cids.add(UUID.randomUUID().toString()); - } - mail.setContent(replaceImageSources(mail.getContent(), cids)); - } - MimeMultipart content = new MimeMultipart("related"); - BodyPart messageBodyPart = new MimeBodyPart(); - messageBodyPart.setContent(mail.getContent(), "text/html; charset=UTF-8"); - content.addBodyPart(messageBodyPart); - if (!imageSources.isEmpty()) { - for (int i =0; i < imageSources.size(); i++) { - MimeBodyPart imagePart = new MimeBodyPart(); - try { - imagePart.attachFile(applicationContext.getResource(imageSources.get(i)).getFile()); - imagePart.setContentID("<" + cids.get(i) + ">"); - imagePart.setDisposition(MimeBodyPart.INLINE); - content.addBodyPart(imagePart); - } catch (IOException | MessagingException e) { - logger.error(e.getMessage(), e); - } - } - } - MimeMessage message = this.emailSender.createMimeMessage(); - message.setSubject(mail.getSubject()); - message.setContent(content); - message.addRecipients(Message.RecipientType.TO, mail.getTo()); - message.setFrom(env.getProperty("mail.from")); - this.emailSender.send(message); - } - - public Environment getEnv() { - return env; - } - - @Override - public String getMailTemplateContent(String resourceTemplate) { - Resource resource = applicationContext.getResource(resourceTemplate); - try { - InputStream inputStream = resource.getInputStream(); - StringWriter writer = new StringWriter(); - IOUtils.copy(inputStream, writer, "UTF-8"); - inputStream.close(); - return writer.toString(); - } catch (IOException e) { - logger.error(e.getMessage(), e); - } - return ""; - } - - @Override - public String getMailTemplateSubject() { - return env.getProperty("mail.subject"); - } - - private List parseImages(String content) { - List imagePaths = new ArrayList<>(); - - int lastIndex = 0; - - while (lastIndex != -1) { - lastIndex = content.indexOf("img src=\"", lastIndex); - - if (lastIndex != -1) { - String imagePath = content.substring(lastIndex + 9, content.indexOf("\"", lastIndex + 9)); - if (!imagePath.contains("data:image/png;base64")) { - imagePaths.add(imagePath); - } - lastIndex++; - } - } - - return imagePaths; - } - - private String replaceImageSources(String content, List cids) { - - int lastIndex = 0; - int cidIndex = 0; - - while (lastIndex != -1) { - lastIndex = content.indexOf("img src=\"", lastIndex); - - if (lastIndex != -1) { - content = content.replace(content.substring(lastIndex + 9, content.indexOf("\"", lastIndex + 9)), "cid:" + cids.get(cidIndex)); - lastIndex ++; - cidIndex ++; - } - } - - return content; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/mail/SimpleMail.java b/dmp-backend/core/src/main/java/eu/eudat/service/mail/SimpleMail.java deleted file mode 100644 index 06812a579..000000000 --- a/dmp-backend/core/src/main/java/eu/eudat/service/mail/SimpleMail.java +++ /dev/null @@ -1,51 +0,0 @@ -package eu.eudat.service.mail; - - -public class SimpleMail { - private String from; - private String to; - private String subject; - private String content; - - public SimpleMail() { - } - - public SimpleMail(String from, String to, String subject, String content) { - this.from = from; - this.to = to; - this.subject = subject; - this.content = content; - } - - public String getFrom() { - return from; - } - - public void setFrom(String from) { - this.from = from; - } - - public String getTo() { - return to; - } - - public void setTo(String to) { - this.to = to; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } -} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/notification/NotificationService.java b/dmp-backend/core/src/main/java/eu/eudat/service/notification/NotificationService.java new file mode 100644 index 000000000..664ab13cf --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/notification/NotificationService.java @@ -0,0 +1,16 @@ +package eu.eudat.service.notification; + +import eu.eudat.model.persist.notification.NotificationPersist; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.exception.MyForbiddenException; +import gr.cite.tools.exception.MyNotFoundException; +import gr.cite.tools.exception.MyValidationException; +import gr.cite.tools.fieldset.FieldSet; + +import javax.management.InvalidApplicationException; + +public interface NotificationService{ + + void persist(NotificationPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException; + +} diff --git a/dmp-backend/core/src/main/java/eu/eudat/service/notification/NotificationServiceImpl.java b/dmp-backend/core/src/main/java/eu/eudat/service/notification/NotificationServiceImpl.java new file mode 100644 index 000000000..818e5a1d0 --- /dev/null +++ b/dmp-backend/core/src/main/java/eu/eudat/service/notification/NotificationServiceImpl.java @@ -0,0 +1,106 @@ +package eu.eudat.service.notification; + +import eu.eudat.authorization.Permission; +import eu.eudat.commons.enums.IsActive; +import eu.eudat.convention.ConventionService; +import eu.eudat.data.TenantEntityManager; +import eu.eudat.data.notification.NotificationEntity; +import eu.eudat.errorcode.ErrorThesaurusProperties; +import eu.eudat.model.persist.notification.NotificationPersist; +import gr.cite.commons.web.authz.service.AuthorizationService; +import gr.cite.tools.data.builder.BuilderFactory; +import gr.cite.tools.data.deleter.DeleterFactory; +import gr.cite.tools.exception.MyApplicationException; +import gr.cite.tools.exception.MyForbiddenException; +import gr.cite.tools.exception.MyNotFoundException; +import gr.cite.tools.exception.MyValidationException; +import gr.cite.tools.fieldset.BaseFieldSet; +import gr.cite.tools.fieldset.FieldSet; +import gr.cite.tools.logging.LoggerService; +import gr.cite.tools.logging.MapLogEntry; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.stereotype.Service; +import org.springframework.web.context.annotation.RequestScope; + +import javax.management.InvalidApplicationException; +import java.time.Instant; +import java.util.UUID; + +@Service +@RequestScope +public class NotificationServiceImpl implements NotificationService { + + private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(NotificationServiceImpl.class)); + private final TenantEntityManager entityManager; + private final AuthorizationService authorizationService; + private final DeleterFactory deleterFactory; + private final BuilderFactory builderFactory; + private final ConventionService conventionService; + private final ErrorThesaurusProperties errors; + private final MessageSource messageSource; + + @Autowired + public NotificationServiceImpl( + TenantEntityManager entityManager, + AuthorizationService authorizationService, + DeleterFactory deleterFactory, + BuilderFactory builderFactory, + ConventionService conventionService, + ErrorThesaurusProperties errors, + MessageSource messageSource + ) { + this.entityManager = entityManager; + this.authorizationService = authorizationService; + this.deleterFactory = deleterFactory; + this.builderFactory = builderFactory; + this.conventionService = conventionService; + this.errors = errors; + this.messageSource = messageSource; + } + + @Override + public void persist(NotificationPersist model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException { + logger.debug(new MapLogEntry("persisting notification").And("model", model).And("fields", fields)); + + //this.authorizationService.authorizeForce(Permission.AuthenticatedRole); + + Boolean isUpdate = this.conventionService.isValidGuid(model.getId()); + + NotificationEntity data = null; + if (isUpdate) { + data = this.entityManager.find(NotificationEntity.class, model.getId()); + if (data == null) throw new MyNotFoundException(messageSource.getMessage("General_ItemNotFound", new Object[]{model.getId(), NotificationEntity.class.getSimpleName()}, LocaleContextHolder.getLocale())); + if (!this.conventionService.hashValue(data.getUpdatedAt()).equals(model.getHash())) throw new MyValidationException(this.errors.getHashConflict().getCode(), this.errors.getHashConflict().getMessage()); + } else { + data = new NotificationEntity(); + data.setId(UUID.randomUUID()); + data.setIsActive(IsActive.Active); + data.setCreatedAt(Instant.now()); + } + + data.setNotifiedAt(model.getNotifiedAt()); + data.setContactHint(model.getContactHint()); + data.setContactTypeHint(model.getContactTypeHint()); + data.setType(model.getType()); + data.setUserId(model.getUserId()); + data.setData(model.getData()); + data.setNotifyState(model.getNotifyState()); + data.setNotifiedWith(model.getNotifiedWith()); + data.setRetryCount(model.getRetryCount()); + data.setTrackingState(model.getTrackingState()); + data.setTrackingProcess(model.getTrackingProcess()); + data.setTrackingData(model.getTrackingData()); +// data.setProvenanceRef(model.getProvenanceRef()); + data.setUpdatedAt(Instant.now()); + + if (isUpdate) this.entityManager.merge(data); + else this.entityManager.persist(data); + + this.entityManager.flush(); + + } + +} diff --git a/dmp-backend/notification-service/notification-web/src/main/resources/config/notification.yml b/dmp-backend/notification-service/notification-web/src/main/resources/config/notification.yml index a30eac93a..1e7a8897f 100644 --- a/dmp-backend/notification-service/notification-web/src/main/resources/config/notification.yml +++ b/dmp-backend/notification-service/notification-web/src/main/resources/config/notification.yml @@ -72,7 +72,7 @@ notification: optional: [ ] body-path: classpath:notification_templates/DataManagementPlan/Email/body.{language}.html body-field-options: - mandatory: [ "{dmpname}", "{dmprole}" ] + mandatory: [ "{dmpname}", "{dmprole}", "{host}", "{invitationID}" ] optional: - key: "{recipient}" value: @@ -116,7 +116,7 @@ notification: optional: [ ] body-path: classpath:notification_templates/MergeConfirmation/Email/body.{language}.html body-field-options: - mandatory: [ "{userName}", "{host}" ] + mandatory: [ "{userName}", "{host}", "{confirmationToken}" ] optional: - key: "{expiration_time}" value: --- @@ -204,7 +204,7 @@ notification: optional: [ ] body-path: classpath:notification_templates/Template/Email/body.{language}.html body-field-options: - mandatory: [ "{templateName}" ] + mandatory: [ "{templateName}", "{host}", "{templateID}" ] optional: - key: "{recipient}" value: @@ -221,7 +221,7 @@ notification: key: C9BC3F16-057E-4BBA-8A5F-36BD835E5604 subject-path: classpath:notification_templates/UnlinkConfirmation/Email/subject.{language}.txt subject-field-options: - mandatory: [ ] + mandatory: ["{host}", "{confirmationToken}"] optional: [ ] body-path: classpath:notification_templates/UnlinkConfirmation/Email/body.{language}.html body-field-options: diff --git a/dmp-backend/notification-service/notification-web/target/classes/config/notification.yml b/dmp-backend/notification-service/notification-web/target/classes/config/notification.yml index a30eac93a..1e7a8897f 100644 --- a/dmp-backend/notification-service/notification-web/target/classes/config/notification.yml +++ b/dmp-backend/notification-service/notification-web/target/classes/config/notification.yml @@ -72,7 +72,7 @@ notification: optional: [ ] body-path: classpath:notification_templates/DataManagementPlan/Email/body.{language}.html body-field-options: - mandatory: [ "{dmpname}", "{dmprole}" ] + mandatory: [ "{dmpname}", "{dmprole}", "{host}", "{invitationID}" ] optional: - key: "{recipient}" value: @@ -116,7 +116,7 @@ notification: optional: [ ] body-path: classpath:notification_templates/MergeConfirmation/Email/body.{language}.html body-field-options: - mandatory: [ "{userName}", "{host}" ] + mandatory: [ "{userName}", "{host}", "{confirmationToken}" ] optional: - key: "{expiration_time}" value: --- @@ -204,7 +204,7 @@ notification: optional: [ ] body-path: classpath:notification_templates/Template/Email/body.{language}.html body-field-options: - mandatory: [ "{templateName}" ] + mandatory: [ "{templateName}", "{host}", "{templateID}" ] optional: - key: "{recipient}" value: @@ -221,7 +221,7 @@ notification: key: C9BC3F16-057E-4BBA-8A5F-36BD835E5604 subject-path: classpath:notification_templates/UnlinkConfirmation/Email/subject.{language}.txt subject-field-options: - mandatory: [ ] + mandatory: ["{host}", "{confirmationToken}"] optional: [ ] body-path: classpath:notification_templates/UnlinkConfirmation/Email/body.{language}.html body-field-options: diff --git a/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/LockController.java b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/LockController.java index 67994b553..bc2bbcbe6 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/LockController.java +++ b/dmp-backend/web/src/main/java/eu/eudat/controllers/v2/LockController.java @@ -2,6 +2,7 @@ package eu.eudat.controllers.v2; import eu.eudat.audit.AuditableAction; import eu.eudat.authorization.AuthorizationFlags; +import eu.eudat.authorization.OwnedResource; import eu.eudat.authorization.Permission; import eu.eudat.data.LockEntity; import eu.eudat.model.Lock; @@ -65,6 +66,7 @@ public class LockController { private final MessageSource messageSource; private final AuthorizationService authorizationService; + private final AuthorizationService authService; @Autowired public LockController(BuilderFactory builderFactory, @@ -73,7 +75,7 @@ public class LockController { CensorFactory censorFactory, QueryFactory queryFactory, MessageSource messageSource, - AuthorizationService authorizationService) { + AuthorizationService authorizationService, AuthorizationService authService) { this.builderFactory = builderFactory; this.auditService = auditService; this.lockService = lockService; @@ -81,6 +83,7 @@ public class LockController { this.queryFactory = queryFactory; this.messageSource = messageSource; this.authorizationService = authorizationService; + this.authService = authService; } @PostMapping("query") @@ -155,19 +158,19 @@ public class LockController { @Transactional @PostMapping("target/status/{id}") - public @ResponseBody ResponseEntity> getLocked(@RequestBody LockLookup lookup) throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); + public @ResponseBody ResponseEntity> getLocked(@PathVariable("id") UUID targetId) throws Exception { + this.authService.authorizeAtLeastOneForce(targetId != null ? List.of(new OwnedResource(targetId)) : null, Permission.BrowseDmp); - boolean locked = this.lockService.isLocked(lookup); + boolean locked = this.lockService.isLocked(targetId); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("locked").payload(locked)); } @Transactional @PostMapping("target/unlock/{id}") - public @ResponseBody ResponseEntity> unlock(@RequestBody LockLookup lookup) throws Exception { - this.authorizationService.authorizeForce(Permission.AuthenticatedRole); + public @ResponseBody ResponseEntity> unlock(@PathVariable("id") UUID targetId) throws Exception { + this.authService.authorizeAtLeastOneForce(targetId != null ? List.of(new OwnedResource(targetId)) : null, Permission.BrowseDmp); - this.lockService.unlock(lookup); + this.lockService.unlock(targetId); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload("Lock Removed")); } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ContactEmailManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ContactEmailManager.java index d6f271d55..239ed6d38 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ContactEmailManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/ContactEmailManager.java @@ -8,7 +8,6 @@ import eu.eudat.models.data.ContactEmail.ContactEmailModel; import eu.eudat.models.data.ContactEmail.PublicContactEmailModel; import eu.eudat.query.UserContactInfoQuery; import eu.eudat.query.UserQuery; -import eu.eudat.service.mail.SimpleMail; import gr.cite.tools.data.query.Ordering; import gr.cite.tools.data.query.QueryFactory; import org.springframework.core.env.Environment; @@ -35,28 +34,28 @@ public class ContactEmailManager { } public void sendContactEmail(ContactEmailModel contactEmailModel) throws MessagingException, InvalidApplicationException { - UserEntity user = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first(); - SimpleMail mail = new SimpleMail(); - UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); - query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); - String enrichedMail = contactEmailModel.getDescription() + "\n\n" + "Send by user: " + query.first().getValue() ; - mail.setSubject(contactEmailModel.getSubject()); - mail.setTo(environment.getProperty("contact_email.mail")); - mail.setContent(enrichedMail); - mail.setFrom(query.first().getValue()); - - apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail); +// UserEntity user = this.queryFactory.query(UserQuery.class).ids(this.userScope.getUserId()).first(); +// SimpleMail mail = new SimpleMail(); +// UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); +// query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); +// String enrichedMail = contactEmailModel.getDescription() + "\n\n" + "Send by user: " + query.first().getValue() ; +// mail.setSubject(contactEmailModel.getSubject()); +// mail.setTo(environment.getProperty("contact_email.mail")); +// mail.setContent(enrichedMail); +// mail.setFrom(query.first().getValue()); +// +// apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail); } public void sendContactEmailNoAuth(PublicContactEmailModel contactEmailModel) throws MessagingException { - SimpleMail mail = new SimpleMail(); - String enrichedMail = contactEmailModel.getMessage() + "\n\n" + "Send by user: " + contactEmailModel.getEmail() ; - mail.setSubject(contactEmailModel.getAffiliation()); - mail.setTo(environment.getProperty("contact_email.mail")); - mail.setContent(enrichedMail); - mail.setFrom(contactEmailModel.getEmail()); - - apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail); +// SimpleMail mail = new SimpleMail(); +// String enrichedMail = contactEmailModel.getMessage() + "\n\n" + "Send by user: " + contactEmailModel.getEmail() ; +// mail.setSubject(contactEmailModel.getAffiliation()); +// mail.setTo(environment.getProperty("contact_email.mail")); +// mail.setContent(enrichedMail); +// mail.setFrom(contactEmailModel.getEmail()); +// +// apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail); } public void emailValidation(ContactEmailModel contactEmailModel) throws Exception { diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/EmailConfirmationManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/EmailConfirmationManager.java index b33baca6e..b562b887f 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/EmailConfirmationManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/EmailConfirmationManager.java @@ -75,12 +75,7 @@ public class EmailConfirmationManager { // if (user.getEmail() != null) //TODO // throw new HasConfirmedEmailException("User already has confirmed his Email."); - apiContext.getUtilitiesService().getConfirmationEmailService().createConfirmationEmail( - databaseRepository.getLoginConfirmationEmailDao(), - apiContext.getUtilitiesService().getMailService(), - email, - this.userScope.getUserId() - ); + apiContext.getUtilitiesService().getConfirmationEmailService().sentConfirmationEmail(email); } private void mergeNewUserToOld(UserEntity newUser, UserEntity oldUser) throws InvalidApplicationException { diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/NotificationManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/NotificationManager.java index 85fd36e4f..5397a2d7f 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/NotificationManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/NotificationManager.java @@ -7,8 +7,6 @@ import eu.eudat.commons.enums.old.notification.ActiveStatus; import eu.eudat.commons.enums.old.notification.NotifyState; import eu.eudat.logic.services.ApiContext; import eu.eudat.query.UserQuery; -import eu.eudat.service.mail.MailService; -import eu.eudat.service.mail.SimpleMail; import gr.cite.tools.data.query.QueryFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,14 +25,16 @@ public class NotificationManager { private ApiContext apiContext; private Environment environment; - private MailService mailService; +// private MailService mailService; private final QueryFactory queryFactory; @Autowired - public NotificationManager(ApiContext apiContext, Environment environment, MailService mailService, QueryFactory queryFactory) { + public NotificationManager(ApiContext apiContext, Environment environment, +// MailService mailService, + QueryFactory queryFactory) { this.apiContext = apiContext; this.environment = environment; - this.mailService = mailService; +// this.mailService = mailService; this.queryFactory = queryFactory; } @@ -64,20 +64,20 @@ public class NotificationManager { case DMP_MODIFIED: case DATASET_MODIFIED: subjectTemplate = this.environment.getProperty("notification.modified.subject"); - contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.modified.template")); +// contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.modified.template")); break; case DMP_PUBLISH: subjectTemplate = this.environment.getProperty("notification.publish.subject"); - contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.publish.template")); +// contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.publish.template")); break; case DMP_FINALISED: subjectTemplate = this.environment.getProperty("notification.finalised.subject"); - contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.finalised.template")); +// contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.finalised.template")); break; case DMP_MODIFIED_FINALISED: case DATASET_MODIFIED_FINALISED: subjectTemplate = this.environment.getProperty("notification.modifiedFinalised.subject"); - contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.modified_finalised.template")); +// contentTemplate = mailService.getMailTemplateContent(this.environment.getProperty("notification.modified_finalised.template")); break; } @@ -95,20 +95,20 @@ public class NotificationManager { } private void sendEmailNotification(Notification notification, UserEntity userInfo, Map data, String subjectTemplate, String contentTemplate) throws IOException { - SimpleMail simpleMail = new SimpleMail(); - simpleMail.setFrom(this.environment.getProperty("mail.from")); - simpleMail.setSubject(makeSubject(data, subjectTemplate)); - simpleMail.setTo(notification.getContactHint()); - simpleMail.setContent(makeContent(data, notification, userInfo, contentTemplate)); - try { - mailService.sendSimpleMail(simpleMail); - notification.setNotifyState(NotifyState.SUCCEEDED); - notification.setUpdatedAt(new Date()); - } catch (MessagingException e) { - notification.setNotifyState(NotifyState.ERROR); - notification.setUpdatedAt(new Date()); - logger.error(e.getMessage(), e); - } +// SimpleMail simpleMail = new SimpleMail(); +// simpleMail.setFrom(this.environment.getProperty("mail.from")); +// simpleMail.setSubject(makeSubject(data, subjectTemplate)); +// simpleMail.setTo(notification.getContactHint()); +// simpleMail.setContent(makeContent(data, notification, userInfo, contentTemplate)); +// try { +// mailService.sendSimpleMail(simpleMail); +// notification.setNotifyState(NotifyState.SUCCEEDED); +// notification.setUpdatedAt(new Date()); +// } catch (MessagingException e) { +// notification.setNotifyState(NotifyState.ERROR); +// notification.setUpdatedAt(new Date()); +// logger.error(e.getMessage(), e); +// } } private String makeSubject(Map data, String subjectTemplate) { diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UnlinkEmailConfirmationManager.java b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UnlinkEmailConfirmationManager.java index 37e66cf3b..84fc793d3 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UnlinkEmailConfirmationManager.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/managers/UnlinkEmailConfirmationManager.java @@ -79,14 +79,13 @@ public class UnlinkEmailConfirmationManager { // } } - public void sendConfirmationEmail(String email, UUID userId, Integer provider) throws InvalidApplicationException { + public void sendUnlinkConfirmationEmail(String email, UUID userId, Integer provider) throws InvalidApplicationException { UserEntity user = this.queryFactory.query(UserQuery.class).ids(userId).first(); UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); if (query.first().getValue() != null && !query.first().getValue().equals(email)) { - apiContext.getUtilitiesService().getConfirmationEmailService().createUnlinkConfirmationEmail( + apiContext.getUtilitiesService().getConfirmationEmailService().sentUnlinkConfirmationEmail( databaseRepository.getLoginConfirmationEmailDao(), - apiContext.getUtilitiesService().getMailService(), email, user, provider diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailService.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailService.java index 80ef61a56..3a844ce42 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailService.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailService.java @@ -1,24 +1,15 @@ package eu.eudat.logic.services.utilities; import eu.eudat.data.dao.entities.EmailConfirmationDao; -import eu.eudat.data.old.EmailConfirmation; import eu.eudat.data.UserEntity; -import eu.eudat.service.mail.MailService; import javax.management.InvalidApplicationException; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; + public interface ConfirmationEmailService { - public void createConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId); - - public void createMergeConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UserEntity user, Integer provider) throws InvalidApplicationException; + public void sentConfirmationEmail(String email) throws InvalidApplicationException; - public void createUnlinkConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UserEntity user, Integer provider) throws InvalidApplicationException; + public void sentUnlinkConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, String email, UserEntity user, Integer provider) throws InvalidApplicationException; - public CompletableFuture sentConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService); - - public CompletableFuture sentMergeConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService, String userName); - - public CompletableFuture sentUnlinkConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService); + public void sentMergeConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, String email, UserEntity user, Integer provider) throws InvalidApplicationException; } \ No newline at end of file diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailServiceImpl.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailServiceImpl.java index 009b131dd..cb46835ba 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailServiceImpl.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/ConfirmationEmailServiceImpl.java @@ -1,16 +1,19 @@ package eu.eudat.logic.services.utilities; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.commons.JsonHandlingService; +import eu.eudat.commons.enums.ContactInfoType; +import eu.eudat.commons.enums.notification.NotificationContactType; import eu.eudat.commons.scope.user.UserScope; +import eu.eudat.commons.types.notification.*; import eu.eudat.data.dao.entities.EmailConfirmationDao; import eu.eudat.data.old.EmailConfirmation; import eu.eudat.data.UserEntity; +import eu.eudat.integrationevent.outbox.notification.NotificationIntegrationEvent; +import eu.eudat.integrationevent.outbox.notification.NotificationIntegrationEventHandler; import eu.eudat.model.UserContactInfo; import eu.eudat.query.UserContactInfoQuery; -import eu.eudat.service.mail.MailService; -import eu.eudat.service.mail.SimpleMail; import gr.cite.tools.data.query.Ordering; import gr.cite.tools.data.query.QueryFactory; import org.slf4j.Logger; @@ -19,10 +22,7 @@ import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import javax.management.InvalidApplicationException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; +import java.util.*; import java.util.concurrent.CompletableFuture; @Service("ConfirmationEmailService") @@ -32,152 +32,40 @@ public class ConfirmationEmailServiceImpl implements ConfirmationEmailService { private Environment environment; private final UserScope userScope; private final QueryFactory queryFactory; + private final JsonHandlingService jsonHandlingService; + private final NotificationIntegrationEventHandler eventHandler; - public ConfirmationEmailServiceImpl(/*Logger logger,*/ Environment environment, UserScope userScope, QueryFactory queryFactory) { + + public ConfirmationEmailServiceImpl(/*Logger logger,*/ Environment environment, UserScope userScope, QueryFactory queryFactory, JsonHandlingService jsonHandlingService, NotificationIntegrationEventHandler eventHandler) { // this.logger = logger; this.environment = environment; this.userScope = userScope; this.queryFactory = queryFactory; + this.jsonHandlingService = jsonHandlingService; + this.eventHandler = eventHandler; } @Override - public void createConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, String email, UUID userId) { - EmailConfirmation confirmationEmail = new EmailConfirmation(); - confirmationEmail.setEmail(email); - confirmationEmail.setExpiresAt(Date - .from(new Date() - .toInstant() - .plusSeconds(Long.parseLong(this.environment.getProperty("conf_email.expiration_time_seconds"))) - ) - ); - confirmationEmail.setUserId(userId); - confirmationEmail.setIsConfirmed(false); - confirmationEmail.setToken(UUID.randomUUID()); - confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail); - sentConfirmationEmail(confirmationEmail, mailService); + public void sentConfirmationEmail(String email) throws InvalidApplicationException { + + NotificationIntegrationEvent event = new NotificationIntegrationEvent(); + event.setUserId(userScope.getUserIdSafe()); + List contactPairs = new ArrayList<>(); + contactPairs.add(new ContactPair(ContactInfoType.Email, email)); + NotificationContactData contactData = new NotificationContactData(contactPairs, null, null); + event.setContactHint(jsonHandlingService.toJsonSafe(contactData)); + event.setContactTypeHint(NotificationContactType.EMAIL); + event.setNotificationType(UUID.fromString("4FDBFA80-7A71-4A69-B854-67CBB70648F1")); + NotificationFieldData data = new NotificationFieldData(); + List fieldInfoList = new ArrayList<>(); + fieldInfoList.add(new FieldInfo("{expiration_time}", DataType.String, this.secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds"))))); + data.setFields(fieldInfoList); + event.setData(jsonHandlingService.toJsonSafe(data)); + eventHandler.handle(event); } @Override - public CompletableFuture sentConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService) { - return CompletableFuture.runAsync(() -> { - SimpleMail mail = new SimpleMail(); - mail.setSubject(environment.getProperty("conf_email.subject")); - mail.setContent(createContent(confirmationEmail.getToken(), mailService)); - mail.setTo(confirmationEmail.getEmail()); - try { - mailService.sendSimpleMail(mail); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - }); - } - - private String createContent(UUID confirmationToken, MailService mailService) { - String content = mailService.getMailTemplateContent(this.environment.getProperty("email.confirmation")); - content = content.replace("{confirmationToken}", confirmationToken.toString()); - content = content.replace("{expiration_time}", secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds")))); - content = content.replace("{host}", this.environment.getProperty("dmp.domain")); - - return content; - } - - @Override - public CompletableFuture sentMergeConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService, String userName) { - return CompletableFuture.runAsync(() -> { - SimpleMail mail = new SimpleMail(); - mail.setSubject(environment.getProperty("conf_email.subject")); - mail.setContent(createMergeContent(confirmationEmail.getToken(), mailService, userName)); - mail.setTo(confirmationEmail.getEmail()); - try { - mailService.sendSimpleMail(mail); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - }); - } - - @Override - public CompletableFuture sentUnlinkConfirmationEmail(EmailConfirmation confirmationEmail, MailService mailService) { - String email = null; - try { - Map map = new ObjectMapper().readValue(confirmationEmail.getData(), new TypeReference>() {}); - email = (String) map.get("email"); - } - catch (JsonProcessingException e){ - logger.error(e.getMessage(), e); - } - String finalEmail = email; - return CompletableFuture.runAsync(() -> { - SimpleMail mail = new SimpleMail(); - mail.setSubject(environment.getProperty("conf_email.subject")); - mail.setContent(createUnlinkContent(confirmationEmail.getToken(), mailService, finalEmail)); - mail.setTo(confirmationEmail.getEmail()); - try { - mailService.sendSimpleMail(mail); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - }); - } - - private String createMergeContent(UUID confirmationToken, MailService mailService, String userName) { - String content = mailService.getMailTemplateContent(this.environment.getProperty("email.merge")); - content = content.replace("{userName}", userName); - content = content.replace("{confirmationToken}", confirmationToken.toString()); - content = content.replace("{expiration_time}", secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds")))); - content = content.replace("{host}", this.environment.getProperty("dmp.domain")); - - return content; - } - - private String createUnlinkContent(UUID confirmationToken, MailService mailService, String email) { - String content = mailService.getMailTemplateContent(this.environment.getProperty("email.unlink")); - content = content.replace("{confirmationToken}", confirmationToken.toString()); - content = content.replace("{expiration_time}", secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds")))); - content = content.replace("{host}", this.environment.getProperty("dmp.domain")); - content = content.replace("{email}", email); - - return content; - } - - private String secondsToTime(int seconds) { - int sec = seconds % 60; - int hour = seconds / 60; - int min = hour % 60; - hour = hour / 60; - return (hour + ":" + min + ":" + sec); - } - - @Override - public void createMergeConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, - String email, UserEntity user, Integer provider) throws InvalidApplicationException { - EmailConfirmation confirmationEmail = new EmailConfirmation(); - confirmationEmail.setEmail(email); - confirmationEmail.setExpiresAt(Date - .from(new Date() - .toInstant() - .plusSeconds(Long.parseLong(this.environment.getProperty("conf_email.expiration_time_seconds"))) - ) - ); - confirmationEmail.setUserId(user.getId()); - try { - Map map = new HashMap<>(); - map.put("userId", this.userScope.getUserId()); - map.put("provider", provider.toString()); - confirmationEmail.setData(new ObjectMapper().writeValueAsString(map)); - } catch (JsonProcessingException | InvalidApplicationException e) { - logger.error(e.getMessage(), e); - } - confirmationEmail.setIsConfirmed(false); - confirmationEmail.setToken(UUID.randomUUID()); - confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail); - sentMergeConfirmationEmail(confirmationEmail, mailService, user.getName()); - - } - - @Override - public void createUnlinkConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, MailService mailService, - String email, UserEntity user, Integer provider) throws InvalidApplicationException { + public void sentUnlinkConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, String email, UserEntity user, Integer provider) throws InvalidApplicationException { EmailConfirmation confirmationEmail = new EmailConfirmation(); UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); @@ -200,6 +88,77 @@ public class ConfirmationEmailServiceImpl implements ConfirmationEmailService { confirmationEmail.setIsConfirmed(false); confirmationEmail.setToken(UUID.randomUUID()); confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail); - sentUnlinkConfirmationEmail(confirmationEmail, mailService); + + NotificationIntegrationEvent event = new NotificationIntegrationEvent(); + event.setUserId(userScope.getUserIdSafe()); + List contactPairs = new ArrayList<>(); + contactPairs.add(new ContactPair(ContactInfoType.Email, email)); + NotificationContactData contactData = new NotificationContactData(contactPairs, null, null); + event.setContactHint(jsonHandlingService.toJsonSafe(contactData)); + event.setContactTypeHint(NotificationContactType.EMAIL); + event.setNotificationType(UUID.fromString("C9BC3F16-057E-4BBA-8A5F-36BD835E5604")); + NotificationFieldData data = new NotificationFieldData(); + List fieldInfoList = new ArrayList<>(); + fieldInfoList.add(new FieldInfo("{host}", DataType.String, this.environment.getProperty("dmp.domain"))); + fieldInfoList.add(new FieldInfo("{confirmationToken}", DataType.String, confirmationEmail.getToken().toString())); + fieldInfoList.add(new FieldInfo("{email}", DataType.String, email)); + fieldInfoList.add(new FieldInfo("{expiration_time}", DataType.String, this.secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds"))))); + data.setFields(fieldInfoList); + event.setData(jsonHandlingService.toJsonSafe(data)); + eventHandler.handle(event); } + + @Override + public void sentMergeConfirmationEmail(EmailConfirmationDao loginConfirmationEmailDao, + String email, UserEntity user, Integer provider) throws InvalidApplicationException { + EmailConfirmation confirmationEmail = new EmailConfirmation(); + confirmationEmail.setEmail(email); + confirmationEmail.setExpiresAt(Date + .from(new Date() + .toInstant() + .plusSeconds(Long.parseLong(this.environment.getProperty("conf_email.expiration_time_seconds"))) + ) + ); + confirmationEmail.setUserId(user.getId()); + try { + Map map = new HashMap<>(); + map.put("userId", this.userScope.getUserId()); + map.put("provider", provider.toString()); + confirmationEmail.setData(new ObjectMapper().writeValueAsString(map)); + } catch (JsonProcessingException | InvalidApplicationException e) { + logger.error(e.getMessage(), e); + } + confirmationEmail.setIsConfirmed(false); + confirmationEmail.setToken(UUID.randomUUID()); + confirmationEmail = loginConfirmationEmailDao.createOrUpdate(confirmationEmail); + + NotificationIntegrationEvent event = new NotificationIntegrationEvent(); + event.setUserId(userScope.getUserIdSafe()); + List contactPairs = new ArrayList<>(); + contactPairs.add(new ContactPair(ContactInfoType.Email, email)); + NotificationContactData contactData = new NotificationContactData(contactPairs, null, null); + event.setContactHint(jsonHandlingService.toJsonSafe(contactData)); + event.setContactTypeHint(NotificationContactType.EMAIL); + event.setNotificationType(UUID.fromString("BFE68845-CB05-4C5A-A03D-29161A7C9660")); + NotificationFieldData data = new NotificationFieldData(); + List fieldInfoList = new ArrayList<>(); + fieldInfoList.add(new FieldInfo("{userName}", DataType.String, user.getName())); + fieldInfoList.add(new FieldInfo("{host}", DataType.String, this.environment.getProperty("dmp.domain"))); + fieldInfoList.add(new FieldInfo("{confirmationToken}", DataType.String, confirmationEmail.getToken().toString())); + fieldInfoList.add(new FieldInfo("{expiration_time}", DataType.String, this.secondsToTime(Integer.parseInt(this.environment.getProperty("conf_email.expiration_time_seconds"))))); + data.setFields(fieldInfoList); + event.setData(jsonHandlingService.toJsonSafe(data)); + eventHandler.handle(event); + + } + + private String secondsToTime(int seconds) { + int sec = seconds % 60; + int hour = seconds / 60; + int min = hour % 60; + hour = hour / 60; + return (hour + ":" + min + ":" + sec); + } + + } \ No newline at end of file diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationService.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationService.java index d2fdafbad..b7f891888 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationService.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationService.java @@ -8,8 +8,9 @@ import eu.eudat.data.dao.entities.InvitationDao; import eu.eudat.data.old.Invitation; import eu.eudat.data.UserEntity; -import eu.eudat.service.mail.MailService; import jakarta.mail.MessagingException; + +import javax.management.InvalidApplicationException; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -19,7 +20,7 @@ public interface InvitationService { void assignToDmp(DMPDao dmpDao, DmpUserEntity user, DmpEntity dmp); - void createInvitations(InvitationDao invitationDao, MailService mailService, List users, DmpEntity dmp, Integer role, UserEntity creator) throws MessagingException; + void createInvitations(InvitationDao invitationDao, List users, DmpEntity dmp, Integer role, UserEntity creator) throws MessagingException, InvalidApplicationException; - CompletableFuture sendInvitationAsync(DmpEntity dmp, Invitation invitation, String recipient, MailService mailService, Integer role) throws MessagingException; + void sendInvitation(DmpEntity dmp, Invitation invitation, UserEntity user, Integer role) throws InvalidApplicationException; } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationServiceImpl.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationServiceImpl.java index 3d15be611..89d2d4312 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationServiceImpl.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/InvitationServiceImpl.java @@ -1,17 +1,22 @@ package eu.eudat.logic.services.utilities; +import eu.eudat.commons.JsonHandlingService; +import eu.eudat.commons.enums.ContactInfoType; +import eu.eudat.commons.enums.notification.NotificationContactType; +import eu.eudat.commons.scope.user.UserScope; +import eu.eudat.commons.types.notification.*; import eu.eudat.data.DmpEntity; import eu.eudat.data.DmpUserEntity; import eu.eudat.data.dao.entities.DMPDao; import eu.eudat.data.dao.entities.InvitationDao; import eu.eudat.data.old.Invitation; import eu.eudat.data.UserEntity; +import eu.eudat.integrationevent.outbox.notification.NotificationIntegrationEvent; +import eu.eudat.integrationevent.outbox.notification.NotificationIntegrationEventHandler; import eu.eudat.model.UserContactInfo; import eu.eudat.models.data.invitation.Properties; import eu.eudat.query.UserContactInfoQuery; -import eu.eudat.service.mail.MailService; -import eu.eudat.service.mail.SimpleMail; import gr.cite.tools.data.query.Ordering; import gr.cite.tools.data.query.QueryFactory; import org.slf4j.Logger; @@ -23,7 +28,10 @@ import org.springframework.stereotype.Service; import jakarta.mail.MessagingException; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.Marshaller; + +import javax.management.InvalidApplicationException; import java.io.StringWriter; +import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -33,10 +41,16 @@ import java.util.concurrent.CompletableFuture; public class InvitationServiceImpl implements InvitationService { private static final Logger logger = LoggerFactory.getLogger(InvitationServiceImpl.class); private Environment environment; + private final UserScope userScope; + private final NotificationIntegrationEventHandler eventHandler; + private final JsonHandlingService jsonHandlingService; @Autowired - public InvitationServiceImpl(Environment environment, QueryFactory queryFactory) { + public InvitationServiceImpl(Environment environment, UserScope userScope, NotificationIntegrationEventHandler eventHandler, JsonHandlingService jsonHandlingService, QueryFactory queryFactory) { this.environment = environment; + this.userScope = userScope; + this.eventHandler = eventHandler; + this.jsonHandlingService = jsonHandlingService; this.queryFactory = queryFactory; } private final QueryFactory queryFactory; @@ -58,11 +72,11 @@ public class InvitationServiceImpl implements InvitationService { } @Override - public void createInvitations(InvitationDao invitationDao, MailService mailService, List users, DmpEntity dmp, Integer role, UserEntity creator) throws MessagingException { - for (UserEntity userInfo : users) { + public void createInvitations(InvitationDao invitationDao, List users, DmpEntity dmp, Integer role, UserEntity creator) throws MessagingException, InvalidApplicationException { + for (UserEntity user : users) { Invitation invitation = new Invitation(); // invitation.setDmp(dmp); //TODO - UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(userInfo.getId()); + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); invitation.setInvitationEmail(query.first().getValue()); invitation.setUser(creator); @@ -80,37 +94,34 @@ public class InvitationServiceImpl implements InvitationService { logger.error(e.getMessage(), e); } invitationDao.createOrUpdate(invitation); - sendInvitationAsync(dmp, invitation, userInfo.getName(), mailService, role); + this.sendInvitation(dmp, invitation, user, role); } } @Override - public CompletableFuture sendInvitationAsync(DmpEntity dmp, Invitation invitation, String recipient, MailService mailService, Integer role) { - return CompletableFuture.runAsync(() -> { - SimpleMail mail = new SimpleMail(); - mail.setSubject(createSubject(dmp, mailService.getMailTemplateSubject())); - mail.setContent(createContent(invitation.getId(), dmp, recipient, mailService.getMailTemplateContent(this.environment.getProperty("email.invite")), role)); - mail.setTo(invitation.getInvitationEmail()); - try { - mailService.sendSimpleMail(mail); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - } - }); - } + public void sendInvitation(DmpEntity dmp, Invitation invitation, UserEntity user, Integer role) throws InvalidApplicationException { - private String createSubject(DmpEntity dmp, String templateSubject) { - String subject = templateSubject.replace("{dmpname}", dmp.getLabel()); - return subject; - } + NotificationIntegrationEvent event = new NotificationIntegrationEvent(); + event.setUserId(userScope.getUserIdSafe()); - private String createContent(UUID invitationID, DmpEntity dmp, String recipient, String templateContent, Integer role) { - String content = templateContent.replace("{dmpname}", dmp.getLabel()); - content = content.replace("{invitationID}", invitationID.toString()); - content = content.replace("{recipient}", recipient); - content = content.replace("{host}", this.environment.getProperty("dmp.domain")); -// content = content.replace("{dmprole}", UserDMP.UserDMPRoles.fromInteger(role).name()); //TODO + UserContactInfoQuery query = this.queryFactory.query(UserContactInfoQuery.class).userIds(user.getId()); + query.setOrder(new Ordering().addAscending(UserContactInfo._ordinal)); - return content; + List contactPairs = new ArrayList<>(); + contactPairs.add(new ContactPair(ContactInfoType.Email, query.first().getValue())); + NotificationContactData contactData = new NotificationContactData(contactPairs, null, null); + event.setContactHint(jsonHandlingService.toJsonSafe(contactData)); + event.setContactTypeHint(NotificationContactType.EMAIL); + event.setNotificationType(UUID.fromString("065DEECD-21BB-44AF-9983-E660FDF24BC4")); + NotificationFieldData data = new NotificationFieldData(); + List fieldInfoList = new ArrayList<>(); + fieldInfoList.add(new FieldInfo("{recipient}", DataType.String, user.getName())); + fieldInfoList.add(new FieldInfo("{invitationID}", DataType.String, invitation.getId().toString())); + fieldInfoList.add(new FieldInfo("{host}", DataType.String, this.environment.getProperty("dmp.domain"))); + fieldInfoList.add(new FieldInfo("{dmpname}", DataType.String, dmp.getLabel())); +// fieldInfoList.add(new FieldInfo("{dmprole}", DataType.String, UserDMP.UserDMPRoles.fromInteger(role).name())); //TODO + data.setFields(fieldInfoList); + event.setData(jsonHandlingService.toJsonSafe(data)); + eventHandler.handle(event); } } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/UtilitiesService.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/UtilitiesService.java index 2959f4433..917284f58 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/UtilitiesService.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/UtilitiesService.java @@ -1,7 +1,7 @@ package eu.eudat.logic.services.utilities; import eu.eudat.logic.services.forms.VisibilityRuleService; -import eu.eudat.service.mail.MailService; +//import eu.eudat.service.mail.MailService; /** * Created by ikalyvas on 3/1/2018. @@ -10,7 +10,5 @@ public interface UtilitiesService { InvitationService getInvitationService(); - MailService getMailService(); - ConfirmationEmailService getConfirmationEmailService(); } diff --git a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/UtilitiesServiceImpl.java b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/UtilitiesServiceImpl.java index 2e50c26fb..d4aa24119 100644 --- a/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/UtilitiesServiceImpl.java +++ b/dmp-backend/web/src/main/java/eu/eudat/logic/services/utilities/UtilitiesServiceImpl.java @@ -1,8 +1,5 @@ package eu.eudat.logic.services.utilities; -import eu.eudat.logic.services.forms.VisibilityRuleService; -import eu.eudat.logic.services.forms.VisibilityRuleServiceImpl; -import eu.eudat.service.mail.MailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -13,13 +10,11 @@ import org.springframework.stereotype.Service; public class UtilitiesServiceImpl implements UtilitiesService { private InvitationService invitationService; - private MailService mailService; private ConfirmationEmailService confirmationEmailService; @Autowired - public UtilitiesServiceImpl(InvitationService invitationService, MailService mailService, ConfirmationEmailService confirmationEmailService) { + public UtilitiesServiceImpl(InvitationService invitationService, ConfirmationEmailService confirmationEmailService) { this.invitationService = invitationService; - this.mailService = mailService; this.confirmationEmailService = confirmationEmailService; } @@ -33,8 +28,4 @@ public class UtilitiesServiceImpl implements UtilitiesService { return invitationService; } - @Override - public MailService getMailService() { - return mailService; - } }