From 48d2a0123bab9138d53123a9ee7603b00410d429 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Wed, 17 Jan 2024 17:06:23 +0530 Subject: [PATCH 01/23] Implement Notification insertion logic for workflows --- .../carbon/apimgt/impl/dao/ApiMgtDAO.java | 11 ++ .../impl/dao/constants/SQLConstants.java | 13 +++ .../carbon/apimgt/impl/dto/WorkflowDTO.java | 16 ++- .../PortalNotificationDAO.java | 98 ++++++++++++++++ .../PortalNotificationDTO.java | 62 ++++++++++ .../PortalNotificationEndUserDTO.java | 32 +++++ .../PortalNotificationMetaData.java | 63 ++++++++++ .../PortalNotificationType.java | 13 +++ .../impl/workflow/WorkflowConstants.java | 1 + .../impl/workflow/WorkflowExecutor.java | 109 ++++++++++++++++++ .../rest/api/admin/v1/dto/WorkflowDTO.java | 24 +++- .../v1/impl/WorkflowsApiServiceImpl.java | 6 + .../src/main/resources/admin-api.yaml | 3 + .../src/main/resources/admin-api.yaml | 3 + .../src/main/resources/sql/h2.sql | 16 +++ 15 files changed, 467 insertions(+), 3 deletions(-) create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java index cfa7ff91cfbc..b43c47009001 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java @@ -5769,6 +5769,7 @@ public WorkflowDTO retrieveWorkflow(String workflowReference) throws APIManageme workflowDTO.setTenantId(rs.getInt("TENANT_ID")); workflowDTO.setWorkflowDescription(rs.getString("WF_STATUS_DESC")); InputStream metadataBlob = rs.getBinaryStream("WF_METADATA"); + InputStream propertiesBlob = rs.getBinaryStream("WF_PROPERTIES"); if (metadataBlob != null) { String metadata = APIMgtDBUtil.getStringFromInputStream(metadataBlob); @@ -5779,6 +5780,16 @@ public WorkflowDTO retrieveWorkflow(String workflowReference) throws APIManageme JSONObject metadataJson = new JSONObject(); workflowDTO.setMetadata(metadataJson); } + + if (propertiesBlob != null) { + String properties = APIMgtDBUtil.getStringFromInputStream(propertiesBlob); + Gson propertiesGson = new Gson(); + JSONObject propertiesJson = propertiesGson.fromJson(properties, JSONObject.class); + workflowDTO.setProperties(propertiesJson); + } else { + JSONObject propertiesJson = new JSONObject(); + workflowDTO.setProperties(propertiesJson); + } } } catch (SQLException e) { handleException("Error while retrieving workflow details for " + workflowReference, e); diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java index 1fb0e3a2e44d..8cb471f34d8c 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java @@ -3168,6 +3168,19 @@ public class SQLConstants { " AND API.ORGANIZATION = ?" + " AND SUBS.SUB_STATUS != '" + APIConstants.SubscriptionStatus.REJECTED + "'"; + + + /** Pub/Dev Notifications related constants **/ + + public static class PortalNotifications { + public static final String ADD_NOTIFICATION = "INSERT INTO AM_NOTIFICATION " + + "(NOTIFICATION_ID, NOTIFICATION_TYPE, CREATED_TIME, NOTIFICATION_METADATA, ORGANIZATION) VALUES (?, ?, ?, ?, ?)"; + + public static final String ADD_NOTIFICATION_END_USER = "INSERT INTO AM_NOTIFICATION_END_USERS " + + "(NOTIFICATION_ID, DESTINATION_USER) " + "VALUES (?, ?)"; + } + + /** Throttle related constants**/ public static class ThrottleSQLConstants{ diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/WorkflowDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/WorkflowDTO.java index ab961ba3fac0..4ac52052fe4b 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/WorkflowDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/WorkflowDTO.java @@ -62,13 +62,18 @@ public class WorkflowDTO implements Serializable { private JSONObject properties; + private String comments; + public WorkflowDTO(){ metadata = new JSONObject(); properties = new JSONObject(); } public String getProperties(String key) { - return properties.get(key).toString(); + if (properties.get(key) != null) { + return properties.get(key).toString(); + } + return null; } public void setProperties(String key, String value) { @@ -202,6 +207,14 @@ public void setProperties(JSONObject properties) { this.properties = properties; } + public String getComments() { + return comments; + } + + public void setComments(String comments) { + this.comments = comments; + } + @Override public String toString() { return "WorkflowDTO{" + @@ -218,6 +231,7 @@ public String toString() { ", metadata=" + metadata + ", properties=" + properties + ", attributes=" + attributes + + ", comments='" + comments + '}'; } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java new file mode 100644 index 000000000000..e5272dbcc2be --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -0,0 +1,98 @@ +package org.wso2.carbon.apimgt.impl.portalNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.simple.JSONObject; +import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants; +import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.UUID; + +public class PortalNotificationDAO { + + private static final Log log = LogFactory.getLog(PortalNotificationDAO.class); + + private static PortalNotificationDAO INSTANCE = null; + + private PortalNotificationDAO() { + } + + public static PortalNotificationDAO getInstance() { + if (INSTANCE == null) { + INSTANCE = new PortalNotificationDAO(); + } + return INSTANCE; + } + + public boolean addNotification(PortalNotificationDTO portalNotificationDTO) { + + String addNotificationQuery = SQLConstants.PortalNotifications.ADD_NOTIFICATION; + String addEndUserQuery = SQLConstants.PortalNotifications.ADD_NOTIFICATION_END_USER; + + Connection conn = null; + PreparedStatement ps = null; + try { + conn = APIMgtDBUtil.getConnection(); + ps = conn.prepareStatement(addNotificationQuery); + String notificationId = UUID.randomUUID().toString(); + + ps.setString(1, notificationId); + ps.setString(2, portalNotificationDTO.getNotificationType().toString()); + ps.setTimestamp(3, portalNotificationDTO.getCreatedTime()); + + String metadataJson = convertMetadataToJson(portalNotificationDTO.getNotificationMetadata()); + + ps.setString(4, metadataJson); + ps.setString(5, portalNotificationDTO.getOrganization()); + + int rowsAffected = ps.executeUpdate(); + if (rowsAffected > 0) { + for (PortalNotificationEndUserDTO endUser : portalNotificationDTO.getEndUsers()) { + addEndUser(conn, addEndUserQuery, notificationId, endUser); + } + return true; + } + + } catch (SQLException e) { + log.error("Error while adding notification", e); + log.error("SQL State: " + e.getSQLState()); + log.error("Error Code: " + e.getErrorCode()); + } finally { + APIMgtDBUtil.closeAllConnections(ps, conn, null); + } + return false; + } + + private void addEndUser(Connection conn, String addEndUserQuery, String notificationId, + PortalNotificationEndUserDTO endUser) throws SQLException { + + PreparedStatement ps = null; + try { + ps = conn.prepareStatement(addEndUserQuery); + ps.setString(1, notificationId); + ps.setString(2, endUser.getDestinationUser()); + ps.executeUpdate(); + } catch (SQLException e) { + log.error("Error while adding end users", e); + } finally { + if (ps != null) { + ps.close(); + } + } + } + + private String convertMetadataToJson(PortalNotificationMetaData metaData) { + JSONObject json = new JSONObject(); + json.put("apiName", metaData.getApi()); + json.put("apiVersion", metaData.getApiVersion()); + json.put("apiContext", metaData.getApiContext()); + json.put("applicationName", metaData.getApplicationName()); + json.put("requestedTier", metaData.getRequestedTier()); + json.put("revisionId", metaData.getRevisionId()); + json.put("comment", metaData.getComment()); + return json.toJSONString(); + } +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java new file mode 100644 index 000000000000..4d8f1d6d6876 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java @@ -0,0 +1,62 @@ +package org.wso2.carbon.apimgt.impl.portalNotifications; + +import java.sql.Timestamp; +import java.util.List; + +public class PortalNotificationDTO { + + private String notificationId; + private PortalNotificationType notificationType; + private Timestamp createdTime; + private PortalNotificationMetaData notificationMetadata; + private String organization; + private List endUsers; + + public String getNotificationId() { + return notificationId; + } + + public void setNotificationId(String notificationId) { + this.notificationId = notificationId; + } + + public PortalNotificationType getNotificationType() { + return notificationType; + } + + public void setNotificationType(PortalNotificationType notificationType) { + this.notificationType = notificationType; + } + + public Timestamp getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(Timestamp createdTime) { + this.createdTime = createdTime; + } + + public PortalNotificationMetaData getNotificationMetadata() { + return notificationMetadata; + } + + public void setNotificationMetadata(PortalNotificationMetaData notificationMetadata) { + this.notificationMetadata = notificationMetadata; + } + + public String getOrganization() { + return organization; + } + + public void setOrganization(String organization) { + this.organization = organization; + } + + public List getEndUsers() { + return endUsers; + } + + public void setEndUsers(List endUsers) { + this.endUsers = endUsers; + } +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java new file mode 100644 index 000000000000..05e40608cc7f --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java @@ -0,0 +1,32 @@ +package org.wso2.carbon.apimgt.impl.portalNotifications; + +public class PortalNotificationEndUserDTO { + + private String notificationId; + private String destinationUser; + private boolean isRead; + + public String getNotificationId() { + return notificationId; + } + + public void setNotificationId(String notificationId) { + this.notificationId = notificationId; + } + + public String getDestinationUser() { + return destinationUser; + } + + public void setDestinationUser(String destinationUser) { + this.destinationUser = destinationUser; + } + + public boolean isRead() { + return isRead; + } + + public void setRead(boolean read) { + isRead = read; + } +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java new file mode 100644 index 000000000000..3c49a0fb452c --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java @@ -0,0 +1,63 @@ +package org.wso2.carbon.apimgt.impl.portalNotifications; + +public class PortalNotificationMetaData { + + private String api; + private String apiVersion; + private String apiContext; + private String applicationName; + private String requestedTier; + private String revisionId; + private String comment; + + public String getApi() { + return api; + } + + public void setApi(String api) { + this.api = api; + } + + public String getApiVersion() { + return apiVersion; + } + + public void setApiVersion(String apiVersion) { + this.apiVersion = apiVersion; + } + + public String getApiContext() { + return apiContext; + } + + public void setApiContext(String apiContext) { + this.apiContext = apiContext; + } + + public String getApplicationName() { + return applicationName; + } + + public void setApplicationName(String applicationName) { + this.applicationName = applicationName; + } + + public String getRequestedTier() { return requestedTier;} + + public void setRequestedTier(String requestedTier) { this.requestedTier = requestedTier;} + + public String getRevisionId() { return revisionId;} + + public void setRevisionId(String revisionId) { this.revisionId = revisionId;} + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java new file mode 100644 index 000000000000..6936883bdd9a --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java @@ -0,0 +1,13 @@ +package org.wso2.carbon.apimgt.impl.portalNotifications; + +public enum PortalNotificationType { + API_STATE_CHANGE, + API_PRODUCT_STATE_CHANGE, + API_REVISION_DEPLOYMENT, + APPLICATION_CREATION, + SUBSCRIPTION_CREATION, + SUBSCRIPTION_UPDATE, + SUBSCRIPTION_DELETION, + APPLICATION_REGISTRATION_PRODUCTION, + APPLICATION_REGISTRATION_SANDBOX +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowConstants.java index 0ccb341c75ac..6bcef88d5f2e 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowConstants.java @@ -155,4 +155,5 @@ private PayloadConstants(){ } + } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java index 09aa9a0a1bc4..d397b2352082 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java @@ -23,10 +23,16 @@ import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationDAO; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationDTO; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationEndUserDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationMetaData; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationType; import org.wso2.carbon.registry.core.utils.UUIDGenerator; import java.io.Serializable; +import java.util.ArrayList; import java.util.List; /** @@ -103,12 +109,115 @@ public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowExcepti ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance(); try { apiMgtDAO.updateWorkflowStatus(workflowDTO); + sendPubDevNotification(workflowDTO); + + } catch (APIManagementException e) { throw new WorkflowException("Error while updating workflow", e); } return new GeneralWorkflowResponse(); } + /** Implements the workflow related Notification logic. **/ + + private void sendPubDevNotification(WorkflowDTO workflowDTO) { + PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); + + portalNotificationsDTO.setNotificationType(getNotificationType(workflowDTO.getWorkflowType())); + portalNotificationsDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); + portalNotificationsDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + portalNotificationsDTO.setOrganization(workflowDTO.getTenantDomain()); + portalNotificationsDTO.setEndUsers(getDestinationUser(workflowDTO)); + + + + boolean result = PortalNotificationDAO.getInstance().addNotification(portalNotificationsDTO); + + if(!result){ + System.out.println("Error while adding publisher developer notification - sedPubDevNotification()"); + } + } + + private PortalNotificationType getNotificationType(String workflowType) { + switch (workflowType) { + case WorkflowConstants.WF_TYPE_AM_API_STATE: + return PortalNotificationType.API_STATE_CHANGE; + case WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE: + return PortalNotificationType.API_PRODUCT_STATE_CHANGE; + case WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION: + return PortalNotificationType.APPLICATION_CREATION; + case WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT: + return PortalNotificationType.API_REVISION_DEPLOYMENT; + case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION: + return PortalNotificationType.APPLICATION_REGISTRATION_PRODUCTION; + case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX: + return PortalNotificationType.APPLICATION_REGISTRATION_SANDBOX; + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION: + return PortalNotificationType.SUBSCRIPTION_CREATION; + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE: + return PortalNotificationType.SUBSCRIPTION_UPDATE; + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION: + return PortalNotificationType.SUBSCRIPTION_DELETION; + + } + return null; + } + + private List getDestinationUser(WorkflowDTO workflowDTO) { + List destinationUserList = new ArrayList<>(); + String destinationUser = null; + + switch (workflowDTO.getWorkflowType()) { + case WorkflowConstants.WF_TYPE_AM_API_STATE: + case WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE: + destinationUser = workflowDTO.getMetadata("Invoker"); + break; + + case WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION: + case WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT: + case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION: + case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX: + destinationUser = workflowDTO.getProperties("userName"); + break; + + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION: + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE: + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION: + destinationUser = workflowDTO.getProperties("subscriber"); + break; + + case WorkflowConstants.WF_TYPE_AM_USER_SIGNUP: + destinationUser = workflowDTO.getMetadata("userName"); + break; + } + + if(destinationUser != null){ + PortalNotificationEndUserDTO endUser = new PortalNotificationEndUserDTO(); + endUser.setDestinationUser(destinationUser); + destinationUserList.add(endUser); + } + + return destinationUserList; + } + + private PortalNotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { + PortalNotificationMetaData portalNotificationMetaData = new PortalNotificationMetaData(); + + portalNotificationMetaData.setApi(workflowDTO.getProperties("apiName")); + portalNotificationMetaData.setApiVersion(workflowDTO.getProperties("apiVersion")); + portalNotificationMetaData.setApplicationName(workflowDTO.getProperties("applicationName")); + portalNotificationMetaData.setRequestedTier(workflowDTO.getProperties("requestedTier")); + portalNotificationMetaData.setRevisionId(workflowDTO.getProperties("revisionId")); + portalNotificationMetaData.setComment(workflowDTO.getComments()); + + if(WorkflowConstants.WF_TYPE_AM_API_STATE.equals(workflowDTO.getWorkflowType()) || WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE.equals(workflowDTO.getWorkflowType())){ + portalNotificationMetaData.setApiContext(workflowDTO.getMetadata("ApiContext")); + } + + return portalNotificationMetaData; + } + + /** * Returns the information of the workflows whose status' match the workflowStatus * diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java index 1da9a6f2e07b..daacc3c84f38 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java @@ -57,6 +57,7 @@ public static StatusEnum fromValue(String v) { private StatusEnum status = null; private Map attributes = new HashMap(); private String description = null; + private String comments = null; /** * This attribute declares whether this workflow task is approved or rejected. @@ -112,6 +113,23 @@ public void setDescription(String description) { this.description = description; } + /** + **/ + public WorkflowDTO comments(String comments) { + this.comments = comments; + return this; + } + + + @ApiModelProperty(example = "Request is rejected because of some reason.", value = "") + @JsonProperty("comments") + public String getComments() { + return comments; + } + public void setComments(String comments) { + this.comments = comments; + } + @Override public boolean equals(java.lang.Object o) { @@ -124,12 +142,13 @@ public boolean equals(java.lang.Object o) { WorkflowDTO workflow = (WorkflowDTO) o; return Objects.equals(status, workflow.status) && Objects.equals(attributes, workflow.attributes) && - Objects.equals(description, workflow.description); + Objects.equals(description, workflow.description) && + Objects.equals(comments, workflow.comments); } @Override public int hashCode() { - return Objects.hash(status, attributes, description); + return Objects.hash(status, attributes, description, comments); } @Override @@ -140,6 +159,7 @@ public String toString() { sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" attributes: ").append(toIndentedString(attributes)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); + sb.append(" comments: ").append(toIndentedString(comments)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java index a35e186969e1..90b6d13b4d1c 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java @@ -187,6 +187,11 @@ public Response workflowsUpdateWorkflowStatusPost(String workflowReferenceId, Wo workflowDTO.setAttributes(body.getAttributes()); } + if(body.getComments() != null) { + System.out.println(body.getComments()); + workflowDTO.setComments(body.getComments()); + } + String workflowType = workflowDTO.getWorkflowType(); if (WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION.equals(workflowType) && @@ -198,6 +203,7 @@ public Response workflowsUpdateWorkflowStatusPost(String workflowReferenceId, Wo WorkflowExecutor workflowExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(workflowType); workflowExecutor.complete(workflowDTO); + if (WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) { WorkflowUtils.sendNotificationAfterWFComplete(workflowDTO, workflowType); diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/resources/admin-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/resources/admin-api.yaml index 9aa4db9ea6a8..e32556344090 100755 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/resources/admin-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/resources/admin-api.yaml @@ -4582,6 +4582,9 @@ components: description: type: string example: Approve workflow request. + comments: + type: string + example: Request is rejected because of some reason. TenantInfo: title: Tenant information type: object diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/admin-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/admin-api.yaml index 9aa4db9ea6a8..e32556344090 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/admin-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/admin-api.yaml @@ -4582,6 +4582,9 @@ components: description: type: string example: Approve workflow request. + comments: + type: string + example: Request is rejected because of some reason. TenantInfo: title: Tenant information type: object diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql index ec4d4d9cb886..e613e4148e44 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql @@ -2450,6 +2450,22 @@ CREATE TABLE IF NOT EXISTS AM_SUBJECT_ENTITY_REVOKED_EVENT ( ); +CREATE TABLE IF NOT EXISTS AM_NOTIFICATION ( + NOTIFICATION_ID VARCHAR(64) NOT NULL UNIQUE, + NOTIFICATION_TYPE VARCHAR(50) NOT NULL, + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + NOTIFICATION_METADATA BLOB DEFAULT NULL, + ORGANIZATION VARCHAR(100) NOT NULL, + PRIMARY KEY (NOTIFICATION_ID) +); + +CREATE TABLE IF NOT EXISTS AM_NOTIFICATION_END_USERS ( + NOTIFICATION_ID VARCHAR(64) NOT NULL, + DESTINATION_USER VARCHAR(255) NOT NULL, + IS_READ BOOLEAN DEFAULT FALSE, + PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER), + FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE +); From 50ece22cdb79c28ae5239d72e5a8ddae66fef0d1 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Mon, 19 Feb 2024 12:51:33 +0530 Subject: [PATCH 02/23] Implement Publisher Notification backend with APIs --- .../wso2/carbon/apimgt/api/APIProvider.java | 20 ++ .../carbon/apimgt/api/model/Notification.java | 50 ++++ .../apimgt/api/model/NotificationList.java | 36 +++ .../carbon/apimgt/impl/APIProviderImpl.java | 28 ++ .../apimgt/impl/AbstractAPIManager.java | 3 + .../impl/dao/constants/SQLConstants.java | 56 +++- .../PortalNotificationDAO.java | 256 ++++++++++++++++- .../PortalNotificationDTO.java | 9 - .../PortalNotificationEndUserDTO.java | 11 +- .../PortalNotificationMetaData.java | 18 +- .../impl/workflow/WorkflowExecutor.java | 10 +- .../src/main/resources/publisher-api.yaml | 272 ++++++++++++++++++ .../api/publisher/v1/dto/NotificationDTO.java | 193 +++++++++++++ .../publisher/v1/dto/NotificationListDTO.java | 128 +++++++++ .../dto/PatchAllNotificationsRequestDTO.java | 82 ++++++ .../v1/dto/PatchNotificationRequestDTO.java | 82 ++++++ .../api/publisher/v1/NotificationsApi.java | 137 +++++++++ .../publisher/v1/NotificationsApiService.java | 32 +++ .../v1/impl/NotificationsApiServiceImpl.java | 121 ++++++++ .../src/main/resources/publisher-api.yaml | 272 ++++++++++++++++++ .../src/main/webapp/WEB-INF/beans.xml | 1 + .../src/main/resources/sql/h2.sql | 4 +- 22 files changed, 1795 insertions(+), 26 deletions(-) create mode 100644 components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationDTO.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationListDTO.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/PatchAllNotificationsRequestDTO.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/PatchNotificationRequestDTO.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApiService.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java index c7e9ac392513..2af79589be1a 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java @@ -1908,4 +1908,24 @@ boolean isPolicyMetadataExists(String gatewayPolicyMappingId) * @throws APIManagementException */ int getPolicyUsageByPolicyUUIDInGatewayPolicies(String commonPolicyUUID) throws APIManagementException; + + /** + * Method to get notifications for the given user + * @param username + * @param organization + * @param sortOrder + * @param limit + * @param offset + * @return NotificationList + */ + NotificationList getNotifications(String username, String organization, String sortOrder, Integer limit, Integer offset) throws APIManagementException; + + boolean deleteAllNotifications(String username, String organization) throws APIManagementException; + + Notification markNotificationAsReadById(String username, String organization, String notificationId); + + boolean deleteNotificationById(String username, String organization, String notificationId); + + NotificationList markAllNotificationsAsRead(String username, String organization); + } diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java new file mode 100644 index 000000000000..2929d8858cb3 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java @@ -0,0 +1,50 @@ +package org.wso2.carbon.apimgt.api.model; + +public class Notification { + private String notificationId; + private String notificationType; + private String comments; + private String createdTime; + private Boolean isRead; + + public String getNotificationId() { + return notificationId; + } + + public void setNotificationId(String notificationId) { + this.notificationId = notificationId; + } + + public String getNotificationType() { + return notificationType; + } + + public void setNotificationType(String notificationType) { + this.notificationType = notificationType; + } + + public String getComments() { + return comments; + } + + public void setComments(String comments) { + this.comments = comments; + } + + public String getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(String createdTime) { + this.createdTime = createdTime; + } + + public Boolean getIsRead() { + return isRead; + } + + public void setIsRead(Boolean read) { + this.isRead = read; + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java new file mode 100644 index 000000000000..9a7a45b33ce6 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java @@ -0,0 +1,36 @@ +package org.wso2.carbon.apimgt.api.model; + +import java.util.ArrayList; +import java.util.List; + +public class NotificationList { + + private Integer count = null; + private List list = new ArrayList(); + private Pagination pagination = null; + + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + public Pagination getPagination() { + return pagination; + } + + public void setPagination(Pagination pagination) { + this.pagination = pagination; + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java index 3025e4581cfe..e354e3a3c84a 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java @@ -83,6 +83,8 @@ import org.wso2.carbon.apimgt.api.model.LifeCycleEvent; import org.wso2.carbon.apimgt.api.model.Mediation; import org.wso2.carbon.apimgt.api.model.Monetization; +import org.wso2.carbon.apimgt.api.model.Notification; +import org.wso2.carbon.apimgt.api.model.NotificationList; import org.wso2.carbon.apimgt.api.model.OperationPolicy; import org.wso2.carbon.apimgt.api.model.OperationPolicyData; import org.wso2.carbon.apimgt.api.model.OperationPolicySpecAttribute; @@ -7232,6 +7234,32 @@ public int getPolicyUsageByPolicyUUIDInGatewayPolicies(String commonPolicyUUID) return apiMgtDAO.getPolicyUUIDCount(commonPolicyUUID); } + @Override + public NotificationList getNotifications(String username, String organization, String sortOrder, Integer limit, + Integer offset) throws APIManagementException { + return portalNotificationDAO.getNotifications(username, organization, sortOrder, limit, offset); + } + + @Override + public boolean deleteAllNotifications(String username, String organization) { + return portalNotificationDAO.deleteAllNotifications(username, organization); + } + + @Override + public Notification markNotificationAsReadById(String username, String organization, String notificationId) { + return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId); + } + + @Override + public boolean deleteNotificationById(String username, String organization, String notificationId) { + return portalNotificationDAO.deleteNotificationById(username, organization, notificationId); + } + + @Override + public NotificationList markAllNotificationsAsRead(String username, String organization) { + return portalNotificationDAO.markAllNotificationsAsRead(username, organization); + } + /** * To get the hashmap of what mappingId is deployed or undeployed in which gateway. */ diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java index a33d7936f85a..7b6edc6adc84 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java @@ -54,6 +54,7 @@ import org.wso2.carbon.apimgt.impl.factory.PersistenceFactory; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationDAO; import org.wso2.carbon.apimgt.impl.utils.*; import org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus; import org.wso2.carbon.apimgt.persistence.APIPersistence; @@ -82,6 +83,7 @@ public abstract class AbstractAPIManager implements APIManager { // API definitions from swagger v2.0 protected Log log = LogFactory.getLog(getClass()); protected ApiMgtDAO apiMgtDAO; + protected PortalNotificationDAO portalNotificationDAO; protected EnvironmentSpecificAPIPropertyDAO environmentSpecificAPIPropertyDAO; protected ScopesDAO scopesDAO; protected int tenantId = MultitenantConstants.INVALID_TENANT_ID; //-1 the issue does not occur.; @@ -105,6 +107,7 @@ public AbstractAPIManager(String username) throws APIManagementException { public AbstractAPIManager(String username, String organization) throws APIManagementException { apiMgtDAO = ApiMgtDAO.getInstance(); + portalNotificationDAO = PortalNotificationDAO.getInstance(); scopesDAO = ScopesDAO.getInstance(); environmentSpecificAPIPropertyDAO = EnvironmentSpecificAPIPropertyDAO.getInstance(); diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java index 8cb471f34d8c..87a3a10fe7ab 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java @@ -3170,14 +3170,64 @@ public class SQLConstants { - /** Pub/Dev Notifications related constants **/ + /** Portal Notifications related constants **/ public static class PortalNotifications { public static final String ADD_NOTIFICATION = "INSERT INTO AM_NOTIFICATION " + - "(NOTIFICATION_ID, NOTIFICATION_TYPE, CREATED_TIME, NOTIFICATION_METADATA, ORGANIZATION) VALUES (?, ?, ?, ?, ?)"; + "(NOTIFICATION_ID, NOTIFICATION_TYPE, CREATED_TIME, NOTIFICATION_METADATA) VALUES (?, ?, ?, ?)"; public static final String ADD_NOTIFICATION_END_USER = "INSERT INTO AM_NOTIFICATION_END_USERS " + - "(NOTIFICATION_ID, DESTINATION_USER) " + "VALUES (?, ?)"; + "(NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION) " + "VALUES (?, ?, ?)"; + + public static final String GET_NOTIFICATIONS = + "SELECT" + + " n.NOTIFICATION_ID," + + " n.NOTIFICATION_TYPE," + + " n.CREATED_TIME," + + " n.NOTIFICATION_METADATA," + + " e.IS_READ " + + "FROM AM_NOTIFICATION n " + + "INNER JOIN AM_NOTIFICATION_END_USERS e ON n.NOTIFICATION_ID = e.NOTIFICATION_ID " + + "WHERE" + + " e.DESTINATION_USER = ?" + + " AND e.ORGANIZATION = ? " + + "ORDER BY n.CREATED_TIME DESC"; + + public static final String DELETE_ALL_NOTIFICATIONS_OF_USER = "DELETE FROM AM_NOTIFICATION_END_USERS " + + "WHERE DESTINATION_USER = ? AND ORGANIZATION = ?"; + + public static final String DELETE_NOTIFICATIONS = + "DELETE " + + "FROM AM_NOTIFICATION " + + "WHERE " + + "NOTIFICATION_ID IN (" + + "SELECT N.NOTIFICATION_ID " + + "FROM AM_NOTIFICATION N " + + "LEFT JOIN AM_NOTIFICATION_END_USERS NU ON N.NOTIFICATION_ID = NU.NOTIFICATION_ID " + + "WHERE NU.NOTIFICATION_ID IS NULL)"; + + public static final String MARK_NOTIFICATION_AS_READ = "UPDATE AM_NOTIFICATION_END_USERS SET IS_READ = TRUE " + + "WHERE NOTIFICATION_ID = ? AND DESTINATION_USER = ? AND ORGANIZATION = ?"; + + public static final String MARK_ALL_NOTIFICATIONS_AS_READ = "UPDATE AM_NOTIFICATION_END_USERS SET IS_READ = TRUE " + + "WHERE DESTINATION_USER = ? AND ORGANIZATION = ?"; + + public static final String GET_NOTIFICATION_BY_ID = + "SELECT" + + " n.NOTIFICATION_ID," + + " n.NOTIFICATION_TYPE," + + " n.CREATED_TIME," + + " n.NOTIFICATION_METADATA," + + " e.IS_READ " + + "FROM AM_NOTIFICATION n " + + "INNER JOIN AM_NOTIFICATION_END_USERS e ON n.NOTIFICATION_ID = e.NOTIFICATION_ID " + + "WHERE" + + " n.NOTIFICATION_ID = ?" + + " AND e.DESTINATION_USER = ?" + + " AND e.ORGANIZATION = ?"; + + public static final String DELETE_NOTIFICATION_BY_ID = "DELETE FROM AM_NOTIFICATION_END_USERS " + + "WHERE NOTIFICATION_ID = ? AND DESTINATION_USER = ? AND ORGANIZATION = ?"; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java index e5272dbcc2be..a70336d50cc6 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -3,12 +3,18 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.wso2.carbon.apimgt.api.model.*; import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; import java.sql.Connection; import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; import java.util.UUID; public class PortalNotificationDAO { @@ -46,7 +52,6 @@ public boolean addNotification(PortalNotificationDTO portalNotificationDTO) { String metadataJson = convertMetadataToJson(portalNotificationDTO.getNotificationMetadata()); ps.setString(4, metadataJson); - ps.setString(5, portalNotificationDTO.getOrganization()); int rowsAffected = ps.executeUpdate(); if (rowsAffected > 0) { @@ -74,6 +79,7 @@ private void addEndUser(Connection conn, String addEndUserQuery, String notifica ps = conn.prepareStatement(addEndUserQuery); ps.setString(1, notificationId); ps.setString(2, endUser.getDestinationUser()); + ps.setString(3, endUser.getOrganization()); ps.executeUpdate(); } catch (SQLException e) { log.error("Error while adding end users", e); @@ -95,4 +101,252 @@ private String convertMetadataToJson(PortalNotificationMetaData metaData) { json.put("comment", metaData.getComment()); return json.toJSONString(); } + + public NotificationList getNotifications(String username, String organization, String sortOrder, Integer limit, + Integer offset) { + + List list = new ArrayList(); + NotificationList notificationList = new NotificationList(); + Pagination pagination = new Pagination(); + notificationList.setPagination(pagination); + int total = 0; + + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try { + String sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS; + conn = APIMgtDBUtil.getConnection(); + ps = conn.prepareStatement(sqlQuery); + ps.setString(1, username); + ps.setString(2, organization); + rs = ps.executeQuery(); + while (rs.next()) { + Notification notification = new Notification(); + notification.setNotificationId(rs.getString("NOTIFICATION_ID")); + notification.setNotificationType(rs.getString("NOTIFICATION_TYPE")); + notification.setCreatedTime(rs.getTimestamp("CREATED_TIME").toString()); + notification.setComments(getCommentFromMetaData(rs.getString("NOTIFICATION_METADATA"), + rs.getString("NOTIFICATION_TYPE"))); + notification.setIsRead(rs.getBoolean("IS_READ")); + list.add(notification); + } + notificationList.setList(list); + } catch (SQLException e) { + log.error("Failed to retrieve notifications", e); + } finally { + APIMgtDBUtil.closeAllConnections(ps, conn, rs); + } + pagination.setLimit(limit); + pagination.setOffset(offset); + notificationList.getPagination().setTotal(total); + notificationList.setList(list); + notificationList.setCount(list.size()); + return notificationList; + } + + private String getCommentFromMetaData(String notificationMetadata, String notificationType) { + String finalComment = null; + try { + JSONParser parser = new JSONParser(); + JSONObject json = (JSONObject) parser.parse(notificationMetadata); + + String comment = (String) json.get("comment"); + String apiName = (String) json.get("apiName"); + String apiVersion = (String) json.get("apiVersion"); + String apiContext = (String) json.get("apiContext"); + String revisionId = (String) json.get("revisionId"); + String applicationName = (String) json.get("applicationName"); + String requestedTier = (String) json.get("requestedTier"); + String status; + + if (comment.equals("APPROVED")) { + status = "approved"; + } else { + status = "rejected"; + } + + switch (notificationType) { + case "API_STATE_CHANGE": + finalComment = "API State Change request of the API: " + apiName + ", version: " + apiVersion + + " that has the context: " + apiContext + " has been " + status + "."; + break; + case "API_PRODUCT_STATE_CHANGE": + finalComment = "API Product State Change request of the API PRODUCT: " + apiName + ", version: " + + apiVersion + " that has the context: " + apiContext + " has been " + status + "."; + break; + case "API_REVISION_DEPLOYMENT": + finalComment = "API Revision Deployment request of the API: " + apiName + ", version: " + apiVersion + + " for RevisionId: " + revisionId + " has been " + status + "."; + break; + case "APPLICATION_CREATION": + finalComment = "Application Creation request for the Application: " + applicationName + " has been " + + status + "."; + break; + case "SUBSCRIPTION_CREATION": + finalComment = "Subscription Creation request for the API: " + apiName + " version: " + apiVersion + + " using Application: " + applicationName + " has been " + status + "."; + break; + case "SUBSCRIPTION_UPDATE": + finalComment = "Subscription Update request for the " + requestedTier + " for the API: " + apiName + + " version: " + apiVersion + " using Application: " + applicationName + " has been " + status + + "."; + break; + case "SUBSCRIPTION_DELETION": + finalComment = "Subscription Deletion request for the API: " + apiName + " version: " + apiVersion + + " using Application: " + applicationName + " has been " + status + "."; + break; + case "APPLICATION_REGISTRATION_PRODUCTION": + finalComment = "Production Key Generation request for the Application: " + applicationName + + " has been " + status + "."; + break; + case "APPLICATION_REGISTRATION_SANDBOX": + finalComment = "Sandbox Key Generation request for the Application: " + applicationName + " has been " + + status + "."; + break; + } + + if (!comment.equals("APPROVED")) { + finalComment = finalComment + " Reason: " + comment; + } + + } catch (ParseException e) { + log.error("Failed to parse notification metadata JSON", e); + } + return finalComment; + } + + public boolean deleteAllNotifications(String username, String organization) { + + Connection conn = null; + PreparedStatement ps = null; + try { + String sqlQuery = SQLConstants.PortalNotifications.DELETE_ALL_NOTIFICATIONS_OF_USER; + conn = APIMgtDBUtil.getConnection(); + ps = conn.prepareStatement(sqlQuery); + ps.setString(1, username); + ps.setString(2, organization); + int rowsAffected = ps.executeUpdate(); + if (rowsAffected > 0) { + String deleteNotification = SQLConstants.PortalNotifications.DELETE_NOTIFICATIONS; + ps = conn.prepareStatement(deleteNotification); + ps.executeUpdate(); + return true; + } + } catch (SQLException e) { + log.error("Failed to delete notifications", e); + } finally { + APIMgtDBUtil.closeAllConnections(ps, conn, null); + } + return false; + } + + public Notification markNotificationAsReadById(String username, String organization, String notificationId) { + + Connection conn = null; + PreparedStatement ps = null; + Notification notification; + try { + String sqlQuery = SQLConstants.PortalNotifications.MARK_NOTIFICATION_AS_READ; + conn = APIMgtDBUtil.getConnection(); + ps = conn.prepareStatement(sqlQuery); + ps.setString(1, notificationId); + ps.setString(2, username); + ps.setString(3, organization); + int rowsAffected = ps.executeUpdate(); + if (rowsAffected > 0) { + notification = getNotificationById(notificationId, username, organization, conn); + if (notification != null) { + return notification; + } + } + } catch (SQLException e) { + log.error("Failed to mark notification as read", e); + } finally { + APIMgtDBUtil.closeAllConnections(ps, conn, null); + } + return null; + } + + private Notification getNotificationById(String notificationId, String username, String organization, + Connection conn) throws SQLException { + + PreparedStatement ps = null; + ResultSet rs = null; + try { + String sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATION_BY_ID; + + ps = conn.prepareStatement(sqlQuery); + ps.setString(1, notificationId); + ps.setString(2, username); + ps.setString(3, organization); + rs = ps.executeQuery(); + if (rs.next()) { + Notification notification = new Notification(); + notification.setNotificationId(rs.getString("NOTIFICATION_ID")); + notification.setNotificationType(rs.getString("NOTIFICATION_TYPE")); + notification.setCreatedTime(rs.getTimestamp("CREATED_TIME").toString()); + notification.setComments(getCommentFromMetaData(rs.getString("NOTIFICATION_METADATA"), + rs.getString("NOTIFICATION_TYPE"))); + notification.setIsRead(rs.getBoolean("IS_READ")); + return notification; + } + } catch (SQLException e) { + log.error("Failed to retrieve notification by id", e); + } finally { + if (ps != null) { + ps.close(); + } + } + return null; + } + + public boolean deleteNotificationById(String username, String organization, String notificationId) { + + Connection conn = null; + PreparedStatement ps = null; + try { + String sqlQuery = SQLConstants.PortalNotifications.DELETE_NOTIFICATION_BY_ID; + conn = APIMgtDBUtil.getConnection(); + ps = conn.prepareStatement(sqlQuery); + ps.setString(1, notificationId); + ps.setString(2, username); + ps.setString(3, organization); + int rowsAffected = ps.executeUpdate(); + if (rowsAffected > 0) { + String deleteNotification = SQLConstants.PortalNotifications.DELETE_NOTIFICATIONS; + ps = conn.prepareStatement(deleteNotification); + ps.executeUpdate(); + return true; + } + } catch (SQLException e) { + log.error("Failed to delete notification by id", e); + } finally { + APIMgtDBUtil.closeAllConnections(ps, conn, null); + } + return false; + } + + public NotificationList markAllNotificationsAsRead(String username, String organization) { + + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try { + String sqlQuery = SQLConstants.PortalNotifications.MARK_ALL_NOTIFICATIONS_AS_READ; + conn = APIMgtDBUtil.getConnection(); + ps = conn.prepareStatement(sqlQuery); + ps.setString(1, username); + ps.setString(2, organization); + int rowsAffected = ps.executeUpdate(); + if (rowsAffected > 0) { + return getNotifications(username, organization, null, null, null); + } + } catch (SQLException e) { + log.error("Failed to mark all notifications as read", e); + } finally { + APIMgtDBUtil.closeAllConnections(ps, conn, rs); + } + return null; + } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java index 4d8f1d6d6876..5fc60a909144 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java @@ -9,7 +9,6 @@ public class PortalNotificationDTO { private PortalNotificationType notificationType; private Timestamp createdTime; private PortalNotificationMetaData notificationMetadata; - private String organization; private List endUsers; public String getNotificationId() { @@ -44,14 +43,6 @@ public void setNotificationMetadata(PortalNotificationMetaData notificationMetad this.notificationMetadata = notificationMetadata; } - public String getOrganization() { - return organization; - } - - public void setOrganization(String organization) { - this.organization = organization; - } - public List getEndUsers() { return endUsers; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java index 05e40608cc7f..bf552596767a 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java @@ -4,6 +4,7 @@ public class PortalNotificationEndUserDTO { private String notificationId; private String destinationUser; + private String organization; private boolean isRead; public String getNotificationId() { @@ -22,11 +23,19 @@ public void setDestinationUser(String destinationUser) { this.destinationUser = destinationUser; } + public String getOrganization() { + return organization; + } + + public void setOrganization(String organization) { + this.organization = organization; + } + public boolean isRead() { return isRead; } public void setRead(boolean read) { - isRead = read; + this.isRead = read; } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java index 3c49a0fb452c..10991641cf3d 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java @@ -42,13 +42,21 @@ public void setApplicationName(String applicationName) { this.applicationName = applicationName; } - public String getRequestedTier() { return requestedTier;} + public String getRequestedTier() { + return requestedTier; + } - public void setRequestedTier(String requestedTier) { this.requestedTier = requestedTier;} + public void setRequestedTier(String requestedTier) { + this.requestedTier = requestedTier; + } - public String getRevisionId() { return revisionId;} + public String getRevisionId() { + return revisionId; + } - public void setRevisionId(String revisionId) { this.revisionId = revisionId;} + public void setRevisionId(String revisionId) { + this.revisionId = revisionId; + } public String getComment() { return comment; @@ -58,6 +66,4 @@ public void setComment(String comment) { this.comment = comment; } - - } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java index d397b2352082..4edde265c911 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java @@ -109,7 +109,7 @@ public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowExcepti ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance(); try { apiMgtDAO.updateWorkflowStatus(workflowDTO); - sendPubDevNotification(workflowDTO); + sendPortalNotifications(workflowDTO); } catch (APIManagementException e) { @@ -120,13 +120,12 @@ public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowExcepti /** Implements the workflow related Notification logic. **/ - private void sendPubDevNotification(WorkflowDTO workflowDTO) { + private void sendPortalNotifications(WorkflowDTO workflowDTO) { PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); portalNotificationsDTO.setNotificationType(getNotificationType(workflowDTO.getWorkflowType())); portalNotificationsDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); portalNotificationsDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); - portalNotificationsDTO.setOrganization(workflowDTO.getTenantDomain()); portalNotificationsDTO.setEndUsers(getDestinationUser(workflowDTO)); @@ -194,6 +193,7 @@ private List getDestinationUser(WorkflowDTO workfl if(destinationUser != null){ PortalNotificationEndUserDTO endUser = new PortalNotificationEndUserDTO(); endUser.setDestinationUser(destinationUser); + endUser.setOrganization(workflowDTO.getTenantDomain()); destinationUserList.add(endUser); } @@ -210,7 +210,9 @@ private PortalNotificationMetaData getNotificationMetaData(WorkflowDTO workflowD portalNotificationMetaData.setRevisionId(workflowDTO.getProperties("revisionId")); portalNotificationMetaData.setComment(workflowDTO.getComments()); - if(WorkflowConstants.WF_TYPE_AM_API_STATE.equals(workflowDTO.getWorkflowType()) || WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE.equals(workflowDTO.getWorkflowType())){ + if (WorkflowConstants.WF_TYPE_AM_API_STATE.equals( + workflowDTO.getWorkflowType()) || WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE.equals( + workflowDTO.getWorkflowType())) { portalNotificationMetaData.setApiContext(workflowDTO.getMetadata("ApiContext")); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml index 747da722370d..2ee1e63fa769 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml @@ -8681,8 +8681,268 @@ paths: "https://127.0.0.1:9443/api/am/publisher/v4/api-products/890a4f4d-09eb-4877-a323-57f6ce2ed79b/lifecycle-state/pending-tasks"' operationId: deleteAPIProductLifecycleStatePendingTasks + ###################################################### + # The "Portal Notifications" resource APIs + ###################################################### + /notifications: + get: + tags: + - Notifications + summary: Get notifications + description: | + Retrieves all notifications for the user. + parameters: + - $ref: '#/components/parameters/sortOrder' + - $ref: '#/components/parameters/limit' + - $ref: '#/components/parameters/offset' + responses: + 200: + description: | + OK. + List of Notifications are returned. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + example: + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + - apim:notifications_view + x-code-samples: + - lang: Curl + source: 'curl -k -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://127.0.0.1:9443/api/am/publisher/v4/notifications"' + operationId: getNotifications + + + delete: + tags: + - Notifications + summary: Delete all notifications + description: | + This operation can be used to delete all the notifications of a user. + responses: + 200: + description: | + OK. + Resource successfully deleted. + content: {} + 401: + $ref: '#/components/responses/Unauthorized' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X DELETE -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://127.0.0.1:9443/api/am/publisher/v4/notifications"' + operationId: deleteNotifications + + patch: + tags: + - Notifications + summary: Mark all Notifications as Read. + description: | + Mark all notifications as read. + requestBody: + description: | + Request body for marking all notifications as read. + content: + application/json: + schema: + title: Patch all notifications request + type: object + properties: + read: + type: boolean + description: | + Indicates whether the notifications should be marked as read. + example: true + required: true + responses: + 200: + description: | + OK. + Successful response with updated Notifications. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + 400: + $ref: '#/components/responses/BadRequest' + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + -H "Content-Type: application/json" -d @data.json "https://localhost:9443/api/am/publisher/v4/notifications"' + operationId: markAllNotificationsAsRead + + + /notifications/{notificationId}: + patch: + tags: + - Notifications + summary: Mark a Notification as Read. + description: | + Mark a specific notification as read. + parameters: + - $ref: '#/components/parameters/notificationId' + requestBody: + description: | + Request body for marking a notification as read. + content: + application/json: + schema: + title: Patch notification request + type: object + properties: + read: + type: boolean + description: | + Indicates whether the notification should be marked as read. + example: true + required: true + responses: + 200: + description: | + OK. + Successful response with updated Notification. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/Notification' + 400: + $ref: '#/components/responses/BadRequest' + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + -H "Content-Type: application/json" -d @data.json "https://localhost:9443/api/am/publisher/v4/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' + operationId: markNotificationAsReadById + + + delete: + tags: + - Notifications + summary: Delete a Notification + description: | + This operation can be used to delete a specific notification of a user. + parameters: + - $ref: '#/components/parameters/notificationId' + responses: + 200: + description: | + OK. + Resource successfully deleted. + content: { } + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://localhost:9443/api/am/publisher/v4/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' + operationId: deleteNotification + + components: schemas: + # "Portal Notification Components" + Notification: + title: Notification object with basic Notification details. + type: object + properties: + notificationId: + type: string + example: 863aef13-dab4-48b4-bf58-7363cd29601a + notificationType: + type: string + enum: + - API_STATE_CHANGE + - API_PRODUCT_STATE_CHANGE + - API_REVISION_DEPLOYMENT + example: + comments: + type: string + example: Application creation is rejected due to some reason. + createdTime: + type: string + example: 2021-02-11 09:57:25 + isRead: + type: boolean + example: false + NotificationList: + title: Notification List + type: object + properties: + count: + type: integer + description: | + Number of Notifications returned. + example: 1 + list: + type: array + items: + $ref: '#/components/schemas/Notification' + pagination: + $ref: '#/components/schemas/Pagination' Comment: title: Comment required: @@ -12637,6 +12897,15 @@ components: moreInfo: "" error: [] parameters: + notificationId: + name: notificationId + in: path + description: | + **NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION + required: true + schema: + type: string + example: 863aef13-dab4-48b4-bf58-7363cd29601a replyLimit: name: replyLimit in: query @@ -13127,3 +13396,6 @@ components: apim:tier_manage: View, update and delete throttling policies apim:api_list_view: View, Retrieve API list apim:api_definition_view: View, Retrieve API definition + apim:notifications_manage: Manage notifications + apim:notifications_view: View notifications + diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationDTO.java new file mode 100644 index 000000000000..019c8a923124 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationDTO.java @@ -0,0 +1,193 @@ +package org.wso2.carbon.apimgt.rest.api.publisher.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + +import javax.xml.bind.annotation.*; +import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope; +import com.fasterxml.jackson.annotation.JsonCreator; + +import javax.validation.Valid; + + + +public class NotificationDTO { + + private String notificationId = null; + + @XmlType(name="NotificationTypeEnum") + @XmlEnum(String.class) + public enum NotificationTypeEnum { + STATE_CHANGE("API_STATE_CHANGE"), + PRODUCT_STATE_CHANGE("API_PRODUCT_STATE_CHANGE"), + REVISION_DEPLOYMENT("API_REVISION_DEPLOYMENT"); + private String value; + + NotificationTypeEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static NotificationTypeEnum fromValue(String v) { + for (NotificationTypeEnum b : NotificationTypeEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } +return null; + } + } + private NotificationTypeEnum notificationType = null; + private String comments = null; + private String createdTime = null; + private Boolean isRead = null; + + /** + **/ + public NotificationDTO notificationId(String notificationId) { + this.notificationId = notificationId; + return this; + } + + + @ApiModelProperty(example = "863aef13-dab4-48b4-bf58-7363cd29601a", value = "") + @JsonProperty("notificationId") + public String getNotificationId() { + return notificationId; + } + public void setNotificationId(String notificationId) { + this.notificationId = notificationId; + } + + /** + **/ + public NotificationDTO notificationType(NotificationTypeEnum notificationType) { + this.notificationType = notificationType; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("notificationType") + public NotificationTypeEnum getNotificationType() { + return notificationType; + } + public void setNotificationType(NotificationTypeEnum notificationType) { + this.notificationType = notificationType; + } + + /** + **/ + public NotificationDTO comments(String comments) { + this.comments = comments; + return this; + } + + + @ApiModelProperty(example = "Application creation is rejected due to some reason.", value = "") + @JsonProperty("comments") + public String getComments() { + return comments; + } + public void setComments(String comments) { + this.comments = comments; + } + + /** + **/ + public NotificationDTO createdTime(String createdTime) { + this.createdTime = createdTime; + return this; + } + + + @ApiModelProperty(example = "2021-02-11 09:57:25", value = "") + @JsonProperty("createdTime") + public String getCreatedTime() { + return createdTime; + } + public void setCreatedTime(String createdTime) { + this.createdTime = createdTime; + } + + /** + **/ + public NotificationDTO isRead(Boolean isRead) { + this.isRead = isRead; + return this; + } + + + @ApiModelProperty(example = "false", value = "") + @JsonProperty("isRead") + public Boolean isIsRead() { + return isRead; + } + public void setIsRead(Boolean isRead) { + this.isRead = isRead; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NotificationDTO notification = (NotificationDTO) o; + return Objects.equals(notificationId, notification.notificationId) && + Objects.equals(notificationType, notification.notificationType) && + Objects.equals(comments, notification.comments) && + Objects.equals(createdTime, notification.createdTime) && + Objects.equals(isRead, notification.isRead); + } + + @Override + public int hashCode() { + return Objects.hash(notificationId, notificationType, comments, createdTime, isRead); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NotificationDTO {\n"); + + sb.append(" notificationId: ").append(toIndentedString(notificationId)).append("\n"); + sb.append(" notificationType: ").append(toIndentedString(notificationType)).append("\n"); + sb.append(" comments: ").append(toIndentedString(comments)).append("\n"); + sb.append(" createdTime: ").append(toIndentedString(createdTime)).append("\n"); + sb.append(" isRead: ").append(toIndentedString(isRead)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationListDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationListDTO.java new file mode 100644 index 000000000000..fb03081d7073 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationListDTO.java @@ -0,0 +1,128 @@ +package org.wso2.carbon.apimgt.rest.api.publisher.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.NotificationDTO; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PaginationDTO; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + +import javax.xml.bind.annotation.*; +import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope; +import com.fasterxml.jackson.annotation.JsonCreator; + +import javax.validation.Valid; + + + +public class NotificationListDTO { + + private Integer count = null; + private List list = new ArrayList(); + private PaginationDTO pagination = null; + + /** + * Number of Notifications returned. + **/ + public NotificationListDTO count(Integer count) { + this.count = count; + return this; + } + + + @ApiModelProperty(example = "1", value = "Number of Notifications returned. ") + @JsonProperty("count") + public Integer getCount() { + return count; + } + public void setCount(Integer count) { + this.count = count; + } + + /** + **/ + public NotificationListDTO list(List list) { + this.list = list; + return this; + } + + + @ApiModelProperty(value = "") + @Valid + @JsonProperty("list") + public List getList() { + return list; + } + public void setList(List list) { + this.list = list; + } + + /** + **/ + public NotificationListDTO pagination(PaginationDTO pagination) { + this.pagination = pagination; + return this; + } + + + @ApiModelProperty(value = "") + @Valid + @JsonProperty("pagination") + public PaginationDTO getPagination() { + return pagination; + } + public void setPagination(PaginationDTO pagination) { + this.pagination = pagination; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NotificationListDTO notificationList = (NotificationListDTO) o; + return Objects.equals(count, notificationList.count) && + Objects.equals(list, notificationList.list) && + Objects.equals(pagination, notificationList.pagination); + } + + @Override + public int hashCode() { + return Objects.hash(count, list, pagination); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NotificationListDTO {\n"); + + sb.append(" count: ").append(toIndentedString(count)).append("\n"); + sb.append(" list: ").append(toIndentedString(list)).append("\n"); + sb.append(" pagination: ").append(toIndentedString(pagination)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/PatchAllNotificationsRequestDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/PatchAllNotificationsRequestDTO.java new file mode 100644 index 000000000000..5b03fc6b94dc --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/PatchAllNotificationsRequestDTO.java @@ -0,0 +1,82 @@ +package org.wso2.carbon.apimgt.rest.api.publisher.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + +import javax.xml.bind.annotation.*; +import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope; +import com.fasterxml.jackson.annotation.JsonCreator; + +import javax.validation.Valid; + + + +public class PatchAllNotificationsRequestDTO { + + private Boolean read = null; + + /** + * Indicates whether the notifications should be marked as read. + **/ + public PatchAllNotificationsRequestDTO read(Boolean read) { + this.read = read; + return this; + } + + + @ApiModelProperty(example = "true", value = "Indicates whether the notifications should be marked as read. ") + @JsonProperty("read") + public Boolean isRead() { + return read; + } + public void setRead(Boolean read) { + this.read = read; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PatchAllNotificationsRequestDTO patchAllNotificationsRequest = (PatchAllNotificationsRequestDTO) o; + return Objects.equals(read, patchAllNotificationsRequest.read); + } + + @Override + public int hashCode() { + return Objects.hash(read); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PatchAllNotificationsRequestDTO {\n"); + + sb.append(" read: ").append(toIndentedString(read)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/PatchNotificationRequestDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/PatchNotificationRequestDTO.java new file mode 100644 index 000000000000..d8c146385deb --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/PatchNotificationRequestDTO.java @@ -0,0 +1,82 @@ +package org.wso2.carbon.apimgt.rest.api.publisher.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + +import javax.xml.bind.annotation.*; +import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope; +import com.fasterxml.jackson.annotation.JsonCreator; + +import javax.validation.Valid; + + + +public class PatchNotificationRequestDTO { + + private Boolean read = null; + + /** + * Indicates whether the notification should be marked as read. + **/ + public PatchNotificationRequestDTO read(Boolean read) { + this.read = read; + return this; + } + + + @ApiModelProperty(example = "true", value = "Indicates whether the notification should be marked as read. ") + @JsonProperty("read") + public Boolean isRead() { + return read; + } + public void setRead(Boolean read) { + this.read = read; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PatchNotificationRequestDTO patchNotificationRequest = (PatchNotificationRequestDTO) o; + return Objects.equals(read, patchNotificationRequest.read); + } + + @Override + public int hashCode() { + return Objects.hash(read); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PatchNotificationRequestDTO {\n"); + + sb.append(" read: ").append(toIndentedString(read)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java new file mode 100644 index 000000000000..6677fd873c68 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java @@ -0,0 +1,137 @@ +package org.wso2.carbon.apimgt.rest.api.publisher.v1; + +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ErrorDTO; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.NotificationDTO; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.NotificationListDTO; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PatchAllNotificationsRequestDTO; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PatchNotificationRequestDTO; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.NotificationsApiService; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.impl.NotificationsApiServiceImpl; +import org.wso2.carbon.apimgt.api.APIManagementException; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.inject.Inject; + +import io.swagger.annotations.*; +import java.io.InputStream; + +import org.apache.cxf.jaxrs.ext.MessageContext; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; + +import java.util.Map; +import java.util.List; +import javax.validation.constraints.*; +@Path("/notifications") + +@Api(description = "the notifications API") + + + + +public class NotificationsApi { + + @Context MessageContext securityContext; + +NotificationsApiService delegate = new NotificationsApiServiceImpl(); + + + @DELETE + @Path("/{notificationId}") + + @Produces({ "application/json" }) + @ApiOperation(value = "Delete a Notification", notes = "This operation can be used to delete a specific notification of a user. ", response = Void.class, authorizations = { + @Authorization(value = "OAuth2Security", scopes = { + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + }) + }, tags={ "Notifications", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. Resource successfully deleted. ", response = Void.class), + @ApiResponse(code = 401, message = "Unauthorized. The user is not authorized.", response = ErrorDTO.class), + @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified.", response = ErrorDTO.class), + @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), + @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) + public Response deleteNotification(@ApiParam(value = "**NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION ",required=true) @PathParam("notificationId") String notificationId) throws APIManagementException{ + return delegate.deleteNotification(notificationId, securityContext); + } + + @DELETE + + + @Produces({ "application/json" }) + @ApiOperation(value = "Delete all notifications", notes = "This operation can be used to delete all the notifications of a user. ", response = Void.class, authorizations = { + @Authorization(value = "OAuth2Security", scopes = { + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + }) + }, tags={ "Notifications", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. Resource successfully deleted. ", response = Void.class), + @ApiResponse(code = 401, message = "Unauthorized. The user is not authorized.", response = ErrorDTO.class), + @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), + @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) + public Response deleteNotifications() throws APIManagementException{ + return delegate.deleteNotifications(securityContext); + } + + @GET + + + @Produces({ "application/json" }) + @ApiOperation(value = "Get notifications", notes = "Retrieves all notifications for the user. ", response = NotificationListDTO.class, authorizations = { + @Authorization(value = "OAuth2Security", scopes = { + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), + @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") + }) + }, tags={ "Notifications", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. List of Notifications are returned. ", response = NotificationListDTO.class), + @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified.", response = ErrorDTO.class), + @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), + @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) + public Response getNotifications( @ApiParam(value = "Order of sorting(ascending/descending). ", allowableValues="asc, desc", defaultValue="desc") @DefaultValue("desc") @QueryParam("sortOrder") String sortOrder, @ApiParam(value = "Maximum size of resource array to return. ", defaultValue="25") @DefaultValue("25") @QueryParam("limit") Integer limit, @ApiParam(value = "Starting point within the complete list of items qualified. ", defaultValue="0") @DefaultValue("0") @QueryParam("offset") Integer offset) throws APIManagementException{ + return delegate.getNotifications(sortOrder, limit, offset, securityContext); + } + + @PATCH + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @ApiOperation(value = "Mark all Notifications as Read.", notes = "Mark all notifications as read. ", response = NotificationListDTO.class, authorizations = { + @Authorization(value = "OAuth2Security", scopes = { + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + }) + }, tags={ "Notifications", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. Successful response with updated Notifications. ", response = NotificationListDTO.class), + @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = ErrorDTO.class), + @ApiResponse(code = 401, message = "Unauthorized. The user is not authorized.", response = ErrorDTO.class), + @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified.", response = ErrorDTO.class), + @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), + @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) + public Response markAllNotificationsAsRead(@ApiParam(value = "" ,required=true) PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO) throws APIManagementException{ + return delegate.markAllNotificationsAsRead(patchAllNotificationsRequestDTO, securityContext); + } + + @PATCH + @Path("/{notificationId}") + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @ApiOperation(value = "Mark a Notification as Read.", notes = "Mark a specific notification as read. ", response = NotificationDTO.class, authorizations = { + @Authorization(value = "OAuth2Security", scopes = { + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + }) + }, tags={ "Notifications" }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. Successful response with updated Notification. ", response = NotificationDTO.class), + @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = ErrorDTO.class), + @ApiResponse(code = 401, message = "Unauthorized. The user is not authorized.", response = ErrorDTO.class), + @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified.", response = ErrorDTO.class), + @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), + @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) + public Response markNotificationAsReadById(@ApiParam(value = "**NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION ",required=true) @PathParam("notificationId") String notificationId, @ApiParam(value = "" ,required=true) PatchNotificationRequestDTO patchNotificationRequestDTO) throws APIManagementException{ + return delegate.markNotificationAsReadById(notificationId, patchNotificationRequestDTO, securityContext); + } +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApiService.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApiService.java new file mode 100644 index 000000000000..d994d62e02a1 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApiService.java @@ -0,0 +1,32 @@ +package org.wso2.carbon.apimgt.rest.api.publisher.v1; + +import org.wso2.carbon.apimgt.rest.api.publisher.v1.*; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.*; + +import org.apache.cxf.jaxrs.ext.MessageContext; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; + +import org.wso2.carbon.apimgt.api.APIManagementException; + +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ErrorDTO; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.NotificationDTO; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.NotificationListDTO; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PatchAllNotificationsRequestDTO; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PatchNotificationRequestDTO; + +import java.util.List; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public interface NotificationsApiService { + public Response deleteNotification(String notificationId, MessageContext messageContext) throws APIManagementException; + public Response deleteNotifications(MessageContext messageContext) throws APIManagementException; + public Response getNotifications(String sortOrder, Integer limit, Integer offset, MessageContext messageContext) throws APIManagementException; + public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, MessageContext messageContext) throws APIManagementException; + public Response markNotificationAsReadById(String notificationId, PatchNotificationRequestDTO patchNotificationRequestDTO, MessageContext messageContext) throws APIManagementException; +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java new file mode 100644 index 000000000000..d1b7b6c07e1b --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java @@ -0,0 +1,121 @@ +package org.wso2.carbon.apimgt.rest.api.publisher.v1.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.APIProvider; +import org.wso2.carbon.apimgt.api.model.Notification; +import org.wso2.carbon.apimgt.api.model.NotificationList; +import org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil; +import org.wso2.carbon.apimgt.rest.api.common.RestApiConstants; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.*; + +import org.apache.cxf.jaxrs.ext.MessageContext; + +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PatchAllNotificationsRequestDTO; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PatchNotificationRequestDTO; +import org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil; + +import javax.ws.rs.core.Response; + +public class NotificationsApiServiceImpl implements NotificationsApiService { + + private static final Log log = LogFactory.getLog(NotificationsApiServiceImpl.class); + + @Override + public Response getNotifications(String sortOrder, Integer limit, Integer offset, MessageContext messageContext) throws APIManagementException { + + + limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT; + offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; + sortOrder = sortOrder != null ? sortOrder : RestApiConstants.DESCENDING_SORT_ORDER; + NotificationList notificationList; + + + String username = RestApiCommonUtil.getLoggedInUsername(); + try { + String organization = RestApiUtil.getValidatedOrganization(messageContext); + APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); + notificationList = apiProvider.getNotifications(username, organization, sortOrder, limit, offset); + } catch (APIManagementException e) { + throw new APIManagementException("Error while getting notifications", e); + } + + return Response.ok().entity(notificationList).build(); + } + + @Override + public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, MessageContext messageContext) + throws APIManagementException { + NotificationList notificationList ; + String username = RestApiCommonUtil.getLoggedInUsername(); + try { + String organization = RestApiUtil.getValidatedOrganization(messageContext); + APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); + notificationList = apiProvider.markAllNotificationsAsRead(username, organization); + if(notificationList == null){ + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (APIManagementException e) { + throw new APIManagementException("Error while getting notifications", e); + } + + return Response.ok().entity(notificationList).build(); + } + + @Override + public Response markNotificationAsReadById(String notificationId, PatchNotificationRequestDTO patchNotificationRequestDTO, + MessageContext messageContext) throws APIManagementException { + Notification notification ; + String username = RestApiCommonUtil.getLoggedInUsername(); + try { + String organization = RestApiUtil.getValidatedOrganization(messageContext); + APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); + notification = apiProvider.markNotificationAsReadById(username, organization, notificationId); + if(notification == null){ + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (APIManagementException e) { + throw new APIManagementException("Error while getting notification", e); + } + + return Response.ok().entity(notification).build(); + } + + @Override + public Response deleteNotifications(MessageContext messageContext) throws APIManagementException { + + String username = RestApiCommonUtil.getLoggedInUsername(); + try { + String organization = RestApiUtil.getValidatedOrganization(messageContext); + APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); + boolean result = apiProvider.deleteAllNotifications(username, organization); + if(!result){ + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (APIManagementException e) { + throw new APIManagementException("Error while deleting notifications", e); + } + return Response.ok().build(); + } + + + + @Override + public Response deleteNotification(String notificationId, MessageContext messageContext) + throws APIManagementException { + String username = RestApiCommonUtil.getLoggedInUsername(); + try { + String organization = RestApiUtil.getValidatedOrganization(messageContext); + APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); + boolean result = apiProvider.deleteNotificationById(username, organization, notificationId); + if(!result){ + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (APIManagementException e) { + throw new APIManagementException("Error while deleting notifications", e); + } + return Response.ok().build(); + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml index 747da722370d..2ee1e63fa769 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml @@ -8681,8 +8681,268 @@ paths: "https://127.0.0.1:9443/api/am/publisher/v4/api-products/890a4f4d-09eb-4877-a323-57f6ce2ed79b/lifecycle-state/pending-tasks"' operationId: deleteAPIProductLifecycleStatePendingTasks + ###################################################### + # The "Portal Notifications" resource APIs + ###################################################### + /notifications: + get: + tags: + - Notifications + summary: Get notifications + description: | + Retrieves all notifications for the user. + parameters: + - $ref: '#/components/parameters/sortOrder' + - $ref: '#/components/parameters/limit' + - $ref: '#/components/parameters/offset' + responses: + 200: + description: | + OK. + List of Notifications are returned. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + example: + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + - apim:notifications_view + x-code-samples: + - lang: Curl + source: 'curl -k -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://127.0.0.1:9443/api/am/publisher/v4/notifications"' + operationId: getNotifications + + + delete: + tags: + - Notifications + summary: Delete all notifications + description: | + This operation can be used to delete all the notifications of a user. + responses: + 200: + description: | + OK. + Resource successfully deleted. + content: {} + 401: + $ref: '#/components/responses/Unauthorized' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X DELETE -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://127.0.0.1:9443/api/am/publisher/v4/notifications"' + operationId: deleteNotifications + + patch: + tags: + - Notifications + summary: Mark all Notifications as Read. + description: | + Mark all notifications as read. + requestBody: + description: | + Request body for marking all notifications as read. + content: + application/json: + schema: + title: Patch all notifications request + type: object + properties: + read: + type: boolean + description: | + Indicates whether the notifications should be marked as read. + example: true + required: true + responses: + 200: + description: | + OK. + Successful response with updated Notifications. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + 400: + $ref: '#/components/responses/BadRequest' + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + -H "Content-Type: application/json" -d @data.json "https://localhost:9443/api/am/publisher/v4/notifications"' + operationId: markAllNotificationsAsRead + + + /notifications/{notificationId}: + patch: + tags: + - Notifications + summary: Mark a Notification as Read. + description: | + Mark a specific notification as read. + parameters: + - $ref: '#/components/parameters/notificationId' + requestBody: + description: | + Request body for marking a notification as read. + content: + application/json: + schema: + title: Patch notification request + type: object + properties: + read: + type: boolean + description: | + Indicates whether the notification should be marked as read. + example: true + required: true + responses: + 200: + description: | + OK. + Successful response with updated Notification. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/Notification' + 400: + $ref: '#/components/responses/BadRequest' + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + -H "Content-Type: application/json" -d @data.json "https://localhost:9443/api/am/publisher/v4/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' + operationId: markNotificationAsReadById + + + delete: + tags: + - Notifications + summary: Delete a Notification + description: | + This operation can be used to delete a specific notification of a user. + parameters: + - $ref: '#/components/parameters/notificationId' + responses: + 200: + description: | + OK. + Resource successfully deleted. + content: { } + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://localhost:9443/api/am/publisher/v4/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' + operationId: deleteNotification + + components: schemas: + # "Portal Notification Components" + Notification: + title: Notification object with basic Notification details. + type: object + properties: + notificationId: + type: string + example: 863aef13-dab4-48b4-bf58-7363cd29601a + notificationType: + type: string + enum: + - API_STATE_CHANGE + - API_PRODUCT_STATE_CHANGE + - API_REVISION_DEPLOYMENT + example: + comments: + type: string + example: Application creation is rejected due to some reason. + createdTime: + type: string + example: 2021-02-11 09:57:25 + isRead: + type: boolean + example: false + NotificationList: + title: Notification List + type: object + properties: + count: + type: integer + description: | + Number of Notifications returned. + example: 1 + list: + type: array + items: + $ref: '#/components/schemas/Notification' + pagination: + $ref: '#/components/schemas/Pagination' Comment: title: Comment required: @@ -12637,6 +12897,15 @@ components: moreInfo: "" error: [] parameters: + notificationId: + name: notificationId + in: path + description: | + **NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION + required: true + schema: + type: string + example: 863aef13-dab4-48b4-bf58-7363cd29601a replyLimit: name: replyLimit in: query @@ -13127,3 +13396,6 @@ components: apim:tier_manage: View, update and delete throttling policies apim:api_list_view: View, Retrieve API list apim:api_definition_view: View, Retrieve API definition + apim:notifications_manage: Manage notifications + apim:notifications_view: View notifications + diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/webapp/WEB-INF/beans.xml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/webapp/WEB-INF/beans.xml index c71906db5707..682b340b5baf 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/webapp/WEB-INF/beans.xml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/webapp/WEB-INF/beans.xml @@ -36,6 +36,7 @@ + diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql index e613e4148e44..6cc995e26761 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql @@ -2455,15 +2455,15 @@ CREATE TABLE IF NOT EXISTS AM_NOTIFICATION ( NOTIFICATION_TYPE VARCHAR(50) NOT NULL, CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, NOTIFICATION_METADATA BLOB DEFAULT NULL, - ORGANIZATION VARCHAR(100) NOT NULL, PRIMARY KEY (NOTIFICATION_ID) ); CREATE TABLE IF NOT EXISTS AM_NOTIFICATION_END_USERS ( NOTIFICATION_ID VARCHAR(64) NOT NULL, DESTINATION_USER VARCHAR(255) NOT NULL, + ORGANIZATION VARCHAR(100) NOT NULL, IS_READ BOOLEAN DEFAULT FALSE, - PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER), + PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION), FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE ); From ee1f8859ab130dd31e5d41dbe83d28305984a055 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Wed, 28 Feb 2024 16:35:27 +0530 Subject: [PATCH 03/23] Change existing test cases to suppress sendPortalNotifications() --- .../ApplicationCreationWSWorkflowExecutorTest.java | 7 +++++++ .../ApplicationRegistrationWSWorkflowExecutorTest.java | 3 +++ .../SubscriptionCreationWSWorkflowExecutorTest.java | 5 +++++ .../impl/workflow/UserSignUpWSWorkflowExecutorTest.java | 5 ++++- 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java index dadbb78fa66c..94596b3f9ace 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java @@ -88,11 +88,14 @@ public void testWorkflowApprove() throws APIManagementException, WorkflowExcepti PowerMockito.doNothing().when(apiMgtDAO).updateApplicationStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_APPROVED); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)).updateApplicationStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_APPROVED); + + } @Test @@ -108,6 +111,7 @@ public void testWorkflowReject() throws APIManagementException, WorkflowExceptio PowerMockito.doNothing().when(apiMgtDAO).updateApplicationStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_REJECTED); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)).updateApplicationStatus( @@ -128,6 +132,7 @@ public void testWorkflowCreate() throws APIManagementException, WorkflowExceptio PowerMockito.doNothing().when(apiMgtDAO).updateApplicationStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_CREATED); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)).updateApplicationStatus( @@ -182,6 +187,7 @@ public void testWorkflowCompleteExceptionWhenStatusUpdateFailed() throws APIMana "creation process")).when(apiMgtDAO).updateApplicationStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_APPROVED); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); } @@ -241,6 +247,7 @@ public void testWorkflowNotAllowedStatus() throws APIManagementException, Workfl Application app = Mockito.mock(Application.class); PowerMockito.doReturn(app).when(apiMgtDAO) .getApplicationById(Integer.parseInt(workflowDTO.getWorkflowReference())); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); // shouldn't update status diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java index f10390b26bd3..3add5cd9e2a8 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java @@ -42,6 +42,7 @@ import org.wso2.carbon.apimgt.impl.TestUtils; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; import org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.apimgt.impl.factory.KeyManagerHolder; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.utils.ConfigurationContextService; @@ -190,6 +191,7 @@ public void testCompletingApplicationRegistrationWSWFWhenWFRejected() throws Exc applicationRegistrationWSWorkflowExecutor.setUsername(adminUsername); applicationRegistrationWSWorkflowExecutor.setPassword(adminPassword.toCharArray()); workflowDTO.setStatus(WorkflowStatus.REJECTED); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); try { Assert.assertNotNull(applicationRegistrationWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { @@ -215,6 +217,7 @@ public void testCompletingApplicationRegistrationWSWFWhenWFApproved() throws Exc applicationRegistrationWSWorkflowExecutor.setPassword(adminPassword.toCharArray()); workflowDTO.setStatus(WorkflowStatus.APPROVED); workflowDTO.setKeyManager("default"); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); try { Assert.assertNotNull(applicationRegistrationWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java index 17507c9de0de..00e90d21428e 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java @@ -86,6 +86,7 @@ public void testWorkflowApprove() throws APIManagementException, WorkflowExcepti workflowDTO.setStatus(WorkflowStatus.APPROVED); PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.UNBLOCKED); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)).updateSubscriptionStatus( @@ -101,6 +102,7 @@ public void testWorkflowReject() throws APIManagementException, WorkflowExceptio workflowDTO.setStatus(WorkflowStatus.REJECTED); PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)).updateSubscriptionStatus( @@ -115,6 +117,7 @@ public void testWorkflowRejectException() throws APIManagementException, Workflo workflowDTO.setStatus(WorkflowStatus.REJECTED); PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO).updateSubscriptionStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); @@ -128,6 +131,7 @@ public void testWorkflowApproveException() throws APIManagementException, Workfl workflowDTO.setStatus(WorkflowStatus.APPROVED); PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO).updateSubscriptionStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.UNBLOCKED); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); @@ -139,6 +143,7 @@ public void testWorkflowNotAllowedStatus() throws APIManagementException, Workfl workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); workflowDTO.setStatus(WorkflowStatus.CREATED); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); // shouldn't update status diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java index 013057811abb..f764267a5aa8 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java @@ -184,6 +184,7 @@ public void testCompletingUserSignUpWorkflowApprovedByAdmin() throws Exception { Mockito.when(userStoreManager.isExistingRole(signUpRole)).thenReturn(true); PowerMockito.doNothing().when(userStoreManager).updateRoleListOfUser(testUsername, null, new String[]{ signUpRole}); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); try { @@ -203,6 +204,7 @@ public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exce PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true); Mockito.when(userStoreManager.isExistingRole(signUpRole)).thenReturn(true); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); @@ -246,7 +248,7 @@ public void testCompletingUserSignUpWorkflowRejectedByAdmin() throws Exception { userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); - + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); try { @@ -264,6 +266,7 @@ public void testFailureToCompleteUserSignUpWorkflowRejectedByAdmin() throws Exce userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); + PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); From d346348599ee253ce73cfe60bee2432d72433dc9 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Thu, 29 Feb 2024 13:29:33 +0530 Subject: [PATCH 04/23] Implement Developer Notification backend with APIs --- .../wso2/carbon/apimgt/api/APIConsumer.java | 10 + .../carbon/apimgt/impl/APIConsumerImpl.java | 29 ++ .../src/main/resources/devportal-api.yaml | 296 ++++++++++++++++++ .../rest/api/store/v1/NotificationsApi.java | 137 ++++++++ .../api/store/v1/NotificationsApiService.java | 32 ++ .../api/store/v1/dto/NotificationDTO.java | 196 ++++++++++++ .../api/store/v1/dto/NotificationListDTO.java | 128 ++++++++ .../dto/PatchAllNotificationsRequestDTO.java | 82 +++++ .../v1/dto/PatchNotificationRequestDTO.java | 82 +++++ .../v1/impl/NotificationsApiServiceImpl.java | 125 ++++++++ .../src/main/resources/devportal-api.yaml | 296 ++++++++++++++++++ .../src/main/webapp/WEB-INF/beans.xml | 1 + 12 files changed, 1414 insertions(+) create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApiService.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationDTO.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationListDTO.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/PatchAllNotificationsRequestDTO.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/PatchNotificationRequestDTO.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java index 05ff8bbc67ed..ecd1e8307845 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java @@ -869,4 +869,14 @@ boolean isKeyManagerByNameAllowedForUser(String keyManagerName, String organizat * @throws APIManagementException */ boolean removalKeys(Application application, String keyMappingId, String xWSO2Tenant) throws APIManagementException; + NotificationList getNotifications(String username, String organization, String sortOrder, Integer limit, Integer offset) + throws APIManagementException; + + NotificationList markAllNotificationsAsRead(String username, String organization) throws APIManagementException; + + Notification markNotificationAsReadById(String username, String organization, String notificationId) throws APIManagementException; + + boolean deleteNotificationById(String username, String organization, String notificationId) throws APIManagementException; + + boolean deleteAllNotifications(String username, String organization) throws APIManagementException; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java index 94d8ea24d00f..b2d47bead0b1 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java @@ -4595,6 +4595,35 @@ public boolean isKeyManagerByNameAllowedForUser(String keyManagerName, String or return true; } + @Override + public NotificationList getNotifications(String username, String organization, String sortOrder, Integer limit, + Integer offset) throws APIManagementException{ + return portalNotificationDAO.getNotifications(username, organization, sortOrder, limit, offset); + } + + @Override + public NotificationList markAllNotificationsAsRead(String username, String organization) + throws APIManagementException { + return portalNotificationDAO.markAllNotificationsAsRead(username, organization); + } + + @Override + public Notification markNotificationAsReadById(String username, String organization, String notificationId) + throws APIManagementException { + return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId); + } + + @Override + public boolean deleteNotificationById(String username, String organization, String notificationId) + throws APIManagementException { + return portalNotificationDAO.deleteNotificationById(username, organization, notificationId); + } + + @Override + public boolean deleteAllNotifications(String username, String organization) throws APIManagementException { + return portalNotificationDAO.deleteAllNotifications(username, organization); + } + public static boolean hasIntersection(String[] arr1, String[] arr2) { Set set = new HashSet<>(); diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml index 01043e4769a8..79fc678e2a16 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml @@ -3770,8 +3770,279 @@ paths: source: 'curl -k -X POST -d request.json "https://localhost:9443/api/am/devportal/v3/apis/marketplace-assistant/chat"' + + ###################################################### + # The "Portal Notifications" resource APIs + ###################################################### + /notifications: + get: + tags: + - Notifications + summary: Get notifications + description: | + Retrieves all notifications for the user. + parameters: + - name: sortOrder + in: query + schema: + type: string + enum: + - asc + - desc + - $ref: '#/components/parameters/limit' + - $ref: '#/components/parameters/offset' + responses: + 200: + description: | + OK. + List of Notifications are returned. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + example: + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + - apim:notifications_view + x-code-samples: + - lang: Curl + source: 'curl -k -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://localhost:9443/api/am/devportal/v3/notifications"' + operationId: getNotifications + + + delete: + tags: + - Notifications + summary: Delete all notifications + description: | + This operation can be used to delete all the notifications of a user. + responses: + 200: + description: | + OK. + Resource successfully deleted. + content: { } + 401: + $ref: '#/components/responses/Unauthorized' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X DELETE -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://localhost:9443/api/am/devportal/v3/notifications"' + operationId: deleteNotifications + + + patch: + tags: + - Notifications + summary: Mark all Notifications as Read. + description: | + Mark all notifications as read. + requestBody: + description: | + Request body for marking all notifications as read. + content: + application/json: + schema: + title: Patch all notifications request + type: object + properties: + read: + type: boolean + description: | + Indicates whether the notifications should be marked as read. + example: true + required: true + responses: + 200: + description: | + OK. + Successful response with updated Notifications. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + 400: + $ref: '#/components/responses/BadRequest' + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + -H "Content-Type: application/json" -d @data.json "https://localhost:9443/api/am/devportal/v3/notifications"' + operationId: markAllNotificationsAsRead + + + /notifications/{notificationId}: + patch: + tags: + - Notifications + summary: Mark a Notification as Read. + description: | + Mark a specific notification as read. + parameters: + - $ref: '#/components/parameters/notificationId' + requestBody: + description: | + Request body for marking a notification as read. + content: + application/json: + schema: + title: Patch notification request + type: object + properties: + read: + type: boolean + description: | + Indicates whether the notification should be marked as read. + example: true + required: true + responses: + 200: + description: | + OK. + Successful response with updated Notification. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/Notification' + 400: + $ref: '#/components/responses/BadRequest' + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + -H "Content-Type: application/json" -d @data.json "https://localhost:9443/api/am/devportal/v3/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' + operationId: markNotificationAsReadById + + + delete: + tags: + - Notifications + summary: Delete a Notification + description: | + This operation can be used to delete a specific notification of a user. + parameters: + - $ref: '#/components/parameters/notificationId' + responses: + 200: + description: | + OK. + Resource successfully deleted. + content: { } + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://localhost:9443/api/am/devportal/v3/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' + operationId: deleteNotification + + components: schemas: + # "Portal Notification Components" + Notification: + title: Notification object with basic Notification details. + type: object + properties: + notificationId: + type: string + example: 863aef13-dab4-48b4-bf58-7363cd29601a + notificationType: + type: string + enum: + - APPLICATION_CREATION + - SUBSCRIPTION_CREATION + - SUBSCRIPTION_UPDATE + - SUBSCRIPTION_DELETION + - APPLICATION_REGISTRATION_PRODUCTION + - APPLICATION_REGISTRATION_SANDBOX + example: + comments: + type: string + example: Application creation is rejected due to some reason. + createdTime: + type: string + example: 2021-02-11 09:57:25 + isRead: + type: boolean + example: false + NotificationList: + title: Notification List + type: object + properties: + count: + type: integer + description: | + Number of Notifications returned. + example: 1 + list: + type: array + items: + $ref: '#/components/schemas/Notification' + pagination: + $ref: '#/components/schemas/Pagination' APIList: title: API List type: object @@ -6209,6 +6480,20 @@ components: description: The specified resource does not exist moreInfo: "" error: [] + Forbidden: + description: Forbidden. The request must be conditional but no condition has + been specified. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + example: + code: 403 + message: Forbidden + description: The request must be conditional but no condition has been + specified + moreInfo: "" + error: [ ] PreconditionFailed: description: Precondition Failed. The request has not been performed because one of the preconditions is not met. @@ -6261,6 +6546,15 @@ components: moreInfo: "" error: [ ] parameters: + notificationId: + name: notificationId + in: path + description: | + **NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION + required: true + schema: + type: string + example: 863aef13-dab4-48b4-bf58-7363cd29601a parentCommentID: name: replyTo in: query @@ -6528,3 +6822,5 @@ components: apim:sub_alert_manage: Retrieve, subscribe and configure Developer Portal alert types apim:app_import_export: Import and export applications related operations apim:admin: Manage all admin operations + apim:notifications_manage: Manage notifications + apim:notifications_view: View notifications diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java new file mode 100644 index 000000000000..135286a50ed0 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java @@ -0,0 +1,137 @@ +package org.wso2.carbon.apimgt.rest.api.store.v1; + +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.ErrorDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.NotificationDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.NotificationListDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.PatchAllNotificationsRequestDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.PatchNotificationRequestDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.NotificationsApiService; +import org.wso2.carbon.apimgt.rest.api.store.v1.impl.NotificationsApiServiceImpl; +import org.wso2.carbon.apimgt.api.APIManagementException; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.inject.Inject; + +import io.swagger.annotations.*; +import java.io.InputStream; + +import org.apache.cxf.jaxrs.ext.MessageContext; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; + +import java.util.Map; +import java.util.List; +import javax.validation.constraints.*; +@Path("/notifications") + +@Api(description = "the notifications API") + + + + +public class NotificationsApi { + + @Context MessageContext securityContext; + +NotificationsApiService delegate = new NotificationsApiServiceImpl(); + + + @DELETE + @Path("/{notificationId}") + + @Produces({ "application/json" }) + @ApiOperation(value = "Delete a Notification", notes = "This operation can be used to delete a specific notification of a user. ", response = Void.class, authorizations = { + @Authorization(value = "OAuth2Security", scopes = { + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + }) + }, tags={ "Notifications", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. Resource successfully deleted. ", response = Void.class), + @ApiResponse(code = 401, message = "Unauthorized. The user is not authorized.", response = ErrorDTO.class), + @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified.", response = ErrorDTO.class), + @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), + @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) + public Response deleteNotification(@ApiParam(value = "**NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION ",required=true) @PathParam("notificationId") String notificationId) throws APIManagementException{ + return delegate.deleteNotification(notificationId, securityContext); + } + + @DELETE + + + @Produces({ "application/json" }) + @ApiOperation(value = "Delete all notifications", notes = "This operation can be used to delete all the notifications of a user. ", response = Void.class, authorizations = { + @Authorization(value = "OAuth2Security", scopes = { + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + }) + }, tags={ "Notifications", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. Resource successfully deleted. ", response = Void.class), + @ApiResponse(code = 401, message = "Unauthorized. The user is not authorized.", response = ErrorDTO.class), + @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), + @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) + public Response deleteNotifications() throws APIManagementException{ + return delegate.deleteNotifications(securityContext); + } + + @GET + + + @Produces({ "application/json" }) + @ApiOperation(value = "Get notifications", notes = "Retrieves all notifications for the user. ", response = NotificationListDTO.class, authorizations = { + @Authorization(value = "OAuth2Security", scopes = { + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), + @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") + }) + }, tags={ "Notifications", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. List of Notifications are returned. ", response = NotificationListDTO.class), + @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified.", response = ErrorDTO.class), + @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), + @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) + public Response getNotifications( @ApiParam(value = "", allowableValues="asc, desc") @QueryParam("sortOrder") String sortOrder, @ApiParam(value = "Maximum size of resource array to return. ", defaultValue="25") @DefaultValue("25") @QueryParam("limit") Integer limit, @ApiParam(value = "Starting point within the complete list of items qualified. ", defaultValue="0") @DefaultValue("0") @QueryParam("offset") Integer offset) throws APIManagementException{ + return delegate.getNotifications(sortOrder, limit, offset, securityContext); + } + + @PATCH + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @ApiOperation(value = "Mark all Notifications as Read.", notes = "Mark all notifications as read. ", response = NotificationListDTO.class, authorizations = { + @Authorization(value = "OAuth2Security", scopes = { + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + }) + }, tags={ "Notifications", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. Successful response with updated Notifications. ", response = NotificationListDTO.class), + @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = ErrorDTO.class), + @ApiResponse(code = 401, message = "Unauthorized. The user is not authorized.", response = ErrorDTO.class), + @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified.", response = ErrorDTO.class), + @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), + @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) + public Response markAllNotificationsAsRead(@ApiParam(value = "" ,required=true) PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO) throws APIManagementException{ + return delegate.markAllNotificationsAsRead(patchAllNotificationsRequestDTO, securityContext); + } + + @PATCH + @Path("/{notificationId}") + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @ApiOperation(value = "Mark a Notification as Read.", notes = "Mark a specific notification as read. ", response = NotificationDTO.class, authorizations = { + @Authorization(value = "OAuth2Security", scopes = { + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + }) + }, tags={ "Notifications" }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. Successful response with updated Notification. ", response = NotificationDTO.class), + @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = ErrorDTO.class), + @ApiResponse(code = 401, message = "Unauthorized. The user is not authorized.", response = ErrorDTO.class), + @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified.", response = ErrorDTO.class), + @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), + @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) + public Response markNotificationAsReadById(@ApiParam(value = "**NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION ",required=true) @PathParam("notificationId") String notificationId, @ApiParam(value = "" ,required=true) PatchNotificationRequestDTO patchNotificationRequestDTO) throws APIManagementException{ + return delegate.markNotificationAsReadById(notificationId, patchNotificationRequestDTO, securityContext); + } +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApiService.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApiService.java new file mode 100644 index 000000000000..75bbe66b8ce9 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApiService.java @@ -0,0 +1,32 @@ +package org.wso2.carbon.apimgt.rest.api.store.v1; + +import org.wso2.carbon.apimgt.rest.api.store.v1.*; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.*; + +import org.apache.cxf.jaxrs.ext.MessageContext; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; + +import org.wso2.carbon.apimgt.api.APIManagementException; + +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.ErrorDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.NotificationDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.NotificationListDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.PatchAllNotificationsRequestDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.PatchNotificationRequestDTO; + +import java.util.List; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public interface NotificationsApiService { + public Response deleteNotification(String notificationId, MessageContext messageContext) throws APIManagementException; + public Response deleteNotifications(MessageContext messageContext) throws APIManagementException; + public Response getNotifications(String sortOrder, Integer limit, Integer offset, MessageContext messageContext) throws APIManagementException; + public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, MessageContext messageContext) throws APIManagementException; + public Response markNotificationAsReadById(String notificationId, PatchNotificationRequestDTO patchNotificationRequestDTO, MessageContext messageContext) throws APIManagementException; +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationDTO.java new file mode 100644 index 000000000000..f479380f1c5e --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationDTO.java @@ -0,0 +1,196 @@ +package org.wso2.carbon.apimgt.rest.api.store.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + +import javax.xml.bind.annotation.*; +import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope; +import com.fasterxml.jackson.annotation.JsonCreator; + +import javax.validation.Valid; + + + +public class NotificationDTO { + + private String notificationId = null; + + @XmlType(name="NotificationTypeEnum") + @XmlEnum(String.class) + public enum NotificationTypeEnum { + APPLICATION_CREATION("APPLICATION_CREATION"), + SUBSCRIPTION_CREATION("SUBSCRIPTION_CREATION"), + SUBSCRIPTION_UPDATE("SUBSCRIPTION_UPDATE"), + SUBSCRIPTION_DELETION("SUBSCRIPTION_DELETION"), + APPLICATION_REGISTRATION_PRODUCTION("APPLICATION_REGISTRATION_PRODUCTION"), + APPLICATION_REGISTRATION_SANDBOX("APPLICATION_REGISTRATION_SANDBOX"); + private String value; + + NotificationTypeEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static NotificationTypeEnum fromValue(String v) { + for (NotificationTypeEnum b : NotificationTypeEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } +return null; + } + } + private NotificationTypeEnum notificationType = null; + private String comments = null; + private String createdTime = null; + private Boolean isRead = null; + + /** + **/ + public NotificationDTO notificationId(String notificationId) { + this.notificationId = notificationId; + return this; + } + + + @ApiModelProperty(example = "863aef13-dab4-48b4-bf58-7363cd29601a", value = "") + @JsonProperty("notificationId") + public String getNotificationId() { + return notificationId; + } + public void setNotificationId(String notificationId) { + this.notificationId = notificationId; + } + + /** + **/ + public NotificationDTO notificationType(NotificationTypeEnum notificationType) { + this.notificationType = notificationType; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("notificationType") + public NotificationTypeEnum getNotificationType() { + return notificationType; + } + public void setNotificationType(NotificationTypeEnum notificationType) { + this.notificationType = notificationType; + } + + /** + **/ + public NotificationDTO comments(String comments) { + this.comments = comments; + return this; + } + + + @ApiModelProperty(example = "Application creation is rejected due to some reason.", value = "") + @JsonProperty("comments") + public String getComments() { + return comments; + } + public void setComments(String comments) { + this.comments = comments; + } + + /** + **/ + public NotificationDTO createdTime(String createdTime) { + this.createdTime = createdTime; + return this; + } + + + @ApiModelProperty(example = "2021-02-11 09:57:25", value = "") + @JsonProperty("createdTime") + public String getCreatedTime() { + return createdTime; + } + public void setCreatedTime(String createdTime) { + this.createdTime = createdTime; + } + + /** + **/ + public NotificationDTO isRead(Boolean isRead) { + this.isRead = isRead; + return this; + } + + + @ApiModelProperty(example = "false", value = "") + @JsonProperty("isRead") + public Boolean isIsRead() { + return isRead; + } + public void setIsRead(Boolean isRead) { + this.isRead = isRead; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NotificationDTO notification = (NotificationDTO) o; + return Objects.equals(notificationId, notification.notificationId) && + Objects.equals(notificationType, notification.notificationType) && + Objects.equals(comments, notification.comments) && + Objects.equals(createdTime, notification.createdTime) && + Objects.equals(isRead, notification.isRead); + } + + @Override + public int hashCode() { + return Objects.hash(notificationId, notificationType, comments, createdTime, isRead); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NotificationDTO {\n"); + + sb.append(" notificationId: ").append(toIndentedString(notificationId)).append("\n"); + sb.append(" notificationType: ").append(toIndentedString(notificationType)).append("\n"); + sb.append(" comments: ").append(toIndentedString(comments)).append("\n"); + sb.append(" createdTime: ").append(toIndentedString(createdTime)).append("\n"); + sb.append(" isRead: ").append(toIndentedString(isRead)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationListDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationListDTO.java new file mode 100644 index 000000000000..153a22d82679 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationListDTO.java @@ -0,0 +1,128 @@ +package org.wso2.carbon.apimgt.rest.api.store.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.NotificationDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.PaginationDTO; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + +import javax.xml.bind.annotation.*; +import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope; +import com.fasterxml.jackson.annotation.JsonCreator; + +import javax.validation.Valid; + + + +public class NotificationListDTO { + + private Integer count = null; + private List list = new ArrayList(); + private PaginationDTO pagination = null; + + /** + * Number of Notifications returned. + **/ + public NotificationListDTO count(Integer count) { + this.count = count; + return this; + } + + + @ApiModelProperty(example = "1", value = "Number of Notifications returned. ") + @JsonProperty("count") + public Integer getCount() { + return count; + } + public void setCount(Integer count) { + this.count = count; + } + + /** + **/ + public NotificationListDTO list(List list) { + this.list = list; + return this; + } + + + @ApiModelProperty(value = "") + @Valid + @JsonProperty("list") + public List getList() { + return list; + } + public void setList(List list) { + this.list = list; + } + + /** + **/ + public NotificationListDTO pagination(PaginationDTO pagination) { + this.pagination = pagination; + return this; + } + + + @ApiModelProperty(value = "") + @Valid + @JsonProperty("pagination") + public PaginationDTO getPagination() { + return pagination; + } + public void setPagination(PaginationDTO pagination) { + this.pagination = pagination; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NotificationListDTO notificationList = (NotificationListDTO) o; + return Objects.equals(count, notificationList.count) && + Objects.equals(list, notificationList.list) && + Objects.equals(pagination, notificationList.pagination); + } + + @Override + public int hashCode() { + return Objects.hash(count, list, pagination); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NotificationListDTO {\n"); + + sb.append(" count: ").append(toIndentedString(count)).append("\n"); + sb.append(" list: ").append(toIndentedString(list)).append("\n"); + sb.append(" pagination: ").append(toIndentedString(pagination)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/PatchAllNotificationsRequestDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/PatchAllNotificationsRequestDTO.java new file mode 100644 index 000000000000..c01895a2d139 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/PatchAllNotificationsRequestDTO.java @@ -0,0 +1,82 @@ +package org.wso2.carbon.apimgt.rest.api.store.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + +import javax.xml.bind.annotation.*; +import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope; +import com.fasterxml.jackson.annotation.JsonCreator; + +import javax.validation.Valid; + + + +public class PatchAllNotificationsRequestDTO { + + private Boolean read = null; + + /** + * Indicates whether the notifications should be marked as read. + **/ + public PatchAllNotificationsRequestDTO read(Boolean read) { + this.read = read; + return this; + } + + + @ApiModelProperty(example = "true", value = "Indicates whether the notifications should be marked as read. ") + @JsonProperty("read") + public Boolean isRead() { + return read; + } + public void setRead(Boolean read) { + this.read = read; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PatchAllNotificationsRequestDTO patchAllNotificationsRequest = (PatchAllNotificationsRequestDTO) o; + return Objects.equals(read, patchAllNotificationsRequest.read); + } + + @Override + public int hashCode() { + return Objects.hash(read); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PatchAllNotificationsRequestDTO {\n"); + + sb.append(" read: ").append(toIndentedString(read)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/PatchNotificationRequestDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/PatchNotificationRequestDTO.java new file mode 100644 index 000000000000..11aa736b599a --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/PatchNotificationRequestDTO.java @@ -0,0 +1,82 @@ +package org.wso2.carbon.apimgt.rest.api.store.v1.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + +import javax.xml.bind.annotation.*; +import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope; +import com.fasterxml.jackson.annotation.JsonCreator; + +import javax.validation.Valid; + + + +public class PatchNotificationRequestDTO { + + private Boolean read = null; + + /** + * Indicates whether the notification should be marked as read. + **/ + public PatchNotificationRequestDTO read(Boolean read) { + this.read = read; + return this; + } + + + @ApiModelProperty(example = "true", value = "Indicates whether the notification should be marked as read. ") + @JsonProperty("read") + public Boolean isRead() { + return read; + } + public void setRead(Boolean read) { + this.read = read; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PatchNotificationRequestDTO patchNotificationRequest = (PatchNotificationRequestDTO) o; + return Objects.equals(read, patchNotificationRequest.read); + } + + @Override + public int hashCode() { + return Objects.hash(read); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PatchNotificationRequestDTO {\n"); + + sb.append(" read: ").append(toIndentedString(read)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java new file mode 100644 index 000000000000..f2addc615b40 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java @@ -0,0 +1,125 @@ +package org.wso2.carbon.apimgt.rest.api.store.v1.impl; + +import org.wso2.carbon.apimgt.api.APIConsumer; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.APIProvider; +import org.wso2.carbon.apimgt.api.model.Notification; +import org.wso2.carbon.apimgt.api.model.NotificationList; +import org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil; +import org.wso2.carbon.apimgt.rest.api.common.RestApiConstants; +import org.wso2.carbon.apimgt.rest.api.store.v1.*; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.MessageContext; + +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.ErrorDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.NotificationDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.NotificationListDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.PatchAllNotificationsRequestDTO; +import org.wso2.carbon.apimgt.rest.api.store.v1.dto.PatchNotificationRequestDTO; +import org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil; + +import java.util.List; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + + +public class NotificationsApiServiceImpl implements NotificationsApiService { + + public Response deleteNotification(String notificationId, MessageContext messageContext) + throws APIManagementException { + + try { + String username = RestApiCommonUtil.getLoggedInUsername(); + String organization = RestApiUtil.getValidatedOrganization(messageContext); + APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); + boolean result = apiConsumer.deleteNotificationById(username, organization, notificationId); + if(!result){ + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (APIManagementException e) { + throw new APIManagementException("Error while deleting notifications", e); + } + return Response.ok().build(); + } + + public Response deleteNotifications(MessageContext messageContext) throws APIManagementException { + + try { + String username = RestApiCommonUtil.getLoggedInUsername(); + String organization = RestApiUtil.getValidatedOrganization(messageContext); + APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); + boolean result = apiConsumer.deleteAllNotifications(username, organization); + if(!result){ + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (APIManagementException e) { + throw new APIManagementException("Error while deleting notifications", e); + } + return Response.ok().build(); + } + + public Response getNotifications(String sortOrder, Integer limit, Integer offset, MessageContext messageContext) + throws APIManagementException { + + limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT; + offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; + sortOrder = sortOrder != null ? sortOrder : RestApiConstants.DESCENDING_SORT_ORDER; + NotificationList notificationList; + + try { + String username = RestApiCommonUtil.getLoggedInUsername(); + String organization = RestApiUtil.getValidatedOrganization(messageContext); + APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); + notificationList = apiConsumer.getNotifications(username, organization, sortOrder, limit, offset); + } catch (APIManagementException e) { + throw new APIManagementException("Error while getting notifications", e); + } + + return Response.ok().entity(notificationList).build(); + } + + public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, MessageContext messageContext) + throws APIManagementException { + + NotificationList notificationList ; + + try { + String username = RestApiCommonUtil.getLoggedInUsername(); + String organization = RestApiUtil.getValidatedOrganization(messageContext); + APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); + notificationList = apiConsumer.markAllNotificationsAsRead(username, organization); + if(notificationList == null){ + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (APIManagementException e) { + throw new APIManagementException("Error while getting notifications", e); + } + + return Response.ok().entity(notificationList).build(); + } + + public Response markNotificationAsReadById(String notificationId, PatchNotificationRequestDTO patchNotificationRequestDTO, MessageContext messageContext) + throws APIManagementException { + + Notification notification ; + + try { + String username = RestApiCommonUtil.getLoggedInUsername(); + String organization = RestApiUtil.getValidatedOrganization(messageContext); + APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); + notification = apiConsumer.markNotificationAsReadById(username, organization, notificationId); + if(notification == null){ + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (APIManagementException e) { + throw new APIManagementException("Error while getting notification", e); + } + + return Response.ok().entity(notification).build(); + } +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml index 01043e4769a8..79fc678e2a16 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml @@ -3770,8 +3770,279 @@ paths: source: 'curl -k -X POST -d request.json "https://localhost:9443/api/am/devportal/v3/apis/marketplace-assistant/chat"' + + ###################################################### + # The "Portal Notifications" resource APIs + ###################################################### + /notifications: + get: + tags: + - Notifications + summary: Get notifications + description: | + Retrieves all notifications for the user. + parameters: + - name: sortOrder + in: query + schema: + type: string + enum: + - asc + - desc + - $ref: '#/components/parameters/limit' + - $ref: '#/components/parameters/offset' + responses: + 200: + description: | + OK. + List of Notifications are returned. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + example: + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + - apim:notifications_view + x-code-samples: + - lang: Curl + source: 'curl -k -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://localhost:9443/api/am/devportal/v3/notifications"' + operationId: getNotifications + + + delete: + tags: + - Notifications + summary: Delete all notifications + description: | + This operation can be used to delete all the notifications of a user. + responses: + 200: + description: | + OK. + Resource successfully deleted. + content: { } + 401: + $ref: '#/components/responses/Unauthorized' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X DELETE -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://localhost:9443/api/am/devportal/v3/notifications"' + operationId: deleteNotifications + + + patch: + tags: + - Notifications + summary: Mark all Notifications as Read. + description: | + Mark all notifications as read. + requestBody: + description: | + Request body for marking all notifications as read. + content: + application/json: + schema: + title: Patch all notifications request + type: object + properties: + read: + type: boolean + description: | + Indicates whether the notifications should be marked as read. + example: true + required: true + responses: + 200: + description: | + OK. + Successful response with updated Notifications. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + 400: + $ref: '#/components/responses/BadRequest' + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + -H "Content-Type: application/json" -d @data.json "https://localhost:9443/api/am/devportal/v3/notifications"' + operationId: markAllNotificationsAsRead + + + /notifications/{notificationId}: + patch: + tags: + - Notifications + summary: Mark a Notification as Read. + description: | + Mark a specific notification as read. + parameters: + - $ref: '#/components/parameters/notificationId' + requestBody: + description: | + Request body for marking a notification as read. + content: + application/json: + schema: + title: Patch notification request + type: object + properties: + read: + type: boolean + description: | + Indicates whether the notification should be marked as read. + example: true + required: true + responses: + 200: + description: | + OK. + Successful response with updated Notification. + headers: + Content-Type: + description: | + The content type of the body. + schema: + type: string + content: + application/json: + schema: + $ref: '#/components/schemas/Notification' + 400: + $ref: '#/components/responses/BadRequest' + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + -H "Content-Type: application/json" -d @data.json "https://localhost:9443/api/am/devportal/v3/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' + operationId: markNotificationAsReadById + + + delete: + tags: + - Notifications + summary: Delete a Notification + description: | + This operation can be used to delete a specific notification of a user. + parameters: + - $ref: '#/components/parameters/notificationId' + responses: + 200: + description: | + OK. + Resource successfully deleted. + content: { } + 401: + $ref: '#/components/responses/Unauthorized' + 403: + $ref: '#/components/responses/Forbidden' + 404: + $ref: '#/components/responses/NotFound' + 500: + $ref: '#/components/responses/InternalServerError' + security: + - OAuth2Security: + - apim:notifications_manage + x-code-samples: + - lang: Curl + source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" + "https://localhost:9443/api/am/devportal/v3/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' + operationId: deleteNotification + + components: schemas: + # "Portal Notification Components" + Notification: + title: Notification object with basic Notification details. + type: object + properties: + notificationId: + type: string + example: 863aef13-dab4-48b4-bf58-7363cd29601a + notificationType: + type: string + enum: + - APPLICATION_CREATION + - SUBSCRIPTION_CREATION + - SUBSCRIPTION_UPDATE + - SUBSCRIPTION_DELETION + - APPLICATION_REGISTRATION_PRODUCTION + - APPLICATION_REGISTRATION_SANDBOX + example: + comments: + type: string + example: Application creation is rejected due to some reason. + createdTime: + type: string + example: 2021-02-11 09:57:25 + isRead: + type: boolean + example: false + NotificationList: + title: Notification List + type: object + properties: + count: + type: integer + description: | + Number of Notifications returned. + example: 1 + list: + type: array + items: + $ref: '#/components/schemas/Notification' + pagination: + $ref: '#/components/schemas/Pagination' APIList: title: API List type: object @@ -6209,6 +6480,20 @@ components: description: The specified resource does not exist moreInfo: "" error: [] + Forbidden: + description: Forbidden. The request must be conditional but no condition has + been specified. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + example: + code: 403 + message: Forbidden + description: The request must be conditional but no condition has been + specified + moreInfo: "" + error: [ ] PreconditionFailed: description: Precondition Failed. The request has not been performed because one of the preconditions is not met. @@ -6261,6 +6546,15 @@ components: moreInfo: "" error: [ ] parameters: + notificationId: + name: notificationId + in: path + description: | + **NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION + required: true + schema: + type: string + example: 863aef13-dab4-48b4-bf58-7363cd29601a parentCommentID: name: replyTo in: query @@ -6528,3 +6822,5 @@ components: apim:sub_alert_manage: Retrieve, subscribe and configure Developer Portal alert types apim:app_import_export: Import and export applications related operations apim:admin: Manage all admin operations + apim:notifications_manage: Manage notifications + apim:notifications_view: View notifications diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/beans.xml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/beans.xml index 071c143fd1b5..00666044159b 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/beans.xml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/beans.xml @@ -30,6 +30,7 @@ + From 21eb9c52002659e24389f5bbbc5962c9d9ca9208 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Fri, 15 Mar 2024 15:35:46 +0530 Subject: [PATCH 05/23] Add new column to store portal to display and change existing code accordingly --- .../wso2/carbon/apimgt/api/APIConsumer.java | 11 +- .../wso2/carbon/apimgt/api/APIProvider.java | 12 +- .../carbon/apimgt/impl/APIConsumerImpl.java | 20 +- .../carbon/apimgt/impl/APIProviderImpl.java | 20 +- .../carbon/apimgt/impl/dao/ApiMgtDAO.java | 26 ++- .../impl/dao/constants/SQLConstants.java | 25 ++- .../carbon/apimgt/impl/dto/WorkflowDTO.java | 5 +- .../PortalNotificationDAO.java | 51 ++++- .../PortalNotificationEndUserDTO.java | 9 + .../PortalNotificationMetaData.java | 9 + .../PortalNotificationService.java | 7 + .../WorkflowNotificationServiceImpl.java | 193 ++++++++++++++++++ .../impl/workflow/WorkflowExecutor.java | 102 --------- .../v1/impl/WorkflowsApiServiceImpl.java | 35 ++-- .../src/main/resources/devportal-api.yaml | 5 +- .../src/main/resources/publisher-api.yaml | 5 +- .../api/publisher/v1/NotificationsApi.java | 13 +- .../v1/impl/NotificationsApiServiceImpl.java | 48 +++-- .../src/main/resources/publisher-api.yaml | 5 +- .../src/main/webapp/WEB-INF/web.xml | 3 +- .../rest/api/store/v1/NotificationsApi.java | 13 +- .../v1/impl/NotificationsApiServiceImpl.java | 15 +- .../src/main/resources/devportal-api.yaml | 5 +- .../src/main/webapp/WEB-INF/web.xml | 2 + .../src/main/resources/sql/h2.sql | 3 +- 25 files changed, 422 insertions(+), 220 deletions(-) create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java index ecd1e8307845..2099723c066b 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java @@ -869,14 +869,15 @@ boolean isKeyManagerByNameAllowedForUser(String keyManagerName, String organizat * @throws APIManagementException */ boolean removalKeys(Application application, String keyMappingId, String xWSO2Tenant) throws APIManagementException; - NotificationList getNotifications(String username, String organization, String sortOrder, Integer limit, Integer offset) + + NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, Integer offset) throws APIManagementException; - NotificationList markAllNotificationsAsRead(String username, String organization) throws APIManagementException; + NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) throws APIManagementException; - Notification markNotificationAsReadById(String username, String organization, String notificationId) throws APIManagementException; + Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) throws APIManagementException; - boolean deleteNotificationById(String username, String organization, String notificationId) throws APIManagementException; + boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) throws APIManagementException; - boolean deleteAllNotifications(String username, String organization) throws APIManagementException; + boolean deleteAllNotifications(String username, String organization, String portalToDisplay) throws APIManagementException; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java index 2af79589be1a..4b3847e40806 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java @@ -1911,21 +1911,23 @@ boolean isPolicyMetadataExists(String gatewayPolicyMappingId) /** * Method to get notifications for the given user + * * @param username * @param organization + * @param portalToDisplay * @param sortOrder * @param limit * @param offset * @return NotificationList */ - NotificationList getNotifications(String username, String organization, String sortOrder, Integer limit, Integer offset) throws APIManagementException; + NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, Integer offset) throws APIManagementException; - boolean deleteAllNotifications(String username, String organization) throws APIManagementException; + boolean deleteAllNotifications(String username, String organization, String portalToDisplay) throws APIManagementException; - Notification markNotificationAsReadById(String username, String organization, String notificationId); + Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay); - boolean deleteNotificationById(String username, String organization, String notificationId); + boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay); - NotificationList markAllNotificationsAsRead(String username, String organization); + NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java index b2d47bead0b1..d6a8dadca94e 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java @@ -4596,32 +4596,32 @@ public boolean isKeyManagerByNameAllowedForUser(String keyManagerName, String or } @Override - public NotificationList getNotifications(String username, String organization, String sortOrder, Integer limit, + public NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, Integer offset) throws APIManagementException{ - return portalNotificationDAO.getNotifications(username, organization, sortOrder, limit, offset); + return portalNotificationDAO.getNotifications(username, organization, portalToDisplay, sortOrder, limit, offset); } @Override - public NotificationList markAllNotificationsAsRead(String username, String organization) + public NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) throws APIManagementException { - return portalNotificationDAO.markAllNotificationsAsRead(username, organization); + return portalNotificationDAO.markAllNotificationsAsRead(username, organization, portalToDisplay); } @Override - public Notification markNotificationAsReadById(String username, String organization, String notificationId) + public Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) throws APIManagementException { - return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId); + return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId, portalToDisplay); } @Override - public boolean deleteNotificationById(String username, String organization, String notificationId) + public boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) throws APIManagementException { - return portalNotificationDAO.deleteNotificationById(username, organization, notificationId); + return portalNotificationDAO.deleteNotificationById(username, organization, notificationId, portalToDisplay); } @Override - public boolean deleteAllNotifications(String username, String organization) throws APIManagementException { - return portalNotificationDAO.deleteAllNotifications(username, organization); + public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) throws APIManagementException { + return portalNotificationDAO.deleteAllNotifications(username, organization, portalToDisplay); } public static boolean hasIntersection(String[] arr1, String[] arr2) { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java index e354e3a3c84a..8b9c4ef03fa2 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java @@ -7235,29 +7235,29 @@ public int getPolicyUsageByPolicyUUIDInGatewayPolicies(String commonPolicyUUID) } @Override - public NotificationList getNotifications(String username, String organization, String sortOrder, Integer limit, + public NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, Integer offset) throws APIManagementException { - return portalNotificationDAO.getNotifications(username, organization, sortOrder, limit, offset); + return portalNotificationDAO.getNotifications(username, organization, portalToDisplay, sortOrder, limit, offset); } @Override - public boolean deleteAllNotifications(String username, String organization) { - return portalNotificationDAO.deleteAllNotifications(username, organization); + public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) { + return portalNotificationDAO.deleteAllNotifications(username, organization, portalToDisplay); } @Override - public Notification markNotificationAsReadById(String username, String organization, String notificationId) { - return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId); + public Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) { + return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId, portalToDisplay); } @Override - public boolean deleteNotificationById(String username, String organization, String notificationId) { - return portalNotificationDAO.deleteNotificationById(username, organization, notificationId); + public boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) { + return portalNotificationDAO.deleteNotificationById(username, organization, notificationId, portalToDisplay); } @Override - public NotificationList markAllNotificationsAsRead(String username, String organization) { - return portalNotificationDAO.markAllNotificationsAsRead(username, organization); + public NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) { + return portalNotificationDAO.markAllNotificationsAsRead(username, organization, portalToDisplay); } /** diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java index b43c47009001..ffb0e33772b3 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java @@ -167,6 +167,8 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; +import static org.wso2.carbon.apimgt.impl.utils.APIUtil.getTenantDomainFromTenantId; + /** * This class represent the ApiMgtDAO. */ @@ -2628,6 +2630,7 @@ public UserApplicationAPIUsage[] getAllAPIUsageByProviderAndApiId(String uuid, S int appId = result.getInt("APPLICATION_ID"); String subStatus = result.getString("SUB_STATUS"); String subsCreateState = result.getString("SUBS_CREATE_STATE"); + String subsOrganization = getTenantDomainFromTenantId(result.getInt("SUB_TENANT_ID")); String key = userId + "::" + application; UserApplicationAPIUsage usage = userApplicationUsages.get(key); if (usage == null) { @@ -2642,6 +2645,7 @@ public UserApplicationAPIUsage[] getAllAPIUsageByProviderAndApiId(String uuid, S SubscribedAPI apiSubscription = new SubscribedAPI(new Subscriber(userId), apiId); apiSubscription.setSubStatus(subStatus); apiSubscription.setSubCreatedStatus(subsCreateState); + apiSubscription.setOrganization(subsOrganization); apiSubscription.setUUID(result.getString("SUB_UUID")); apiSubscription.setTier(new Tier(result.getString("SUB_TIER_ID"))); Application applicationObj = new Application(result.getString("APP_UUID")); @@ -14988,7 +14992,7 @@ public void addAPIProductResourceMappings(List productResour } int productId = getAPIID(uuid, connection); int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(productIdentifier.getProviderName())); - String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); + String tenantDomain = getTenantDomainFromTenantId(tenantId); URITemplate uriTemplateOriginal = apiProductResource.getUriTemplate(); int urlMappingId = uriTemplateOriginal.getId(); // Adding to AM_API_URL_MAPPING table @@ -15888,7 +15892,7 @@ public void updateCategory(APICategory apiCategory) throws APIManagementExceptio statement.execute(); } catch (SQLException e) { handleException("Failed to update API Category : " + apiCategory.getName() + " of tenant " + - APIUtil.getTenantDomainFromTenantId(apiCategory.getTenantID()), e); + getTenantDomainFromTenantId(apiCategory.getTenantID()), e); } } @@ -16544,7 +16548,7 @@ public void addTenantTheme(int tenantId, InputStream themeContent) throws APIMan statement.executeUpdate(); } catch (SQLException e) { handleException("Failed to add tenant theme of tenant " - + APIUtil.getTenantDomainFromTenantId(tenantId), e); + + getTenantDomainFromTenantId(tenantId), e); } } @@ -16565,7 +16569,7 @@ public void updateTenantTheme(int tenantId, InputStream themeContent) throws API statement.executeUpdate(); } catch (SQLException e) { handleException("Failed to update tenant theme of tenant " - + APIUtil.getTenantDomainFromTenantId(tenantId), e); + + getTenantDomainFromTenantId(tenantId), e); } } @@ -16589,7 +16593,7 @@ public InputStream getTenantTheme(int tenantId) throws APIManagementException { } } catch (SQLException e) { handleException("Failed to fetch tenant theme of tenant " - + APIUtil.getTenantDomainFromTenantId(tenantId), e); + + getTenantDomainFromTenantId(tenantId), e); } return tenantThemeContent; } @@ -16612,7 +16616,7 @@ public boolean isTenantThemeExist(int tenantId) throws APIManagementException { return resultSet.next(); } catch (SQLException e) { handleException("Failed to check whether tenant theme exist for tenant " - + APIUtil.getTenantDomainFromTenantId(tenantId), e); + + getTenantDomainFromTenantId(tenantId), e); } return false; } @@ -16632,7 +16636,7 @@ public void deleteTenantTheme(int tenantId) throws APIManagementException { statement.executeUpdate(); } catch (SQLException e) { handleException("Failed to delete tenant theme of tenant " - + APIUtil.getTenantDomainFromTenantId(tenantId), e); + + getTenantDomainFromTenantId(tenantId), e); } } @@ -16863,7 +16867,7 @@ public void addAPIRevision(APIRevision apiRevision) throws APIManagementExceptio APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiRevision.getApiUUID()); int apiId = getAPIID(apiRevision.getApiUUID(), connection); int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName())); - String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); + String tenantDomain = getTenantDomainFromTenantId(tenantId); // Adding to AM_API_URL_MAPPING table PreparedStatement getURLMappingsStatement = connection @@ -17770,7 +17774,7 @@ public void restoreAPIRevision(APIRevision apiRevision) throws APIManagementExce APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiRevision.getApiUUID()); int apiId = getAPIID(apiRevision.getApiUUID(), connection); int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName())); - String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); + String tenantDomain = getTenantDomainFromTenantId(tenantId); // Removing related Current API entries from AM_API_URL_MAPPING table PreparedStatement removeURLMappingsStatement = connection.prepareStatement(SQLConstants .APIRevisionSqlConstants.REMOVE_CURRENT_API_ENTRIES_IN_AM_API_URL_MAPPING_BY_API_ID); @@ -18069,7 +18073,7 @@ public void addAPIProductRevision(APIRevision apiRevision) throws APIManagementE int apiId = getAPIID(apiRevision.getApiUUID(), connection); int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiProductIdentifier.getProviderName())); - String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); + String tenantDomain = getTenantDomainFromTenantId(tenantId); // Adding to AM_API_URL_MAPPING table PreparedStatement getURLMappingsStatement = connection @@ -18307,7 +18311,7 @@ public void restoreAPIProductRevision(APIRevision apiRevision) throws APIManagem int apiId = getAPIID(apiRevision.getApiUUID(), connection); int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiProductIdentifier.getProviderName())); - String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); + String tenantDomain = getTenantDomainFromTenantId(tenantId); //Remove Current API Product entries from AM_API_URL_MAPPING table PreparedStatement removeURLMappingsFromCurrentAPIProduct = connection.prepareStatement( diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java index 87a3a10fe7ab..0fcbd1193e46 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java @@ -913,7 +913,8 @@ public class SQLConstants { " SUBS.UUID AS SUB_UUID, " + " SUBS.TIER_ID AS SUB_TIER_ID, " + " APP.UUID AS APP_UUID, " + - " SUBS.SUBS_CREATE_STATE AS SUBS_CREATE_STATE " + + " SUBS.SUBS_CREATE_STATE AS SUBS_CREATE_STATE, " + + " SUB.TENANT_ID AS SUB_TENANT_ID " + " FROM " + " AM_SUBSCRIPTION SUBS, " + " AM_APPLICATION APP, " + @@ -2127,7 +2128,7 @@ public class SQLConstants { public static final String GET_SUBSCRIPTION_STATUS_SQL = "SELECT SUB_STATUS FROM AM_SUBSCRIPTION WHERE API_ID = ? AND APPLICATION_ID = ?"; - + public static final String GET_SUBSCRIPTION_ID_SQL = "SELECT SUBSCRIPTION_ID FROM AM_SUBSCRIPTION WHERE API_ID = ? AND APPLICATION_ID = ?"; @@ -3177,8 +3178,7 @@ public static class PortalNotifications { "(NOTIFICATION_ID, NOTIFICATION_TYPE, CREATED_TIME, NOTIFICATION_METADATA) VALUES (?, ?, ?, ?)"; public static final String ADD_NOTIFICATION_END_USER = "INSERT INTO AM_NOTIFICATION_END_USERS " + - "(NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION) " + "VALUES (?, ?, ?)"; - + "(NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY) " + "VALUES (?, ?, ?, ?)"; public static final String GET_NOTIFICATIONS = "SELECT" + " n.NOTIFICATION_ID," + @@ -3190,11 +3190,12 @@ public static class PortalNotifications { "INNER JOIN AM_NOTIFICATION_END_USERS e ON n.NOTIFICATION_ID = e.NOTIFICATION_ID " + "WHERE" + " e.DESTINATION_USER = ?" + - " AND e.ORGANIZATION = ? " + + " AND e.ORGANIZATION = ?" + + " AND e.PORTAL_TO_DISPLAY = ? " + "ORDER BY n.CREATED_TIME DESC"; public static final String DELETE_ALL_NOTIFICATIONS_OF_USER = "DELETE FROM AM_NOTIFICATION_END_USERS " + - "WHERE DESTINATION_USER = ? AND ORGANIZATION = ?"; + "WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; public static final String DELETE_NOTIFICATIONS = "DELETE " + @@ -3207,10 +3208,10 @@ public static class PortalNotifications { "WHERE NU.NOTIFICATION_ID IS NULL)"; public static final String MARK_NOTIFICATION_AS_READ = "UPDATE AM_NOTIFICATION_END_USERS SET IS_READ = TRUE " + - "WHERE NOTIFICATION_ID = ? AND DESTINATION_USER = ? AND ORGANIZATION = ?"; + "WHERE NOTIFICATION_ID = ? AND DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; public static final String MARK_ALL_NOTIFICATIONS_AS_READ = "UPDATE AM_NOTIFICATION_END_USERS SET IS_READ = TRUE " + - "WHERE DESTINATION_USER = ? AND ORGANIZATION = ?"; + "WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; public static final String GET_NOTIFICATION_BY_ID = "SELECT" + @@ -3224,10 +3225,14 @@ public static class PortalNotifications { "WHERE" + " n.NOTIFICATION_ID = ?" + " AND e.DESTINATION_USER = ?" + - " AND e.ORGANIZATION = ?"; + " AND e.ORGANIZATION = ?" + + " AND e.PORTAL_TO_DISPLAY = ?"; public static final String DELETE_NOTIFICATION_BY_ID = "DELETE FROM AM_NOTIFICATION_END_USERS " + - "WHERE NOTIFICATION_ID = ? AND DESTINATION_USER = ? AND ORGANIZATION = ?"; + "WHERE NOTIFICATION_ID = ? AND DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; + + public static final String GET_API_UUID_USING_NAME_CONTEXT_VERSION = "SELECT API_UUID FROM AM_API WHERE " + + "API_NAME = ? AND CONTEXT = ? AND API_VERSION = ? AND ORGANIZATION = ?"; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/WorkflowDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/WorkflowDTO.java index 4ac52052fe4b..bb3d005c423b 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/WorkflowDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/WorkflowDTO.java @@ -184,7 +184,10 @@ public void setAttributes(Map attributes) { } public String getMetadata(String key) { - return metadata.get(key).toString(); + if (metadata.get(key) != null) { + return metadata.get(key).toString(); + } + return null; } public void setMetadata(String key, String value) { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java index a70336d50cc6..d1120ee69485 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -6,6 +6,7 @@ import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.wso2.carbon.apimgt.api.model.*; +import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; @@ -80,6 +81,7 @@ private void addEndUser(Connection conn, String addEndUserQuery, String notifica ps.setString(1, notificationId); ps.setString(2, endUser.getDestinationUser()); ps.setString(3, endUser.getOrganization()); + ps.setString(4, endUser.getPortalToDisplay()); ps.executeUpdate(); } catch (SQLException e) { log.error("Error while adding end users", e); @@ -95,6 +97,7 @@ private String convertMetadataToJson(PortalNotificationMetaData metaData) { json.put("apiName", metaData.getApi()); json.put("apiVersion", metaData.getApiVersion()); json.put("apiContext", metaData.getApiContext()); + json.put("action", metaData.getAction()); json.put("applicationName", metaData.getApplicationName()); json.put("requestedTier", metaData.getRequestedTier()); json.put("revisionId", metaData.getRevisionId()); @@ -102,7 +105,7 @@ private String convertMetadataToJson(PortalNotificationMetaData metaData) { return json.toJSONString(); } - public NotificationList getNotifications(String username, String organization, String sortOrder, Integer limit, + public NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, Integer offset) { List list = new ArrayList(); @@ -120,6 +123,7 @@ public NotificationList getNotifications(String username, String organization, S ps = conn.prepareStatement(sqlQuery); ps.setString(1, username); ps.setString(2, organization); + ps.setString(3, portalToDisplay); rs = ps.executeQuery(); while (rs.next()) { Notification notification = new Notification(); @@ -155,6 +159,7 @@ private String getCommentFromMetaData(String notificationMetadata, String notifi String apiName = (String) json.get("apiName"); String apiVersion = (String) json.get("apiVersion"); String apiContext = (String) json.get("apiContext"); + String action = (String) json.get("action"); String revisionId = (String) json.get("revisionId"); String applicationName = (String) json.get("applicationName"); String requestedTier = (String) json.get("requestedTier"); @@ -168,7 +173,7 @@ private String getCommentFromMetaData(String notificationMetadata, String notifi switch (notificationType) { case "API_STATE_CHANGE": - finalComment = "API State Change request of the API: " + apiName + ", version: " + apiVersion + finalComment = "API State Change request to " + action + " the API: " + apiName + ", version: " + apiVersion + " that has the context: " + apiContext + " has been " + status + "."; break; case "API_PRODUCT_STATE_CHANGE": @@ -216,7 +221,7 @@ private String getCommentFromMetaData(String notificationMetadata, String notifi return finalComment; } - public boolean deleteAllNotifications(String username, String organization) { + public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) { Connection conn = null; PreparedStatement ps = null; @@ -226,6 +231,7 @@ public boolean deleteAllNotifications(String username, String organization) { ps = conn.prepareStatement(sqlQuery); ps.setString(1, username); ps.setString(2, organization); + ps.setString(3, portalToDisplay); int rowsAffected = ps.executeUpdate(); if (rowsAffected > 0) { String deleteNotification = SQLConstants.PortalNotifications.DELETE_NOTIFICATIONS; @@ -241,7 +247,7 @@ public boolean deleteAllNotifications(String username, String organization) { return false; } - public Notification markNotificationAsReadById(String username, String organization, String notificationId) { + public Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) { Connection conn = null; PreparedStatement ps = null; @@ -253,9 +259,10 @@ public Notification markNotificationAsReadById(String username, String organizat ps.setString(1, notificationId); ps.setString(2, username); ps.setString(3, organization); + ps.setString(4, portalToDisplay); int rowsAffected = ps.executeUpdate(); if (rowsAffected > 0) { - notification = getNotificationById(notificationId, username, organization, conn); + notification = getNotificationById(notificationId, username, organization, portalToDisplay, conn); if (notification != null) { return notification; } @@ -268,7 +275,7 @@ public Notification markNotificationAsReadById(String username, String organizat return null; } - private Notification getNotificationById(String notificationId, String username, String organization, + private Notification getNotificationById(String notificationId, String username, String organization, String portalToDisplay, Connection conn) throws SQLException { PreparedStatement ps = null; @@ -280,6 +287,7 @@ private Notification getNotificationById(String notificationId, String username, ps.setString(1, notificationId); ps.setString(2, username); ps.setString(3, organization); + ps.setString(4, portalToDisplay); rs = ps.executeQuery(); if (rs.next()) { Notification notification = new Notification(); @@ -301,7 +309,7 @@ private Notification getNotificationById(String notificationId, String username, return null; } - public boolean deleteNotificationById(String username, String organization, String notificationId) { + public boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) { Connection conn = null; PreparedStatement ps = null; @@ -312,6 +320,7 @@ public boolean deleteNotificationById(String username, String organization, Stri ps.setString(1, notificationId); ps.setString(2, username); ps.setString(3, organization); + ps.setString(4, portalToDisplay); int rowsAffected = ps.executeUpdate(); if (rowsAffected > 0) { String deleteNotification = SQLConstants.PortalNotifications.DELETE_NOTIFICATIONS; @@ -327,7 +336,7 @@ public boolean deleteNotificationById(String username, String organization, Stri return false; } - public NotificationList markAllNotificationsAsRead(String username, String organization) { + public NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) { Connection conn = null; PreparedStatement ps = null; @@ -338,9 +347,10 @@ public NotificationList markAllNotificationsAsRead(String username, String organ ps = conn.prepareStatement(sqlQuery); ps.setString(1, username); ps.setString(2, organization); + ps.setString(3, portalToDisplay); int rowsAffected = ps.executeUpdate(); if (rowsAffected > 0) { - return getNotifications(username, organization, null, null, null); + return getNotifications(username, organization, portalToDisplay,null, null, null); } } catch (SQLException e) { log.error("Failed to mark all notifications as read", e); @@ -349,4 +359,27 @@ public NotificationList markAllNotificationsAsRead(String username, String organ } return null; } + + public String getAPIUUIDUsingNameContextVersion(String apiName, String apiContext, String apiVersion, String organization) { + + String apiUUID = null; + String sqlQuery = SQLConstants.PortalNotifications.GET_API_UUID_USING_NAME_CONTEXT_VERSION; + try (Connection connection = APIMgtDBUtil.getConnection(); + PreparedStatement ps = connection.prepareStatement(sqlQuery)) { + ps.setString(1, apiName); + ps.setString(2, apiContext); + ps.setString(3, apiVersion); + ps.setString(4, organization); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + apiUUID = rs.getString("API_UUID"); + } + } + } catch (SQLException e) { + log.error("Failed to retrieve API UUID using name, context and version", e); + } + return apiUUID; + + + } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java index bf552596767a..ab2af0569405 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java @@ -6,6 +6,7 @@ public class PortalNotificationEndUserDTO { private String destinationUser; private String organization; private boolean isRead; + private String portalToDisplay; public String getNotificationId() { return notificationId; @@ -38,4 +39,12 @@ public boolean isRead() { public void setRead(boolean read) { this.isRead = read; } + + public String getPortalToDisplay() { + return portalToDisplay; + } + + public void setPortalToDisplay(String portalToDisplay) { + this.portalToDisplay = portalToDisplay; + } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java index 10991641cf3d..ae788c3d2782 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java @@ -2,6 +2,7 @@ public class PortalNotificationMetaData { + private String action; private String api; private String apiVersion; private String apiContext; @@ -10,6 +11,14 @@ public class PortalNotificationMetaData { private String revisionId; private String comment; + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + public String getApi() { return api; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java new file mode 100644 index 000000000000..fa020f877248 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java @@ -0,0 +1,7 @@ +package org.wso2.carbon.apimgt.impl.portalNotifications; + +public interface PortalNotificationService { + + void sendPortalNotifications(T notificationObject); + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java new file mode 100644 index 000000000000..d9630cfad042 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java @@ -0,0 +1,193 @@ +package org.wso2.carbon.apimgt.impl.portalNotifications; + +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.api.model.SubscribedAPI; +import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; + +import java.util.ArrayList; +import java.util.List; + +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; + +public class WorkflowNotificationServiceImpl implements PortalNotificationService { + public void sendPortalNotifications(WorkflowDTO workflowDTO) { + PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); + + portalNotificationsDTO.setNotificationType(getNotificationType(workflowDTO.getWorkflowType())); + portalNotificationsDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); + portalNotificationsDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + portalNotificationsDTO.setEndUsers(getDestinationUser(workflowDTO)); + + boolean result = PortalNotificationDAO.getInstance().addNotification(portalNotificationsDTO); + + if (!result) { + System.out.println("Error while adding publisher developer notification - sedPubDevNotification()"); + } + } + + private PortalNotificationType getNotificationType(String workflowType) { + switch (workflowType) { + case WorkflowConstants.WF_TYPE_AM_API_STATE: + return PortalNotificationType.API_STATE_CHANGE; + case WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE: + return PortalNotificationType.API_PRODUCT_STATE_CHANGE; + case WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION: + return PortalNotificationType.APPLICATION_CREATION; + case WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT: + return PortalNotificationType.API_REVISION_DEPLOYMENT; + case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION: + return PortalNotificationType.APPLICATION_REGISTRATION_PRODUCTION; + case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX: + return PortalNotificationType.APPLICATION_REGISTRATION_SANDBOX; + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION: + return PortalNotificationType.SUBSCRIPTION_CREATION; + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE: + return PortalNotificationType.SUBSCRIPTION_UPDATE; + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION: + return PortalNotificationType.SUBSCRIPTION_DELETION; + + } + return null; + } + + private List getDestinationUser( + org.wso2.carbon.apimgt.impl.dto.WorkflowDTO workflowDTO) { + List destinationUserList = new ArrayList<>(); + String destinationUser = null; + + switch (workflowDTO.getWorkflowType()) { + case WorkflowConstants.WF_TYPE_AM_API_STATE: + case WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE: + destinationUser = workflowDTO.getMetadata("Invoker"); + break; + + case WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION: + case WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT: + case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION: + case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX: + destinationUser = workflowDTO.getProperties("userName"); + break; + + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION: + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE: + case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION: + destinationUser = workflowDTO.getProperties("subscriber"); + break; + + case WorkflowConstants.WF_TYPE_AM_USER_SIGNUP: + destinationUser = workflowDTO.getMetadata("userName"); + break; + } + + if (destinationUser != null) { + PortalNotificationEndUserDTO endUser = new PortalNotificationEndUserDTO(); + endUser.setDestinationUser(destinationUser); + endUser.setOrganization(workflowDTO.getTenantDomain()); + endUser.setPortalToDisplay(setPortalToDisplay(workflowDTO.getWorkflowType())); + destinationUserList.add(endUser); + } + + if (workflowDTO.getWorkflowType() + .equals(WorkflowConstants.WF_TYPE_AM_API_STATE) || workflowDTO.getWorkflowType() + .equals(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)) { + if (workflowDTO.getMetadata("Action").equals("Block") || workflowDTO.getMetadata("Action") + .equals("Deprecated") || workflowDTO.getMetadata("Action").equals("Retired")) { + String apiUUID = null; + String apiName = workflowDTO.getProperties("apiName"); + String apiContext = workflowDTO.getMetadata("ApiContext"); + String apiVersion = workflowDTO.getProperties("apiVersion"); + String provider = workflowDTO.getMetadata("ApiProvider"); + try { + apiUUID = getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, + workflowDTO.getTenantDomain()); + APIIdentifier apiIdEmailReplaced = new APIIdentifier(APIUtil.replaceEmailDomain(provider), apiName, + apiVersion); + List subscribers = getSubscribersOfAPI(apiUUID, workflowDTO.getTenantDomain(), + apiIdEmailReplaced); + for (SubscribedAPI subscriber : subscribers) { + PortalNotificationEndUserDTO endUser = new PortalNotificationEndUserDTO(); + endUser.setDestinationUser(subscriber.getSubscriber().getName()); + endUser.setOrganization(subscriber.getOrganization()); + endUser.setPortalToDisplay("developer"); + destinationUserList.add(endUser); + } + } catch (APIManagementException e) { + System.out.println("Error while getting subscribers of API - getDestinationUser()"); + } + } + } + + return destinationUserList; + } + + private PortalNotificationMetaData getNotificationMetaData( + org.wso2.carbon.apimgt.impl.dto.WorkflowDTO workflowDTO) { + PortalNotificationMetaData portalNotificationMetaData = new PortalNotificationMetaData(); + + portalNotificationMetaData.setApi(workflowDTO.getProperties("apiName")); + portalNotificationMetaData.setApiVersion(workflowDTO.getProperties("apiVersion")); + portalNotificationMetaData.setAction(workflowDTO.getProperties("action")); + portalNotificationMetaData.setApplicationName(workflowDTO.getProperties("applicationName")); + portalNotificationMetaData.setRequestedTier(workflowDTO.getProperties("requestedTier")); + portalNotificationMetaData.setRevisionId(workflowDTO.getProperties("revisionId")); + portalNotificationMetaData.setComment(workflowDTO.getComments()); + + if (WorkflowConstants.WF_TYPE_AM_API_STATE.equals( + workflowDTO.getWorkflowType()) || WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE.equals( + workflowDTO.getWorkflowType())) { + portalNotificationMetaData.setApiContext(workflowDTO.getMetadata("ApiContext")); + } + + return portalNotificationMetaData; + } + + private String setPortalToDisplay(String workflowType) { + switch (workflowType) { + case WorkflowConstants.WF_TYPE_AM_API_STATE: + case WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE: + case WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT: + return "publisher"; + default: + return "developer"; + } + } + + private String getAPIUUIDUsingNameContextVersion(String apiName, String apiContext, String apiVersion, + String organization) throws APIManagementException { + return PortalNotificationDAO.getInstance() + .getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, organization); + } + + private List getSubscribersOfAPI(String apiUUID, String organization, + APIIdentifier apiIdEmailReplaced) throws APIManagementException { + return getAPIUsageByAPIId(apiUUID, organization, apiIdEmailReplaced); + } + + private List getAPIUsageByAPIId(String uuid, String organization, APIIdentifier apiIdEmailReplaced) + throws APIManagementException { + List subscribedAPIs = new ArrayList<>(); + try{ + UserApplicationAPIUsage[] allApiResult = ApiMgtDAO.getInstance().getAllAPIUsageByProviderAndApiId(uuid, organization); + for (UserApplicationAPIUsage usage : allApiResult) { + for (SubscribedAPI apiSubscription : usage.getApiSubscriptions()) { + APIIdentifier subsApiId = apiSubscription.getAPIIdentifier(); + APIIdentifier subsApiIdEmailReplaced = new APIIdentifier( + APIUtil.replaceEmailDomain(subsApiId.getProviderName()), subsApiId.getApiName(), + subsApiId.getVersion()); + if (subsApiIdEmailReplaced.equals(apiIdEmailReplaced)) { + subscribedAPIs.add(apiSubscription); + } + } + } + } catch (APIManagementException e) { + System.out.println("Error while getting API usage by API ID - getAPIUsageByAPIId()"); + } + + return subscribedAPIs; + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java index 4edde265c911..777d6430a343 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java @@ -109,7 +109,6 @@ public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowExcepti ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance(); try { apiMgtDAO.updateWorkflowStatus(workflowDTO); - sendPortalNotifications(workflowDTO); } catch (APIManagementException e) { @@ -118,107 +117,6 @@ public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowExcepti return new GeneralWorkflowResponse(); } - /** Implements the workflow related Notification logic. **/ - - private void sendPortalNotifications(WorkflowDTO workflowDTO) { - PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); - - portalNotificationsDTO.setNotificationType(getNotificationType(workflowDTO.getWorkflowType())); - portalNotificationsDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); - portalNotificationsDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); - portalNotificationsDTO.setEndUsers(getDestinationUser(workflowDTO)); - - - - boolean result = PortalNotificationDAO.getInstance().addNotification(portalNotificationsDTO); - - if(!result){ - System.out.println("Error while adding publisher developer notification - sedPubDevNotification()"); - } - } - - private PortalNotificationType getNotificationType(String workflowType) { - switch (workflowType) { - case WorkflowConstants.WF_TYPE_AM_API_STATE: - return PortalNotificationType.API_STATE_CHANGE; - case WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE: - return PortalNotificationType.API_PRODUCT_STATE_CHANGE; - case WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION: - return PortalNotificationType.APPLICATION_CREATION; - case WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT: - return PortalNotificationType.API_REVISION_DEPLOYMENT; - case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION: - return PortalNotificationType.APPLICATION_REGISTRATION_PRODUCTION; - case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX: - return PortalNotificationType.APPLICATION_REGISTRATION_SANDBOX; - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION: - return PortalNotificationType.SUBSCRIPTION_CREATION; - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE: - return PortalNotificationType.SUBSCRIPTION_UPDATE; - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION: - return PortalNotificationType.SUBSCRIPTION_DELETION; - - } - return null; - } - - private List getDestinationUser(WorkflowDTO workflowDTO) { - List destinationUserList = new ArrayList<>(); - String destinationUser = null; - - switch (workflowDTO.getWorkflowType()) { - case WorkflowConstants.WF_TYPE_AM_API_STATE: - case WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE: - destinationUser = workflowDTO.getMetadata("Invoker"); - break; - - case WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION: - case WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT: - case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION: - case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX: - destinationUser = workflowDTO.getProperties("userName"); - break; - - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION: - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE: - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION: - destinationUser = workflowDTO.getProperties("subscriber"); - break; - - case WorkflowConstants.WF_TYPE_AM_USER_SIGNUP: - destinationUser = workflowDTO.getMetadata("userName"); - break; - } - - if(destinationUser != null){ - PortalNotificationEndUserDTO endUser = new PortalNotificationEndUserDTO(); - endUser.setDestinationUser(destinationUser); - endUser.setOrganization(workflowDTO.getTenantDomain()); - destinationUserList.add(endUser); - } - - return destinationUserList; - } - - private PortalNotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { - PortalNotificationMetaData portalNotificationMetaData = new PortalNotificationMetaData(); - - portalNotificationMetaData.setApi(workflowDTO.getProperties("apiName")); - portalNotificationMetaData.setApiVersion(workflowDTO.getProperties("apiVersion")); - portalNotificationMetaData.setApplicationName(workflowDTO.getProperties("applicationName")); - portalNotificationMetaData.setRequestedTier(workflowDTO.getProperties("requestedTier")); - portalNotificationMetaData.setRevisionId(workflowDTO.getProperties("revisionId")); - portalNotificationMetaData.setComment(workflowDTO.getComments()); - - if (WorkflowConstants.WF_TYPE_AM_API_STATE.equals( - workflowDTO.getWorkflowType()) || WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE.equals( - workflowDTO.getWorkflowType())) { - portalNotificationMetaData.setApiContext(workflowDTO.getMetadata("ApiContext")); - } - - return portalNotificationMetaData; - } - /** * Returns the information of the workflows whose status' match the workflowStatus diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java index 90b6d13b4d1c..3ef30788a01a 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java @@ -29,7 +29,7 @@ import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerFactory; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; -import org.wso2.carbon.apimgt.impl.dao.GatewayArtifactsMgtDAO; +import org.wso2.carbon.apimgt.impl.portalNotifications.WorkflowNotificationServiceImpl; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; import org.wso2.carbon.apimgt.impl.workflow.WorkflowException; @@ -74,12 +74,13 @@ public Response workflowsExternalWorkflowRefGet(String externalWorkflowRef, Mess String status = "CREATED"; String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain(); APIAdmin apiAdmin = new APIAdminImpl(); - workflow = apiAdmin.getworkflowReferenceByExternalWorkflowReferenceID(externalWorkflowRef, status, tenantDomain); + workflow = apiAdmin.getworkflowReferenceByExternalWorkflowReferenceID(externalWorkflowRef, status, + tenantDomain); workflowinfoDTO = WorkflowMappingUtil.fromWorkflowsToInfoDTO(workflow); return Response.ok().entity(workflowinfoDTO).build(); } catch (APIManagementException e) { - RestApiUtil.handleInternalServerError("Error while retrieving workflow request by the " + - "external workflow reference. ", e, log); + RestApiUtil.handleInternalServerError( + "Error while retrieving workflow request by the " + "external workflow reference. ", e, log); } return null; } @@ -90,12 +91,13 @@ public Response workflowsExternalWorkflowRefGet(String externalWorkflowRef, Mess * @param limit maximum number of workflow returns * @param offset starting index * @param accept accept header value - * @param workflowType is the the type of the workflow request. (e.g: Application Creation, Application Subscription etc.) + * @param workflowType is the the type of the workflow request. (e.g: Application Creation, Application Subscription + * etc.) * @return */ @Override public Response workflowsGet(Integer limit, Integer offset, String accept, String workflowType, - MessageContext messageContext) throws APIManagementException { + MessageContext messageContext) throws APIManagementException { limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT; offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain(); @@ -104,7 +106,7 @@ public Response workflowsGet(Integer limit, Integer offset, String accept, Strin Workflow[] workflows; String status = "CREATED"; APIAdmin apiAdmin = new APIAdminImpl(); - if(workflowType != null) { + if (workflowType != null) { if (workflowType.equals("APPLICATION_CREATION")) { workflowType = "AM_APPLICATION_CREATION"; } else if (workflowType.equals("SUBSCRIPTION_CREATION")) { @@ -125,8 +127,7 @@ public Response workflowsGet(Integer limit, Integer offset, String accept, Strin } workflows = apiAdmin.getworkflows(workflowType, status, tenantDomain); workflowListDTO = WorkflowMappingUtil.fromWorkflowsToDTO(workflows, limit, offset); - WorkflowMappingUtil.setPaginationParams(workflowListDTO, limit, offset, - workflows.length); + WorkflowMappingUtil.setPaginationParams(workflowListDTO, limit, offset, workflows.length); return Response.ok().entity(workflowListDTO).build(); } catch (APIManagementException e) { RestApiUtil.handleInternalServerError("Error while retrieving workflow requests. ", e, log); @@ -138,13 +139,13 @@ public Response workflowsGet(Integer limit, Integer offset, String accept, Strin * This is used to update the workflow status * * @param workflowReferenceId workflow reference id that is unique to each workflow - * @param body body should contain the status, optionally can contain a - * description and an attributes object + * @param body body should contain the status, optionally can contain a description and an attributes + * object * @return */ @Override public Response workflowsUpdateWorkflowStatusPost(String workflowReferenceId, WorkflowDTO body, - MessageContext messageContext) { + MessageContext messageContext) { ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance(); boolean isTenantFlowStarted = false; String username = RestApiCommonUtil.getLoggedInUsername(); @@ -187,15 +188,15 @@ public Response workflowsUpdateWorkflowStatusPost(String workflowReferenceId, Wo workflowDTO.setAttributes(body.getAttributes()); } - if(body.getComments() != null) { + if (body.getComments() != null) { System.out.println(body.getComments()); workflowDTO.setComments(body.getComments()); } String workflowType = workflowDTO.getWorkflowType(); - if (WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION.equals(workflowType) && - WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) { + if (WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION.equals( + workflowType) && WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) { APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username); int applicationId = Integer.parseInt(workflowDTO.getWorkflowReference()); apiConsumer.cleanupPendingTasksForApplicationDeletion(applicationId); @@ -204,6 +205,9 @@ public Response workflowsUpdateWorkflowStatusPost(String workflowReferenceId, Wo WorkflowExecutor workflowExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(workflowType); workflowExecutor.complete(workflowDTO); + WorkflowNotificationServiceImpl portalNotification = new WorkflowNotificationServiceImpl(); + portalNotification.sendPortalNotifications(workflowDTO); + if (WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) { WorkflowUtils.sendNotificationAfterWFComplete(workflowDTO, workflowType); @@ -232,4 +236,5 @@ public Response workflowsUpdateWorkflowStatusPost(String workflowReferenceId, Wo } return null; } + } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml index 79fc678e2a16..816514bb5092 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml @@ -3815,7 +3815,6 @@ paths: $ref: '#/components/responses/InternalServerError' security: - OAuth2Security: - - apim:notifications_manage - apim:notifications_view x-code-samples: - lang: Curl @@ -3845,6 +3844,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X DELETE -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -3901,6 +3901,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -3960,6 +3961,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -3992,6 +3994,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml index 2ee1e63fa769..e812649d57d8 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml @@ -8719,7 +8719,6 @@ paths: $ref: '#/components/responses/InternalServerError' security: - OAuth2Security: - - apim:notifications_manage - apim:notifications_view x-code-samples: - lang: Curl @@ -8749,6 +8748,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X DELETE -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -8804,6 +8804,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -8863,6 +8864,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -8895,6 +8897,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java index 6677fd873c68..87f6f1b2e7cf 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java @@ -45,7 +45,8 @@ public class NotificationsApi { @Produces({ "application/json" }) @ApiOperation(value = "Delete a Notification", notes = "This operation can be used to delete a specific notification of a user. ", response = Void.class, authorizations = { @Authorization(value = "OAuth2Security", scopes = { - @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), + @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") }) }, tags={ "Notifications", }) @ApiResponses(value = { @@ -64,7 +65,8 @@ public Response deleteNotification(@ApiParam(value = "**NOTIFICATION ID** consis @Produces({ "application/json" }) @ApiOperation(value = "Delete all notifications", notes = "This operation can be used to delete all the notifications of a user. ", response = Void.class, authorizations = { @Authorization(value = "OAuth2Security", scopes = { - @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), + @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") }) }, tags={ "Notifications", }) @ApiResponses(value = { @@ -82,7 +84,6 @@ public Response deleteNotifications() throws APIManagementException{ @Produces({ "application/json" }) @ApiOperation(value = "Get notifications", notes = "Retrieves all notifications for the user. ", response = NotificationListDTO.class, authorizations = { @Authorization(value = "OAuth2Security", scopes = { - @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") }) }, tags={ "Notifications", }) @@ -101,7 +102,8 @@ public Response getNotifications( @ApiParam(value = "Order of sorting(ascending/ @Produces({ "application/json" }) @ApiOperation(value = "Mark all Notifications as Read.", notes = "Mark all notifications as read. ", response = NotificationListDTO.class, authorizations = { @Authorization(value = "OAuth2Security", scopes = { - @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), + @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") }) }, tags={ "Notifications", }) @ApiResponses(value = { @@ -121,7 +123,8 @@ public Response markAllNotificationsAsRead(@ApiParam(value = "" ,required=true) @Produces({ "application/json" }) @ApiOperation(value = "Mark a Notification as Read.", notes = "Mark a specific notification as read. ", response = NotificationDTO.class, authorizations = { @Authorization(value = "OAuth2Security", scopes = { - @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), + @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") }) }, tags={ "Notifications" }) @ApiResponses(value = { diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java index d1b7b6c07e1b..3857f60beafc 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java @@ -23,37 +23,39 @@ public class NotificationsApiServiceImpl implements NotificationsApiService { private static final Log log = LogFactory.getLog(NotificationsApiServiceImpl.class); @Override - public Response getNotifications(String sortOrder, Integer limit, Integer offset, MessageContext messageContext) throws APIManagementException { - + public Response getNotifications(String sortOrder, Integer limit, Integer offset, MessageContext messageContext) + throws APIManagementException { limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT; offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; sortOrder = sortOrder != null ? sortOrder : RestApiConstants.DESCENDING_SORT_ORDER; NotificationList notificationList; - + String portalToDisplay = "publisher"; String username = RestApiCommonUtil.getLoggedInUsername(); try { String organization = RestApiUtil.getValidatedOrganization(messageContext); APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); - notificationList = apiProvider.getNotifications(username, organization, sortOrder, limit, offset); + notificationList = apiProvider.getNotifications(username, organization, portalToDisplay, sortOrder, limit, + offset); } catch (APIManagementException e) { throw new APIManagementException("Error while getting notifications", e); - } + } return Response.ok().entity(notificationList).build(); } @Override - public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, MessageContext messageContext) - throws APIManagementException { - NotificationList notificationList ; + public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, + MessageContext messageContext) throws APIManagementException { + NotificationList notificationList; String username = RestApiCommonUtil.getLoggedInUsername(); + String portalToDisplay = "publisher"; try { String organization = RestApiUtil.getValidatedOrganization(messageContext); APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); - notificationList = apiProvider.markAllNotificationsAsRead(username, organization); - if(notificationList == null){ + notificationList = apiProvider.markAllNotificationsAsRead(username, organization, portalToDisplay); + if (notificationList == null) { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { @@ -64,15 +66,18 @@ public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patch } @Override - public Response markNotificationAsReadById(String notificationId, PatchNotificationRequestDTO patchNotificationRequestDTO, - MessageContext messageContext) throws APIManagementException { - Notification notification ; + public Response markNotificationAsReadById(String notificationId, + PatchNotificationRequestDTO patchNotificationRequestDTO, MessageContext messageContext) + throws APIManagementException { + Notification notification; String username = RestApiCommonUtil.getLoggedInUsername(); + String portalToDisplay = "publisher"; try { String organization = RestApiUtil.getValidatedOrganization(messageContext); APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); - notification = apiProvider.markNotificationAsReadById(username, organization, notificationId); - if(notification == null){ + notification = apiProvider.markNotificationAsReadById(username, organization, notificationId, + portalToDisplay); + if (notification == null) { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { @@ -86,11 +91,12 @@ public Response markNotificationAsReadById(String notificationId, PatchNotificat public Response deleteNotifications(MessageContext messageContext) throws APIManagementException { String username = RestApiCommonUtil.getLoggedInUsername(); + String portalToDisplay = "publisher"; try { String organization = RestApiUtil.getValidatedOrganization(messageContext); APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); - boolean result = apiProvider.deleteAllNotifications(username, organization); - if(!result){ + boolean result = apiProvider.deleteAllNotifications(username, organization, portalToDisplay); + if (!result) { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { @@ -98,18 +104,18 @@ public Response deleteNotifications(MessageContext messageContext) throws APIMan } return Response.ok().build(); } - - @Override public Response deleteNotification(String notificationId, MessageContext messageContext) throws APIManagementException { String username = RestApiCommonUtil.getLoggedInUsername(); + String portalToDisplay = "publisher"; try { String organization = RestApiUtil.getValidatedOrganization(messageContext); APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); - boolean result = apiProvider.deleteNotificationById(username, organization, notificationId); - if(!result){ + boolean result = apiProvider.deleteNotificationById(username, organization, notificationId, + portalToDisplay); + if (!result) { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml index 2ee1e63fa769..e812649d57d8 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml @@ -8719,7 +8719,6 @@ paths: $ref: '#/components/responses/InternalServerError' security: - OAuth2Security: - - apim:notifications_manage - apim:notifications_view x-code-samples: - lang: Curl @@ -8749,6 +8748,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X DELETE -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -8804,6 +8804,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -8863,6 +8864,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -8895,6 +8897,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/webapp/WEB-INF/web.xml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/webapp/WEB-INF/web.xml index b75d351bf530..4e637fc529bb 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/webapp/WEB-INF/web.xml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/webapp/WEB-INF/web.xml @@ -52,7 +52,8 @@ org.wso2.carbon.apimgt.rest.api.publisher.v1.KeyManagersApi, org.wso2.carbon.apimgt.rest.api.publisher.v1.OperationPoliciesApi, org.wso2.carbon.apimgt.rest.api.publisher.v1.LinterCustomRulesApi, - org.wso2.carbon.apimgt.rest.api.publisher.v1.GatewayPoliciesApi + org.wso2.carbon.apimgt.rest.api.publisher.v1.GatewayPoliciesApi, + org.wso2.carbon.apimgt.rest.api.publisher.v1.NotificationsApi diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java index 135286a50ed0..f386496c9e80 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java @@ -45,7 +45,8 @@ public class NotificationsApi { @Produces({ "application/json" }) @ApiOperation(value = "Delete a Notification", notes = "This operation can be used to delete a specific notification of a user. ", response = Void.class, authorizations = { @Authorization(value = "OAuth2Security", scopes = { - @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), + @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") }) }, tags={ "Notifications", }) @ApiResponses(value = { @@ -64,7 +65,8 @@ public Response deleteNotification(@ApiParam(value = "**NOTIFICATION ID** consis @Produces({ "application/json" }) @ApiOperation(value = "Delete all notifications", notes = "This operation can be used to delete all the notifications of a user. ", response = Void.class, authorizations = { @Authorization(value = "OAuth2Security", scopes = { - @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), + @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") }) }, tags={ "Notifications", }) @ApiResponses(value = { @@ -82,7 +84,6 @@ public Response deleteNotifications() throws APIManagementException{ @Produces({ "application/json" }) @ApiOperation(value = "Get notifications", notes = "Retrieves all notifications for the user. ", response = NotificationListDTO.class, authorizations = { @Authorization(value = "OAuth2Security", scopes = { - @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") }) }, tags={ "Notifications", }) @@ -101,7 +102,8 @@ public Response getNotifications( @ApiParam(value = "", allowableValues="asc, de @Produces({ "application/json" }) @ApiOperation(value = "Mark all Notifications as Read.", notes = "Mark all notifications as read. ", response = NotificationListDTO.class, authorizations = { @Authorization(value = "OAuth2Security", scopes = { - @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), + @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") }) }, tags={ "Notifications", }) @ApiResponses(value = { @@ -121,7 +123,8 @@ public Response markAllNotificationsAsRead(@ApiParam(value = "" ,required=true) @Produces({ "application/json" }) @ApiOperation(value = "Mark a Notification as Read.", notes = "Mark a specific notification as read. ", response = NotificationDTO.class, authorizations = { @Authorization(value = "OAuth2Security", scopes = { - @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications") + @AuthorizationScope(scope = "apim:notifications_manage", description = "Manage notifications"), + @AuthorizationScope(scope = "apim:notifications_view", description = "View notifications") }) }, tags={ "Notifications" }) @ApiResponses(value = { diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java index f2addc615b40..9c89847e276a 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java @@ -33,11 +33,12 @@ public class NotificationsApiServiceImpl implements NotificationsApiService { public Response deleteNotification(String notificationId, MessageContext messageContext) throws APIManagementException { + String portalToDisplay = "developer"; try { String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); - boolean result = apiConsumer.deleteNotificationById(username, organization, notificationId); + boolean result = apiConsumer.deleteNotificationById(username, organization, notificationId, portalToDisplay); if(!result){ return Response.status(Response.Status.NOT_FOUND).build(); } @@ -49,11 +50,12 @@ public Response deleteNotification(String notificationId, MessageContext message public Response deleteNotifications(MessageContext messageContext) throws APIManagementException { + String portalToDisplay = "developer"; try { String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); - boolean result = apiConsumer.deleteAllNotifications(username, organization); + boolean result = apiConsumer.deleteAllNotifications(username, organization, portalToDisplay); if(!result){ return Response.status(Response.Status.NOT_FOUND).build(); } @@ -70,12 +72,13 @@ public Response getNotifications(String sortOrder, Integer limit, Integer offset offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; sortOrder = sortOrder != null ? sortOrder : RestApiConstants.DESCENDING_SORT_ORDER; NotificationList notificationList; + String portalToDisplay = "developer"; try { String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); - notificationList = apiConsumer.getNotifications(username, organization, sortOrder, limit, offset); + notificationList = apiConsumer.getNotifications(username, organization, portalToDisplay, sortOrder, limit, offset); } catch (APIManagementException e) { throw new APIManagementException("Error while getting notifications", e); } @@ -87,12 +90,13 @@ public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patch throws APIManagementException { NotificationList notificationList ; + String portalToDisplay = "developer"; try { String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); - notificationList = apiConsumer.markAllNotificationsAsRead(username, organization); + notificationList = apiConsumer.markAllNotificationsAsRead(username, organization, portalToDisplay); if(notificationList == null){ return Response.status(Response.Status.NOT_FOUND).build(); } @@ -107,12 +111,13 @@ public Response markNotificationAsReadById(String notificationId, PatchNotificat throws APIManagementException { Notification notification ; + String portalToDisplay = "developer"; try { String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); - notification = apiConsumer.markNotificationAsReadById(username, organization, notificationId); + notification = apiConsumer.markNotificationAsReadById(username, organization, notificationId, portalToDisplay); if(notification == null){ return Response.status(Response.Status.NOT_FOUND).build(); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml index 79fc678e2a16..816514bb5092 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml @@ -3815,7 +3815,6 @@ paths: $ref: '#/components/responses/InternalServerError' security: - OAuth2Security: - - apim:notifications_manage - apim:notifications_view x-code-samples: - lang: Curl @@ -3845,6 +3844,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X DELETE -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -3901,6 +3901,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -3960,6 +3961,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X PATCH -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" @@ -3992,6 +3994,7 @@ paths: security: - OAuth2Security: - apim:notifications_manage + - apim:notifications_view x-code-samples: - lang: Curl source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml index 5f789228c98f..775b97aa53f8 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml @@ -50,6 +50,8 @@ org.wso2.carbon.apimgt.rest.api.store.v1.MeApi, org.wso2.carbon.apimgt.rest.api.store.v1.WebhooksApi, org.wso2.carbon.apimgt.rest.api.store.v1.MarketplaceAssistantApi + org.wso2.carbon.apimgt.rest.api.store.v1.WebhooksApi, + org.wso2.carbon.apimgt.rest.api.store.v1.NotificationsApi diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql index 6cc995e26761..02798f7383fe 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql @@ -2463,7 +2463,8 @@ CREATE TABLE IF NOT EXISTS AM_NOTIFICATION_END_USERS ( DESTINATION_USER VARCHAR(255) NOT NULL, ORGANIZATION VARCHAR(100) NOT NULL, IS_READ BOOLEAN DEFAULT FALSE, - PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION), + PORTAL_TO_DISPLAY VARCHAR(64) NOT NULL, + PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY), FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE ); From 390ca5d44dcf4b35e538c87810e5d04aaabb60a9 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Thu, 21 Mar 2024 10:48:20 +0530 Subject: [PATCH 06/23] Complete getAllUsersBelongToGroup and getSubscribersOfApi functions --- .../carbon/apimgt/impl/dao/ApiMgtDAO.java | 5 ++ .../impl/dao/constants/SQLConstants.java | 17 +++- .../PortalNotificationDAO.java | 7 +- .../PortalNotificationService.java | 2 +- .../WorkflowNotificationServiceImpl.java | 83 ++++++++++++++++++- .../v1/impl/WorkflowsApiServiceImpl.java | 2 +- 6 files changed, 108 insertions(+), 8 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java index ffb0e33772b3..601b7794287c 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java @@ -8721,6 +8721,11 @@ public void populateAppRegistrationWorkflowDTO(ApplicationRegistrationWorkflowDT workflowDTO.setDomainList(rs.getString("ALLOWED_DOMAINS")); workflowDTO.setValidityTime(rs.getLong("VALIDITY_PERIOD")); String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName()); + if (multiGroupAppSharingEnabled) { + if (application.getGroupId() == null || application.getGroupId().isEmpty()) { + application.setGroupId(getGroupId(conn, application.getId())); + } + } String keyManagerUUID = rs.getString("KEY_MANAGER"); workflowDTO.setKeyManager(keyManagerUUID); KeyManagerConfigurationDTO keyManagerConfigurationByUUID = getKeyManagerConfigurationByUUID(conn, diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java index 0fcbd1193e46..f004ffe02fd2 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java @@ -3179,7 +3179,7 @@ public static class PortalNotifications { public static final String ADD_NOTIFICATION_END_USER = "INSERT INTO AM_NOTIFICATION_END_USERS " + "(NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY) " + "VALUES (?, ?, ?, ?)"; - public static final String GET_NOTIFICATIONS = + public static final String GET_NOTIFICATIONS_DESC = "SELECT" + " n.NOTIFICATION_ID," + " n.NOTIFICATION_TYPE," + @@ -3194,6 +3194,21 @@ public static class PortalNotifications { " AND e.PORTAL_TO_DISPLAY = ? " + "ORDER BY n.CREATED_TIME DESC"; + public static final String GET_NOTIFICATIONS_ASC = + "SELECT" + + " n.NOTIFICATION_ID," + + " n.NOTIFICATION_TYPE," + + " n.CREATED_TIME," + + " n.NOTIFICATION_METADATA," + + " e.IS_READ " + + "FROM AM_NOTIFICATION n " + + "INNER JOIN AM_NOTIFICATION_END_USERS e ON n.NOTIFICATION_ID = e.NOTIFICATION_ID " + + "WHERE" + + " e.DESTINATION_USER = ?" + + " AND e.ORGANIZATION = ?" + + " AND e.PORTAL_TO_DISPLAY = ? " + + "ORDER BY n.CREATED_TIME ASC"; + public static final String DELETE_ALL_NOTIFICATIONS_OF_USER = "DELETE FROM AM_NOTIFICATION_END_USERS " + "WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java index d1120ee69485..8a7540998910 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -117,8 +117,13 @@ public NotificationList getNotifications(String username, String organization, S Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; + String sqlQuery; try { - String sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS; + if (sortOrder != null && sortOrder.equals("asc")) { + sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_ASC; + } else { + sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_DESC; + } conn = APIMgtDBUtil.getConnection(); ps = conn.prepareStatement(sqlQuery); ps.setString(1, username); diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java index fa020f877248..2ca96fa457d8 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java @@ -2,6 +2,6 @@ public interface PortalNotificationService { - void sendPortalNotifications(T notificationObject); + void sendPortalNotifications(T notificationObject, String tenantDomain); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java index d9630cfad042..2ebd6e70a0d6 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java @@ -1,26 +1,37 @@ package org.wso2.carbon.apimgt.impl.portalNotifications; +import org.apache.commons.lang3.StringUtils; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage; import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.api.model.Application; import org.wso2.carbon.apimgt.api.model.SubscribedAPI; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; +import org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO; +import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.core.UserRealm; +import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import java.util.ArrayList; import java.util.List; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.user.core.common.User; +import org.wso2.carbon.user.core.service.RealmService; public class WorkflowNotificationServiceImpl implements PortalNotificationService { - public void sendPortalNotifications(WorkflowDTO workflowDTO) { + public void sendPortalNotifications(WorkflowDTO workflowDTO, String tenantDomainOfUser) { PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); portalNotificationsDTO.setNotificationType(getNotificationType(workflowDTO.getWorkflowType())); portalNotificationsDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); portalNotificationsDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); - portalNotificationsDTO.setEndUsers(getDestinationUser(workflowDTO)); + portalNotificationsDTO.setEndUsers(getDestinationUser(workflowDTO, tenantDomainOfUser)); boolean result = PortalNotificationDAO.getInstance().addNotification(portalNotificationsDTO); @@ -55,7 +66,7 @@ private PortalNotificationType getNotificationType(String workflowType) { } private List getDestinationUser( - org.wso2.carbon.apimgt.impl.dto.WorkflowDTO workflowDTO) { + org.wso2.carbon.apimgt.impl.dto.WorkflowDTO workflowDTO, String tenantDomainOfUser) { List destinationUserList = new ArrayList<>(); String destinationUser = null; @@ -95,7 +106,7 @@ private List getDestinationUser( .equals(WorkflowConstants.WF_TYPE_AM_API_STATE) || workflowDTO.getWorkflowType() .equals(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)) { if (workflowDTO.getMetadata("Action").equals("Block") || workflowDTO.getMetadata("Action") - .equals("Deprecated") || workflowDTO.getMetadata("Action").equals("Retired")) { + .equals("Deprecate") || workflowDTO.getMetadata("Action").equals("Retire")) { String apiUUID = null; String apiName = workflowDTO.getProperties("apiName"); String apiContext = workflowDTO.getMetadata("ApiContext"); @@ -121,6 +132,27 @@ private List getDestinationUser( } } + if(APIUtil.isMultiGroupAppSharingEnabled()){ + try { + List users = getAllUsersBelongToGroup(workflowDTO, tenantDomainOfUser); + for (User user : users) { + PortalNotificationEndUserDTO endUser = new PortalNotificationEndUserDTO(); + if(user.getUsername().equals(destinationUser)){ + continue; + } + endUser.setDestinationUser(user.getUsername()); + endUser.setOrganization(user.getTenantDomain()); + endUser.setPortalToDisplay("developer"); + destinationUserList.add(endUser); + } + } catch (APIManagementException e) { + System.out.println("Error while getting users belong to group - getDestinationUser()"); + } catch (UserStoreException e) { + throw new RuntimeException(e); + } + } + + return destinationUserList; } @@ -190,4 +222,47 @@ private List getAPIUsageByAPIId(String uuid, String organization, return subscribedAPIs; } + private List getAllUsersBelongToGroup(WorkflowDTO workflowDTO, String tenantDomainOfUser) + throws APIManagementException, UserStoreException { + List users = new ArrayList<>(); + String groupId = null; + if (workflowDTO.getWorkflowType().equals(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION)) { + String applicationId = workflowDTO.getWorkflowReference(); + int appId = Integer.parseInt(applicationId); + ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance(); + Application application = apiMgtDAO.getApplicationById(appId); + groupId = application.getGroupId(); + } else if (workflowDTO.getWorkflowType() + .equals(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION) || workflowDTO.getWorkflowType() + .equals(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE) || workflowDTO.getWorkflowType() + .equals(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION)) { + SubscribedAPI sub = ApiMgtDAO.getInstance() + .getSubscriptionById(Integer.parseInt(workflowDTO.getWorkflowReference())); + groupId = sub.getApplication().getGroupId(); + } else if (workflowDTO.getWorkflowType().equals(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION) + || workflowDTO.getWorkflowType().equals(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX)) { + groupId = ((ApplicationRegistrationWorkflowDTO) workflowDTO).getApplication().getGroupId(); + } + + if (groupId != null) { + int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() + .getTenantId(tenantDomainOfUser); + RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService(); + UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId); + if(realm != null){ + org.wso2.carbon.user.core.UserStoreManager manager = realm.getUserStoreManager(); + AbstractUserStoreManager abstractManager = (AbstractUserStoreManager) manager; + APIManagerConfiguration config = ServiceReferenceHolder.getInstance(). + getAPIManagerConfigurationService().getAPIManagerConfiguration(); + String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI); + if (StringUtils.isBlank(claim)) { + claim = "http://wso2.org/claims/organization"; + } + users = abstractManager.getUserListWithID(claim , groupId, "default"); + } + + } + return users; + } + } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java index 3ef30788a01a..9d4cce760338 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java @@ -206,7 +206,7 @@ public Response workflowsUpdateWorkflowStatusPost(String workflowReferenceId, Wo workflowExecutor.complete(workflowDTO); WorkflowNotificationServiceImpl portalNotification = new WorkflowNotificationServiceImpl(); - portalNotification.sendPortalNotifications(workflowDTO); + portalNotification.sendPortalNotifications(workflowDTO, tenantDomainOfUser); if (WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) { WorkflowUtils.sendNotificationAfterWFComplete(workflowDTO, workflowType); From 4a89dfb40a53bac10b6c6abe29f0631686831d34 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Tue, 26 Mar 2024 16:08:55 +0530 Subject: [PATCH 07/23] Set the total notification count --- .../impl/dao/constants/SQLConstants.java | 10 ++- .../PortalNotificationDAO.java | 79 ++++++++++++------- 2 files changed, 58 insertions(+), 31 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java index f004ffe02fd2..3eed11a43b53 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java @@ -3192,7 +3192,9 @@ public static class PortalNotifications { " e.DESTINATION_USER = ?" + " AND e.ORGANIZATION = ?" + " AND e.PORTAL_TO_DISPLAY = ? " + - "ORDER BY n.CREATED_TIME DESC"; + "ORDER BY n.CREATED_TIME DESC " + + "LIMIT ? , ?" + ; public static final String GET_NOTIFICATIONS_ASC = "SELECT" + @@ -3207,7 +3209,9 @@ public static class PortalNotifications { " e.DESTINATION_USER = ?" + " AND e.ORGANIZATION = ?" + " AND e.PORTAL_TO_DISPLAY = ? " + - "ORDER BY n.CREATED_TIME ASC"; + "ORDER BY n.CREATED_TIME ASC " + + "LIMIT ? , ?" + ; public static final String DELETE_ALL_NOTIFICATIONS_OF_USER = "DELETE FROM AM_NOTIFICATION_END_USERS " + "WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; @@ -3248,6 +3252,8 @@ public static class PortalNotifications { public static final String GET_API_UUID_USING_NAME_CONTEXT_VERSION = "SELECT API_UUID FROM AM_API WHERE " + "API_NAME = ? AND CONTEXT = ? AND API_VERSION = ? AND ORGANIZATION = ?"; + public static final String GET_NOTIFICATIONS_COUNT = "SELECT COUNT(*) AS NOTIFICATION_COUNT FROM " + + "AM_NOTIFICATION_END_USERS WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java index 8a7540998910..7fb7dc04756d 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -5,9 +5,11 @@ import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; +import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.model.*; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants; +import org.wso2.carbon.apimgt.impl.factory.SQLConstantManagerFactory; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; import java.sql.Connection; @@ -18,6 +20,8 @@ import java.util.List; import java.util.UUID; +import static org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException; + public class PortalNotificationDAO { private static final Log log = LogFactory.getLog(PortalNotificationDAO.class); @@ -106,7 +110,7 @@ private String convertMetadataToJson(PortalNotificationMetaData metaData) { } public NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, - Integer offset) { + Integer offset) throws APIManagementException { List list = new ArrayList(); NotificationList notificationList = new NotificationList(); @@ -114,43 +118,58 @@ public NotificationList getNotifications(String username, String organization, S notificationList.setPagination(pagination); int total = 0; - Connection conn = null; - PreparedStatement ps = null; - ResultSet rs = null; + String sqlQueryForCount = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_COUNT; String sqlQuery; - try { - if (sortOrder != null && sortOrder.equals("asc")) { - sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_ASC; - } else { - sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_DESC; - } - conn = APIMgtDBUtil.getConnection(); - ps = conn.prepareStatement(sqlQuery); - ps.setString(1, username); - ps.setString(2, organization); - ps.setString(3, portalToDisplay); - rs = ps.executeQuery(); - while (rs.next()) { - Notification notification = new Notification(); - notification.setNotificationId(rs.getString("NOTIFICATION_ID")); - notification.setNotificationType(rs.getString("NOTIFICATION_TYPE")); - notification.setCreatedTime(rs.getTimestamp("CREATED_TIME").toString()); - notification.setComments(getCommentFromMetaData(rs.getString("NOTIFICATION_METADATA"), - rs.getString("NOTIFICATION_TYPE"))); - notification.setIsRead(rs.getBoolean("IS_READ")); - list.add(notification); + + try (Connection conn = APIMgtDBUtil.getConnection(); + PreparedStatement psForCount = conn.prepareStatement(sqlQueryForCount)) { + psForCount.setString(1, username); + psForCount.setString(2, organization); + psForCount.setString(3, portalToDisplay); + try (ResultSet rsForCount = psForCount.executeQuery()) { + while (rsForCount.next()) { + total = rsForCount.getInt("NOTIFICATION_COUNT"); + } + if (total > 0 && limit > 0) { + if (sortOrder != null && sortOrder.equals("asc")) { + sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_ASC; + } else { + sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_DESC; + } + try (PreparedStatement ps = conn.prepareStatement(sqlQuery)) { + ps.setString(1, username); + ps.setString(2, organization); + ps.setString(3, portalToDisplay); + ps.setInt(4, offset); + ps.setInt(5, limit); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + Notification notification = new Notification(); + notification.setNotificationId(rs.getString("NOTIFICATION_ID")); + notification.setNotificationType(rs.getString("NOTIFICATION_TYPE")); + notification.setCreatedTime(rs.getTimestamp("CREATED_TIME").toString()); + notification.setComments(getCommentFromMetaData(rs.getString("NOTIFICATION_METADATA"), + rs.getString("NOTIFICATION_TYPE"))); + notification.setIsRead(rs.getBoolean("IS_READ")); + list.add(notification); + } + } + } + } else { + notificationList.getPagination().setTotal(total); + notificationList.setCount(total); + return notificationList; + } } - notificationList.setList(list); } catch (SQLException e) { - log.error("Failed to retrieve notifications", e); - } finally { - APIMgtDBUtil.closeAllConnections(ps, conn, rs); + handleException("Failed to retrieve notifications of the user " + username, e); } pagination.setLimit(limit); pagination.setOffset(offset); notificationList.getPagination().setTotal(total); notificationList.setList(list); notificationList.setCount(list.size()); + return notificationList; } @@ -359,6 +378,8 @@ public NotificationList markAllNotificationsAsRead(String username, String organ } } catch (SQLException e) { log.error("Failed to mark all notifications as read", e); + } catch (APIManagementException e) { + throw new RuntimeException(e); } finally { APIMgtDBUtil.closeAllConnections(ps, conn, rs); } From c6cf38b184cb1289f5310fc7782fe26692db66d4 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Thu, 28 Mar 2024 09:13:16 +0530 Subject: [PATCH 08/23] Implement method to get the unread notification count --- .../wso2/carbon/apimgt/api/APIConsumer.java | 2 ++ .../apimgt/api/model/NotificationList.java | 6 +++++ .../carbon/apimgt/impl/APIConsumerImpl.java | 2 ++ .../impl/dao/constants/SQLConstants.java | 4 +++ .../PortalNotificationDAO.java | 24 ++++++++++++++++++ .../src/main/resources/devportal-api.yaml | 5 ++++ .../src/main/resources/publisher-api.yaml | 5 ++++ .../publisher/v1/dto/NotificationListDTO.java | 25 +++++++++++++++++-- .../src/main/resources/publisher-api.yaml | 5 ++++ .../api/store/v1/dto/NotificationListDTO.java | 25 +++++++++++++++++-- .../src/main/resources/devportal-api.yaml | 5 ++++ .../src/main/webapp/WEB-INF/web.xml | 2 +- 12 files changed, 105 insertions(+), 5 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java index 2099723c066b..23a6aff224b9 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java @@ -35,6 +35,8 @@ import org.wso2.carbon.apimgt.api.model.Identifier; import org.wso2.carbon.apimgt.api.model.KeyManagerApplicationInfo; import org.wso2.carbon.apimgt.api.model.Monetization; +import org.wso2.carbon.apimgt.api.model.NotificationList; +import org.wso2.carbon.apimgt.api.model.Notification; import org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo; import org.wso2.carbon.apimgt.api.model.ResourceFile; import org.wso2.carbon.apimgt.api.model.Scope; diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java index 9a7a45b33ce6..d41d38ae3a57 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java @@ -9,6 +9,8 @@ public class NotificationList { private List list = new ArrayList(); private Pagination pagination = null; + private Integer unreadCount = null; + public Integer getCount() { return count; } @@ -33,4 +35,8 @@ public void setPagination(Pagination pagination) { this.pagination = pagination; } + public Integer getUnreadCount() { return unreadCount; } + + public void setUnreadCount(Integer unreadCount) { this.unreadCount = unreadCount; } + } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java index d6a8dadca94e..55214b53955c 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java @@ -72,6 +72,8 @@ import org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration; import org.wso2.carbon.apimgt.api.model.Label; import org.wso2.carbon.apimgt.api.model.Monetization; +import org.wso2.carbon.apimgt.api.model.NotificationList; +import org.wso2.carbon.apimgt.api.model.Notification; import org.wso2.carbon.apimgt.api.model.OAuthAppRequest; import org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo; import org.wso2.carbon.apimgt.api.model.ResourceFile; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java index 3eed11a43b53..c4c422ff9ecd 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java @@ -3254,6 +3254,10 @@ public static class PortalNotifications { + "API_NAME = ? AND CONTEXT = ? AND API_VERSION = ? AND ORGANIZATION = ?"; public static final String GET_NOTIFICATIONS_COUNT = "SELECT COUNT(*) AS NOTIFICATION_COUNT FROM " + "AM_NOTIFICATION_END_USERS WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; + + public static final String GET_UNREAD_NOTIFICATION_COUNT = "SELECT COUNT(*) AS UNREAD_NOTIFICATION_COUNT FROM " + + "AM_NOTIFICATION_END_USERS WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ? " + + "AND IS_READ = FALSE"; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java index 7fb7dc04756d..89f781bd96d6 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -117,6 +117,7 @@ public NotificationList getNotifications(String username, String organization, S Pagination pagination = new Pagination(); notificationList.setPagination(pagination); int total = 0; + int unreadCount = 0; String sqlQueryForCount = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_COUNT; String sqlQuery; @@ -161,6 +162,7 @@ public NotificationList getNotifications(String username, String organization, S return notificationList; } } + unreadCount = getUnreadNotificationCount(username, organization, portalToDisplay, conn); } catch (SQLException e) { handleException("Failed to retrieve notifications of the user " + username, e); } @@ -169,6 +171,7 @@ public NotificationList getNotifications(String username, String organization, S notificationList.getPagination().setTotal(total); notificationList.setList(list); notificationList.setCount(list.size()); + notificationList.setUnreadCount(unreadCount); return notificationList; } @@ -408,4 +411,25 @@ public String getAPIUUIDUsingNameContextVersion(String apiName, String apiContex } + + public int getUnreadNotificationCount(String username, String organization, String portalToDisplay, Connection conn) + throws APIManagementException { + int unreadCount = 0; + String sqlQuery = SQLConstants.PortalNotifications.GET_UNREAD_NOTIFICATION_COUNT; + + try (PreparedStatement ps = conn.prepareStatement(sqlQuery)) { + ps.setString(1, username); + ps.setString(2, organization); + ps.setString(3, portalToDisplay); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + unreadCount = rs.getInt("UNREAD_NOTIFICATION_COUNT"); + } + } + } catch (SQLException e) { + handleException("Failed to get unread notification count for user " + username, e); + } + + return unreadCount; + } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml index 816514bb5092..0283d551dfde 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml @@ -4046,6 +4046,11 @@ components: $ref: '#/components/schemas/Notification' pagination: $ref: '#/components/schemas/Pagination' + unreadCount: + type: integer + description: | + Number of Unread Notifications returned. + example: 5 APIList: title: API List type: object diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml index e812649d57d8..0d6bb055834c 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml @@ -8946,6 +8946,11 @@ components: $ref: '#/components/schemas/Notification' pagination: $ref: '#/components/schemas/Pagination' + unreadCount: + type: integer + description: | + Number of Unread Notifications returned. + example: 5 Comment: title: Comment required: diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationListDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationListDTO.java index fb03081d7073..da75f0f0a9c4 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationListDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1.common/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/dto/NotificationListDTO.java @@ -27,6 +27,7 @@ public class NotificationListDTO { private Integer count = null; private List list = new ArrayList(); private PaginationDTO pagination = null; + private Integer unreadCount = null; /** * Number of Notifications returned. @@ -82,6 +83,24 @@ public void setPagination(PaginationDTO pagination) { this.pagination = pagination; } + /** + * Number of Unread Notifications returned. + **/ + public NotificationListDTO unreadCount(Integer unreadCount) { + this.unreadCount = unreadCount; + return this; + } + + + @ApiModelProperty(example = "5", value = "Number of Unread Notifications returned. ") + @JsonProperty("unreadCount") + public Integer getUnreadCount() { + return unreadCount; + } + public void setUnreadCount(Integer unreadCount) { + this.unreadCount = unreadCount; + } + @Override public boolean equals(java.lang.Object o) { @@ -94,12 +113,13 @@ public boolean equals(java.lang.Object o) { NotificationListDTO notificationList = (NotificationListDTO) o; return Objects.equals(count, notificationList.count) && Objects.equals(list, notificationList.list) && - Objects.equals(pagination, notificationList.pagination); + Objects.equals(pagination, notificationList.pagination) && + Objects.equals(unreadCount, notificationList.unreadCount); } @Override public int hashCode() { - return Objects.hash(count, list, pagination); + return Objects.hash(count, list, pagination, unreadCount); } @Override @@ -110,6 +130,7 @@ public String toString() { sb.append(" count: ").append(toIndentedString(count)).append("\n"); sb.append(" list: ").append(toIndentedString(list)).append("\n"); sb.append(" pagination: ").append(toIndentedString(pagination)).append("\n"); + sb.append(" unreadCount: ").append(toIndentedString(unreadCount)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml index e812649d57d8..0d6bb055834c 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml @@ -8946,6 +8946,11 @@ components: $ref: '#/components/schemas/Notification' pagination: $ref: '#/components/schemas/Pagination' + unreadCount: + type: integer + description: | + Number of Unread Notifications returned. + example: 5 Comment: title: Comment required: diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationListDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationListDTO.java index 153a22d82679..2d0bbb64e130 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationListDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/NotificationListDTO.java @@ -27,6 +27,7 @@ public class NotificationListDTO { private Integer count = null; private List list = new ArrayList(); private PaginationDTO pagination = null; + private Integer unreadCount = null; /** * Number of Notifications returned. @@ -82,6 +83,24 @@ public void setPagination(PaginationDTO pagination) { this.pagination = pagination; } + /** + * Number of Unread Notifications returned. + **/ + public NotificationListDTO unreadCount(Integer unreadCount) { + this.unreadCount = unreadCount; + return this; + } + + + @ApiModelProperty(example = "5", value = "Number of Unread Notifications returned. ") + @JsonProperty("unreadCount") + public Integer getUnreadCount() { + return unreadCount; + } + public void setUnreadCount(Integer unreadCount) { + this.unreadCount = unreadCount; + } + @Override public boolean equals(java.lang.Object o) { @@ -94,12 +113,13 @@ public boolean equals(java.lang.Object o) { NotificationListDTO notificationList = (NotificationListDTO) o; return Objects.equals(count, notificationList.count) && Objects.equals(list, notificationList.list) && - Objects.equals(pagination, notificationList.pagination); + Objects.equals(pagination, notificationList.pagination) && + Objects.equals(unreadCount, notificationList.unreadCount); } @Override public int hashCode() { - return Objects.hash(count, list, pagination); + return Objects.hash(count, list, pagination, unreadCount); } @Override @@ -110,6 +130,7 @@ public String toString() { sb.append(" count: ").append(toIndentedString(count)).append("\n"); sb.append(" list: ").append(toIndentedString(list)).append("\n"); sb.append(" pagination: ").append(toIndentedString(pagination)).append("\n"); + sb.append(" unreadCount: ").append(toIndentedString(unreadCount)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml index 816514bb5092..0283d551dfde 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml @@ -4046,6 +4046,11 @@ components: $ref: '#/components/schemas/Notification' pagination: $ref: '#/components/schemas/Pagination' + unreadCount: + type: integer + description: | + Number of Unread Notifications returned. + example: 5 APIList: title: API List type: object diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml index 775b97aa53f8..aa8429904d79 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml @@ -49,7 +49,7 @@ org.wso2.carbon.apimgt.rest.api.store.v1.KeyManagersApi, org.wso2.carbon.apimgt.rest.api.store.v1.MeApi, org.wso2.carbon.apimgt.rest.api.store.v1.WebhooksApi, - org.wso2.carbon.apimgt.rest.api.store.v1.MarketplaceAssistantApi + org.wso2.carbon.apimgt.rest.api.store.v1.MarketplaceAssistantApi, org.wso2.carbon.apimgt.rest.api.store.v1.WebhooksApi, org.wso2.carbon.apimgt.rest.api.store.v1.NotificationsApi From 99db48b3bb16514380e5ea35df98a8cacf037a32 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Thu, 28 Mar 2024 14:04:32 +0530 Subject: [PATCH 09/23] Stop duplicating the subscriber --- .../WorkflowNotificationServiceImpl.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java index 2ebd6e70a0d6..63423d6a68c9 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java @@ -18,7 +18,9 @@ import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.user.core.common.User; @@ -202,6 +204,7 @@ private List getSubscribersOfAPI(String apiUUID, String organizat private List getAPIUsageByAPIId(String uuid, String organization, APIIdentifier apiIdEmailReplaced) throws APIManagementException { List subscribedAPIs = new ArrayList<>(); + Set uniqueUserSet = new HashSet<>(); try{ UserApplicationAPIUsage[] allApiResult = ApiMgtDAO.getInstance().getAllAPIUsageByProviderAndApiId(uuid, organization); for (UserApplicationAPIUsage usage : allApiResult) { @@ -211,7 +214,10 @@ private List getAPIUsageByAPIId(String uuid, String organization, APIUtil.replaceEmailDomain(subsApiId.getProviderName()), subsApiId.getApiName(), subsApiId.getVersion()); if (subsApiIdEmailReplaced.equals(apiIdEmailReplaced)) { - subscribedAPIs.add(apiSubscription); + String userIdentifier = apiSubscription.getSubscriber().getName()+ "-" + apiSubscription.getOrganization(); + if (uniqueUserSet.add(userIdentifier)){ + subscribedAPIs.add(apiSubscription); + } } } } From f58c242c7aa5783deefe5130120c83dc2d311137 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Fri, 26 Apr 2024 13:32:59 +0530 Subject: [PATCH 10/23] Add license headers, format code, remove unwanted spaces and imports --- .../wso2/carbon/apimgt/api/APIProvider.java | 34 +++++++++++ .../carbon/apimgt/api/model/Notification.java | 18 ++++++ .../apimgt/api/model/NotificationList.java | 18 ++++++ .../carbon/apimgt/impl/dao/ApiMgtDAO.java | 26 ++++---- .../PortalNotificationDAO.java | 31 +++++++--- .../PortalNotificationDTO.java | 18 ++++++ .../PortalNotificationEndUserDTO.java | 18 ++++++ .../PortalNotificationMetaData.java | 18 ++++++ .../PortalNotificationService.java | 18 ++++++ .../PortalNotificationType.java | 18 ++++++ .../WorkflowNotificationServiceImpl.java | 48 ++++++++++----- .../impl/workflow/WorkflowConstants.java | 1 - .../impl/workflow/WorkflowExecutor.java | 9 --- ...icationCreationWSWorkflowExecutorTest.java | 1 - .../v1/impl/WorkflowsApiServiceImpl.java | 1 - .../v1/impl/NotificationsApiServiceImpl.java | 20 ++++++- .../v1/impl/NotificationsApiServiceImpl.java | 60 +++++++++++-------- .../src/main/webapp/WEB-INF/web.xml | 1 - 18 files changed, 283 insertions(+), 75 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java index 4b3847e40806..640362bd5f8f 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java @@ -1922,12 +1922,46 @@ boolean isPolicyMetadataExists(String gatewayPolicyMappingId) */ NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, Integer offset) throws APIManagementException; + /** + * Method to delete the notifications of a given user + * + * @param username + * @param organization + * @param portalToDisplay + * @return true after successful deletion + */ boolean deleteAllNotifications(String username, String organization, String portalToDisplay) throws APIManagementException; + /** + * Method to mark a notification as read + * + * @param username + * @param organization + * @param notificationId + * @param portalToDisplay + * @return updated Notification + */ Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay); + /** + * Method to delete a notification by notification id + * + * @param username + * @param organization + * @param notificationId + * @param portalToDisplay + * @return true after successful deletion + */ boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay); + /** + * Method to mark all notifications as read + * + * @param username + * @param organization + * @param portalToDisplay + * @return updated NotificationList + */ NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java index 2929d8858cb3..086f3b585074 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.apimgt.api.model; public class Notification { diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java index d41d38ae3a57..ce84effdb196 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.apimgt.api.model; import java.util.ArrayList; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java index 601b7794287c..55683a31126c 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java @@ -167,8 +167,6 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; -import static org.wso2.carbon.apimgt.impl.utils.APIUtil.getTenantDomainFromTenantId; - /** * This class represent the ApiMgtDAO. */ @@ -2630,7 +2628,7 @@ public UserApplicationAPIUsage[] getAllAPIUsageByProviderAndApiId(String uuid, S int appId = result.getInt("APPLICATION_ID"); String subStatus = result.getString("SUB_STATUS"); String subsCreateState = result.getString("SUBS_CREATE_STATE"); - String subsOrganization = getTenantDomainFromTenantId(result.getInt("SUB_TENANT_ID")); + String subsOrganization = APIUtil.getTenantDomainFromTenantId(result.getInt("SUB_TENANT_ID")); String key = userId + "::" + application; UserApplicationAPIUsage usage = userApplicationUsages.get(key); if (usage == null) { @@ -14997,7 +14995,7 @@ public void addAPIProductResourceMappings(List productResour } int productId = getAPIID(uuid, connection); int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(productIdentifier.getProviderName())); - String tenantDomain = getTenantDomainFromTenantId(tenantId); + String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); URITemplate uriTemplateOriginal = apiProductResource.getUriTemplate(); int urlMappingId = uriTemplateOriginal.getId(); // Adding to AM_API_URL_MAPPING table @@ -15897,7 +15895,7 @@ public void updateCategory(APICategory apiCategory) throws APIManagementExceptio statement.execute(); } catch (SQLException e) { handleException("Failed to update API Category : " + apiCategory.getName() + " of tenant " + - getTenantDomainFromTenantId(apiCategory.getTenantID()), e); + APIUtil.getTenantDomainFromTenantId(apiCategory.getTenantID()), e); } } @@ -16553,7 +16551,7 @@ public void addTenantTheme(int tenantId, InputStream themeContent) throws APIMan statement.executeUpdate(); } catch (SQLException e) { handleException("Failed to add tenant theme of tenant " - + getTenantDomainFromTenantId(tenantId), e); + + APIUtil.getTenantDomainFromTenantId(tenantId), e); } } @@ -16574,7 +16572,7 @@ public void updateTenantTheme(int tenantId, InputStream themeContent) throws API statement.executeUpdate(); } catch (SQLException e) { handleException("Failed to update tenant theme of tenant " - + getTenantDomainFromTenantId(tenantId), e); + + APIUtil.getTenantDomainFromTenantId(tenantId), e); } } @@ -16598,7 +16596,7 @@ public InputStream getTenantTheme(int tenantId) throws APIManagementException { } } catch (SQLException e) { handleException("Failed to fetch tenant theme of tenant " - + getTenantDomainFromTenantId(tenantId), e); + + APIUtil.getTenantDomainFromTenantId(tenantId), e); } return tenantThemeContent; } @@ -16621,7 +16619,7 @@ public boolean isTenantThemeExist(int tenantId) throws APIManagementException { return resultSet.next(); } catch (SQLException e) { handleException("Failed to check whether tenant theme exist for tenant " - + getTenantDomainFromTenantId(tenantId), e); + + APIUtil.getTenantDomainFromTenantId(tenantId), e); } return false; } @@ -16641,7 +16639,7 @@ public void deleteTenantTheme(int tenantId) throws APIManagementException { statement.executeUpdate(); } catch (SQLException e) { handleException("Failed to delete tenant theme of tenant " - + getTenantDomainFromTenantId(tenantId), e); + + APIUtil.getTenantDomainFromTenantId(tenantId), e); } } @@ -16872,7 +16870,7 @@ public void addAPIRevision(APIRevision apiRevision) throws APIManagementExceptio APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiRevision.getApiUUID()); int apiId = getAPIID(apiRevision.getApiUUID(), connection); int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName())); - String tenantDomain = getTenantDomainFromTenantId(tenantId); + String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); // Adding to AM_API_URL_MAPPING table PreparedStatement getURLMappingsStatement = connection @@ -17779,7 +17777,7 @@ public void restoreAPIRevision(APIRevision apiRevision) throws APIManagementExce APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiRevision.getApiUUID()); int apiId = getAPIID(apiRevision.getApiUUID(), connection); int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName())); - String tenantDomain = getTenantDomainFromTenantId(tenantId); + String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); // Removing related Current API entries from AM_API_URL_MAPPING table PreparedStatement removeURLMappingsStatement = connection.prepareStatement(SQLConstants .APIRevisionSqlConstants.REMOVE_CURRENT_API_ENTRIES_IN_AM_API_URL_MAPPING_BY_API_ID); @@ -18078,7 +18076,7 @@ public void addAPIProductRevision(APIRevision apiRevision) throws APIManagementE int apiId = getAPIID(apiRevision.getApiUUID(), connection); int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiProductIdentifier.getProviderName())); - String tenantDomain = getTenantDomainFromTenantId(tenantId); + String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); // Adding to AM_API_URL_MAPPING table PreparedStatement getURLMappingsStatement = connection @@ -18316,7 +18314,7 @@ public void restoreAPIProductRevision(APIRevision apiRevision) throws APIManagem int apiId = getAPIID(apiRevision.getApiUUID(), connection); int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiProductIdentifier.getProviderName())); - String tenantDomain = getTenantDomainFromTenantId(tenantId); + String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId); //Remove Current API Product entries from AM_API_URL_MAPPING table PreparedStatement removeURLMappingsFromCurrentAPIProduct = connection.prepareStatement( diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java index 89f781bd96d6..9efb09a6c3e3 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.apimgt.impl.portalNotifications; import org.apache.commons.logging.Log; @@ -6,11 +24,12 @@ import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.wso2.carbon.apimgt.api.APIManagementException; -import org.wso2.carbon.apimgt.api.model.*; -import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.api.model.Pagination; +import org.wso2.carbon.apimgt.api.model.Notification; +import org.wso2.carbon.apimgt.api.model.NotificationList; import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants; -import org.wso2.carbon.apimgt.impl.factory.SQLConstantManagerFactory; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; import java.sql.Connection; import java.sql.PreparedStatement; @@ -20,8 +39,6 @@ import java.util.List; import java.util.UUID; -import static org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException; - public class PortalNotificationDAO { private static final Log log = LogFactory.getLog(PortalNotificationDAO.class); @@ -164,7 +181,7 @@ public NotificationList getNotifications(String username, String organization, S } unreadCount = getUnreadNotificationCount(username, organization, portalToDisplay, conn); } catch (SQLException e) { - handleException("Failed to retrieve notifications of the user " + username, e); + APIUtil.handleException("Failed to retrieve notifications of the user " + username, e); } pagination.setLimit(limit); pagination.setOffset(offset); @@ -427,7 +444,7 @@ public int getUnreadNotificationCount(String username, String organization, Stri } } } catch (SQLException e) { - handleException("Failed to get unread notification count for user " + username, e); + APIUtil.handleException("Failed to get unread notification count for user " + username, e); } return unreadCount; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java index 5fc60a909144..d01d8b0233fb 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.apimgt.impl.portalNotifications; import java.sql.Timestamp; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java index ab2af0569405..570f5245938a 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.apimgt.impl.portalNotifications; public class PortalNotificationEndUserDTO { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java index ae788c3d2782..bb8923390558 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.apimgt.impl.portalNotifications; public class PortalNotificationMetaData { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java index 2ca96fa457d8..e34c65c3ff8e 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.apimgt.impl.portalNotifications; public interface PortalNotificationService { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java index 6936883bdd9a..4013b8042c51 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.apimgt.impl.portalNotifications; public enum PortalNotificationType { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java index 63423d6a68c9..57145e19bb5f 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.apimgt.impl.portalNotifications; import org.apache.commons.lang3.StringUtils; @@ -29,7 +47,6 @@ public class WorkflowNotificationServiceImpl implements PortalNotificationService { public void sendPortalNotifications(WorkflowDTO workflowDTO, String tenantDomainOfUser) { PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); - portalNotificationsDTO.setNotificationType(getNotificationType(workflowDTO.getWorkflowType())); portalNotificationsDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); portalNotificationsDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); @@ -62,7 +79,6 @@ private PortalNotificationType getNotificationType(String workflowType) { return PortalNotificationType.SUBSCRIPTION_UPDATE; case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION: return PortalNotificationType.SUBSCRIPTION_DELETION; - } return null; } @@ -134,12 +150,12 @@ private List getDestinationUser( } } - if(APIUtil.isMultiGroupAppSharingEnabled()){ + if (APIUtil.isMultiGroupAppSharingEnabled()) { try { List users = getAllUsersBelongToGroup(workflowDTO, tenantDomainOfUser); for (User user : users) { PortalNotificationEndUserDTO endUser = new PortalNotificationEndUserDTO(); - if(user.getUsername().equals(destinationUser)){ + if (user.getUsername().equals(destinationUser)) { continue; } endUser.setDestinationUser(user.getUsername()); @@ -154,7 +170,6 @@ private List getDestinationUser( } } - return destinationUserList; } @@ -205,8 +220,9 @@ private List getAPIUsageByAPIId(String uuid, String organization, throws APIManagementException { List subscribedAPIs = new ArrayList<>(); Set uniqueUserSet = new HashSet<>(); - try{ - UserApplicationAPIUsage[] allApiResult = ApiMgtDAO.getInstance().getAllAPIUsageByProviderAndApiId(uuid, organization); + try { + UserApplicationAPIUsage[] allApiResult = ApiMgtDAO.getInstance() + .getAllAPIUsageByProviderAndApiId(uuid, organization); for (UserApplicationAPIUsage usage : allApiResult) { for (SubscribedAPI apiSubscription : usage.getApiSubscriptions()) { APIIdentifier subsApiId = apiSubscription.getAPIIdentifier(); @@ -214,8 +230,9 @@ private List getAPIUsageByAPIId(String uuid, String organization, APIUtil.replaceEmailDomain(subsApiId.getProviderName()), subsApiId.getApiName(), subsApiId.getVersion()); if (subsApiIdEmailReplaced.equals(apiIdEmailReplaced)) { - String userIdentifier = apiSubscription.getSubscriber().getName()+ "-" + apiSubscription.getOrganization(); - if (uniqueUserSet.add(userIdentifier)){ + String userIdentifier = apiSubscription.getSubscriber() + .getName() + "-" + apiSubscription.getOrganization(); + if (uniqueUserSet.add(userIdentifier)) { subscribedAPIs.add(apiSubscription); } } @@ -245,8 +262,9 @@ private List getAllUsersBelongToGroup(WorkflowDTO workflowDTO, String tena SubscribedAPI sub = ApiMgtDAO.getInstance() .getSubscriptionById(Integer.parseInt(workflowDTO.getWorkflowReference())); groupId = sub.getApplication().getGroupId(); - } else if (workflowDTO.getWorkflowType().equals(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION) - || workflowDTO.getWorkflowType().equals(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX)) { + } else if (workflowDTO.getWorkflowType() + .equals(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION) || workflowDTO.getWorkflowType() + .equals(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX)) { groupId = ((ApplicationRegistrationWorkflowDTO) workflowDTO).getApplication().getGroupId(); } @@ -255,16 +273,16 @@ private List getAllUsersBelongToGroup(WorkflowDTO workflowDTO, String tena .getTenantId(tenantDomainOfUser); RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService(); UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId); - if(realm != null){ + if (realm != null) { org.wso2.carbon.user.core.UserStoreManager manager = realm.getUserStoreManager(); AbstractUserStoreManager abstractManager = (AbstractUserStoreManager) manager; - APIManagerConfiguration config = ServiceReferenceHolder.getInstance(). - getAPIManagerConfigurationService().getAPIManagerConfiguration(); + APIManagerConfiguration config = ServiceReferenceHolder.getInstance() + .getAPIManagerConfigurationService().getAPIManagerConfiguration(); String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI); if (StringUtils.isBlank(claim)) { claim = "http://wso2.org/claims/organization"; } - users = abstractManager.getUserListWithID(claim , groupId, "default"); + users = abstractManager.getUserListWithID(claim, groupId, "default"); } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowConstants.java index 6bcef88d5f2e..0ccb341c75ac 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowConstants.java @@ -155,5 +155,4 @@ private PayloadConstants(){ } - } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java index 777d6430a343..09aa9a0a1bc4 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/WorkflowExecutor.java @@ -23,16 +23,10 @@ import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationDAO; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationDTO; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationEndUserDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationMetaData; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationType; import org.wso2.carbon.registry.core.utils.UUIDGenerator; import java.io.Serializable; -import java.util.ArrayList; import java.util.List; /** @@ -109,15 +103,12 @@ public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowExcepti ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance(); try { apiMgtDAO.updateWorkflowStatus(workflowDTO); - - } catch (APIManagementException e) { throw new WorkflowException("Error while updating workflow", e); } return new GeneralWorkflowResponse(); } - /** * Returns the information of the workflows whose status' match the workflowStatus * diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java index 94596b3f9ace..cf14e0ab6015 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java @@ -95,7 +95,6 @@ public void testWorkflowApprove() throws APIManagementException, WorkflowExcepti Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_APPROVED); - } @Test diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java index 9d4cce760338..7c101bb3cb56 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java @@ -236,5 +236,4 @@ public Response workflowsUpdateWorkflowStatusPost(String workflowReferenceId, Wo } return null; } - } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java index 3857f60beafc..5f8c1b1ccc6e 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.apimgt.rest.api.publisher.v1.impl; import org.apache.commons.logging.Log; @@ -8,7 +26,7 @@ import org.wso2.carbon.apimgt.api.model.NotificationList; import org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil; import org.wso2.carbon.apimgt.rest.api.common.RestApiConstants; -import org.wso2.carbon.apimgt.rest.api.publisher.v1.*; +import org.wso2.carbon.apimgt.rest.api.publisher.v1.NotificationsApiService; import org.apache.cxf.jaxrs.ext.MessageContext; diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java index 9c89847e276a..e7f4e57d37ea 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java @@ -1,32 +1,38 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.apimgt.rest.api.store.v1.impl; import org.wso2.carbon.apimgt.api.APIConsumer; import org.wso2.carbon.apimgt.api.APIManagementException; -import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.model.Notification; import org.wso2.carbon.apimgt.api.model.NotificationList; import org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil; import org.wso2.carbon.apimgt.rest.api.common.RestApiConstants; -import org.wso2.carbon.apimgt.rest.api.store.v1.*; -import org.wso2.carbon.apimgt.rest.api.store.v1.dto.*; +import org.wso2.carbon.apimgt.rest.api.store.v1.NotificationsApiService; -import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.MessageContext; -import org.wso2.carbon.apimgt.rest.api.store.v1.dto.ErrorDTO; -import org.wso2.carbon.apimgt.rest.api.store.v1.dto.NotificationDTO; -import org.wso2.carbon.apimgt.rest.api.store.v1.dto.NotificationListDTO; import org.wso2.carbon.apimgt.rest.api.store.v1.dto.PatchAllNotificationsRequestDTO; import org.wso2.carbon.apimgt.rest.api.store.v1.dto.PatchNotificationRequestDTO; import org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil; -import java.util.List; - -import java.io.InputStream; - import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - public class NotificationsApiServiceImpl implements NotificationsApiService { @@ -38,8 +44,9 @@ public Response deleteNotification(String notificationId, MessageContext message String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); - boolean result = apiConsumer.deleteNotificationById(username, organization, notificationId, portalToDisplay); - if(!result){ + boolean result = apiConsumer.deleteNotificationById(username, organization, notificationId, + portalToDisplay); + if (!result) { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { @@ -56,7 +63,7 @@ public Response deleteNotifications(MessageContext messageContext) throws APIMan String organization = RestApiUtil.getValidatedOrganization(messageContext); APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); boolean result = apiConsumer.deleteAllNotifications(username, organization, portalToDisplay); - if(!result){ + if (!result) { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { @@ -78,7 +85,8 @@ public Response getNotifications(String sortOrder, Integer limit, Integer offset String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); - notificationList = apiConsumer.getNotifications(username, organization, portalToDisplay, sortOrder, limit, offset); + notificationList = apiConsumer.getNotifications(username, organization, portalToDisplay, sortOrder, limit, + offset); } catch (APIManagementException e) { throw new APIManagementException("Error while getting notifications", e); } @@ -86,10 +94,10 @@ public Response getNotifications(String sortOrder, Integer limit, Integer offset return Response.ok().entity(notificationList).build(); } - public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, MessageContext messageContext) - throws APIManagementException { + public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, + MessageContext messageContext) throws APIManagementException { - NotificationList notificationList ; + NotificationList notificationList; String portalToDisplay = "developer"; try { @@ -97,7 +105,7 @@ public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patch String organization = RestApiUtil.getValidatedOrganization(messageContext); APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); notificationList = apiConsumer.markAllNotificationsAsRead(username, organization, portalToDisplay); - if(notificationList == null){ + if (notificationList == null) { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { @@ -107,18 +115,20 @@ public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patch return Response.ok().entity(notificationList).build(); } - public Response markNotificationAsReadById(String notificationId, PatchNotificationRequestDTO patchNotificationRequestDTO, MessageContext messageContext) + public Response markNotificationAsReadById(String notificationId, + PatchNotificationRequestDTO patchNotificationRequestDTO, MessageContext messageContext) throws APIManagementException { - Notification notification ; + Notification notification; String portalToDisplay = "developer"; try { String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); - notification = apiConsumer.markNotificationAsReadById(username, organization, notificationId, portalToDisplay); - if(notification == null){ + notification = apiConsumer.markNotificationAsReadById(username, organization, notificationId, + portalToDisplay); + if (notification == null) { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml index aa8429904d79..941bcb16442b 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/webapp/WEB-INF/web.xml @@ -50,7 +50,6 @@ org.wso2.carbon.apimgt.rest.api.store.v1.MeApi, org.wso2.carbon.apimgt.rest.api.store.v1.WebhooksApi, org.wso2.carbon.apimgt.rest.api.store.v1.MarketplaceAssistantApi, - org.wso2.carbon.apimgt.rest.api.store.v1.WebhooksApi, org.wso2.carbon.apimgt.rest.api.store.v1.NotificationsApi From 43cdcac94b0f160da8bbbf325990df632bf6a593 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Sun, 28 Apr 2024 11:23:33 +0530 Subject: [PATCH 11/23] Modify to try with resources and replace logs with exception handling functions --- .../wso2/carbon/apimgt/api/APIProvider.java | 15 +- .../carbon/apimgt/impl/APIConsumerImpl.java | 71 +++++++- .../carbon/apimgt/impl/APIProviderImpl.java | 72 +++++++- .../PortalNotificationDAO.java | 164 +++++++----------- .../PortalNotificationService.java | 4 +- .../WorkflowNotificationServiceImpl.java | 3 +- .../rest/api/common/RestApiConstants.java | 1 + .../v1/impl/NotificationsApiServiceImpl.java | 47 +++-- .../v1/impl/NotificationsApiServiceImpl.java | 51 ++++-- 9 files changed, 284 insertions(+), 144 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java index 640362bd5f8f..ac23c88f4d61 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java @@ -1920,7 +1920,8 @@ boolean isPolicyMetadataExists(String gatewayPolicyMappingId) * @param offset * @return NotificationList */ - NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, Integer offset) throws APIManagementException; + NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, + Integer limit, Integer offset) throws APIManagementException; /** * Method to delete the notifications of a given user @@ -1930,7 +1931,8 @@ boolean isPolicyMetadataExists(String gatewayPolicyMappingId) * @param portalToDisplay * @return true after successful deletion */ - boolean deleteAllNotifications(String username, String organization, String portalToDisplay) throws APIManagementException; + boolean deleteAllNotifications(String username, String organization, String portalToDisplay) + throws APIManagementException; /** * Method to mark a notification as read @@ -1941,7 +1943,8 @@ boolean isPolicyMetadataExists(String gatewayPolicyMappingId) * @param portalToDisplay * @return updated Notification */ - Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay); + Notification markNotificationAsReadById(String username, String organization, String notificationId, + String portalToDisplay) throws APIManagementException; /** * Method to delete a notification by notification id @@ -1952,7 +1955,8 @@ boolean isPolicyMetadataExists(String gatewayPolicyMappingId) * @param portalToDisplay * @return true after successful deletion */ - boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay); + boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) + throws APIManagementException; /** * Method to mark all notifications as read @@ -1962,6 +1966,7 @@ boolean isPolicyMetadataExists(String gatewayPolicyMappingId) * @param portalToDisplay * @return updated NotificationList */ - NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay); + NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) + throws APIManagementException; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java index 55214b53955c..6271b4fdb238 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java @@ -4597,32 +4597,85 @@ public boolean isKeyManagerByNameAllowedForUser(String keyManagerName, String or return true; } + /** + * Get the list of Notifications belongs to a particular developer user + * + * @param username + * @param organization + * @param portalToDisplay + * @param sortOrder + * @param limit + * @param offset + * @return List of Notifications + * @throws APIManagementException if failed to get notifications + */ @Override - public NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, - Integer offset) throws APIManagementException{ - return portalNotificationDAO.getNotifications(username, organization, portalToDisplay, sortOrder, limit, offset); + public NotificationList getNotifications(String username, String organization, String portalToDisplay, + String sortOrder, Integer limit, Integer offset) throws APIManagementException { + return portalNotificationDAO.getNotifications(username, organization, portalToDisplay, sortOrder, limit, + offset); } + /** + * Mark all the notifications as read for a particular developer user + * + * @param username + * @param organization + * @param portalToDisplay + * @return List of Notifications + * @throws APIManagementException if failed to mark all notifications as read + */ @Override public NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) throws APIManagementException { return portalNotificationDAO.markAllNotificationsAsRead(username, organization, portalToDisplay); } + /** + * Mark a particular notification as read for a particular developer user + * + * @param username + * @param organization + * @param notificationId + * @param portalToDisplay + * @return updated Notification after marking as read + * @throws APIManagementException if failed to mark the notification as read + */ @Override - public Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) - throws APIManagementException { - return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId, portalToDisplay); + public Notification markNotificationAsReadById(String username, String organization, String notificationId, + String portalToDisplay) throws APIManagementException { + return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId, + portalToDisplay); } + /** + * Delete a particular notification for a particular developer user + * + * @param username + * @param organization + * @param notificationId + * @param portalToDisplay + * @return true after deleting the notifications + * @throws APIManagementException if failed to delete the notification + */ @Override - public boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) - throws APIManagementException { + public boolean deleteNotificationById(String username, String organization, String notificationId, + String portalToDisplay) throws APIManagementException { return portalNotificationDAO.deleteNotificationById(username, organization, notificationId, portalToDisplay); } + /** + * Delete all the notifications for a particular developer user + * + * @param username + * @param organization + * @param portalToDisplay + * @return true after deleting all notifications + * @throws APIManagementException if failed to delete all notifications + */ @Override - public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) throws APIManagementException { + public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) + throws APIManagementException { return portalNotificationDAO.deleteAllNotifications(username, organization, portalToDisplay); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java index 8b9c4ef03fa2..9031bf33624d 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java @@ -7234,29 +7234,85 @@ public int getPolicyUsageByPolicyUUIDInGatewayPolicies(String commonPolicyUUID) return apiMgtDAO.getPolicyUUIDCount(commonPolicyUUID); } + /** + * Get the list of Notifications belongs to a particular publisher user + * + * @param username + * @param organization + * @param portalToDisplay + * @param sortOrder + * @param limit + * @param offset + * @return List of Notifications + * @throws APIManagementException if failed to get notifications + */ @Override - public NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, - Integer offset) throws APIManagementException { - return portalNotificationDAO.getNotifications(username, organization, portalToDisplay, sortOrder, limit, offset); + public NotificationList getNotifications(String username, String organization, String portalToDisplay, + String sortOrder, Integer limit, Integer offset) throws APIManagementException { + return portalNotificationDAO.getNotifications(username, organization, portalToDisplay, sortOrder, limit, + offset); } + /** + * Delete all notifications belongs to a particular publisher user + * + * @param username + * @param organization + * @param portalToDisplay + * @return true after deleting all notifications + * @throws APIManagementException if failed to delete notifications + */ @Override - public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) { + public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) + throws APIManagementException { return portalNotificationDAO.deleteAllNotifications(username, organization, portalToDisplay); } + /** + * Mark a notification as read by notification ID + * + * @param username + * @param organization + * @param notificationId + * @param portalToDisplay + * @return updated Notification after marking as read + * @throws APIManagementException if failed to mark the notification as read + */ @Override - public Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) { - return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId, portalToDisplay); + public Notification markNotificationAsReadById(String username, String organization, String notificationId, + String portalToDisplay) throws APIManagementException { + return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId, + portalToDisplay); } + /** + * Delete a notification by notification ID + * + * @param username + * @param organization + * @param notificationId + * @param portalToDisplay + * @return true after deleting the notification + * @throws APIManagementException if failed to delete the notification + */ @Override - public boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) { + public boolean deleteNotificationById(String username, String organization, String notificationId, + String portalToDisplay) throws APIManagementException { return portalNotificationDAO.deleteNotificationById(username, organization, notificationId, portalToDisplay); } + /** + * Mark all notifications as read + * + * @param username + * @param organization + * @param portalToDisplay + * @return updated NotificationList after marking all notifications as read + * @throws APIManagementException if failed to mark all notifications as read + */ @Override - public NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) { + public NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) + throws APIManagementException { return portalNotificationDAO.markAllNotificationsAsRead(username, organization, portalToDisplay); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java index 9efb09a6c3e3..2569eb57f5a4 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -29,7 +29,6 @@ import org.wso2.carbon.apimgt.api.model.NotificationList; import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; -import org.wso2.carbon.apimgt.impl.utils.APIUtil; import java.sql.Connection; import java.sql.PreparedStatement; @@ -55,24 +54,19 @@ public static PortalNotificationDAO getInstance() { return INSTANCE; } - public boolean addNotification(PortalNotificationDTO portalNotificationDTO) { + public boolean addNotification(PortalNotificationDTO portalNotificationDTO) throws APIManagementException { String addNotificationQuery = SQLConstants.PortalNotifications.ADD_NOTIFICATION; String addEndUserQuery = SQLConstants.PortalNotifications.ADD_NOTIFICATION_END_USER; - Connection conn = null; - PreparedStatement ps = null; - try { - conn = APIMgtDBUtil.getConnection(); - ps = conn.prepareStatement(addNotificationQuery); - String notificationId = UUID.randomUUID().toString(); + try (Connection conn = APIMgtDBUtil.getConnection(); + PreparedStatement ps = conn.prepareStatement(addNotificationQuery)) { + String notificationId = UUID.randomUUID().toString(); ps.setString(1, notificationId); ps.setString(2, portalNotificationDTO.getNotificationType().toString()); ps.setTimestamp(3, portalNotificationDTO.getCreatedTime()); - String metadataJson = convertMetadataToJson(portalNotificationDTO.getNotificationMetadata()); - ps.setString(4, metadataJson); int rowsAffected = ps.executeUpdate(); @@ -84,32 +78,22 @@ public boolean addNotification(PortalNotificationDTO portalNotificationDTO) { } } catch (SQLException e) { - log.error("Error while adding notification", e); - log.error("SQL State: " + e.getSQLState()); - log.error("Error Code: " + e.getErrorCode()); - } finally { - APIMgtDBUtil.closeAllConnections(ps, conn, null); + handleException("Error while adding notification", e); } return false; } private void addEndUser(Connection conn, String addEndUserQuery, String notificationId, - PortalNotificationEndUserDTO endUser) throws SQLException { + PortalNotificationEndUserDTO endUser) throws APIManagementException { - PreparedStatement ps = null; - try { - ps = conn.prepareStatement(addEndUserQuery); + try (PreparedStatement ps = conn.prepareStatement(addEndUserQuery)) { ps.setString(1, notificationId); ps.setString(2, endUser.getDestinationUser()); ps.setString(3, endUser.getOrganization()); ps.setString(4, endUser.getPortalToDisplay()); ps.executeUpdate(); } catch (SQLException e) { - log.error("Error while adding end users", e); - } finally { - if (ps != null) { - ps.close(); - } + handleException("Error while adding end users", e); } } @@ -181,7 +165,7 @@ public NotificationList getNotifications(String username, String organization, S } unreadCount = getUnreadNotificationCount(username, organization, portalToDisplay, conn); } catch (SQLException e) { - APIUtil.handleException("Failed to retrieve notifications of the user " + username, e); + handleException("Failed to retrieve notifications of the user " + username, e); } pagination.setLimit(limit); pagination.setOffset(offset); @@ -265,41 +249,36 @@ private String getCommentFromMetaData(String notificationMetadata, String notifi return finalComment; } - public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) { + public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) + throws APIManagementException { - Connection conn = null; - PreparedStatement ps = null; - try { - String sqlQuery = SQLConstants.PortalNotifications.DELETE_ALL_NOTIFICATIONS_OF_USER; - conn = APIMgtDBUtil.getConnection(); - ps = conn.prepareStatement(sqlQuery); + String sqlQuery = SQLConstants.PortalNotifications.DELETE_ALL_NOTIFICATIONS_OF_USER; + try (Connection conn = APIMgtDBUtil.getConnection(); + PreparedStatement ps = conn.prepareStatement(sqlQuery)) { ps.setString(1, username); ps.setString(2, organization); ps.setString(3, portalToDisplay); int rowsAffected = ps.executeUpdate(); if (rowsAffected > 0) { String deleteNotification = SQLConstants.PortalNotifications.DELETE_NOTIFICATIONS; - ps = conn.prepareStatement(deleteNotification); - ps.executeUpdate(); + try (PreparedStatement preparedStatement = conn.prepareStatement(deleteNotification)) { + preparedStatement.executeUpdate(); + } return true; } } catch (SQLException e) { - log.error("Failed to delete notifications", e); - } finally { - APIMgtDBUtil.closeAllConnections(ps, conn, null); + handleException("Failed to delete notifications", e); } return false; } - public Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) { + public Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) + throws APIManagementException { - Connection conn = null; - PreparedStatement ps = null; Notification notification; - try { - String sqlQuery = SQLConstants.PortalNotifications.MARK_NOTIFICATION_AS_READ; - conn = APIMgtDBUtil.getConnection(); - ps = conn.prepareStatement(sqlQuery); + String sqlQuery = SQLConstants.PortalNotifications.MARK_NOTIFICATION_AS_READ; + try (Connection conn = APIMgtDBUtil.getConnection(); + PreparedStatement ps = conn.prepareStatement(sqlQuery)) { ps.setString(1, notificationId); ps.setString(2, username); ps.setString(3, organization); @@ -312,55 +291,45 @@ public Notification markNotificationAsReadById(String username, String organizat } } } catch (SQLException e) { - log.error("Failed to mark notification as read", e); - } finally { - APIMgtDBUtil.closeAllConnections(ps, conn, null); + handleException("Failed to mark notification as read", e); } return null; } private Notification getNotificationById(String notificationId, String username, String organization, String portalToDisplay, - Connection conn) throws SQLException { - - PreparedStatement ps = null; - ResultSet rs = null; - try { - String sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATION_BY_ID; + Connection conn) throws APIManagementException { - ps = conn.prepareStatement(sqlQuery); + String sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATION_BY_ID; + try (PreparedStatement ps = conn.prepareStatement(sqlQuery)) { ps.setString(1, notificationId); ps.setString(2, username); ps.setString(3, organization); ps.setString(4, portalToDisplay); - rs = ps.executeQuery(); - if (rs.next()) { - Notification notification = new Notification(); - notification.setNotificationId(rs.getString("NOTIFICATION_ID")); - notification.setNotificationType(rs.getString("NOTIFICATION_TYPE")); - notification.setCreatedTime(rs.getTimestamp("CREATED_TIME").toString()); - notification.setComments(getCommentFromMetaData(rs.getString("NOTIFICATION_METADATA"), - rs.getString("NOTIFICATION_TYPE"))); - notification.setIsRead(rs.getBoolean("IS_READ")); - return notification; + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + Notification notification = new Notification(); + notification.setNotificationId(rs.getString("NOTIFICATION_ID")); + notification.setNotificationType(rs.getString("NOTIFICATION_TYPE")); + notification.setCreatedTime(rs.getTimestamp("CREATED_TIME").toString()); + notification.setComments(getCommentFromMetaData(rs.getString("NOTIFICATION_METADATA"), + rs.getString("NOTIFICATION_TYPE"))); + notification.setIsRead(rs.getBoolean("IS_READ")); + return notification; + } } + } catch (SQLException e) { - log.error("Failed to retrieve notification by id", e); - } finally { - if (ps != null) { - ps.close(); - } + handleException("Failed to retrieve notification by id", e); } return null; } - public boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) { + public boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) + throws APIManagementException { - Connection conn = null; - PreparedStatement ps = null; - try { - String sqlQuery = SQLConstants.PortalNotifications.DELETE_NOTIFICATION_BY_ID; - conn = APIMgtDBUtil.getConnection(); - ps = conn.prepareStatement(sqlQuery); + String sqlQuery = SQLConstants.PortalNotifications.DELETE_NOTIFICATION_BY_ID; + try (Connection conn = APIMgtDBUtil.getConnection(); + PreparedStatement ps = conn.prepareStatement(sqlQuery)){ ps.setString(1, notificationId); ps.setString(2, username); ps.setString(3, organization); @@ -368,45 +337,39 @@ public boolean deleteNotificationById(String username, String organization, Stri int rowsAffected = ps.executeUpdate(); if (rowsAffected > 0) { String deleteNotification = SQLConstants.PortalNotifications.DELETE_NOTIFICATIONS; - ps = conn.prepareStatement(deleteNotification); - ps.executeUpdate(); + try (PreparedStatement preparedStatement = conn.prepareStatement(deleteNotification)) { + preparedStatement.executeUpdate(); + } return true; } } catch (SQLException e) { - log.error("Failed to delete notification by id", e); - } finally { - APIMgtDBUtil.closeAllConnections(ps, conn, null); + handleException("Failed to delete notification by id", e); } return false; } - public NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) { + public NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) + throws APIManagementException { - Connection conn = null; - PreparedStatement ps = null; - ResultSet rs = null; - try { - String sqlQuery = SQLConstants.PortalNotifications.MARK_ALL_NOTIFICATIONS_AS_READ; - conn = APIMgtDBUtil.getConnection(); - ps = conn.prepareStatement(sqlQuery); + String sqlQuery = SQLConstants.PortalNotifications.MARK_ALL_NOTIFICATIONS_AS_READ; + + try (Connection connection = APIMgtDBUtil.getConnection(); + PreparedStatement ps = connection.prepareStatement(sqlQuery)) { ps.setString(1, username); ps.setString(2, organization); ps.setString(3, portalToDisplay); int rowsAffected = ps.executeUpdate(); if (rowsAffected > 0) { - return getNotifications(username, organization, portalToDisplay,null, null, null); + return getNotifications(username, organization, portalToDisplay,"desc", 10, 0); } } catch (SQLException e) { - log.error("Failed to mark all notifications as read", e); - } catch (APIManagementException e) { - throw new RuntimeException(e); - } finally { - APIMgtDBUtil.closeAllConnections(ps, conn, rs); + handleException("Failed to mark all notifications as read", e); } return null; } - public String getAPIUUIDUsingNameContextVersion(String apiName, String apiContext, String apiVersion, String organization) { + public String getAPIUUIDUsingNameContextVersion(String apiName, String apiContext, String apiVersion, String organization) + throws APIManagementException { String apiUUID = null; String sqlQuery = SQLConstants.PortalNotifications.GET_API_UUID_USING_NAME_CONTEXT_VERSION; @@ -422,7 +385,7 @@ public String getAPIUUIDUsingNameContextVersion(String apiName, String apiContex } } } catch (SQLException e) { - log.error("Failed to retrieve API UUID using name, context and version", e); + handleException("Failed to retrieve API UUID using name, context and version", e); } return apiUUID; @@ -444,9 +407,14 @@ public int getUnreadNotificationCount(String username, String organization, Stri } } } catch (SQLException e) { - APIUtil.handleException("Failed to get unread notification count for user " + username, e); + handleException("Failed to get unread notification count for user " + username, e); } return unreadCount; } + + private void handleException(String message, Throwable t) throws APIManagementException { + log.error(message, t); + throw new APIManagementException(message, t); + } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java index e34c65c3ff8e..39b853f348ba 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java @@ -18,8 +18,10 @@ package org.wso2.carbon.apimgt.impl.portalNotifications; +import org.wso2.carbon.apimgt.api.APIManagementException; + public interface PortalNotificationService { - void sendPortalNotifications(T notificationObject, String tenantDomain); + void sendPortalNotifications(T notificationObject, String tenantDomain) throws APIManagementException; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java index 57145e19bb5f..17597ac61c61 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java @@ -45,7 +45,8 @@ import org.wso2.carbon.user.core.service.RealmService; public class WorkflowNotificationServiceImpl implements PortalNotificationService { - public void sendPortalNotifications(WorkflowDTO workflowDTO, String tenantDomainOfUser) { + public void sendPortalNotifications(WorkflowDTO workflowDTO, String tenantDomainOfUser) + throws APIManagementException { PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); portalNotificationsDTO.setNotificationType(getNotificationType(workflowDTO.getWorkflowType())); portalNotificationsDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/java/org/wso2/carbon/apimgt/rest/api/common/RestApiConstants.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/java/org/wso2/carbon/apimgt/rest/api/common/RestApiConstants.java index 2de0f6b2a50b..289ccf501636 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/java/org/wso2/carbon/apimgt/rest/api/common/RestApiConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/java/org/wso2/carbon/apimgt/rest/api/common/RestApiConstants.java @@ -62,6 +62,7 @@ public final class RestApiConstants { public static final String DEFAULT_RESPONSE_CONTENT_TYPE = APPLICATION_JSON; public static final String RESOURCE = "resource"; + public static final String RESOURCE_NOTIFICATION = "Notification"; public static final String RESOURCE_API = "API"; public static final String RESOURCE_API_PRODUCT = "API Product"; public static final String RESOURCE_PRODUCT_DOCUMENTATION = "product documentation"; diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java index 5f8c1b1ccc6e..4a9e8b3da6bb 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java @@ -56,11 +56,16 @@ public Response getNotifications(String sortOrder, Integer limit, Integer offset APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); notificationList = apiProvider.getNotifications(username, organization, portalToDisplay, sortOrder, limit, offset); + return Response.ok().entity(notificationList).build(); } catch (APIManagementException e) { - throw new APIManagementException("Error while getting notifications", e); + if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { + RestApiUtil.handleResourceNotFoundError("No any notification found", e, log); + } else { + String errorMessage = "Error while getting notifications"; + RestApiUtil.handleInternalServerError(errorMessage, e, log); + } } - - return Response.ok().entity(notificationList).build(); + return null; } @Override @@ -76,11 +81,16 @@ public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patch if (notificationList == null) { return Response.status(Response.Status.NOT_FOUND).build(); } + return Response.ok().entity(notificationList).build(); } catch (APIManagementException e) { - throw new APIManagementException("Error while getting notifications", e); + if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { + RestApiUtil.handleResourceNotFoundError("No any notification found", e, log); + } else { + String errorMessage = "Error while marking notifications as read"; + RestApiUtil.handleInternalServerError(errorMessage, e, log); + } } - - return Response.ok().entity(notificationList).build(); + return null; } @Override @@ -98,11 +108,16 @@ public Response markNotificationAsReadById(String notificationId, if (notification == null) { return Response.status(Response.Status.NOT_FOUND).build(); } + return Response.ok().entity(notification).build(); } catch (APIManagementException e) { - throw new APIManagementException("Error while getting notification", e); + if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { + RestApiUtil.handleResourceNotFoundError("No any notification found", e, log); + } else { + String errorMessage = "Error while marking the notification " + notificationId + " as read"; + RestApiUtil.handleInternalServerError(errorMessage, e, log); + } } - - return Response.ok().entity(notification).build(); + return null; } @Override @@ -118,7 +133,12 @@ public Response deleteNotifications(MessageContext messageContext) throws APIMan return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { - throw new APIManagementException("Error while deleting notifications", e); + if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { + RestApiUtil.handleResourceNotFoundError("No any notification found", e, log); + } else { + String errorMessage = "Error while deleting notifications"; + RestApiUtil.handleInternalServerError(errorMessage, e, log); + } } return Response.ok().build(); } @@ -137,7 +157,12 @@ public Response deleteNotification(String notificationId, MessageContext message return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { - throw new APIManagementException("Error while deleting notifications", e); + if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { + RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_NOTIFICATION, notificationId, e, log); + } else { + String errorMessage = "Error while deleting the notification"; + RestApiUtil.handleInternalServerError(errorMessage, e, log); + } } return Response.ok().build(); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java index e7f4e57d37ea..1e843f5d44b7 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java @@ -18,6 +18,8 @@ package org.wso2.carbon.apimgt.rest.api.store.v1.impl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.api.APIConsumer; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.model.Notification; @@ -36,6 +38,8 @@ public class NotificationsApiServiceImpl implements NotificationsApiService { + private static final Log log = LogFactory.getLog(NotificationsApiServiceImpl.class); + public Response deleteNotification(String notificationId, MessageContext messageContext) throws APIManagementException { @@ -50,7 +54,12 @@ public Response deleteNotification(String notificationId, MessageContext message return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { - throw new APIManagementException("Error while deleting notifications", e); + if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { + RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_NOTIFICATION, notificationId, e, log); + } else { + String errorMessage = "Error while deleting the notification"; + RestApiUtil.handleInternalServerError(errorMessage, e, log); + } } return Response.ok().build(); } @@ -67,7 +76,12 @@ public Response deleteNotifications(MessageContext messageContext) throws APIMan return Response.status(Response.Status.NOT_FOUND).build(); } } catch (APIManagementException e) { - throw new APIManagementException("Error while deleting notifications", e); + if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { + RestApiUtil.handleResourceNotFoundError("No any notification found", e, log); + } else { + String errorMessage = "Error while deleting notifications"; + RestApiUtil.handleInternalServerError(errorMessage, e, log); + } } return Response.ok().build(); } @@ -87,11 +101,16 @@ public Response getNotifications(String sortOrder, Integer limit, Integer offset APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer(); notificationList = apiConsumer.getNotifications(username, organization, portalToDisplay, sortOrder, limit, offset); + return Response.ok().entity(notificationList).build(); } catch (APIManagementException e) { - throw new APIManagementException("Error while getting notifications", e); + if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { + RestApiUtil.handleResourceNotFoundError("No any notification found", e, log); + } else { + String errorMessage = "Error while getting notifications"; + RestApiUtil.handleInternalServerError(errorMessage, e, log); + } } - - return Response.ok().entity(notificationList).build(); + return null; } public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, @@ -108,11 +127,16 @@ public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patch if (notificationList == null) { return Response.status(Response.Status.NOT_FOUND).build(); } + return Response.ok().entity(notificationList).build(); } catch (APIManagementException e) { - throw new APIManagementException("Error while getting notifications", e); + if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { + RestApiUtil.handleResourceNotFoundError("No any notification found", e, log); + } else { + String errorMessage = "Error while marking notifications as read"; + RestApiUtil.handleInternalServerError(errorMessage, e, log); + } } - - return Response.ok().entity(notificationList).build(); + return null; } public Response markNotificationAsReadById(String notificationId, @@ -131,10 +155,15 @@ public Response markNotificationAsReadById(String notificationId, if (notification == null) { return Response.status(Response.Status.NOT_FOUND).build(); } + return Response.ok().entity(notification).build(); } catch (APIManagementException e) { - throw new APIManagementException("Error while getting notification", e); + if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) { + RestApiUtil.handleResourceNotFoundError("No any notification found", e, log); + } else { + String errorMessage = "Error while marking the notification " + notificationId + " as read"; + RestApiUtil.handleInternalServerError(errorMessage, e, log); + } } - - return Response.ok().entity(notification).build(); + return null; } } From 71951bed1b8b8364b000e245aa3c3ab0114e5e12 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Sun, 28 Apr 2024 20:24:06 +0530 Subject: [PATCH 12/23] Replace reusable string values with constant values --- .../wso2/carbon/apimgt/impl/APIConstants.java | 19 ++++++++ .../PortalNotificationDAO.java | 39 +++++++++-------- .../WorkflowNotificationServiceImpl.java | 43 +++++++++++-------- .../rest/api/common/RestApiConstants.java | 3 ++ .../v1/impl/NotificationsApiServiceImpl.java | 7 +-- .../v1/impl/NotificationsApiServiceImpl.java | 13 +----- 6 files changed, 69 insertions(+), 55 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java index c915fa3aa805..781ab2f646ea 100755 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java @@ -3153,4 +3153,23 @@ public static class APILogHandler { //Property for enabling tenant aware sub claims when invoking APIs with API key public static final String ENABLE_TENANT_AWARE_SUB_CLAIM= "enable.tenant.aware.subclaim"; + + public static class PortalNotifications { + public static final String ACTION = "action"; + public static final String API_NAME = "apiName"; + public static final String API_VERSION = "apiVersion"; + public static final String API_CONTEXT = "apiContext"; + public static final String APPLICATION_NAME = "applicationName"; + public static final String REQUESTED_TIER = "requestedTier"; + public static final String REVISION_ID = "revisionId"; + public static final String COMMENT = "comment"; + public static final String STATUS_APPROVED = "approved"; + public static final String STATUS_REJECTED = "rejected"; + public static final String PUBLISHER_PORTAL = "publisher"; + public static final String DEV_PORTAL = "devportal"; + public static final String DEFAULT_CLAIM = "http://wso2.org/claims/organization"; + public static final String API_BLOCK = "Block"; + public static final String API_DEPRECATE = "Deprecate"; + public static final String API_RETIRE = "Retire"; + } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java index 2569eb57f5a4..f87bc72b995d 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -27,6 +27,7 @@ import org.wso2.carbon.apimgt.api.model.Pagination; import org.wso2.carbon.apimgt.api.model.Notification; import org.wso2.carbon.apimgt.api.model.NotificationList; +import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; @@ -99,14 +100,14 @@ private void addEndUser(Connection conn, String addEndUserQuery, String notifica private String convertMetadataToJson(PortalNotificationMetaData metaData) { JSONObject json = new JSONObject(); - json.put("apiName", metaData.getApi()); - json.put("apiVersion", metaData.getApiVersion()); - json.put("apiContext", metaData.getApiContext()); - json.put("action", metaData.getAction()); - json.put("applicationName", metaData.getApplicationName()); - json.put("requestedTier", metaData.getRequestedTier()); - json.put("revisionId", metaData.getRevisionId()); - json.put("comment", metaData.getComment()); + json.put(APIConstants.PortalNotifications.API_NAME, metaData.getApi()); + json.put(APIConstants.PortalNotifications.API_VERSION, metaData.getApiVersion()); + json.put(APIConstants.PortalNotifications.API_CONTEXT, metaData.getApiContext()); + json.put(APIConstants.PortalNotifications.ACTION, metaData.getAction()); + json.put(APIConstants.PortalNotifications.APPLICATION_NAME, metaData.getApplicationName()); + json.put(APIConstants.PortalNotifications.REQUESTED_TIER, metaData.getRequestedTier()); + json.put(APIConstants.PortalNotifications.REVISION_ID, metaData.getRevisionId()); + json.put(APIConstants.PortalNotifications.COMMENT, metaData.getComment()); return json.toJSONString(); } @@ -183,20 +184,20 @@ private String getCommentFromMetaData(String notificationMetadata, String notifi JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(notificationMetadata); - String comment = (String) json.get("comment"); - String apiName = (String) json.get("apiName"); - String apiVersion = (String) json.get("apiVersion"); - String apiContext = (String) json.get("apiContext"); - String action = (String) json.get("action"); - String revisionId = (String) json.get("revisionId"); - String applicationName = (String) json.get("applicationName"); - String requestedTier = (String) json.get("requestedTier"); + String comment = (String) json.get(APIConstants.PortalNotifications.COMMENT); + String apiName = (String) json.get(APIConstants.PortalNotifications.API_NAME); + String apiVersion = (String) json.get(APIConstants.PortalNotifications.API_VERSION); + String apiContext = (String) json.get(APIConstants.PortalNotifications.API_CONTEXT); + String action = (String) json.get(APIConstants.PortalNotifications.ACTION); + String revisionId = (String) json.get(APIConstants.PortalNotifications.REVISION_ID); + String applicationName = (String) json.get(APIConstants.PortalNotifications.APPLICATION_NAME); + String requestedTier = (String) json.get(APIConstants.PortalNotifications.REQUESTED_TIER); String status; - if (comment.equals("APPROVED")) { - status = "approved"; + if ("APPROVED".equals(comment)) { + status = APIConstants.PortalNotifications.STATUS_APPROVED; } else { - status = "rejected"; + status = APIConstants.PortalNotifications.STATUS_REJECTED; } switch (notificationType) { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java index 17597ac61c61..21215669d44f 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java @@ -85,7 +85,8 @@ private PortalNotificationType getNotificationType(String workflowType) { } private List getDestinationUser( - org.wso2.carbon.apimgt.impl.dto.WorkflowDTO workflowDTO, String tenantDomainOfUser) { + org.wso2.carbon.apimgt.impl.dto.WorkflowDTO workflowDTO, String tenantDomainOfUser) + throws APIManagementException { List destinationUserList = new ArrayList<>(); String destinationUser = null; @@ -124,8 +125,10 @@ private List getDestinationUser( if (workflowDTO.getWorkflowType() .equals(WorkflowConstants.WF_TYPE_AM_API_STATE) || workflowDTO.getWorkflowType() .equals(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)) { - if (workflowDTO.getMetadata("Action").equals("Block") || workflowDTO.getMetadata("Action") - .equals("Deprecate") || workflowDTO.getMetadata("Action").equals("Retire")) { + if (workflowDTO.getMetadata("Action") + .equals(APIConstants.PortalNotifications.API_BLOCK) || workflowDTO.getMetadata("Action") + .equals(APIConstants.PortalNotifications.API_DEPRECATE) || workflowDTO.getMetadata("Action") + .equals(APIConstants.PortalNotifications.API_RETIRE)) { String apiUUID = null; String apiName = workflowDTO.getProperties("apiName"); String apiContext = workflowDTO.getMetadata("ApiContext"); @@ -142,11 +145,11 @@ private List getDestinationUser( PortalNotificationEndUserDTO endUser = new PortalNotificationEndUserDTO(); endUser.setDestinationUser(subscriber.getSubscriber().getName()); endUser.setOrganization(subscriber.getOrganization()); - endUser.setPortalToDisplay("developer"); + endUser.setPortalToDisplay(APIConstants.PortalNotifications.DEV_PORTAL); destinationUserList.add(endUser); } } catch (APIManagementException e) { - System.out.println("Error while getting subscribers of API - getDestinationUser()"); + APIUtil.handleException("Error while getting subscribers of API - getDestinationUser()", e); } } } @@ -161,13 +164,13 @@ private List getDestinationUser( } endUser.setDestinationUser(user.getUsername()); endUser.setOrganization(user.getTenantDomain()); - endUser.setPortalToDisplay("developer"); + endUser.setPortalToDisplay(APIConstants.PortalNotifications.DEV_PORTAL); destinationUserList.add(endUser); } } catch (APIManagementException e) { - System.out.println("Error while getting users belong to group - getDestinationUser()"); + APIUtil.handleException("Error while getting users belong to group - getDestinationUser()", e); } catch (UserStoreException e) { - throw new RuntimeException(e); + APIUtil.handleException("User-Store Exception ", e); } } @@ -178,12 +181,16 @@ private PortalNotificationMetaData getNotificationMetaData( org.wso2.carbon.apimgt.impl.dto.WorkflowDTO workflowDTO) { PortalNotificationMetaData portalNotificationMetaData = new PortalNotificationMetaData(); - portalNotificationMetaData.setApi(workflowDTO.getProperties("apiName")); - portalNotificationMetaData.setApiVersion(workflowDTO.getProperties("apiVersion")); - portalNotificationMetaData.setAction(workflowDTO.getProperties("action")); - portalNotificationMetaData.setApplicationName(workflowDTO.getProperties("applicationName")); - portalNotificationMetaData.setRequestedTier(workflowDTO.getProperties("requestedTier")); - portalNotificationMetaData.setRevisionId(workflowDTO.getProperties("revisionId")); + portalNotificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); + portalNotificationMetaData.setApiVersion( + workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + portalNotificationMetaData.setAction(workflowDTO.getProperties(APIConstants.PortalNotifications.ACTION)); + portalNotificationMetaData.setApplicationName( + workflowDTO.getProperties(APIConstants.PortalNotifications.APPLICATION_NAME)); + portalNotificationMetaData.setRequestedTier( + workflowDTO.getProperties(APIConstants.PortalNotifications.REQUESTED_TIER)); + portalNotificationMetaData.setRevisionId( + workflowDTO.getProperties(APIConstants.PortalNotifications.REVISION_ID)); portalNotificationMetaData.setComment(workflowDTO.getComments()); if (WorkflowConstants.WF_TYPE_AM_API_STATE.equals( @@ -200,9 +207,9 @@ private String setPortalToDisplay(String workflowType) { case WorkflowConstants.WF_TYPE_AM_API_STATE: case WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE: case WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT: - return "publisher"; + return APIConstants.PortalNotifications.PUBLISHER_PORTAL; default: - return "developer"; + return APIConstants.PortalNotifications.DEV_PORTAL; } } @@ -240,7 +247,7 @@ private List getAPIUsageByAPIId(String uuid, String organization, } } } catch (APIManagementException e) { - System.out.println("Error while getting API usage by API ID - getAPIUsageByAPIId()"); + APIUtil.handleException("Error while getting API usage by API ID - getAPIUsageByAPIId()", e); } return subscribedAPIs; @@ -281,7 +288,7 @@ private List getAllUsersBelongToGroup(WorkflowDTO workflowDTO, String tena .getAPIManagerConfigurationService().getAPIManagerConfiguration(); String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI); if (StringUtils.isBlank(claim)) { - claim = "http://wso2.org/claims/organization"; + claim = APIConstants.PortalNotifications.DEFAULT_CLAIM; } users = abstractManager.getUserListWithID(claim, groupId, "default"); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/java/org/wso2/carbon/apimgt/rest/api/common/RestApiConstants.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/java/org/wso2/carbon/apimgt/rest/api/common/RestApiConstants.java index 289ccf501636..e69027731e40 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/java/org/wso2/carbon/apimgt/rest/api/common/RestApiConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/java/org/wso2/carbon/apimgt/rest/api/common/RestApiConstants.java @@ -351,4 +351,7 @@ public final class RestApiConstants { public static final String RESOURCE_PATH_GATEWAY_POLICIES = "gateway-policies"; public static final String AUTH_TOKEN_INFO = "AUTH_TOKEN_INFO"; + + public static final String PUBLISHER_PORTAL = "publisher"; + public static final String DEV_PORTAL = "devportal"; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java index 4a9e8b3da6bb..271efcf57ad4 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java @@ -39,6 +39,7 @@ public class NotificationsApiServiceImpl implements NotificationsApiService { private static final Log log = LogFactory.getLog(NotificationsApiServiceImpl.class); + private final String portalToDisplay = RestApiConstants.PUBLISHER_PORTAL; @Override public Response getNotifications(String sortOrder, Integer limit, Integer offset, MessageContext messageContext) @@ -48,8 +49,6 @@ public Response getNotifications(String sortOrder, Integer limit, Integer offset offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; sortOrder = sortOrder != null ? sortOrder : RestApiConstants.DESCENDING_SORT_ORDER; NotificationList notificationList; - String portalToDisplay = "publisher"; - String username = RestApiCommonUtil.getLoggedInUsername(); try { String organization = RestApiUtil.getValidatedOrganization(messageContext); @@ -73,7 +72,6 @@ public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patch MessageContext messageContext) throws APIManagementException { NotificationList notificationList; String username = RestApiCommonUtil.getLoggedInUsername(); - String portalToDisplay = "publisher"; try { String organization = RestApiUtil.getValidatedOrganization(messageContext); APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); @@ -99,7 +97,6 @@ public Response markNotificationAsReadById(String notificationId, throws APIManagementException { Notification notification; String username = RestApiCommonUtil.getLoggedInUsername(); - String portalToDisplay = "publisher"; try { String organization = RestApiUtil.getValidatedOrganization(messageContext); APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); @@ -124,7 +121,6 @@ public Response markNotificationAsReadById(String notificationId, public Response deleteNotifications(MessageContext messageContext) throws APIManagementException { String username = RestApiCommonUtil.getLoggedInUsername(); - String portalToDisplay = "publisher"; try { String organization = RestApiUtil.getValidatedOrganization(messageContext); APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); @@ -147,7 +143,6 @@ public Response deleteNotifications(MessageContext messageContext) throws APIMan public Response deleteNotification(String notificationId, MessageContext messageContext) throws APIManagementException { String username = RestApiCommonUtil.getLoggedInUsername(); - String portalToDisplay = "publisher"; try { String organization = RestApiUtil.getValidatedOrganization(messageContext); APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider(); diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java index 1e843f5d44b7..42e13083ca1c 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java @@ -39,11 +39,10 @@ public class NotificationsApiServiceImpl implements NotificationsApiService { private static final Log log = LogFactory.getLog(NotificationsApiServiceImpl.class); + private final String portalToDisplay = RestApiConstants.DEV_PORTAL; public Response deleteNotification(String notificationId, MessageContext messageContext) throws APIManagementException { - - String portalToDisplay = "developer"; try { String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); @@ -65,8 +64,6 @@ public Response deleteNotification(String notificationId, MessageContext message } public Response deleteNotifications(MessageContext messageContext) throws APIManagementException { - - String portalToDisplay = "developer"; try { String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); @@ -93,8 +90,6 @@ public Response getNotifications(String sortOrder, Integer limit, Integer offset offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT; sortOrder = sortOrder != null ? sortOrder : RestApiConstants.DESCENDING_SORT_ORDER; NotificationList notificationList; - String portalToDisplay = "developer"; - try { String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); @@ -115,10 +110,7 @@ public Response getNotifications(String sortOrder, Integer limit, Integer offset public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, MessageContext messageContext) throws APIManagementException { - NotificationList notificationList; - String portalToDisplay = "developer"; - try { String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); @@ -142,10 +134,7 @@ public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patch public Response markNotificationAsReadById(String notificationId, PatchNotificationRequestDTO patchNotificationRequestDTO, MessageContext messageContext) throws APIManagementException { - Notification notification; - String portalToDisplay = "developer"; - try { String username = RestApiCommonUtil.getLoggedInUsername(); String organization = RestApiUtil.getValidatedOrganization(messageContext); From 8586d1927640728049adb5f52bfcbccc32fd650a Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Mon, 29 Apr 2024 09:22:27 +0530 Subject: [PATCH 13/23] Change deleteNotification method name to deleteNotificationById --- .../WorkflowNotificationServiceImpl.java | 16 ++++++++++------ .../src/main/resources/devportal-api.yaml | 2 +- .../src/main/resources/publisher-api.yaml | 2 +- .../rest/api/publisher/v1/NotificationsApi.java | 4 ++-- .../publisher/v1/NotificationsApiService.java | 2 +- .../v1/impl/NotificationsApiServiceImpl.java | 2 +- .../src/main/resources/publisher-api.yaml | 2 +- .../rest/api/store/v1/NotificationsApi.java | 4 ++-- .../api/store/v1/NotificationsApiService.java | 2 +- .../v1/impl/NotificationsApiServiceImpl.java | 2 +- .../src/main/resources/devportal-api.yaml | 2 +- 11 files changed, 22 insertions(+), 18 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java index 21215669d44f..6f86413171ce 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java @@ -19,6 +19,8 @@ package org.wso2.carbon.apimgt.impl.portalNotifications; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage; import org.wso2.carbon.apimgt.api.model.APIIdentifier; @@ -33,6 +35,7 @@ import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.UserRealm; +import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import java.util.ArrayList; @@ -45,6 +48,9 @@ import org.wso2.carbon.user.core.service.RealmService; public class WorkflowNotificationServiceImpl implements PortalNotificationService { + + private static final Log log = LogFactory.getLog(WorkflowNotificationServiceImpl.class); + public void sendPortalNotifications(WorkflowDTO workflowDTO, String tenantDomainOfUser) throws APIManagementException { PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); @@ -56,7 +62,7 @@ public void sendPortalNotifications(WorkflowDTO workflowDTO, String tenantDomain boolean result = PortalNotificationDAO.getInstance().addNotification(portalNotificationsDTO); if (!result) { - System.out.println("Error while adding publisher developer notification - sedPubDevNotification()"); + log.error("Error while adding publisher developer notification - sendPortalNotifications()"); } } @@ -84,8 +90,7 @@ private PortalNotificationType getNotificationType(String workflowType) { return null; } - private List getDestinationUser( - org.wso2.carbon.apimgt.impl.dto.WorkflowDTO workflowDTO, String tenantDomainOfUser) + private List getDestinationUser(WorkflowDTO workflowDTO, String tenantDomainOfUser) throws APIManagementException { List destinationUserList = new ArrayList<>(); String destinationUser = null; @@ -177,8 +182,7 @@ private List getDestinationUser( return destinationUserList; } - private PortalNotificationMetaData getNotificationMetaData( - org.wso2.carbon.apimgt.impl.dto.WorkflowDTO workflowDTO) { + private PortalNotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { PortalNotificationMetaData portalNotificationMetaData = new PortalNotificationMetaData(); portalNotificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); @@ -282,7 +286,7 @@ private List getAllUsersBelongToGroup(WorkflowDTO workflowDTO, String tena RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService(); UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId); if (realm != null) { - org.wso2.carbon.user.core.UserStoreManager manager = realm.getUserStoreManager(); + UserStoreManager manager = realm.getUserStoreManager(); AbstractUserStoreManager abstractManager = (AbstractUserStoreManager) manager; APIManagerConfiguration config = ServiceReferenceHolder.getInstance() .getAPIManagerConfigurationService().getAPIManagerConfiguration(); diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml index 0283d551dfde..28fdc448aafc 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml @@ -3999,7 +3999,7 @@ paths: - lang: Curl source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" "https://localhost:9443/api/am/devportal/v3/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' - operationId: deleteNotification + operationId: deleteNotificationById components: diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml index 0d6bb055834c..0a6860e36a23 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/publisher-api.yaml @@ -8902,7 +8902,7 @@ paths: - lang: Curl source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" "https://localhost:9443/api/am/publisher/v4/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' - operationId: deleteNotification + operationId: deleteNotificationById components: diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java index 87f6f1b2e7cf..2274ae50a558 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApi.java @@ -55,8 +55,8 @@ public class NotificationsApi { @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified.", response = ErrorDTO.class), @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) - public Response deleteNotification(@ApiParam(value = "**NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION ",required=true) @PathParam("notificationId") String notificationId) throws APIManagementException{ - return delegate.deleteNotification(notificationId, securityContext); + public Response deleteNotificationById(@ApiParam(value = "**NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION ",required=true) @PathParam("notificationId") String notificationId) throws APIManagementException{ + return delegate.deleteNotificationById(notificationId, securityContext); } @DELETE diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApiService.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApiService.java index d994d62e02a1..6edc2dc725f3 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApiService.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/NotificationsApiService.java @@ -24,7 +24,7 @@ public interface NotificationsApiService { - public Response deleteNotification(String notificationId, MessageContext messageContext) throws APIManagementException; + public Response deleteNotificationById(String notificationId, MessageContext messageContext) throws APIManagementException; public Response deleteNotifications(MessageContext messageContext) throws APIManagementException; public Response getNotifications(String sortOrder, Integer limit, Integer offset, MessageContext messageContext) throws APIManagementException; public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, MessageContext messageContext) throws APIManagementException; diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java index 271efcf57ad4..a989ce1c90b1 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java @@ -140,7 +140,7 @@ public Response deleteNotifications(MessageContext messageContext) throws APIMan } @Override - public Response deleteNotification(String notificationId, MessageContext messageContext) + public Response deleteNotificationById(String notificationId, MessageContext messageContext) throws APIManagementException { String username = RestApiCommonUtil.getLoggedInUsername(); try { diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml index 0d6bb055834c..0a6860e36a23 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/resources/publisher-api.yaml @@ -8902,7 +8902,7 @@ paths: - lang: Curl source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" "https://localhost:9443/api/am/publisher/v4/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' - operationId: deleteNotification + operationId: deleteNotificationById components: diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java index f386496c9e80..b86287138eef 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApi.java @@ -55,8 +55,8 @@ public class NotificationsApi { @ApiResponse(code = 403, message = "Forbidden. The request must be conditional but no condition has been specified.", response = ErrorDTO.class), @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class), @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) }) - public Response deleteNotification(@ApiParam(value = "**NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION ",required=true) @PathParam("notificationId") String notificationId) throws APIManagementException{ - return delegate.deleteNotification(notificationId, securityContext); + public Response deleteNotificationById(@ApiParam(value = "**NOTIFICATION ID** consisting of the **UUID** of the NOTIFICATION ",required=true) @PathParam("notificationId") String notificationId) throws APIManagementException{ + return delegate.deleteNotificationById(notificationId, securityContext); } @DELETE diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApiService.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApiService.java index 75bbe66b8ce9..3a2edd8cbe19 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApiService.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/NotificationsApiService.java @@ -24,7 +24,7 @@ public interface NotificationsApiService { - public Response deleteNotification(String notificationId, MessageContext messageContext) throws APIManagementException; + public Response deleteNotificationById(String notificationId, MessageContext messageContext) throws APIManagementException; public Response deleteNotifications(MessageContext messageContext) throws APIManagementException; public Response getNotifications(String sortOrder, Integer limit, Integer offset, MessageContext messageContext) throws APIManagementException; public Response markAllNotificationsAsRead(PatchAllNotificationsRequestDTO patchAllNotificationsRequestDTO, MessageContext messageContext) throws APIManagementException; diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java index 42e13083ca1c..94c873e4a1cd 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java @@ -41,7 +41,7 @@ public class NotificationsApiServiceImpl implements NotificationsApiService { private static final Log log = LogFactory.getLog(NotificationsApiServiceImpl.class); private final String portalToDisplay = RestApiConstants.DEV_PORTAL; - public Response deleteNotification(String notificationId, MessageContext messageContext) + public Response deleteNotificationById(String notificationId, MessageContext messageContext) throws APIManagementException { try { String username = RestApiCommonUtil.getLoggedInUsername(); diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml index 0283d551dfde..28fdc448aafc 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml @@ -3999,7 +3999,7 @@ paths: - lang: Curl source: 'curl -k -X DELETE -H "Authorization:Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" "https://localhost:9443/api/am/devportal/v3/notifications/863aef13-dab4-48b4-bf58-7363cd29601a"' - operationId: deleteNotification + operationId: deleteNotificationById components: From 977288ea3f9ae7a88936715ab38cd94bb2163d83 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Tue, 30 Apr 2024 15:23:10 +0530 Subject: [PATCH 14/23] Add unit tests --- .../PortalNotificationDAO.java | 76 ++--- .../dao/test/PortalNotificationDAOTest.java | 275 ++++++++++++++++++ .../WorkflowNotificationServiceImplTest.java | 80 +++++ ...icationCreationWSWorkflowExecutorTest.java | 20 +- ...ionRegistrationWSWorkflowExecutorTest.java | 11 +- ...riptionCreationWSWorkflowExecutorTest.java | 20 +- .../UserSignUpWSWorkflowExecutorTest.java | 16 +- .../resources/dbscripts/h2-sample-data.sql | 8 + 8 files changed, 444 insertions(+), 62 deletions(-) create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java index f87bc72b995d..f652f4bcf793 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -79,6 +79,8 @@ public boolean addNotification(PortalNotificationDTO portalNotificationDTO) thro } } catch (SQLException e) { + handleException("Error while adding notification - SQL", e); + } catch (APIManagementException e) { handleException("Error while adding notification", e); } return false; @@ -111,8 +113,8 @@ private String convertMetadataToJson(PortalNotificationMetaData metaData) { return json.toJSONString(); } - public NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, - Integer offset) throws APIManagementException { + public NotificationList getNotifications(String username, String organization, String portalToDisplay, + String sortOrder, Integer limit, Integer offset) throws APIManagementException { List list = new ArrayList(); NotificationList notificationList = new NotificationList(); @@ -202,8 +204,8 @@ private String getCommentFromMetaData(String notificationMetadata, String notifi switch (notificationType) { case "API_STATE_CHANGE": - finalComment = "API State Change request to " + action + " the API: " + apiName + ", version: " + apiVersion - + " that has the context: " + apiContext + " has been " + status + "."; + finalComment = "API State Change request to " + action + " the API: " + apiName + ", version: " + + apiVersion + " that has the context: " + apiContext + " has been " + status + "."; break; case "API_PRODUCT_STATE_CHANGE": finalComment = "API Product State Change request of the API PRODUCT: " + apiName + ", version: " @@ -223,8 +225,8 @@ private String getCommentFromMetaData(String notificationMetadata, String notifi break; case "SUBSCRIPTION_UPDATE": finalComment = "Subscription Update request for the " + requestedTier + " for the API: " + apiName - + " version: " + apiVersion + " using Application: " + applicationName + " has been " + status - + "."; + + " version: " + apiVersion + " using Application: " + applicationName + " has been " + + status + "."; break; case "SUBSCRIPTION_DELETION": finalComment = "Subscription Deletion request for the API: " + apiName + " version: " + apiVersion @@ -254,8 +256,7 @@ public boolean deleteAllNotifications(String username, String organization, Stri throws APIManagementException { String sqlQuery = SQLConstants.PortalNotifications.DELETE_ALL_NOTIFICATIONS_OF_USER; - try (Connection conn = APIMgtDBUtil.getConnection(); - PreparedStatement ps = conn.prepareStatement(sqlQuery)) { + try (Connection conn = APIMgtDBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sqlQuery)) { ps.setString(1, username); ps.setString(2, organization); ps.setString(3, portalToDisplay); @@ -273,13 +274,12 @@ public boolean deleteAllNotifications(String username, String organization, Stri return false; } - public Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) - throws APIManagementException { + public Notification markNotificationAsReadById(String username, String organization, String notificationId, + String portalToDisplay) throws APIManagementException { Notification notification; String sqlQuery = SQLConstants.PortalNotifications.MARK_NOTIFICATION_AS_READ; - try (Connection conn = APIMgtDBUtil.getConnection(); - PreparedStatement ps = conn.prepareStatement(sqlQuery)) { + try (Connection conn = APIMgtDBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sqlQuery)) { ps.setString(1, notificationId); ps.setString(2, username); ps.setString(3, organization); @@ -292,13 +292,15 @@ public Notification markNotificationAsReadById(String username, String organizat } } } catch (SQLException e) { + handleException("Failed to mark notification as read - SQL", e); + } catch (APIManagementException e) { handleException("Failed to mark notification as read", e); } return null; } - private Notification getNotificationById(String notificationId, String username, String organization, String portalToDisplay, - Connection conn) throws APIManagementException { + private Notification getNotificationById(String notificationId, String username, String organization, + String portalToDisplay, Connection conn) throws APIManagementException { String sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATION_BY_ID; try (PreparedStatement ps = conn.prepareStatement(sqlQuery)) { @@ -325,12 +327,11 @@ private Notification getNotificationById(String notificationId, String username, return null; } - public boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) - throws APIManagementException { + public boolean deleteNotificationById(String username, String organization, String notificationId, + String portalToDisplay) throws APIManagementException { String sqlQuery = SQLConstants.PortalNotifications.DELETE_NOTIFICATION_BY_ID; - try (Connection conn = APIMgtDBUtil.getConnection(); - PreparedStatement ps = conn.prepareStatement(sqlQuery)){ + try (Connection conn = APIMgtDBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sqlQuery)) { ps.setString(1, notificationId); ps.setString(2, username); ps.setString(3, organization); @@ -361,35 +362,36 @@ public NotificationList markAllNotificationsAsRead(String username, String organ ps.setString(3, portalToDisplay); int rowsAffected = ps.executeUpdate(); if (rowsAffected > 0) { - return getNotifications(username, organization, portalToDisplay,"desc", 10, 0); + return getNotifications(username, organization, portalToDisplay, "desc", 10, 0); } } catch (SQLException e) { + handleException("Failed to mark all notifications as read - SQL", e); + } catch (APIManagementException e) { handleException("Failed to mark all notifications as read", e); } return null; } - public String getAPIUUIDUsingNameContextVersion(String apiName, String apiContext, String apiVersion, String organization) - throws APIManagementException { + public String getAPIUUIDUsingNameContextVersion(String apiName, String apiContext, String apiVersion, + String organization) throws APIManagementException { - String apiUUID = null; - String sqlQuery = SQLConstants.PortalNotifications.GET_API_UUID_USING_NAME_CONTEXT_VERSION; - try (Connection connection = APIMgtDBUtil.getConnection(); - PreparedStatement ps = connection.prepareStatement(sqlQuery)) { - ps.setString(1, apiName); - ps.setString(2, apiContext); - ps.setString(3, apiVersion); - ps.setString(4, organization); - try (ResultSet rs = ps.executeQuery()) { - if (rs.next()) { - apiUUID = rs.getString("API_UUID"); - } + String apiUUID = null; + String sqlQuery = SQLConstants.PortalNotifications.GET_API_UUID_USING_NAME_CONTEXT_VERSION; + try (Connection connection = APIMgtDBUtil.getConnection(); + PreparedStatement ps = connection.prepareStatement(sqlQuery)) { + ps.setString(1, apiName); + ps.setString(2, apiContext); + ps.setString(3, apiVersion); + ps.setString(4, organization); + try (ResultSet rs = ps.executeQuery()) { + if (rs.next()) { + apiUUID = rs.getString("API_UUID"); } - } catch (SQLException e) { - handleException("Failed to retrieve API UUID using name, context and version", e); } - return apiUUID; - + } catch (SQLException e) { + handleException("Failed to retrieve API UUID using name, context and version", e); + } + return apiUUID; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java new file mode 100644 index 000000000000..a68d98e65bba --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java @@ -0,0 +1,275 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.dao.test; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.commons.io.FileUtils; +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.PowerMockRunner; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.Notification; +import org.wso2.carbon.apimgt.api.model.NotificationList; +import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; +import org.wso2.carbon.apimgt.impl.APIManagerConfigurationServiceImpl; +import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; +import org.wso2.carbon.apimgt.impl.portalNotifications.*; +import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; +import org.wso2.carbon.base.MultitenantConstants; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.*; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore("javax.management.*") +public class PortalNotificationDAOTest { + public static PortalNotificationDAO portalNotificationDAO; + + private static final String organization = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; + + @Before + public void setUp() throws Exception { + String dbConfigPath = System.getProperty("APIManagerDBConfigurationPath"); + APIManagerConfiguration config = new APIManagerConfiguration(); + initializeDatabase(dbConfigPath); + config.load(dbConfigPath); + ServiceReferenceHolder.getInstance() + .setAPIManagerConfigurationService(new APIManagerConfigurationServiceImpl(config)); + APIMgtDBUtil.initialize(); + portalNotificationDAO = PortalNotificationDAO.getInstance(); + } + + private static void initializeDatabase(String configFilePath) + throws IOException, XMLStreamException, NamingException { + + InputStream in; + in = FileUtils.openInputStream(new File(configFilePath)); + StAXOMBuilder builder = new StAXOMBuilder(in); + String dataSource = builder.getDocumentElement().getFirstChildWithName(new QName("DataSourceName")).getText(); + OMElement databaseElement = builder.getDocumentElement().getFirstChildWithName(new QName("Database")); + String databaseURL = databaseElement.getFirstChildWithName(new QName("URL")).getText(); + String databaseUser = databaseElement.getFirstChildWithName(new QName("Username")).getText(); + String databasePass = databaseElement.getFirstChildWithName(new QName("Password")).getText(); + String databaseDriver = databaseElement.getFirstChildWithName(new QName("Driver")).getText(); + + BasicDataSource basicDataSource = new BasicDataSource(); + basicDataSource.setDriverClassName(databaseDriver); + basicDataSource.setUrl(databaseURL); + basicDataSource.setUsername(databaseUser); + basicDataSource.setPassword(databasePass); + + // Create initial context + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory"); + System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming"); + try { + InitialContext.doLookup("java:/comp/env/jdbc/WSO2AM_DB"); + } catch (NamingException e) { + InitialContext ic = new InitialContext(); + ic.createSubcontext("java:"); + ic.createSubcontext("java:/comp"); + ic.createSubcontext("java:/comp/env"); + ic.createSubcontext("java:/comp/env/jdbc"); + + ic.bind("java:/comp/env/jdbc/WSO2AM_DB", basicDataSource); + } + } + + @Test + public void testAddNotificationSuccess() throws APIManagementException { + PortalNotificationMetaData metaData = getPortalNotificationMetaData(); + PortalNotificationDTO portalNotificationDTO = getPortalNotificationDTO(metaData); + + boolean result = portalNotificationDAO.addNotification(portalNotificationDTO); + Assert.assertTrue(result); + } + + @NotNull + private static PortalNotificationDTO getPortalNotificationDTO(PortalNotificationMetaData metaData) { + PortalNotificationEndUserDTO endUser1 = new PortalNotificationEndUserDTO(); + endUser1.setDestinationUser("Kevin"); + endUser1.setOrganization(organization); + endUser1.setPortalToDisplay("publisher"); + List endUsersList = new ArrayList<>(); + endUsersList.add(endUser1); + + PortalNotificationDTO portalNotificationDTO = new PortalNotificationDTO(); + portalNotificationDTO.setNotificationType(PortalNotificationType.API_STATE_CHANGE); + portalNotificationDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); + portalNotificationDTO.setNotificationMetadata(metaData); + portalNotificationDTO.setEndUsers(endUsersList); + return portalNotificationDTO; + } + + @NotNull + private static PortalNotificationMetaData getPortalNotificationMetaData() { + PortalNotificationMetaData metaData = new PortalNotificationMetaData(); + metaData.setApi("Sample_API"); + metaData.setApiVersion("1.0"); + metaData.setApiContext("/sample"); + metaData.setApplicationName(null); + metaData.setRequestedTier(null); + metaData.setRevisionId(null); + metaData.setComment("Sample comment"); + metaData.setAction("Publish"); + return metaData; + } + + @Test + public void testGetNotificationsSuccess() throws APIManagementException { + NotificationList notificationList = portalNotificationDAO.getNotifications("helani", organization, + "publisher", "desc", 0, 10); + Assert.assertNotNull(notificationList); + } + + @Test + public void testMarkNotificationAsReadByIdSuccess() throws Exception { + Notification notification = portalNotificationDAO.markNotificationAsReadById("helani", organization, + "1e2736ab-7882-4184-a1ba-6d3c07271b69", "publisher"); + assertEquals(true, notification.getIsRead()); + } + + @Test + public void testMarkAllNotificationsAsReadSuccess() throws Exception { + NotificationList notificationList = portalNotificationDAO.markAllNotificationsAsRead("helani", + organization, "publisher"); + assertEquals(true, notificationList.getList().get(0).getIsRead()); + } + + @Test + public void testDeleteNotificationByIdSuccess() throws Exception { + boolean result = portalNotificationDAO.deleteNotificationById("helani", organization, + "7dc674f1-2b4c-4826-8e95-fa9b2628b816", "publisher"); + Assert.assertTrue(result); + } + + @Test + public void testDeleteAllNotificationsSuccess() throws Exception { + boolean result = portalNotificationDAO.deleteAllNotifications("Kevin", organization, + "publisher"); + Assert.assertTrue(result); + } + + @Test + public void testGetAPIUUIDUsingNameContextVersionSuccess() throws Exception { + String apiUUID = portalNotificationDAO.getAPIUUIDUsingNameContextVersion("testAPI1", + "/sample/api", "1.0.0", organization); + assertEquals("821b9824-eeca-4173-9f56-3dc6d46bd6eb", apiUUID); + } + + @Test + public void testGetUnreadNotificationCountSuccess() throws Exception { + Connection connection = APIMgtDBUtil.getConnection(); + int unreadCount = portalNotificationDAO.getUnreadNotificationCount("Nisha", organization, + "devportal", connection); + assertEquals(1, unreadCount); + + } + + @Test + public void testAddNotificationFailure() { + PortalNotificationMetaData metaData = getPortalNotificationMetaData(); + PortalNotificationEndUserDTO endUser1 = new PortalNotificationEndUserDTO(); + endUser1.setDestinationUser("Kevin"); + endUser1.setOrganization(organization); + List endUsersList = new ArrayList<>(); + endUsersList.add(endUser1); + + PortalNotificationDTO portalNotificationDTO = new PortalNotificationDTO(); + portalNotificationDTO.setNotificationType(PortalNotificationType.API_STATE_CHANGE); + portalNotificationDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); + portalNotificationDTO.setNotificationMetadata(metaData); + portalNotificationDTO.setEndUsers(endUsersList); + + Exception exception = assertThrows(APIManagementException.class, () -> { + portalNotificationDAO.addNotification(portalNotificationDTO); + }); + + String expectedMessage = "Error while adding notification"; + String actualMessage = exception.getMessage(); + assertEquals(expectedMessage, actualMessage); + } + + @Test + public void testGetNotificationsFailure() throws APIManagementException { + NotificationList notificationList = portalNotificationDAO.getNotifications("Rush", organization, + "publisher", "desc", 0, 10); + assertEquals(0, notificationList.getList().size()); + } + + @Test + public void testMarkNotificationAsReadByIdFailure() throws Exception { + Notification notification = portalNotificationDAO.markNotificationAsReadById("Rush", organization, + "1e2736ab-7882-4184-a1ba-6d3c07271b69", "publisher"); + assertNull(notification); + } + + @Test + public void testMarkAllNotificationsAsReadFailure() throws Exception { + NotificationList notificationList = portalNotificationDAO.markAllNotificationsAsRead("Rush", + organization, "publisher"); + assertNull(notificationList); + } + + @Test + public void testDeleteNotificationByIdFailure() throws Exception { + boolean result = portalNotificationDAO.deleteNotificationById("Rush", organization, + "7dc674f1-2b4c-4826-8e95-fa9b2628b816", "publisher"); + Assert.assertFalse(result); + } + + @Test + public void testDeleteAllNotificationsFailure() throws Exception { + boolean result = portalNotificationDAO.deleteAllNotifications("Rush", organization, + "publisher"); + Assert.assertFalse(result); + } + + @Test + public void testGetAPIUUIDUsingNameContextVersionFailure() throws Exception { + String apiUUID = portalNotificationDAO.getAPIUUIDUsingNameContextVersion("MyApi", "/api", + "1.0.0", organization); + assertNull(apiUUID); + } + + @Test + public void testGetUnreadNotificationCountFailure() throws Exception { + Connection connection = APIMgtDBUtil.getConnection(); + int unreadCount = portalNotificationDAO.getUnreadNotificationCount("Rush", organization, + "publisher", connection); + assertEquals(0, unreadCount); + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java new file mode 100644 index 000000000000..5b75395f29b0 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.portalNotifications; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; + +import static org.mockito.Mockito.*; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ APIUtil.class, PortalNotificationDAO.class }) +public class WorkflowNotificationServiceImplTest { + + private WorkflowNotificationServiceImpl notificationService; + private PortalNotificationDAO portalNotificationDAO; + + private WorkflowDTO workflowDTO; + + @Before + public void init() { + notificationService = new WorkflowNotificationServiceImpl(); + portalNotificationDAO = Mockito.mock(PortalNotificationDAO.class); + workflowDTO = createMockWorkflowDTO(); + } + + @Test + public void testSendPortalNotificationsSuccess() throws APIManagementException { + + PowerMockito.mockStatic(APIUtil.class); + PowerMockito.mockStatic(PortalNotificationDAO.class); + String tenantDomainOfUser = "carbonSuper"; + + PowerMockito.when(APIUtil.isMultiGroupAppSharingEnabled()).thenReturn(false); + PowerMockito.when(PortalNotificationDAO.getInstance()).thenReturn(portalNotificationDAO); + when(portalNotificationDAO.addNotification(any(PortalNotificationDTO.class))).thenReturn(true); + notificationService.sendPortalNotifications(workflowDTO, tenantDomainOfUser); + verify(portalNotificationDAO, times(1)).addNotification(any(PortalNotificationDTO.class)); + } + + private WorkflowDTO createMockWorkflowDTO() { + WorkflowDTO workflowDTO = new WorkflowDTO(); + workflowDTO.setProperties("apiName", "Test API"); + workflowDTO.setProperties("apiVersion", "1.0"); + workflowDTO.setMetadata("Action", "Publish"); + workflowDTO.setMetadata("Provider", "Ali"); + workflowDTO.setProperties("revisionId", "1"); + workflowDTO.setComments("Test Comment"); + workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_API_STATE); + workflowDTO.setMetadata("ApiContext", "/test/1.0"); + workflowDTO.setMetadata("Invoker", "Kevin"); + return workflowDTO; + } + +} + diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java index cf14e0ab6015..884e6d93fdd5 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java @@ -40,21 +40,25 @@ import org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; +import org.wso2.carbon.apimgt.impl.portalNotifications.WorkflowNotificationServiceImpl; import javax.xml.stream.XMLStreamException; import java.util.UUID; +import static org.mockito.ArgumentMatchers.any; + /** * ApplicationCreationWSWorkflowExecutor test cases */ @RunWith(PowerMockRunner.class) @PrepareForTest({ ServiceReferenceHolder.class, ApiMgtDAO.class, ApplicationCreationWSWorkflowExecutor.class, - AXIOMUtil.class}) + AXIOMUtil.class, WorkflowNotificationServiceImpl.class}) public class ApplicationCreationWSWorkflowExecutorTest { private ApplicationCreationWSWorkflowExecutor applicationCreationWSWorkflowExecutor; private ApiMgtDAO apiMgtDAO; private ServiceClient serviceClient; + WorkflowNotificationServiceImpl workflowsApiService; @Before public void init() { @@ -67,6 +71,7 @@ public void init() { PowerMockito.mockStatic(ApiMgtDAO.class); apiMgtDAO = Mockito.mock(ApiMgtDAO.class); serviceClient = Mockito.mock(ServiceClient.class); + workflowsApiService = PowerMockito.mock(WorkflowNotificationServiceImpl.class); PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO); } @@ -88,9 +93,9 @@ public void testWorkflowApprove() throws APIManagementException, WorkflowExcepti PowerMockito.doNothing().when(apiMgtDAO).updateApplicationStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_APPROVED); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); - applicationCreationWSWorkflowExecutor.complete(workflowDTO); + applicationCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)).updateApplicationStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_APPROVED); @@ -110,7 +115,7 @@ public void testWorkflowReject() throws APIManagementException, WorkflowExceptio PowerMockito.doNothing().when(apiMgtDAO).updateApplicationStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_REJECTED); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)).updateApplicationStatus( @@ -131,7 +136,7 @@ public void testWorkflowCreate() throws APIManagementException, WorkflowExceptio PowerMockito.doNothing().when(apiMgtDAO).updateApplicationStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_CREATED); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)).updateApplicationStatus( @@ -186,7 +191,8 @@ public void testWorkflowCompleteExceptionWhenStatusUpdateFailed() throws APIMana "creation process")).when(apiMgtDAO).updateApplicationStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_APPROVED); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + applicationCreationWSWorkflowExecutor.complete(workflowDTO); } @@ -246,7 +252,7 @@ public void testWorkflowNotAllowedStatus() throws APIManagementException, Workfl Application app = Mockito.mock(Application.class); PowerMockito.doReturn(app).when(apiMgtDAO) .getApplicationById(Integer.parseInt(workflowDTO.getWorkflowReference())); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); // shouldn't update status diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java index 3add5cd9e2a8..10a89913124a 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java @@ -45,16 +45,19 @@ import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.apimgt.impl.factory.KeyManagerHolder; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; +import org.wso2.carbon.apimgt.impl.portalNotifications.WorkflowNotificationServiceImpl; import org.wso2.carbon.utils.ConfigurationContextService; import javax.xml.stream.XMLStreamException; +import static org.mockito.ArgumentMatchers.any; + /** * ApplicationRegistrationWSWorkflowExecutor test cases */ @RunWith(PowerMockRunner.class) @PrepareForTest({ApiMgtDAO.class, ApplicationRegistrationWSWorkflowExecutor.class, - ServiceReferenceHolder.class, AXIOMUtil.class, KeyManagerHolder.class}) + ServiceReferenceHolder.class, AXIOMUtil.class, KeyManagerHolder.class, WorkflowNotificationServiceImpl.class}) public class ApplicationRegistrationWSWorkflowExecutorTest { private ApplicationRegistrationWSWorkflowExecutor applicationRegistrationWSWorkflowExecutor; @@ -67,6 +70,7 @@ public class ApplicationRegistrationWSWorkflowExecutorTest { private String adminUsername = "admin"; private String adminPassword = "admin"; private String callBaclURL = "http://localhost:8090/playground2.0/oauth2client"; + WorkflowNotificationServiceImpl workflowsApiService; @Before @@ -107,6 +111,7 @@ public void init() throws Exception { kmConfigDTO.setOrganization("carbon.super"); kmConfigDTO.setName("default"); PowerMockito.when(apiMgtDAO.getKeyManagerConfigurationByUUID("default")).thenReturn(kmConfigDTO); + workflowsApiService = PowerMockito.mock(WorkflowNotificationServiceImpl.class); } @Test @@ -191,7 +196,7 @@ public void testCompletingApplicationRegistrationWSWFWhenWFRejected() throws Exc applicationRegistrationWSWorkflowExecutor.setUsername(adminUsername); applicationRegistrationWSWorkflowExecutor.setPassword(adminPassword.toCharArray()); workflowDTO.setStatus(WorkflowStatus.REJECTED); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); try { Assert.assertNotNull(applicationRegistrationWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { @@ -217,7 +222,7 @@ public void testCompletingApplicationRegistrationWSWFWhenWFApproved() throws Exc applicationRegistrationWSWorkflowExecutor.setPassword(adminPassword.toCharArray()); workflowDTO.setStatus(WorkflowStatus.APPROVED); workflowDTO.setKeyManager("default"); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); try { Assert.assertNotNull(applicationRegistrationWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java index 00e90d21428e..8f58a855551b 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java @@ -44,20 +44,24 @@ import org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; +import org.wso2.carbon.apimgt.impl.portalNotifications.WorkflowNotificationServiceImpl; import javax.xml.stream.XMLStreamException; +import static org.mockito.ArgumentMatchers.any; + /** * SubscriptionCreationSimpleWorkflowExecutor test cases */ @RunWith(PowerMockRunner.class) @PrepareForTest({ ServiceReferenceHolder.class, ApiMgtDAO.class, SubscriptionCreationWSWorkflowExecutor.class, - AXIOMUtil.class }) + AXIOMUtil.class, WorkflowNotificationServiceImpl.class}) public class SubscriptionCreationWSWorkflowExecutorTest { private SubscriptionCreationWSWorkflowExecutor subscriptionCreationWSWorkflowExecutor; private ApiMgtDAO apiMgtDAO; private ServiceClient serviceClient; + WorkflowNotificationServiceImpl workflowsApiService; @Before public void init() { @@ -71,6 +75,7 @@ public void init() { apiMgtDAO = Mockito.mock(ApiMgtDAO.class); serviceClient = Mockito.mock(ServiceClient.class); PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO); + workflowsApiService = PowerMockito.mock(WorkflowNotificationServiceImpl.class); } @Test @@ -86,7 +91,7 @@ public void testWorkflowApprove() throws APIManagementException, WorkflowExcepti workflowDTO.setStatus(WorkflowStatus.APPROVED); PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.UNBLOCKED); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)).updateSubscriptionStatus( @@ -102,7 +107,7 @@ public void testWorkflowReject() throws APIManagementException, WorkflowExceptio workflowDTO.setStatus(WorkflowStatus.REJECTED); PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)).updateSubscriptionStatus( @@ -117,8 +122,7 @@ public void testWorkflowRejectException() throws APIManagementException, Workflo workflowDTO.setStatus(WorkflowStatus.REJECTED); PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO).updateSubscriptionStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); - + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); } @@ -131,8 +135,7 @@ public void testWorkflowApproveException() throws APIManagementException, Workfl workflowDTO.setStatus(WorkflowStatus.APPROVED); PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO).updateSubscriptionStatus( Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.UNBLOCKED); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); - + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); } @@ -143,8 +146,7 @@ public void testWorkflowNotAllowedStatus() throws APIManagementException, Workfl workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); workflowDTO.setStatus(WorkflowStatus.CREATED); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); - + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); // shouldn't update status Mockito.verify(apiMgtDAO, Mockito.never()).updateSubscriptionStatus( diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java index f764267a5aa8..a5f799fa8f3a 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java @@ -40,6 +40,7 @@ import org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; +import org.wso2.carbon.apimgt.impl.portalNotifications.WorkflowNotificationServiceImpl; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.utils.SelfSignUpUtil; import org.wso2.carbon.registry.core.utils.UUIDGenerator; @@ -53,12 +54,14 @@ import java.util.ArrayList; import javax.xml.stream.XMLStreamException; +import static org.mockito.ArgumentMatchers.any; + /** * UserSignUpWSWorkflowExecutor test cases */ @RunWith(PowerMockRunner.class) @PrepareForTest({ServiceReferenceHolder.class, UserSignUpWSWorkflowExecutor.class, ApiMgtDAO.class, APIUtil.class, - AXIOMUtil.class, SelfSignUpUtil.class, CarbonUtils.class}) + AXIOMUtil.class, SelfSignUpUtil.class, CarbonUtils.class, WorkflowNotificationServiceImpl.class}) public class UserSignUpWSWorkflowExecutorTest { private UserSignUpWSWorkflowExecutor userSignUpWSWorkflowExecutor; @@ -75,6 +78,7 @@ public class UserSignUpWSWorkflowExecutorTest { private String signUpRole = "Internal/subscriber"; private int tenantID = -1234; private String testUsername = "PRIMARY/testuser"; + WorkflowNotificationServiceImpl workflowsApiService; @Before public void init() throws Exception { @@ -113,6 +117,7 @@ public void init() throws Exception { workflowDTO.setTenantDomain(tenantDomain); workflowDTO.setExternalWorkflowReference(externalWFReference); workflowDTO.setWorkflowReference(testUsername + "@carbon.super"); + workflowsApiService = PowerMockito.mock(WorkflowNotificationServiceImpl.class); } @Test @@ -184,7 +189,7 @@ public void testCompletingUserSignUpWorkflowApprovedByAdmin() throws Exception { Mockito.when(userStoreManager.isExistingRole(signUpRole)).thenReturn(true); PowerMockito.doNothing().when(userStoreManager).updateRoleListOfUser(testUsername, null, new String[]{ signUpRole}); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); try { @@ -204,7 +209,7 @@ public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exce PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true); Mockito.when(userStoreManager.isExistingRole(signUpRole)).thenReturn(true); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); @@ -248,7 +253,7 @@ public void testCompletingUserSignUpWorkflowRejectedByAdmin() throws Exception { userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); try { @@ -266,8 +271,7 @@ public void testFailureToCompleteUserSignUpWorkflowRejectedByAdmin() throws Exce userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); - PowerMockito.suppress(PowerMockito.method(WorkflowExecutor.class, "sendPortalNotifications", WorkflowDTO.class)); - + PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); Mockito.doThrow(UserStoreException.class).when(userStoreManager).deleteUser(Mockito.anyString()); diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/resources/dbscripts/h2-sample-data.sql b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/resources/dbscripts/h2-sample-data.sql index 9e89094260fe..2208d9e95c08 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/resources/dbscripts/h2-sample-data.sql +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/resources/dbscripts/h2-sample-data.sql @@ -68,6 +68,14 @@ INSERT INTO AM_DEPLOYMENT_REVISION_MAPPING (NAME, VHOST, REVISION_UUID, REVISION INSERT INTO AM_POLICY_SUBSCRIPTION (NAME, DISPLAY_NAME, TENANT_ID, QUOTA_TYPE, QUOTA, UNIT_TIME, TIME_UNIT,BILLING_PLAN) VALUES ('Gold', 'Gold', -1234, 'requestCount', 2, 1, 'min', 'Free'); +INSERT INTO AM_NOTIFICATION (NOTIFICATION_ID, NOTIFICATION_TYPE, CREATED_TIME, NOTIFICATION_METADATA) VALUES ('7dc674f1-2b4c-4826-8e95-fa9b2628b816','APPLICATION_CREATION', '2024-04-29 09:17:31.336', '7b227265766973696f6e4964223a6e756c6c2c226170694e616d65223a6e756c6c2c2261706956657273696f6e223a6e756c6c2c22616374696f6e223a6e756c6c2c22617069436f6e74657874223a6e756c6c2c22636f6d6d656e74223a22415050524f564544222c226170706c69636174696f6e4e616d65223a22536861726564417070222c2272657175657374656454696572223a6e756c6c7d'); +INSERT INTO AM_NOTIFICATION (NOTIFICATION_ID, NOTIFICATION_TYPE, CREATED_TIME, NOTIFICATION_METADATA) VALUES ('1e2736ab-7882-4184-a1ba-6d3c07271b69',' API_STATE_CHANGE', '2024-04-29 10:17:31.336', '7b227265766973696f6e4964223a6e756c6c2c226170694e616d65223a2250697a7a61536861636b415049222c2261706956657273696f6e223a22312e302e30222c22616374696f6e223a22426c6f636b222c22617069436f6e74657874223a225c2f70697a7a61736861636b5c2f312e302e30222c22636f6d6d656e74223a22415050524f564544222c226170706c69636174696f6e4e616d65223a6e756c6c2c2272657175657374656454696572223a6e756c6c7d'); +INSERT INTO AM_NOTIFICATION (NOTIFICATION_ID, NOTIFICATION_TYPE, CREATED_TIME, NOTIFICATION_METADATA) VALUES ('2c3ebc71-8244-49b0-a0c6-7a92cfd7e5ac',' SUBSCRIPTION_CREATION', '2024-04-30 08:27:31.336', '7b227265766973696f6e4964223a6e756c6c2c226170694e616d65223a2250697a7a61536861636b415049222c2261706956657273696f6e223a22312e302e30222c22616374696f6e223a6e756c6c2c22617069436f6e74657874223a6e756c6c2c22636f6d6d656e74223a22415050524f564544222c226170706c69636174696f6e4e616d65223a22536861726564417070222c2272657175657374656454696572223a6e756c6c7d'); + +INSERT INTO AM_NOTIFICATION_END_USERS (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY) VALUES ('7dc674f1-2b4c-4826-8e95-fa9b2628b816','helani','carbon.super','publisher'); +INSERT INTO AM_NOTIFICATION_END_USERS (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY) VALUES ('1e2736ab-7882-4184-a1ba-6d3c07271b69','helani','carbon.super','publisher'); +INSERT INTO AM_NOTIFICATION_END_USERS (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY) VALUES ('2c3ebc71-8244-49b0-a0c6-7a92cfd7e5ac','Nisha','carbon.super','devportal'); + SELECT * FROM AM_SUBSCRIBER; SELECT * FROM AM_APPLICATION; SELECT * FROM AM_SUBSCRIPTION; From 0cbb0905a3cdd34834d444a0abeb214f9cd17911 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Tue, 30 Apr 2024 16:01:05 +0530 Subject: [PATCH 15/23] Handle APIManagement Exception within the sendPortalNotifications method --- .../PortalNotificationService.java | 2 +- .../WorkflowNotificationServiceImpl.java | 23 +++++++++++-------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java index 39b853f348ba..bcdfccae74f4 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java @@ -22,6 +22,6 @@ public interface PortalNotificationService { - void sendPortalNotifications(T notificationObject, String tenantDomain) throws APIManagementException; + void sendPortalNotifications(T notificationObject, String tenantDomain); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java index 6f86413171ce..2e20225abbcc 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java @@ -51,18 +51,21 @@ public class WorkflowNotificationServiceImpl implements PortalNotificationServic private static final Log log = LogFactory.getLog(WorkflowNotificationServiceImpl.class); - public void sendPortalNotifications(WorkflowDTO workflowDTO, String tenantDomainOfUser) - throws APIManagementException { - PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); - portalNotificationsDTO.setNotificationType(getNotificationType(workflowDTO.getWorkflowType())); - portalNotificationsDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); - portalNotificationsDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); - portalNotificationsDTO.setEndUsers(getDestinationUser(workflowDTO, tenantDomainOfUser)); + public void sendPortalNotifications(WorkflowDTO workflowDTO, String tenantDomainOfUser) { + try { + PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); + portalNotificationsDTO.setNotificationType(getNotificationType(workflowDTO.getWorkflowType())); + portalNotificationsDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); + portalNotificationsDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + portalNotificationsDTO.setEndUsers(getDestinationUser(workflowDTO, tenantDomainOfUser)); - boolean result = PortalNotificationDAO.getInstance().addNotification(portalNotificationsDTO); + boolean result = PortalNotificationDAO.getInstance().addNotification(portalNotificationsDTO); - if (!result) { - log.error("Error while adding publisher developer notification - sendPortalNotifications()"); + if (!result) { + log.error("Error while adding publisher developer notification - sendPortalNotifications()"); + } + } catch (APIManagementException e) { + log.error("Error while sending portal notifications - APIManagementException"); } } From 011879e80fa76dca9a3520d8aaaf7a351fd5bbea Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Tue, 30 Apr 2024 23:19:52 +0530 Subject: [PATCH 16/23] Modify based on review comments --- .../wso2/carbon/apimgt/api/APIConsumer.java | 61 +++++- .../wso2/carbon/apimgt/api/APIProvider.java | 40 ++-- .../carbon/apimgt/api/model/Notification.java | 4 +- .../apimgt/api/model/NotificationList.java | 4 +- .../carbon/apimgt/impl/APIConsumerImpl.java | 48 ++--- .../carbon/apimgt/impl/APIProviderImpl.java | 44 ++-- .../impl/dao/constants/SQLConstants.java | 9 +- .../PortalNotificationDAO.java | 4 +- .../PortalNotificationDTO.java | 4 +- .../PortalNotificationEndUserDTO.java | 4 +- .../PortalNotificationMetaData.java | 4 +- .../PortalNotificationService.java | 4 +- .../PortalNotificationType.java | 4 +- .../WorkflowNotificationServiceImpl.java | 64 +++++- .../dao/test/PortalNotificationDAOTest.java | 47 +++-- .../WorkflowNotificationServiceImplTest.java | 20 +- ...icationCreationWSWorkflowExecutorTest.java | 197 ++++++++++-------- ...ionRegistrationWSWorkflowExecutorTest.java | 8 +- ...riptionCreationWSWorkflowExecutorTest.java | 65 +++--- .../UserSignUpWSWorkflowExecutorTest.java | 22 +- .../rest/api/admin/v1/dto/WorkflowDTO.java | 1 + .../v1/impl/NotificationsApiServiceImpl.java | 4 +- .../v1/impl/NotificationsApiServiceImpl.java | 4 +- 23 files changed, 400 insertions(+), 266 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java index 23a6aff224b9..25031307104e 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java @@ -872,14 +872,63 @@ boolean isKeyManagerByNameAllowedForUser(String keyManagerName, String organizat */ boolean removalKeys(Application application, String keyMappingId, String xWSO2Tenant) throws APIManagementException; - NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, Integer offset) - throws APIManagementException; + /** + * Method to get notifications for the given user + * + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to see the notifications + * @param sortOrder sort order of the notifications + * @param limit limit of the notifications + * @param offset offset of the notifications + * @return NotificationList + */ + NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, + Integer limit, Integer offset) throws APIManagementException; - NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) throws APIManagementException; + /** + * Method to mark all notifications as read + * + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to update the notifications + * @return updated NotificationList + */ + NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) + throws APIManagementException; - Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) throws APIManagementException; + /** + * Method to mark a notification as read + * + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param notificationId id of the notification that needs to update the mark as read status + * @param portalToDisplay the portal user needs to update the notification + * @return updated Notification + */ + Notification markNotificationAsReadById(String username, String organization, String notificationId, + String portalToDisplay) throws APIManagementException; - boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) throws APIManagementException; + /** + * Method to delete a notification by notification id + * + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param notificationId id of the notification that needs to delete + * @param portalToDisplay the portal user needs to delete the notification + * @return true after successful deletion + */ + boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) + throws APIManagementException; - boolean deleteAllNotifications(String username, String organization, String portalToDisplay) throws APIManagementException; + /** + * Method to delete the notifications of a given user + * + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to delete the notifications + * @return true after successful deletion + */ + boolean deleteAllNotifications(String username, String organization, String portalToDisplay) + throws APIManagementException; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java index ac23c88f4d61..cea963e9ad24 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIProvider.java @@ -1912,12 +1912,12 @@ boolean isPolicyMetadataExists(String gatewayPolicyMappingId) /** * Method to get notifications for the given user * - * @param username - * @param organization - * @param portalToDisplay - * @param sortOrder - * @param limit - * @param offset + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to see the notifications + * @param sortOrder sort order of the notifications + * @param limit limit of the notifications + * @param offset offset of the notifications * @return NotificationList */ NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, @@ -1926,9 +1926,9 @@ NotificationList getNotifications(String username, String organization, String p /** * Method to delete the notifications of a given user * - * @param username - * @param organization - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to delete the notifications * @return true after successful deletion */ boolean deleteAllNotifications(String username, String organization, String portalToDisplay) @@ -1937,10 +1937,10 @@ boolean deleteAllNotifications(String username, String organization, String port /** * Method to mark a notification as read * - * @param username - * @param organization - * @param notificationId - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param notificationId id of the notification that needs to update the mark as read status + * @param portalToDisplay the portal user needs to update the notification * @return updated Notification */ Notification markNotificationAsReadById(String username, String organization, String notificationId, @@ -1949,10 +1949,10 @@ Notification markNotificationAsReadById(String username, String organization, St /** * Method to delete a notification by notification id * - * @param username - * @param organization - * @param notificationId - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param notificationId id of the notification that needs to delete + * @param portalToDisplay the portal user needs to delete the notification * @return true after successful deletion */ boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) @@ -1961,9 +1961,9 @@ boolean deleteNotificationById(String username, String organization, String noti /** * Method to mark all notifications as read * - * @param username - * @param organization - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to update the notifications * @return updated NotificationList */ NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java index 086f3b585074..f9c88f065a61 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/Notification.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java index ce84effdb196..491376230361 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java +++ b/components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/NotificationList.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java index 6271b4fdb238..f49eb7eabea9 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java @@ -4600,12 +4600,12 @@ public boolean isKeyManagerByNameAllowedForUser(String keyManagerName, String or /** * Get the list of Notifications belongs to a particular developer user * - * @param username - * @param organization - * @param portalToDisplay - * @param sortOrder - * @param limit - * @param offset + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to see the notifications + * @param sortOrder sort order of the notifications + * @param limit limit of the notifications + * @param offset offset of the notifications * @return List of Notifications * @throws APIManagementException if failed to get notifications */ @@ -4617,11 +4617,11 @@ public NotificationList getNotifications(String username, String organization, S } /** - * Mark all the notifications as read for a particular developer user + * Mark all notifications as read of a particular developer user * - * @param username - * @param organization - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to update the notifications * @return List of Notifications * @throws APIManagementException if failed to mark all notifications as read */ @@ -4632,12 +4632,12 @@ public NotificationList markAllNotificationsAsRead(String username, String organ } /** - * Mark a particular notification as read for a particular developer user + * Mark a notification as read by notification ID * - * @param username - * @param organization - * @param notificationId - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param notificationId id of the notification that needs to update the mark as read status + * @param portalToDisplay the portal user needs to update the notification * @return updated Notification after marking as read * @throws APIManagementException if failed to mark the notification as read */ @@ -4649,12 +4649,12 @@ public Notification markNotificationAsReadById(String username, String organizat } /** - * Delete a particular notification for a particular developer user + * Delete a notification by notification ID * - * @param username - * @param organization - * @param notificationId - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param notificationId id of the notification that needs to delete + * @param portalToDisplay the portal user needs to delete the notification * @return true after deleting the notifications * @throws APIManagementException if failed to delete the notification */ @@ -4665,11 +4665,11 @@ public boolean deleteNotificationById(String username, String organization, Stri } /** - * Delete all the notifications for a particular developer user + * Delete all notifications belongs to a particular developer user * - * @param username - * @param organization - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to delete the notifications * @return true after deleting all notifications * @throws APIManagementException if failed to delete all notifications */ diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java index 9031bf33624d..ad1eda3f8536 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java @@ -7237,12 +7237,12 @@ public int getPolicyUsageByPolicyUUIDInGatewayPolicies(String commonPolicyUUID) /** * Get the list of Notifications belongs to a particular publisher user * - * @param username - * @param organization - * @param portalToDisplay - * @param sortOrder - * @param limit - * @param offset + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to see the notifications + * @param sortOrder sort order of the notifications + * @param limit limit of the notifications + * @param offset offset of the notifications * @return List of Notifications * @throws APIManagementException if failed to get notifications */ @@ -7256,11 +7256,11 @@ public NotificationList getNotifications(String username, String organization, S /** * Delete all notifications belongs to a particular publisher user * - * @param username - * @param organization - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to delete the notifications * @return true after deleting all notifications - * @throws APIManagementException if failed to delete notifications + * @throws APIManagementException if failed to delete all notifications */ @Override public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) @@ -7271,10 +7271,10 @@ public boolean deleteAllNotifications(String username, String organization, Stri /** * Mark a notification as read by notification ID * - * @param username - * @param organization - * @param notificationId - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param notificationId id of the notification that needs to update the mark as read status + * @param portalToDisplay the portal user needs to update the notification * @return updated Notification after marking as read * @throws APIManagementException if failed to mark the notification as read */ @@ -7288,10 +7288,10 @@ public Notification markNotificationAsReadById(String username, String organizat /** * Delete a notification by notification ID * - * @param username - * @param organization - * @param notificationId - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param notificationId id of the notification that needs to delete + * @param portalToDisplay the portal user needs to delete the notification * @return true after deleting the notification * @throws APIManagementException if failed to delete the notification */ @@ -7302,11 +7302,11 @@ public boolean deleteNotificationById(String username, String organization, Stri } /** - * Mark all notifications as read + * Mark all notifications as read of a particular publisher user * - * @param username - * @param organization - * @param portalToDisplay + * @param username username of the logged in user + * @param organization organization of the logged in user + * @param portalToDisplay the portal user needs to update the notifications * @return updated NotificationList after marking all notifications as read * @throws APIManagementException if failed to mark all notifications as read */ diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java index c4c422ff9ecd..a9a6c9c87948 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java @@ -3229,7 +3229,8 @@ public static class PortalNotifications { public static final String MARK_NOTIFICATION_AS_READ = "UPDATE AM_NOTIFICATION_END_USERS SET IS_READ = TRUE " + "WHERE NOTIFICATION_ID = ? AND DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; - public static final String MARK_ALL_NOTIFICATIONS_AS_READ = "UPDATE AM_NOTIFICATION_END_USERS SET IS_READ = TRUE " + + public static final String MARK_ALL_NOTIFICATIONS_AS_READ = + "UPDATE AM_NOTIFICATION_END_USERS SET IS_READ = TRUE " + "WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; public static final String GET_NOTIFICATION_BY_ID = @@ -3255,9 +3256,9 @@ public static class PortalNotifications { public static final String GET_NOTIFICATIONS_COUNT = "SELECT COUNT(*) AS NOTIFICATION_COUNT FROM " + "AM_NOTIFICATION_END_USERS WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; - public static final String GET_UNREAD_NOTIFICATION_COUNT = "SELECT COUNT(*) AS UNREAD_NOTIFICATION_COUNT FROM " + - "AM_NOTIFICATION_END_USERS WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ? " + - "AND IS_READ = FALSE"; + public static final String GET_UNREAD_NOTIFICATION_COUNT = + "SELECT COUNT(*) AS UNREAD_NOTIFICATION_COUNT FROM AM_NOTIFICATION_END_USERS " + + "WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ? AND IS_READ = FALSE"; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java index f652f4bcf793..6b29a9dd987e 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java index d01d8b0233fb..0f84b201f447 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java index 570f5245938a..be8b6c03e30a 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java index bb8923390558..acb2ab9af273 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java index bcdfccae74f4..d5fc3e2c3ba8 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java index 4013b8042c51..d3dfe5b3fb42 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java index 2e20225abbcc..32d62d477435 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -47,10 +47,20 @@ import org.wso2.carbon.user.core.common.User; import org.wso2.carbon.user.core.service.RealmService; +/** + * This class used to insert workflow related notifications to the database, + * whenever admin approves or rejects a workflow request + */ public class WorkflowNotificationServiceImpl implements PortalNotificationService { private static final Log log = LogFactory.getLog(WorkflowNotificationServiceImpl.class); + /** + * This method will insert workflow related notifications to the database + * + * @param workflowDTO WorkflowDTO object that contains the workflow details + * @param tenantDomainOfUser Tenant domain of the user + */ public void sendPortalNotifications(WorkflowDTO workflowDTO, String tenantDomainOfUser) { try { PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); @@ -65,10 +75,16 @@ public void sendPortalNotifications(WorkflowDTO workflowDTO, String tenantDomain log.error("Error while adding publisher developer notification - sendPortalNotifications()"); } } catch (APIManagementException e) { - log.error("Error while sending portal notifications - APIManagementException"); + log.error("Error while sending portal notifications"); } } + /** + * This method will return the type of the notification + * + * @param workflowType workflow type + * @return PortalNotificationType type of the notification + */ private PortalNotificationType getNotificationType(String workflowType) { switch (workflowType) { case WorkflowConstants.WF_TYPE_AM_API_STATE: @@ -93,6 +109,13 @@ private PortalNotificationType getNotificationType(String workflowType) { return null; } + /** + * This method will return a list of users that need to send notifications based on the workflow type + * + * @param workflowDTO WorkflowDTO object that contains the workflow details + * @param tenantDomainOfUser Tenant domain of the user + * @return list of PortalNotificationEndUserDTO objects + */ private List getDestinationUser(WorkflowDTO workflowDTO, String tenantDomainOfUser) throws APIManagementException { List destinationUserList = new ArrayList<>(); @@ -185,6 +208,12 @@ private List getDestinationUser(WorkflowDTO workfl return destinationUserList; } + /** + * This method will return a PortalNotificationMetaData object containing metadata related to the notification + * + * @param workflowDTO WorkflowDTO object that contains the workflow details + * @return PortalNotificationMetaData object containing metadata related to the notification + */ private PortalNotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { PortalNotificationMetaData portalNotificationMetaData = new PortalNotificationMetaData(); @@ -209,6 +238,12 @@ private PortalNotificationMetaData getNotificationMetaData(WorkflowDTO workflowD return portalNotificationMetaData; } + /** + * This method will return the portal that the notifications should display + * + * @param workflowType workflow type + * @return the portal that the notifications should display + */ private String setPortalToDisplay(String workflowType) { switch (workflowType) { case WorkflowConstants.WF_TYPE_AM_API_STATE: @@ -220,12 +255,28 @@ private String setPortalToDisplay(String workflowType) { } } + /** + * This method will return the UUID of a given API + * + * @param apiName Name of the API + * @param apiContext Context of the API + * @param apiVersion Version of the API + * @return the UUID of the API + */ private String getAPIUUIDUsingNameContextVersion(String apiName, String apiContext, String apiVersion, String organization) throws APIManagementException { return PortalNotificationDAO.getInstance() .getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, organization); } + /** + * This method will return the list of subscribers of a given API + * + * @param apiUUID UUID of the API + * @param organization Organization of the API + * @param apiIdEmailReplaced APIIdentifier object with email replaced provider name + * @return the subscribers of the API + */ private List getSubscribersOfAPI(String apiUUID, String organization, APIIdentifier apiIdEmailReplaced) throws APIManagementException { return getAPIUsageByAPIId(apiUUID, organization, apiIdEmailReplaced); @@ -260,6 +311,13 @@ private List getAPIUsageByAPIId(String uuid, String organization, return subscribedAPIs; } + /** + * This method will return all the users belongs to a given group + * + * @param workflowDTO WorkflowDTO object that contains the workflow details + * @param tenantDomainOfUser Tenant domain of the user + * @return a list of users belongs to a given group + */ private List getAllUsersBelongToGroup(WorkflowDTO workflowDTO, String tenantDomainOfUser) throws APIManagementException, UserStoreException { List users = new ArrayList<>(); diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java index a68d98e65bba..d9d2933a01a1 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java @@ -1,17 +1,17 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @@ -35,7 +35,11 @@ import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationServiceImpl; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; -import org.wso2.carbon.apimgt.impl.portalNotifications.*; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationDAO; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationDTO; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationMetaData; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationType; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; import org.wso2.carbon.base.MultitenantConstants; @@ -51,8 +55,6 @@ import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.*; - @RunWith(PowerMockRunner.class) @PowerMockIgnore("javax.management.*") public class PortalNotificationDAOTest { @@ -75,8 +77,7 @@ public void setUp() throws Exception { private static void initializeDatabase(String configFilePath) throws IOException, XMLStreamException, NamingException { - InputStream in; - in = FileUtils.openInputStream(new File(configFilePath)); + InputStream in = FileUtils.openInputStream(new File(configFilePath)); StAXOMBuilder builder = new StAXOMBuilder(in); String dataSource = builder.getDocumentElement().getFirstChildWithName(new QName("DataSourceName")).getText(); OMElement databaseElement = builder.getDocumentElement().getFirstChildWithName(new QName("Database")); @@ -158,14 +159,14 @@ public void testGetNotificationsSuccess() throws APIManagementException { public void testMarkNotificationAsReadByIdSuccess() throws Exception { Notification notification = portalNotificationDAO.markNotificationAsReadById("helani", organization, "1e2736ab-7882-4184-a1ba-6d3c07271b69", "publisher"); - assertEquals(true, notification.getIsRead()); + Assert.assertEquals(true, notification.getIsRead()); } @Test public void testMarkAllNotificationsAsReadSuccess() throws Exception { NotificationList notificationList = portalNotificationDAO.markAllNotificationsAsRead("helani", organization, "publisher"); - assertEquals(true, notificationList.getList().get(0).getIsRead()); + Assert.assertEquals(true, notificationList.getList().get(0).getIsRead()); } @Test @@ -186,7 +187,7 @@ public void testDeleteAllNotificationsSuccess() throws Exception { public void testGetAPIUUIDUsingNameContextVersionSuccess() throws Exception { String apiUUID = portalNotificationDAO.getAPIUUIDUsingNameContextVersion("testAPI1", "/sample/api", "1.0.0", organization); - assertEquals("821b9824-eeca-4173-9f56-3dc6d46bd6eb", apiUUID); + Assert.assertEquals("821b9824-eeca-4173-9f56-3dc6d46bd6eb", apiUUID); } @Test @@ -194,7 +195,7 @@ public void testGetUnreadNotificationCountSuccess() throws Exception { Connection connection = APIMgtDBUtil.getConnection(); int unreadCount = portalNotificationDAO.getUnreadNotificationCount("Nisha", organization, "devportal", connection); - assertEquals(1, unreadCount); + Assert.assertEquals(1, unreadCount); } @@ -213,34 +214,34 @@ public void testAddNotificationFailure() { portalNotificationDTO.setNotificationMetadata(metaData); portalNotificationDTO.setEndUsers(endUsersList); - Exception exception = assertThrows(APIManagementException.class, () -> { + Exception exception = Assert.assertThrows(APIManagementException.class, () -> { portalNotificationDAO.addNotification(portalNotificationDTO); }); String expectedMessage = "Error while adding notification"; String actualMessage = exception.getMessage(); - assertEquals(expectedMessage, actualMessage); + Assert.assertEquals(expectedMessage, actualMessage); } @Test public void testGetNotificationsFailure() throws APIManagementException { NotificationList notificationList = portalNotificationDAO.getNotifications("Rush", organization, "publisher", "desc", 0, 10); - assertEquals(0, notificationList.getList().size()); + Assert.assertEquals(0, notificationList.getList().size()); } @Test public void testMarkNotificationAsReadByIdFailure() throws Exception { Notification notification = portalNotificationDAO.markNotificationAsReadById("Rush", organization, "1e2736ab-7882-4184-a1ba-6d3c07271b69", "publisher"); - assertNull(notification); + Assert.assertNull(notification); } @Test public void testMarkAllNotificationsAsReadFailure() throws Exception { NotificationList notificationList = portalNotificationDAO.markAllNotificationsAsRead("Rush", organization, "publisher"); - assertNull(notificationList); + Assert.assertNull(notificationList); } @Test @@ -261,7 +262,7 @@ public void testDeleteAllNotificationsFailure() throws Exception { public void testGetAPIUUIDUsingNameContextVersionFailure() throws Exception { String apiUUID = portalNotificationDAO.getAPIUUIDUsingNameContextVersion("MyApi", "/api", "1.0.0", organization); - assertNull(apiUUID); + Assert.assertNull(apiUUID); } @Test @@ -269,7 +270,7 @@ public void testGetUnreadNotificationCountFailure() throws Exception { Connection connection = APIMgtDBUtil.getConnection(); int unreadCount = portalNotificationDAO.getUnreadNotificationCount("Rush", organization, "publisher", connection); - assertEquals(0, unreadCount); + Assert.assertEquals(0, unreadCount); } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java index 5b75395f29b0..f06bc4c4c1ae 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java @@ -1,17 +1,17 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @@ -30,8 +30,6 @@ import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; -import static org.mockito.Mockito.*; - @RunWith(PowerMockRunner.class) @PrepareForTest({ APIUtil.class, PortalNotificationDAO.class }) public class WorkflowNotificationServiceImplTest { @@ -57,9 +55,9 @@ public void testSendPortalNotificationsSuccess() throws APIManagementException { PowerMockito.when(APIUtil.isMultiGroupAppSharingEnabled()).thenReturn(false); PowerMockito.when(PortalNotificationDAO.getInstance()).thenReturn(portalNotificationDAO); - when(portalNotificationDAO.addNotification(any(PortalNotificationDTO.class))).thenReturn(true); + Mockito.when(portalNotificationDAO.addNotification(Mockito.any(PortalNotificationDTO.class))).thenReturn(true); notificationService.sendPortalNotifications(workflowDTO, tenantDomainOfUser); - verify(portalNotificationDAO, times(1)).addNotification(any(PortalNotificationDTO.class)); + Mockito.verify(portalNotificationDAO, Mockito.times(1)).addNotification(Mockito.any(PortalNotificationDTO.class)); } private WorkflowDTO createMockWorkflowDTO() { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java index 884e6d93fdd5..18ed8ede8c86 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java @@ -45,14 +45,12 @@ import javax.xml.stream.XMLStreamException; import java.util.UUID; -import static org.mockito.ArgumentMatchers.any; - /** * ApplicationCreationWSWorkflowExecutor test cases */ @RunWith(PowerMockRunner.class) @PrepareForTest({ ServiceReferenceHolder.class, ApiMgtDAO.class, ApplicationCreationWSWorkflowExecutor.class, - AXIOMUtil.class, WorkflowNotificationServiceImpl.class}) + AXIOMUtil.class, WorkflowNotificationServiceImpl.class }) public class ApplicationCreationWSWorkflowExecutorTest { private ApplicationCreationWSWorkflowExecutor applicationCreationWSWorkflowExecutor; @@ -90,15 +88,16 @@ public void testWorkflowApprove() throws APIManagementException, WorkflowExcepti Application app = Mockito.mock(Application.class); PowerMockito.doReturn(app).when(apiMgtDAO) .getApplicationById(Integer.parseInt(workflowDTO.getWorkflowReference())); - PowerMockito.doNothing().when(apiMgtDAO).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_APPROVED); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(apiMgtDAO) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_APPROVED); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); - applicationCreationWSWorkflowExecutor.complete(workflowDTO); - Mockito.verify(apiMgtDAO, Mockito.times(1)).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_APPROVED); + applicationCreationWSWorkflowExecutor.complete(workflowDTO); + Mockito.verify(apiMgtDAO, Mockito.times(1)) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_APPROVED); } @@ -112,15 +111,16 @@ public void testWorkflowReject() throws APIManagementException, WorkflowExceptio Application app = Mockito.mock(Application.class); PowerMockito.doReturn(app).when(apiMgtDAO) .getApplicationById(Integer.parseInt(workflowDTO.getWorkflowReference())); - PowerMockito.doNothing().when(apiMgtDAO).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_REJECTED); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(apiMgtDAO) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_REJECTED); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); - Mockito.verify(apiMgtDAO, Mockito.times(1)).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_REJECTED); + Mockito.verify(apiMgtDAO, Mockito.times(1)) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_REJECTED); } @Test @@ -133,15 +133,16 @@ public void testWorkflowCreate() throws APIManagementException, WorkflowExceptio Application app = Mockito.mock(Application.class); PowerMockito.doReturn(app).when(apiMgtDAO) .getApplicationById(Integer.parseInt(workflowDTO.getWorkflowReference())); - PowerMockito.doNothing().when(apiMgtDAO).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_CREATED); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(apiMgtDAO) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_CREATED); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); - Mockito.verify(apiMgtDAO, Mockito.times(1)).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_CREATED); + Mockito.verify(apiMgtDAO, Mockito.times(1)) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_CREATED); } @Test(expected = WorkflowException.class) @@ -150,13 +151,14 @@ public void testWorkflowRejectException() throws APIManagementException, Workflo workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); workflowDTO.setStatus(WorkflowStatus.REJECTED); - PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); + PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.REJECTED); applicationCreationWSWorkflowExecutor.complete(workflowDTO); } - + @Test(expected = WorkflowException.class) public void testWorkflowCompleteException() throws APIManagementException, WorkflowException { WorkflowDTO workflowDTO = new WorkflowDTO(); @@ -168,12 +170,12 @@ public void testWorkflowCompleteException() throws APIManagementException, Workf //application is not in DB for the given id PowerMockito.doReturn(null).when(apiMgtDAO) .getApplicationById(Integer.parseInt(workflowDTO.getWorkflowReference())); - PowerMockito.doNothing().when(apiMgtDAO).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_APPROVED); + PowerMockito.doNothing().when(apiMgtDAO) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_APPROVED); applicationCreationWSWorkflowExecutor.complete(workflowDTO); - + } @Test(expected = WorkflowException.class) @@ -187,16 +189,17 @@ public void testWorkflowCompleteExceptionWhenStatusUpdateFailed() throws APIMana //application is not in DB for the given id PowerMockito.doReturn(app).when(apiMgtDAO) .getApplicationById(Integer.parseInt(workflowDTO.getWorkflowReference())); - PowerMockito.doThrow(new APIManagementException("Error occurred when updating the status of the Application " + - "creation process")).when(apiMgtDAO).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_APPROVED); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doThrow(new APIManagementException( + "Error occurred when updating the status of the Application " + "creation process")).when(apiMgtDAO) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_APPROVED); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); } - + @Test(expected = WorkflowException.class) public void testWorkflowCompleteExceptionWhenReadingDB() throws APIManagementException, WorkflowException { WorkflowDTO workflowDTO = new WorkflowDTO(); @@ -208,36 +211,39 @@ public void testWorkflowCompleteExceptionWhenReadingDB() throws APIManagementExc PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO) .getApplicationById(Integer.parseInt(workflowDTO.getWorkflowReference())); - PowerMockito.doNothing().when(apiMgtDAO).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_APPROVED); + PowerMockito.doNothing().when(apiMgtDAO) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_APPROVED); applicationCreationWSWorkflowExecutor.complete(workflowDTO); - + } @Test(expected = WorkflowException.class) - public void testWorkflowCompleteExceptionWhenUpdatingApplication() throws APIManagementException, WorkflowException { + public void testWorkflowCompleteExceptionWhenUpdatingApplication() + throws APIManagementException, WorkflowException { WorkflowDTO workflowDTO = new WorkflowDTO(); workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); workflowDTO.setStatus(WorkflowStatus.APPROVED); - PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_APPROVED); + PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_APPROVED); applicationCreationWSWorkflowExecutor.complete(workflowDTO); - + } + @Test(expected = WorkflowException.class) public void testWorkflowApproveException() throws APIManagementException, WorkflowException { WorkflowDTO workflowDTO = new WorkflowDTO(); workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); workflowDTO.setStatus(WorkflowStatus.APPROVED); - PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.UNBLOCKED); + PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.UNBLOCKED); applicationCreationWSWorkflowExecutor.complete(workflowDTO); @@ -252,19 +258,20 @@ public void testWorkflowNotAllowedStatus() throws APIManagementException, Workfl Application app = Mockito.mock(Application.class); PowerMockito.doReturn(app).when(apiMgtDAO) .getApplicationById(Integer.parseInt(workflowDTO.getWorkflowReference())); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); // shouldn't update status - Mockito.verify(apiMgtDAO, Mockito.never()).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_CREATED); - Mockito.verify(apiMgtDAO, Mockito.never()).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_APPROVED); - Mockito.verify(apiMgtDAO, Mockito.never()).updateApplicationStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), - APIConstants.ApplicationStatus.APPLICATION_REJECTED); + Mockito.verify(apiMgtDAO, Mockito.never()) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_CREATED); + Mockito.verify(apiMgtDAO, Mockito.never()) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_APPROVED); + Mockito.verify(apiMgtDAO, Mockito.never()) + .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.ApplicationStatus.APPLICATION_REJECTED); } @Test @@ -285,7 +292,7 @@ public void testWorkflowCleanupTask() throws Exception { } } - + @Test(expected = WorkflowException.class) public void testWorkflowCleanupTaskException() throws Exception { WorkflowDTO workflowDTO = new WorkflowDTO(); @@ -304,20 +311,20 @@ public void testWorkflowCleanupTaskExceptionWhenMessageProcessingFailed() throws ServiceReferenceHolderMockCreator serviceRefMock = new ServiceReferenceHolderMockCreator(-1234); ServiceReferenceHolderMockCreator.initContextService(); PowerMockito.mockStatic(AXIOMUtil.class); - PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(new XMLStreamException("Error " + - "converting String to OMElement")); + PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())) + .thenThrow(new XMLStreamException("Error " + "converting String to OMElement")); applicationCreationWSWorkflowExecutor.cleanUpPendingTask(workflowDTO.getExternalWorkflowReference()); } @Test public void testWorkflowExecute() throws Exception { - ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO(); + ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO(); Application application = new Application("TestAPP", new Subscriber(null)); - + application.setTier("Gold"); application.setCallbackUrl("www.wso2.com"); - application.setDescription("Description"); + application.setDescription("Description"); workflowDTO.setApplication(application); workflowDTO.setTenantDomain("wso2"); workflowDTO.setUserName("admin"); @@ -325,8 +332,9 @@ public void testWorkflowExecute() throws Exception { workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); - PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); + PowerMockito.doNothing().when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.REJECTED); ServiceReferenceHolderMockCreator serviceRefMock = new ServiceReferenceHolderMockCreator(-1234); ServiceReferenceHolderMockCreator.initContextService(); @@ -345,8 +353,8 @@ public void testWorkflowExecute() throws Exception { public void testWorkflowExecuteFailWhenMessageProcessingFailed() throws Exception { ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO(); PowerMockito.mockStatic(AXIOMUtil.class); - PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(new XMLStreamException("Error " + - "converting String to OMElement")); + PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())) + .thenThrow(new XMLStreamException("Error " + "converting String to OMElement")); Application application = new Application("TestAPP", new Subscriber(null)); application.setTier("Gold"); @@ -359,8 +367,9 @@ public void testWorkflowExecuteFailWhenMessageProcessingFailed() throws Exceptio workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); - PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); + PowerMockito.doNothing().when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.REJECTED); ServiceReferenceHolderMockCreator serviceRefMock = new ServiceReferenceHolderMockCreator(-1234); ServiceReferenceHolderMockCreator.initContextService(); @@ -377,20 +386,21 @@ public void testWorkflowExecuteFailWhenMessageProcessingFailed() throws Exceptio @Test public void testWorkflowExecuteWithLimitedParam() throws Exception { //application without a callback url - ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO(); + ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO(); Application application = new Application("TestAPP", new Subscriber(null)); - + application.setTier("Gold"); - application.setDescription("Description"); + application.setDescription("Description"); workflowDTO.setApplication(application); workflowDTO.setTenantDomain("wso2"); workflowDTO.setUserName("admin"); workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); - PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); + PowerMockito.doNothing().when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.REJECTED); ServiceReferenceHolderMockCreator serviceRefMock = new ServiceReferenceHolderMockCreator(-1234); ServiceReferenceHolderMockCreator.initContextService(); @@ -404,16 +414,16 @@ public void testWorkflowExecuteWithLimitedParam() throws Exception { } } - + @Test(expected = WorkflowException.class) public void testWorkflowExecuteException() throws Exception { - ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO(); + ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO(); Application application = new Application("TestAPP", new Subscriber(null)); - + application.setTier("Gold"); application.setCallbackUrl("www.wso2.com"); - application.setDescription("Description"); + application.setDescription("Description"); workflowDTO.setApplication(application); workflowDTO.setTenantDomain("wso2"); workflowDTO.setUserName("admin"); @@ -421,8 +431,9 @@ public void testWorkflowExecuteException() throws Exception { workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); - PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); + PowerMockito.doNothing().when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.REJECTED); ServiceReferenceHolderMockCreator serviceRefMock = new ServiceReferenceHolderMockCreator(-1234); ServiceReferenceHolderMockCreator.initContextService(); @@ -433,13 +444,13 @@ public void testWorkflowExecuteException() throws Exception { @Test public void testWorkflowExecuteWithoutExecutorParam() throws Exception { - ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO(); + ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO(); Application application = new Application("TestAPP", new Subscriber(null)); - + application.setTier("Gold"); application.setCallbackUrl("www.wso2.com"); - application.setDescription("Description"); + application.setDescription("Description"); workflowDTO.setApplication(application); workflowDTO.setTenantDomain("wso2"); workflowDTO.setUserName("admin"); @@ -447,8 +458,9 @@ public void testWorkflowExecuteWithoutExecutorParam() throws Exception { workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); - PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); + PowerMockito.doNothing().when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.REJECTED); ServiceReferenceHolderMockCreator serviceRefMock = new ServiceReferenceHolderMockCreator(-1234); ServiceReferenceHolderMockCreator.initContextService(); @@ -515,13 +527,13 @@ public void testWorkflowExecuteWithoutExecutorParam() throws Exception { @Test public void testWorkflowExecuteWithDifferentMediatype() throws Exception { - ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO(); + ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO(); Application application = new Application("TestAPP", new Subscriber(null)); - + application.setTier("Gold"); application.setCallbackUrl("www.wso2.com"); - application.setDescription("Description"); + application.setDescription("Description"); workflowDTO.setApplication(application); workflowDTO.setTenantDomain("wso2"); workflowDTO.setUserName("admin"); @@ -529,8 +541,9 @@ public void testWorkflowExecuteWithDifferentMediatype() throws Exception { workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); - PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); + PowerMockito.doNothing().when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.REJECTED); ServiceReferenceHolderMockCreator serviceRefMock = new ServiceReferenceHolderMockCreator(-1234); ServiceReferenceHolderMockCreator.initContextService(); diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java index 10a89913124a..e3d8af62cb67 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java @@ -50,8 +50,6 @@ import javax.xml.stream.XMLStreamException; -import static org.mockito.ArgumentMatchers.any; - /** * ApplicationRegistrationWSWorkflowExecutor test cases */ @@ -196,7 +194,8 @@ public void testCompletingApplicationRegistrationWSWFWhenWFRejected() throws Exc applicationRegistrationWSWorkflowExecutor.setUsername(adminUsername); applicationRegistrationWSWorkflowExecutor.setPassword(adminPassword.toCharArray()); workflowDTO.setStatus(WorkflowStatus.REJECTED); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); try { Assert.assertNotNull(applicationRegistrationWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { @@ -222,7 +221,8 @@ public void testCompletingApplicationRegistrationWSWFWhenWFApproved() throws Exc applicationRegistrationWSWorkflowExecutor.setPassword(adminPassword.toCharArray()); workflowDTO.setStatus(WorkflowStatus.APPROVED); workflowDTO.setKeyManager("default"); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); try { Assert.assertNotNull(applicationRegistrationWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java index 8f58a855551b..e19c87a1be45 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java @@ -48,8 +48,6 @@ import javax.xml.stream.XMLStreamException; -import static org.mockito.ArgumentMatchers.any; - /** * SubscriptionCreationSimpleWorkflowExecutor test cases */ @@ -89,13 +87,16 @@ public void testWorkflowApprove() throws APIManagementException, WorkflowExcepti workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); workflowDTO.setStatus(WorkflowStatus.APPROVED); - PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.UNBLOCKED); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.UNBLOCKED); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); - Mockito.verify(apiMgtDAO, Mockito.times(1)).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.UNBLOCKED); + Mockito.verify(apiMgtDAO, Mockito.times(1)) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.UNBLOCKED); } @@ -105,37 +106,44 @@ public void testWorkflowReject() throws APIManagementException, WorkflowExceptio workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); workflowDTO.setStatus(WorkflowStatus.REJECTED); - PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.REJECTED); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); - Mockito.verify(apiMgtDAO, Mockito.times(1)).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); + Mockito.verify(apiMgtDAO, Mockito.times(1)) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.REJECTED); } - - @Test (expected = WorkflowException.class) + + @Test(expected = WorkflowException.class) public void testWorkflowRejectException() throws APIManagementException, WorkflowException { WorkflowDTO workflowDTO = new WorkflowDTO(); workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); workflowDTO.setStatus(WorkflowStatus.REJECTED); - PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.REJECTED); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); } - - @Test (expected = WorkflowException.class) + + @Test(expected = WorkflowException.class) public void testWorkflowApproveException() throws APIManagementException, WorkflowException { WorkflowDTO workflowDTO = new WorkflowDTO(); workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); workflowDTO.setStatus(WorkflowStatus.APPROVED); - PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.UNBLOCKED); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.UNBLOCKED); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); } @@ -146,13 +154,16 @@ public void testWorkflowNotAllowedStatus() throws APIManagementException, Workfl workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); workflowDTO.setStatus(WorkflowStatus.CREATED); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); // shouldn't update status - Mockito.verify(apiMgtDAO, Mockito.never()).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.UNBLOCKED); - Mockito.verify(apiMgtDAO, Mockito.never()).updateSubscriptionStatus( - Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); + Mockito.verify(apiMgtDAO, Mockito.never()) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.UNBLOCKED); + Mockito.verify(apiMgtDAO, Mockito.never()) + .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), + APIConstants.SubscriptionStatus.REJECTED); } @Test diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java index a5f799fa8f3a..40f27f4c6b63 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java @@ -54,8 +54,6 @@ import java.util.ArrayList; import javax.xml.stream.XMLStreamException; -import static org.mockito.ArgumentMatchers.any; - /** * UserSignUpWSWorkflowExecutor test cases */ @@ -187,9 +185,10 @@ public void testCompletingUserSignUpWorkflowApprovedByAdmin() throws Exception { PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true); Mockito.when(userStoreManager.isExistingRole(signUpRole)).thenReturn(true); - PowerMockito.doNothing().when(userStoreManager).updateRoleListOfUser(testUsername, null, new String[]{ - signUpRole}); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(userStoreManager) + .updateRoleListOfUser(testUsername, null, new String[] { signUpRole }); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); try { @@ -209,7 +208,8 @@ public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exce PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true); Mockito.when(userStoreManager.isExistingRole(signUpRole)).thenReturn(true); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); @@ -235,8 +235,8 @@ public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exce } //Test failure to complete workflow execution, when error has been occurred while retrieving signup config - PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenThrow(new APIManagementException - ("Error occurred while retrieving signup configuration")); + PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)) + .thenThrow(new APIManagementException("Error occurred while retrieving signup configuration")); try { userSignUpWSWorkflowExecutor.complete(workflowDTO); Assert.fail("Expected WorkflowException has not been thrown when signup role is not existing"); @@ -253,7 +253,8 @@ public void testCompletingUserSignUpWorkflowRejectedByAdmin() throws Exception { userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); try { @@ -271,7 +272,8 @@ public void testFailureToCompleteUserSignUpWorkflowRejectedByAdmin() throws Exce userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); - PowerMockito.doNothing().when(workflowsApiService).sendPortalNotifications(any(WorkflowDTO.class), any(String.class)); + PowerMockito.doNothing().when(workflowsApiService) + .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); Mockito.doThrow(UserStoreException.class).when(userStoreManager).deleteUser(Mockito.anyString()); diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java index daacc3c84f38..1033dccfc6ff 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java @@ -114,6 +114,7 @@ public void setDescription(String description) { } /** + * This attribute contains the comments of the user who is approving or rejecting the workflow task. **/ public WorkflowDTO comments(String comments) { this.comments = comments; diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java index a989ce1c90b1..5577a702f0e0 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/impl/NotificationsApiServiceImpl.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java index 94c873e4a1cd..e917ae8bfde7 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/NotificationsApiServiceImpl.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2005-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at From 9f0da3b789da1601af7ede8d4619646915715c23 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Wed, 1 May 2024 16:46:42 +0530 Subject: [PATCH 17/23] Modify code --- .../wso2/carbon/apimgt/impl/APIConstants.java | 6 ++--- .../PortalNotificationDAO.java | 22 +++++++++---------- .../WorkflowNotificationServiceImpl.java | 14 +++--------- .../rest/api/admin/v1/dto/WorkflowDTO.java | 1 - 4 files changed, 17 insertions(+), 26 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java index 781ab2f646ea..64f5514bc799 100755 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java @@ -1729,6 +1729,8 @@ private ConfigParameters() { public static final String DEPLOY_AS_A_PROTOTYPE = "Deploy as a Prototype"; public static final String REPUBLISH = "Re-Publish"; + public static final String RETIRE = "Retire"; + public static final String API_SPEC_TYPE_REST = "api_spec"; public static final String API_SPEC_TYPE_GRAPHQL = "sdl_schema"; public static final String API_SPEC_TYPE_ASYNC = "async_spec"; @@ -3168,8 +3170,6 @@ public static class PortalNotifications { public static final String PUBLISHER_PORTAL = "publisher"; public static final String DEV_PORTAL = "devportal"; public static final String DEFAULT_CLAIM = "http://wso2.org/claims/organization"; - public static final String API_BLOCK = "Block"; - public static final String API_DEPRECATE = "Deprecate"; - public static final String API_RETIRE = "Retire"; + public static final String APPROVED = "APPROVED"; } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java index 6b29a9dd987e..adf403cd13db 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java @@ -196,47 +196,47 @@ private String getCommentFromMetaData(String notificationMetadata, String notifi String requestedTier = (String) json.get(APIConstants.PortalNotifications.REQUESTED_TIER); String status; - if ("APPROVED".equals(comment)) { + if (APIConstants.PortalNotifications.APPROVED.equals(comment)) { status = APIConstants.PortalNotifications.STATUS_APPROVED; } else { status = APIConstants.PortalNotifications.STATUS_REJECTED; } - switch (notificationType) { - case "API_STATE_CHANGE": + switch (PortalNotificationType.valueOf(notificationType)) { + case API_STATE_CHANGE: finalComment = "API State Change request to " + action + " the API: " + apiName + ", version: " + apiVersion + " that has the context: " + apiContext + " has been " + status + "."; break; - case "API_PRODUCT_STATE_CHANGE": + case API_PRODUCT_STATE_CHANGE: finalComment = "API Product State Change request of the API PRODUCT: " + apiName + ", version: " + apiVersion + " that has the context: " + apiContext + " has been " + status + "."; break; - case "API_REVISION_DEPLOYMENT": + case API_REVISION_DEPLOYMENT: finalComment = "API Revision Deployment request of the API: " + apiName + ", version: " + apiVersion + " for RevisionId: " + revisionId + " has been " + status + "."; break; - case "APPLICATION_CREATION": + case APPLICATION_CREATION: finalComment = "Application Creation request for the Application: " + applicationName + " has been " + status + "."; break; - case "SUBSCRIPTION_CREATION": + case SUBSCRIPTION_CREATION: finalComment = "Subscription Creation request for the API: " + apiName + " version: " + apiVersion + " using Application: " + applicationName + " has been " + status + "."; break; - case "SUBSCRIPTION_UPDATE": + case SUBSCRIPTION_UPDATE: finalComment = "Subscription Update request for the " + requestedTier + " for the API: " + apiName + " version: " + apiVersion + " using Application: " + applicationName + " has been " + status + "."; break; - case "SUBSCRIPTION_DELETION": + case SUBSCRIPTION_DELETION: finalComment = "Subscription Deletion request for the API: " + apiName + " version: " + apiVersion + " using Application: " + applicationName + " has been " + status + "."; break; - case "APPLICATION_REGISTRATION_PRODUCTION": + case APPLICATION_REGISTRATION_PRODUCTION: finalComment = "Production Key Generation request for the Application: " + applicationName + " has been " + status + "."; break; - case "APPLICATION_REGISTRATION_SANDBOX": + case APPLICATION_REGISTRATION_SANDBOX: finalComment = "Sandbox Key Generation request for the Application: " + applicationName + " has been " + status + "."; break; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java index 32d62d477435..d829d2bbdd6b 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java @@ -156,10 +156,8 @@ private List getDestinationUser(WorkflowDTO workfl if (workflowDTO.getWorkflowType() .equals(WorkflowConstants.WF_TYPE_AM_API_STATE) || workflowDTO.getWorkflowType() .equals(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)) { - if (workflowDTO.getMetadata("Action") - .equals(APIConstants.PortalNotifications.API_BLOCK) || workflowDTO.getMetadata("Action") - .equals(APIConstants.PortalNotifications.API_DEPRECATE) || workflowDTO.getMetadata("Action") - .equals(APIConstants.PortalNotifications.API_RETIRE)) { + if (workflowDTO.getMetadata("Action").equals(APIConstants.BLOCK) || workflowDTO.getMetadata("Action") + .equals(APIConstants.DEPRECATE) || workflowDTO.getMetadata("Action").equals(APIConstants.RETIRE)) { String apiUUID = null; String apiName = workflowDTO.getProperties("apiName"); String apiContext = workflowDTO.getMetadata("ApiContext"); @@ -279,16 +277,11 @@ private String getAPIUUIDUsingNameContextVersion(String apiName, String apiConte */ private List getSubscribersOfAPI(String apiUUID, String organization, APIIdentifier apiIdEmailReplaced) throws APIManagementException { - return getAPIUsageByAPIId(apiUUID, organization, apiIdEmailReplaced); - } - - private List getAPIUsageByAPIId(String uuid, String organization, APIIdentifier apiIdEmailReplaced) - throws APIManagementException { List subscribedAPIs = new ArrayList<>(); Set uniqueUserSet = new HashSet<>(); try { UserApplicationAPIUsage[] allApiResult = ApiMgtDAO.getInstance() - .getAllAPIUsageByProviderAndApiId(uuid, organization); + .getAllAPIUsageByProviderAndApiId(apiUUID, organization); for (UserApplicationAPIUsage usage : allApiResult) { for (SubscribedAPI apiSubscription : usage.getApiSubscriptions()) { APIIdentifier subsApiId = apiSubscription.getAPIIdentifier(); @@ -307,7 +300,6 @@ private List getAPIUsageByAPIId(String uuid, String organization, } catch (APIManagementException e) { APIUtil.handleException("Error while getting API usage by API ID - getAPIUsageByAPIId()", e); } - return subscribedAPIs; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java index 1033dccfc6ff..daacc3c84f38 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/admin/v1/dto/WorkflowDTO.java @@ -114,7 +114,6 @@ public void setDescription(String description) { } /** - * This attribute contains the comments of the user who is approving or rejecting the workflow task. **/ public WorkflowDTO comments(String comments) { this.comments = comments; From e30488c75a4cf38ffb65d47ae238a37c9eb3be48 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Thu, 2 May 2024 09:37:48 +0530 Subject: [PATCH 18/23] Add Notification tables to all types of DBs --- .../src/main/resources/sql/db2.sql | 18 +++++++++++++++++ .../src/main/resources/sql/h2.sql | 3 --- .../src/main/resources/sql/mssql.sql | 20 +++++++++++++++++++ .../src/main/resources/sql/mysql.sql | 18 +++++++++++++++++ .../src/main/resources/sql/mysql_cluster.sql | 16 +++++++++++++++ .../src/main/resources/sql/oracle.sql | 19 +++++++++++++++++- .../src/main/resources/sql/oracle_23c.sql | 18 +++++++++++++++++ .../src/main/resources/sql/oracle_rac.sql | 19 ++++++++++++++++++ .../src/main/resources/sql/postgresql.sql | 20 +++++++++++++++++++ 9 files changed, 147 insertions(+), 4 deletions(-) diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/db2.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/db2.sql index f2d25cc9370d..a735a584b75b 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/db2.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/db2.sql @@ -3255,7 +3255,25 @@ CREATE TABLE AM_SUBJECT_ENTITY_REVOKED_EVENT ) / +CREATE TABLE AM_NOTIFICATION ( + NOTIFICATION_ID VARCHAR(64) NOT NULL UNIQUE, + NOTIFICATION_TYPE VARCHAR(50) NOT NULL, + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + NOTIFICATION_METADATA BLOB DEFAULT NULL, + PRIMARY KEY (NOTIFICATION_ID) +) +/ +CREATE TABLE AM_NOTIFICATION_END_USERS ( + NOTIFICATION_ID VARCHAR(64) NOT NULL, + DESTINATION_USER VARCHAR(255) NOT NULL, + ORGANIZATION VARCHAR(100) NOT NULL, + IS_READ BOOLEAN DEFAULT FALSE, + PORTAL_TO_DISPLAY VARCHAR(64) NOT NULL, + PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY), + FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE +) +/ diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql index 02798f7383fe..2748300df8c9 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/h2.sql @@ -2449,7 +2449,6 @@ CREATE TABLE IF NOT EXISTS AM_SUBJECT_ENTITY_REVOKED_EVENT ( PRIMARY KEY (ENTITY_ID, ENTITY_TYPE, ORGANIZATION) ); - CREATE TABLE IF NOT EXISTS AM_NOTIFICATION ( NOTIFICATION_ID VARCHAR(64) NOT NULL UNIQUE, NOTIFICATION_TYPE VARCHAR(50) NOT NULL, @@ -2468,8 +2467,6 @@ CREATE TABLE IF NOT EXISTS AM_NOTIFICATION_END_USERS ( FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE ); - - -- End of API-MGT Tables -- -- Index creation for APIM Tables diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mssql.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mssql.sql index 7ccf9e4bb3d2..08c90a1619e3 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mssql.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mssql.sql @@ -2718,6 +2718,26 @@ CREATE TABLE AM_SUBJECT_ENTITY_REVOKED_EVENT ( PRIMARY KEY (ENTITY_ID, ENTITY_TYPE, ORGANIZATION) ); +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_NOTIFICATION]') AND TYPE IN (N'U')) +CREATE TABLE AM_NOTIFICATION ( + NOTIFICATION_ID VARCHAR(64) NOT NULL UNIQUE, + NOTIFICATION_TYPE VARCHAR(50) NOT NULL, + CREATED_TIME DATETIME DEFAULT CURRENT_TIMESTAMP, + NOTIFICATION_METADATA VARBINARY(MAX) DEFAULT NULL, + PRIMARY KEY (NOTIFICATION_ID) +); + +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[AM_NOTIFICATION_END_USERS]') AND TYPE IN (N'U')) +CREATE TABLE AM_NOTIFICATION_END_USERS ( + NOTIFICATION_ID VARCHAR(64) NOT NULL, + DESTINATION_USER VARCHAR(255) NOT NULL, + ORGANIZATION VARCHAR(100) NOT NULL, + IS_READ BIT DEFAULT 0, + PORTAL_TO_DISPLAY VARCHAR(64) NOT NULL, + PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY), + FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE +); + --Performance indexes start-- create index IDX_ITS_LMT on IDN_THRIFT_SESSION (LAST_MODIFIED_TIME); diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mysql.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mysql.sql index 9638f78a38e5..b83a6e04a2d7 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mysql.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mysql.sql @@ -2473,6 +2473,24 @@ CREATE TABLE IF NOT EXISTS AM_SUBJECT_ENTITY_REVOKED_EVENT ( PRIMARY KEY (ENTITY_ID, ENTITY_TYPE, ORGANIZATION) )ENGINE INNODB; +CREATE TABLE IF NOT EXISTS AM_NOTIFICATION ( + NOTIFICATION_ID VARCHAR(64) NOT NULL UNIQUE, + NOTIFICATION_TYPE VARCHAR(50) NOT NULL, + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + NOTIFICATION_METADATA BLOB DEFAULT NULL, + PRIMARY KEY (NOTIFICATION_ID) +)ENGINE INNODB; + +CREATE TABLE IF NOT EXISTS AM_NOTIFICATION_END_USERS ( + NOTIFICATION_ID VARCHAR(64) NOT NULL, + DESTINATION_USER VARCHAR(255) NOT NULL, + ORGANIZATION VARCHAR(100) NOT NULL, + IS_READ BOOLEAN DEFAULT FALSE, + PORTAL_TO_DISPLAY VARCHAR(64) NOT NULL, + PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY), + FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE +)ENGINE INNODB; + -- Performance indexes start-- diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mysql_cluster.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mysql_cluster.sql index 64f9a447abe1..3dad0a79e1a4 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mysql_cluster.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/mysql_cluster.sql @@ -2646,7 +2646,23 @@ CREATE TABLE IF NOT EXISTS AM_SUBJECT_ENTITY_REVOKED_EVENT ( PRIMARY KEY (ENTITY_ID, ENTITY_TYPE, ORGANIZATION) )ENGINE=NDB; +CREATE TABLE IF NOT EXISTS AM_NOTIFICATION ( + NOTIFICATION_ID VARCHAR(64) NOT NULL UNIQUE, + NOTIFICATION_TYPE VARCHAR(50) NOT NULL, + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + NOTIFICATION_METADATA BLOB DEFAULT NULL, + PRIMARY KEY (NOTIFICATION_ID) +)ENGINE=NDB; +CREATE TABLE IF NOT EXISTS AM_NOTIFICATION_END_USERS ( + NOTIFICATION_ID VARCHAR(64) NOT NULL, + DESTINATION_USER VARCHAR(255) NOT NULL, + ORGANIZATION VARCHAR(100) NOT NULL, + IS_READ BOOLEAN DEFAULT 0, + PORTAL_TO_DISPLAY VARCHAR(64) NOT NULL, + PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY), + FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE +)ENGINE=NDB; -- End of API-MGT Tables -- diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle.sql index d4e87d8f85ce..5e2d86293cee 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle.sql @@ -3835,8 +3835,25 @@ CREATE TABLE AM_SUBJECT_ENTITY_REVOKED_EVENT ) / +CREATE TABLE AM_NOTIFICATION ( + NOTIFICATION_ID VARCHAR(64) NOT NULL UNIQUE, + NOTIFICATION_TYPE VARCHAR(50) NOT NULL, + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + NOTIFICATION_METADATA BLOB DEFAULT NULL, + PRIMARY KEY (NOTIFICATION_ID) +) +/ - +CREATE TABLE AM_NOTIFICATION_END_USERS ( + NOTIFICATION_ID VARCHAR(64) NOT NULL, + DESTINATION_USER VARCHAR(255) NOT NULL, + ORGANIZATION VARCHAR(100) NOT NULL, + IS_READ CHAR(1) DEFAULT 0, + PORTAL_TO_DISPLAY VARCHAR(64) NOT NULL, + PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY), + FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE +) +/ -- End of API-MGT Tables -- diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle_23c.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle_23c.sql index a04316907f90..7ca1449f30bb 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle_23c.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle_23c.sql @@ -3835,7 +3835,25 @@ CREATE TABLE AM_SUBJECT_ENTITY_REVOKED_EVENT ) / +CREATE TABLE AM_NOTIFICATION ( + NOTIFICATION_ID VARCHAR(64) NOT NULL UNIQUE, + NOTIFICATION_TYPE VARCHAR(50) NOT NULL, + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + NOTIFICATION_METADATA BLOB DEFAULT NULL, + PRIMARY KEY (NOTIFICATION_ID) +) +/ +CREATE TABLE AM_NOTIFICATION_END_USERS ( + NOTIFICATION_ID VARCHAR(64) NOT NULL, + DESTINATION_USER VARCHAR(255) NOT NULL, + ORGANIZATION VARCHAR(100) NOT NULL, + IS_READ BOOLEAN DEFAULT FALSE, + PORTAL_TO_DISPLAY VARCHAR(64) NOT NULL, + PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY), + FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE +) +/ -- End of API-MGT Tables -- diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle_rac.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle_rac.sql index d91dc23057d2..cad26be24e76 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle_rac.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/oracle_rac.sql @@ -3806,6 +3806,25 @@ CREATE TABLE AM_SUBJECT_ENTITY_REVOKED_EVENT ) / +CREATE TABLE AM_NOTIFICATION ( + NOTIFICATION_ID VARCHAR(64) NOT NULL UNIQUE, + NOTIFICATION_TYPE VARCHAR(50) NOT NULL, + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + NOTIFICATION_METADATA BLOB DEFAULT NULL, + PRIMARY KEY (NOTIFICATION_ID) +) +/ + +CREATE TABLE AM_NOTIFICATION_END_USERS ( + NOTIFICATION_ID VARCHAR(64) NOT NULL, + DESTINATION_USER VARCHAR(255) NOT NULL, + ORGANIZATION VARCHAR(100) NOT NULL, + IS_READ CHAR(1) DEFAULT 0, + PORTAL_TO_DISPLAY VARCHAR(64) NOT NULL, + PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY), + FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE +) +/ -- End of API-MGT Tables -- diff --git a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/postgresql.sql b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/postgresql.sql index f3a6e5ab6804..a1fc1ab6eabf 100644 --- a/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/postgresql.sql +++ b/features/apimgt/org.wso2.carbon.apimgt.core.feature/src/main/resources/sql/postgresql.sql @@ -2822,6 +2822,26 @@ CREATE TABLE IF NOT EXISTS AM_SUBJECT_ENTITY_REVOKED_EVENT ( PRIMARY KEY (ENTITY_ID, ENTITY_TYPE, ORGANIZATION) ); +DROP TABLE IF EXISTS AM_NOTIFICATION; +CREATE TABLE IF NOT EXISTS AM_NOTIFICATION ( + NOTIFICATION_ID VARCHAR(64) NOT NULL UNIQUE, + NOTIFICATION_TYPE VARCHAR(50) NOT NULL, + CREATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + NOTIFICATION_METADATA BYTEA DEFAULT NULL, + PRIMARY KEY (NOTIFICATION_ID) +); + +DROP TABLE IF EXISTS AM_NOTIFICATION_END_USERS; +CREATE TABLE IF NOT EXISTS AM_NOTIFICATION_END_USERS ( + NOTIFICATION_ID VARCHAR(64) NOT NULL, + DESTINATION_USER VARCHAR(255) NOT NULL, + ORGANIZATION VARCHAR(100) NOT NULL, + IS_READ BOOLEAN DEFAULT FALSE, + PORTAL_TO_DISPLAY VARCHAR(64) NOT NULL, + PRIMARY KEY (NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY), + FOREIGN KEY (NOTIFICATION_ID) REFERENCES AM_NOTIFICATION(NOTIFICATION_ID) ON DELETE CASCADE +); + -- End of API-MGT Tables -- From 898d5d6c47533aac20ba8436807f117360f9d741 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Thu, 2 May 2024 11:31:58 +0530 Subject: [PATCH 19/23] Update the code --- .../wso2/carbon/apimgt/impl/APIConstants.java | 3 +++ .../apimgt/impl/AbstractAPIManager.java | 2 +- .../PortalNotificationDAO.java | 12 +++++------- .../PortalNotificationDTO.java | 5 ++++- .../PortalNotificationEndUserDTO.java | 2 +- .../PortalNotificationService.java | 2 -- .../WorkflowNotificationServiceImpl.java | 19 ++++++++++++------- .../dao/test/PortalNotificationDAOTest.java | 8 ++++---- .../WorkflowNotificationServiceImplTest.java | 2 ++ .../v1/impl/WorkflowsApiServiceImpl.java | 1 - 10 files changed, 32 insertions(+), 24 deletions(-) rename components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/{portalNotifications => dao}/PortalNotificationDAO.java (97%) rename components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/{ => dto}/portalNotifications/PortalNotificationDTO.java (90%) rename components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/{ => dto}/portalNotifications/PortalNotificationEndUserDTO.java (96%) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java index 64f5514bc799..bc78d5a49e88 100755 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConstants.java @@ -3158,9 +3158,12 @@ public static class APILogHandler { public static class PortalNotifications { public static final String ACTION = "action"; + public static final String ACTION_META = "Action"; public static final String API_NAME = "apiName"; public static final String API_VERSION = "apiVersion"; public static final String API_CONTEXT = "apiContext"; + public static final String API_CONTEXT_META = "ApiContext"; + public static final String API_PROVIDER = "ApiProvider"; public static final String APPLICATION_NAME = "applicationName"; public static final String REQUESTED_TIER = "requestedTier"; public static final String REVISION_ID = "revisionId"; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java index 7b6edc6adc84..a025db841833 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java @@ -54,7 +54,7 @@ import org.wso2.carbon.apimgt.impl.factory.PersistenceFactory; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationDAO; +import org.wso2.carbon.apimgt.impl.dao.PortalNotificationDAO; import org.wso2.carbon.apimgt.impl.utils.*; import org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus; import org.wso2.carbon.apimgt.persistence.APIPersistence; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/PortalNotificationDAO.java similarity index 97% rename from components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java rename to components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/PortalNotificationDAO.java index adf403cd13db..939e75bda747 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/PortalNotificationDAO.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.apimgt.impl.portalNotifications; +package org.wso2.carbon.apimgt.impl.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -29,6 +29,10 @@ import org.wso2.carbon.apimgt.api.model.NotificationList; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants; +import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationMetaData; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationType; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; import java.sql.Connection; @@ -79,8 +83,6 @@ public boolean addNotification(PortalNotificationDTO portalNotificationDTO) thro } } catch (SQLException e) { - handleException("Error while adding notification - SQL", e); - } catch (APIManagementException e) { handleException("Error while adding notification", e); } return false; @@ -292,8 +294,6 @@ public Notification markNotificationAsReadById(String username, String organizat } } } catch (SQLException e) { - handleException("Failed to mark notification as read - SQL", e); - } catch (APIManagementException e) { handleException("Failed to mark notification as read", e); } return null; @@ -365,8 +365,6 @@ public NotificationList markAllNotificationsAsRead(String username, String organ return getNotifications(username, organization, portalToDisplay, "desc", 10, 0); } } catch (SQLException e) { - handleException("Failed to mark all notifications as read - SQL", e); - } catch (APIManagementException e) { handleException("Failed to mark all notifications as read", e); } return null; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationDTO.java similarity index 90% rename from components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java rename to components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationDTO.java index 0f84b201f447..dd2fe1424e61 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationDTO.java @@ -16,7 +16,10 @@ * under the License. */ -package org.wso2.carbon.apimgt.impl.portalNotifications; +package org.wso2.carbon.apimgt.impl.dto.portalNotifications; + +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationMetaData; +import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationType; import java.sql.Timestamp; import java.util.List; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationEndUserDTO.java similarity index 96% rename from components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java rename to components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationEndUserDTO.java index be8b6c03e30a..e119954ac077 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationEndUserDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationEndUserDTO.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.apimgt.impl.portalNotifications; +package org.wso2.carbon.apimgt.impl.dto.portalNotifications; public class PortalNotificationEndUserDTO { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java index d5fc3e2c3ba8..f6d962c42eea 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java @@ -18,8 +18,6 @@ package org.wso2.carbon.apimgt.impl.portalNotifications; -import org.wso2.carbon.apimgt.api.APIManagementException; - public interface PortalNotificationService { void sendPortalNotifications(T notificationObject, String tenantDomain); diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java index d829d2bbdd6b..039ec2089917 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java @@ -29,7 +29,10 @@ import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; +import org.wso2.carbon.apimgt.impl.dao.PortalNotificationDAO; import org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationEndUserDTO; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; @@ -156,13 +159,15 @@ private List getDestinationUser(WorkflowDTO workfl if (workflowDTO.getWorkflowType() .equals(WorkflowConstants.WF_TYPE_AM_API_STATE) || workflowDTO.getWorkflowType() .equals(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)) { - if (workflowDTO.getMetadata("Action").equals(APIConstants.BLOCK) || workflowDTO.getMetadata("Action") - .equals(APIConstants.DEPRECATE) || workflowDTO.getMetadata("Action").equals(APIConstants.RETIRE)) { + if (workflowDTO.getMetadata(APIConstants.PortalNotifications.ACTION_META) + .equals(APIConstants.BLOCK) || workflowDTO.getMetadata(APIConstants.PortalNotifications.ACTION_META) + .equals(APIConstants.DEPRECATE) || workflowDTO.getMetadata( + APIConstants.PortalNotifications.ACTION_META).equals(APIConstants.RETIRE)) { String apiUUID = null; - String apiName = workflowDTO.getProperties("apiName"); - String apiContext = workflowDTO.getMetadata("ApiContext"); - String apiVersion = workflowDTO.getProperties("apiVersion"); - String provider = workflowDTO.getMetadata("ApiProvider"); + String apiName = workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME); + String apiContext = workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META); + String apiVersion = workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION); + String provider = workflowDTO.getMetadata(APIConstants.PortalNotifications.API_PROVIDER); try { apiUUID = getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, workflowDTO.getTenantDomain()); @@ -230,7 +235,7 @@ private PortalNotificationMetaData getNotificationMetaData(WorkflowDTO workflowD if (WorkflowConstants.WF_TYPE_AM_API_STATE.equals( workflowDTO.getWorkflowType()) || WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE.equals( workflowDTO.getWorkflowType())) { - portalNotificationMetaData.setApiContext(workflowDTO.getMetadata("ApiContext")); + portalNotificationMetaData.setApiContext(workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META)); } return portalNotificationMetaData; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java index d9d2933a01a1..9dc0003766ad 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java @@ -35,9 +35,9 @@ import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationServiceImpl; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationDAO; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationDTO; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.dao.PortalNotificationDAO; +import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationEndUserDTO; import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationMetaData; import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationType; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; @@ -218,7 +218,7 @@ public void testAddNotificationFailure() { portalNotificationDAO.addNotification(portalNotificationDTO); }); - String expectedMessage = "Error while adding notification"; + String expectedMessage = "Error while adding end users"; String actualMessage = exception.getMessage(); Assert.assertEquals(expectedMessage, actualMessage); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java index f06bc4c4c1ae..de451118de58 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java @@ -26,7 +26,9 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.dao.PortalNotificationDAO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationDTO; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java index 7c101bb3cb56..1fa1ae1292f6 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java @@ -189,7 +189,6 @@ public Response workflowsUpdateWorkflowStatusPost(String workflowReferenceId, Wo } if (body.getComments() != null) { - System.out.println(body.getComments()); workflowDTO.setComments(body.getComments()); } From 26b4cd496946ca97a270aed7ad2d24867c8c352b Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Mon, 13 May 2024 16:38:50 +0530 Subject: [PATCH 20/23] Update the code --- .../carbon/apimgt/impl/APIConsumerImpl.java | 10 +- .../carbon/apimgt/impl/APIProviderImpl.java | 10 +- .../apimgt/impl/AbstractAPIManager.java | 6 +- ...ificationDAO.java => NotificationDAO.java} | 284 +++++++------- .../NotificationDTO.java} | 26 +- .../NotificationEndUserDTO.java} | 4 +- .../WorkflowNotificationServiceImpl.java | 362 ------------------ .../APIProductStateChangeWFNotifier.java | 82 ++++ .../APIRevisionDeploymentWFNotifier.java | 66 ++++ .../APIStateChangeWFNotifier.java | 80 ++++ .../AbstractWFNotifier.java | 210 ++++++++++ .../ApplicationCreationWFNotifier.java | 83 ++++ ...ationRegistrationProductionWFNotifier.java | 78 ++++ ...licationRegistrationSandboxWFNotifier.java | 77 ++++ .../systemNotifications/BaseNotifier.java | 43 +++ .../NotificationMetaData.java} | 4 +- .../NotificationType.java} | 4 +- .../Notifier.java} | 10 +- .../SubscriptionCreationWFNotifier.java | 86 +++++ .../SubscriptionDeletionWFNotifier.java | 87 +++++ .../SubscriptionUpdateWFNotifier.java | 87 +++++ .../WFNotifierFactory.java | 53 +++ ...ptionCreationApprovalWorkflowExecutor.java | 1 + ...nDAOTest.java => NotificationDAOTest.java} | 92 ++--- .../WorkflowNotificationServiceImplTest.java | 80 ---- ...icationCreationWSWorkflowExecutorTest.java | 18 +- ...ionRegistrationWSWorkflowExecutorTest.java | 12 +- ...riptionCreationWSWorkflowExecutorTest.java | 24 +- .../UserSignUpWSWorkflowExecutorTest.java | 16 +- .../swagger.json | 4 +- .../v1/impl/WorkflowsApiServiceImpl.java | 11 +- 31 files changed, 1293 insertions(+), 717 deletions(-) rename components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/{PortalNotificationDAO.java => NotificationDAO.java} (59%) rename components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/{portalNotifications/PortalNotificationDTO.java => systemNotifications/NotificationDTO.java} (62%) rename components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/{portalNotifications/PortalNotificationEndUserDTO.java => systemNotifications/NotificationEndUserDTO.java} (94%) delete mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIProductStateChangeWFNotifier.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIRevisionDeploymentWFNotifier.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIStateChangeWFNotifier.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/AbstractWFNotifier.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationCreationWFNotifier.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationProductionWFNotifier.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationSandboxWFNotifier.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/BaseNotifier.java rename components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/{portalNotifications/PortalNotificationMetaData.java => systemNotifications/NotificationMetaData.java} (95%) rename components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/{portalNotifications/PortalNotificationType.java => systemNotifications/NotificationType.java} (90%) rename components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/{portalNotifications/PortalNotificationService.java => systemNotifications/Notifier.java} (75%) create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionCreationWFNotifier.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionDeletionWFNotifier.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionUpdateWFNotifier.java create mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/WFNotifierFactory.java rename components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/{PortalNotificationDAOTest.java => NotificationDAOTest.java} (68%) delete mode 100644 components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java index f49eb7eabea9..9bfe347268ca 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java @@ -4612,7 +4612,7 @@ public boolean isKeyManagerByNameAllowedForUser(String keyManagerName, String or @Override public NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, Integer offset) throws APIManagementException { - return portalNotificationDAO.getNotifications(username, organization, portalToDisplay, sortOrder, limit, + return notificationDAO.getNotifications(username, organization, portalToDisplay, sortOrder, limit, offset); } @@ -4628,7 +4628,7 @@ public NotificationList getNotifications(String username, String organization, S @Override public NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) throws APIManagementException { - return portalNotificationDAO.markAllNotificationsAsRead(username, organization, portalToDisplay); + return notificationDAO.markAllNotificationsAsRead(username, organization, portalToDisplay); } /** @@ -4644,7 +4644,7 @@ public NotificationList markAllNotificationsAsRead(String username, String organ @Override public Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) throws APIManagementException { - return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId, + return notificationDAO.markNotificationAsReadById(username, organization, notificationId, portalToDisplay); } @@ -4661,7 +4661,7 @@ public Notification markNotificationAsReadById(String username, String organizat @Override public boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) throws APIManagementException { - return portalNotificationDAO.deleteNotificationById(username, organization, notificationId, portalToDisplay); + return notificationDAO.deleteNotificationById(username, organization, notificationId, portalToDisplay); } /** @@ -4676,7 +4676,7 @@ public boolean deleteNotificationById(String username, String organization, Stri @Override public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) throws APIManagementException { - return portalNotificationDAO.deleteAllNotifications(username, organization, portalToDisplay); + return notificationDAO.deleteAllNotifications(username, organization, portalToDisplay); } public static boolean hasIntersection(String[] arr1, String[] arr2) { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java index ad1eda3f8536..77464b345a0b 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java @@ -7249,7 +7249,7 @@ public int getPolicyUsageByPolicyUUIDInGatewayPolicies(String commonPolicyUUID) @Override public NotificationList getNotifications(String username, String organization, String portalToDisplay, String sortOrder, Integer limit, Integer offset) throws APIManagementException { - return portalNotificationDAO.getNotifications(username, organization, portalToDisplay, sortOrder, limit, + return notificationDAO.getNotifications(username, organization, portalToDisplay, sortOrder, limit, offset); } @@ -7265,7 +7265,7 @@ public NotificationList getNotifications(String username, String organization, S @Override public boolean deleteAllNotifications(String username, String organization, String portalToDisplay) throws APIManagementException { - return portalNotificationDAO.deleteAllNotifications(username, organization, portalToDisplay); + return notificationDAO.deleteAllNotifications(username, organization, portalToDisplay); } /** @@ -7281,7 +7281,7 @@ public boolean deleteAllNotifications(String username, String organization, Stri @Override public Notification markNotificationAsReadById(String username, String organization, String notificationId, String portalToDisplay) throws APIManagementException { - return portalNotificationDAO.markNotificationAsReadById(username, organization, notificationId, + return notificationDAO.markNotificationAsReadById(username, organization, notificationId, portalToDisplay); } @@ -7298,7 +7298,7 @@ public Notification markNotificationAsReadById(String username, String organizat @Override public boolean deleteNotificationById(String username, String organization, String notificationId, String portalToDisplay) throws APIManagementException { - return portalNotificationDAO.deleteNotificationById(username, organization, notificationId, portalToDisplay); + return notificationDAO.deleteNotificationById(username, organization, notificationId, portalToDisplay); } /** @@ -7313,7 +7313,7 @@ public boolean deleteNotificationById(String username, String organization, Stri @Override public NotificationList markAllNotificationsAsRead(String username, String organization, String portalToDisplay) throws APIManagementException { - return portalNotificationDAO.markAllNotificationsAsRead(username, organization, portalToDisplay); + return notificationDAO.markAllNotificationsAsRead(username, organization, portalToDisplay); } /** diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java index a025db841833..2ef2ef2f7ec1 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AbstractAPIManager.java @@ -54,7 +54,7 @@ import org.wso2.carbon.apimgt.impl.factory.PersistenceFactory; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.notifier.events.ApplicationEvent; -import org.wso2.carbon.apimgt.impl.dao.PortalNotificationDAO; +import org.wso2.carbon.apimgt.impl.dao.NotificationDAO; import org.wso2.carbon.apimgt.impl.utils.*; import org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus; import org.wso2.carbon.apimgt.persistence.APIPersistence; @@ -83,7 +83,7 @@ public abstract class AbstractAPIManager implements APIManager { // API definitions from swagger v2.0 protected Log log = LogFactory.getLog(getClass()); protected ApiMgtDAO apiMgtDAO; - protected PortalNotificationDAO portalNotificationDAO; + protected NotificationDAO notificationDAO; protected EnvironmentSpecificAPIPropertyDAO environmentSpecificAPIPropertyDAO; protected ScopesDAO scopesDAO; protected int tenantId = MultitenantConstants.INVALID_TENANT_ID; //-1 the issue does not occur.; @@ -107,7 +107,7 @@ public AbstractAPIManager(String username) throws APIManagementException { public AbstractAPIManager(String username, String organization) throws APIManagementException { apiMgtDAO = ApiMgtDAO.getInstance(); - portalNotificationDAO = PortalNotificationDAO.getInstance(); + notificationDAO = NotificationDAO.getInstance(); scopesDAO = ScopesDAO.getInstance(); environmentSpecificAPIPropertyDAO = EnvironmentSpecificAPIPropertyDAO.getInstance(); diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/PortalNotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/NotificationDAO.java similarity index 59% rename from components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/PortalNotificationDAO.java rename to components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/NotificationDAO.java index 939e75bda747..31456f3e887a 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/PortalNotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/NotificationDAO.java @@ -29,67 +29,65 @@ import org.wso2.carbon.apimgt.api.model.NotificationList; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants; -import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationDTO; -import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationEndUserDTO; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationMetaData; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationType; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.systemNotifications.NotificationMetaData; +import org.wso2.carbon.apimgt.impl.systemNotifications.NotificationType; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; +import java.sql.*; +import java.time.Instant; +import java.util.*; -public class PortalNotificationDAO { +public class NotificationDAO { - private static final Log log = LogFactory.getLog(PortalNotificationDAO.class); + private static final Log log = LogFactory.getLog(NotificationDAO.class); + private static final NotificationDAO INSTANCE = new NotificationDAO(); - private static PortalNotificationDAO INSTANCE = null; - - private PortalNotificationDAO() { + private NotificationDAO() { } - public static PortalNotificationDAO getInstance() { - if (INSTANCE == null) { - INSTANCE = new PortalNotificationDAO(); - } + public static NotificationDAO getInstance() { return INSTANCE; } - public boolean addNotification(PortalNotificationDTO portalNotificationDTO) throws APIManagementException { + public boolean addNotification(NotificationDTO notificationDTO) throws APIManagementException { String addNotificationQuery = SQLConstants.PortalNotifications.ADD_NOTIFICATION; String addEndUserQuery = SQLConstants.PortalNotifications.ADD_NOTIFICATION_END_USER; - try (Connection conn = APIMgtDBUtil.getConnection(); - PreparedStatement ps = conn.prepareStatement(addNotificationQuery)) { + try (Connection conn = APIMgtDBUtil.getConnection()) { + conn.setAutoCommit(false); + try (PreparedStatement ps = conn.prepareStatement(addNotificationQuery)) { - String notificationId = UUID.randomUUID().toString(); - ps.setString(1, notificationId); - ps.setString(2, portalNotificationDTO.getNotificationType().toString()); - ps.setTimestamp(3, portalNotificationDTO.getCreatedTime()); - String metadataJson = convertMetadataToJson(portalNotificationDTO.getNotificationMetadata()); - ps.setString(4, metadataJson); - - int rowsAffected = ps.executeUpdate(); - if (rowsAffected > 0) { - for (PortalNotificationEndUserDTO endUser : portalNotificationDTO.getEndUsers()) { - addEndUser(conn, addEndUserQuery, notificationId, endUser); + String notificationId = UUID.randomUUID().toString(); + ps.setString(1, notificationId); + ps.setString(2, notificationDTO.getNotificationType().toString()); + ps.setTimestamp(3, Timestamp.from(Instant.now())); + String metadataJson = convertMetadataToJson(notificationDTO.getNotificationMetadata()); + ps.setString(4, metadataJson); + + int rowsAffected = ps.executeUpdate(); + + if (rowsAffected > 0) { + for (NotificationEndUserDTO endUser : notificationDTO.getEndUsers()) { + addEndUser(conn, addEndUserQuery, notificationId, endUser); + } + conn.commit(); + return true; } - return true; + } catch (SQLException e) { + conn.rollback(); + handleException("Error while adding notification", e); } - } catch (SQLException e) { - handleException("Error while adding notification", e); + handleException("Error while establishing database connection", e); } return false; } private void addEndUser(Connection conn, String addEndUserQuery, String notificationId, - PortalNotificationEndUserDTO endUser) throws APIManagementException { + NotificationEndUserDTO endUser) throws SQLException { try (PreparedStatement ps = conn.prepareStatement(addEndUserQuery)) { ps.setString(1, notificationId); @@ -97,12 +95,10 @@ private void addEndUser(Connection conn, String addEndUserQuery, String notifica ps.setString(3, endUser.getOrganization()); ps.setString(4, endUser.getPortalToDisplay()); ps.executeUpdate(); - } catch (SQLException e) { - handleException("Error while adding end users", e); } } - private String convertMetadataToJson(PortalNotificationMetaData metaData) { + private String convertMetadataToJson(NotificationMetaData metaData) { JSONObject json = new JSONObject(); json.put(APIConstants.PortalNotifications.API_NAME, metaData.getApi()); json.put(APIConstants.PortalNotifications.API_VERSION, metaData.getApiVersion()); @@ -128,50 +124,54 @@ public NotificationList getNotifications(String username, String organization, S String sqlQueryForCount = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_COUNT; String sqlQuery; - try (Connection conn = APIMgtDBUtil.getConnection(); - PreparedStatement psForCount = conn.prepareStatement(sqlQueryForCount)) { - psForCount.setString(1, username); - psForCount.setString(2, organization); - psForCount.setString(3, portalToDisplay); - try (ResultSet rsForCount = psForCount.executeQuery()) { - while (rsForCount.next()) { - total = rsForCount.getInt("NOTIFICATION_COUNT"); - } - if (total > 0 && limit > 0) { - if (sortOrder != null && sortOrder.equals("asc")) { - sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_ASC; - } else { - sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_DESC; + try (Connection conn = APIMgtDBUtil.getConnection()) { + try (PreparedStatement psForCount = conn.prepareStatement(sqlQueryForCount)) { + psForCount.setString(1, username); + psForCount.setString(2, organization); + psForCount.setString(3, portalToDisplay); + try (ResultSet rsForCount = psForCount.executeQuery()) { + while (rsForCount.next()) { + total = rsForCount.getInt("NOTIFICATION_COUNT"); } - try (PreparedStatement ps = conn.prepareStatement(sqlQuery)) { - ps.setString(1, username); - ps.setString(2, organization); - ps.setString(3, portalToDisplay); - ps.setInt(4, offset); - ps.setInt(5, limit); - try (ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - Notification notification = new Notification(); - notification.setNotificationId(rs.getString("NOTIFICATION_ID")); - notification.setNotificationType(rs.getString("NOTIFICATION_TYPE")); - notification.setCreatedTime(rs.getTimestamp("CREATED_TIME").toString()); - notification.setComments(getCommentFromMetaData(rs.getString("NOTIFICATION_METADATA"), - rs.getString("NOTIFICATION_TYPE"))); - notification.setIsRead(rs.getBoolean("IS_READ")); - list.add(notification); + if (total > 0 && limit > 0) { + if (sortOrder != null && sortOrder.equals("asc")) { + sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_ASC; + } else { + sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATIONS_DESC; + } + try (PreparedStatement ps = conn.prepareStatement(sqlQuery)) { + ps.setString(1, username); + ps.setString(2, organization); + ps.setString(3, portalToDisplay); + ps.setInt(4, offset); + ps.setInt(5, limit); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + Notification notification = new Notification(); + notification.setNotificationId(rs.getString("NOTIFICATION_ID")); + notification.setNotificationType(rs.getString("NOTIFICATION_TYPE")); + notification.setCreatedTime(rs.getTimestamp("CREATED_TIME").toString()); + notification.setComments(getCommentFromMetaData(rs.getString("NOTIFICATION_METADATA"), + rs.getString("NOTIFICATION_TYPE"))); + notification.setIsRead(rs.getBoolean("IS_READ")); + list.add(notification); + } } } + } else { + notificationList.getPagination().setTotal(total); + notificationList.setCount(total); + return notificationList; } - } else { - notificationList.getPagination().setTotal(total); - notificationList.setCount(total); - return notificationList; } + unreadCount = getUnreadNotificationCount(username, organization, portalToDisplay, conn); + } catch (SQLException e) { + handleException("Failed to retrieve notifications of the user " + username, e); } - unreadCount = getUnreadNotificationCount(username, organization, portalToDisplay, conn); } catch (SQLException e) { - handleException("Failed to retrieve notifications of the user " + username, e); + handleException("Failed to establish database connection", e); } + pagination.setLimit(limit); pagination.setOffset(offset); notificationList.getPagination().setTotal(total); @@ -204,7 +204,7 @@ private String getCommentFromMetaData(String notificationMetadata, String notifi status = APIConstants.PortalNotifications.STATUS_REJECTED; } - switch (PortalNotificationType.valueOf(notificationType)) { + switch (NotificationType.valueOf(notificationType)) { case API_STATE_CHANGE: finalComment = "API State Change request to " + action + " the API: " + apiName + ", version: " + apiVersion + " that has the context: " + apiContext + " has been " + status + "."; @@ -244,7 +244,7 @@ private String getCommentFromMetaData(String notificationMetadata, String notifi break; } - if (!comment.equals("APPROVED")) { + if (!APIConstants.PortalNotifications.APPROVED.equals(comment)) { finalComment = finalComment + " Reason: " + comment; } @@ -258,21 +258,29 @@ public boolean deleteAllNotifications(String username, String organization, Stri throws APIManagementException { String sqlQuery = SQLConstants.PortalNotifications.DELETE_ALL_NOTIFICATIONS_OF_USER; - try (Connection conn = APIMgtDBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sqlQuery)) { - ps.setString(1, username); - ps.setString(2, organization); - ps.setString(3, portalToDisplay); - int rowsAffected = ps.executeUpdate(); - if (rowsAffected > 0) { - String deleteNotification = SQLConstants.PortalNotifications.DELETE_NOTIFICATIONS; - try (PreparedStatement preparedStatement = conn.prepareStatement(deleteNotification)) { - preparedStatement.executeUpdate(); + try (Connection conn = APIMgtDBUtil.getConnection()){ + conn.setAutoCommit(false); + try ( PreparedStatement ps = conn.prepareStatement(sqlQuery)) { + ps.setString(1, username); + ps.setString(2, organization); + ps.setString(3, portalToDisplay); + int rowsAffected = ps.executeUpdate(); + if (rowsAffected > 0) { + String deleteNotification = SQLConstants.PortalNotifications.DELETE_NOTIFICATIONS; + try (PreparedStatement preparedStatement = conn.prepareStatement(deleteNotification)) { + preparedStatement.executeUpdate(); + } + conn.commit(); + return true; } - return true; + } catch (SQLException e) { + conn.rollback(); + handleException("Failed to delete notifications", e); } } catch (SQLException e) { - handleException("Failed to delete notifications", e); + handleException("Error while establishing database connection", e); } + return false; } @@ -281,26 +289,34 @@ public Notification markNotificationAsReadById(String username, String organizat Notification notification; String sqlQuery = SQLConstants.PortalNotifications.MARK_NOTIFICATION_AS_READ; - try (Connection conn = APIMgtDBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sqlQuery)) { - ps.setString(1, notificationId); - ps.setString(2, username); - ps.setString(3, organization); - ps.setString(4, portalToDisplay); - int rowsAffected = ps.executeUpdate(); - if (rowsAffected > 0) { - notification = getNotificationById(notificationId, username, organization, portalToDisplay, conn); - if (notification != null) { - return notification; + + try (Connection conn = APIMgtDBUtil.getConnection()) { + conn.setAutoCommit(false); + try (PreparedStatement ps = conn.prepareStatement(sqlQuery)) { + ps.setString(1, notificationId); + ps.setString(2, username); + ps.setString(3, organization); + ps.setString(4, portalToDisplay); + int rowsAffected = ps.executeUpdate(); + if (rowsAffected > 0) { + notification = getNotificationById(notificationId, username, organization, portalToDisplay, conn); + if (notification != null) { + conn.commit(); + return notification; + } } + } catch (SQLException e) { + conn.rollback(); + handleException("Failed to mark notification as read", e); } } catch (SQLException e) { - handleException("Failed to mark notification as read", e); + handleException("Failed to establish database connection", e); } return null; } private Notification getNotificationById(String notificationId, String username, String organization, - String portalToDisplay, Connection conn) throws APIManagementException { + String portalToDisplay, Connection conn) throws SQLException { String sqlQuery = SQLConstants.PortalNotifications.GET_NOTIFICATION_BY_ID; try (PreparedStatement ps = conn.prepareStatement(sqlQuery)) { @@ -320,9 +336,6 @@ private Notification getNotificationById(String notificationId, String username, return notification; } } - - } catch (SQLException e) { - handleException("Failed to retrieve notification by id", e); } return null; } @@ -331,21 +344,29 @@ public boolean deleteNotificationById(String username, String organization, Stri String portalToDisplay) throws APIManagementException { String sqlQuery = SQLConstants.PortalNotifications.DELETE_NOTIFICATION_BY_ID; - try (Connection conn = APIMgtDBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sqlQuery)) { - ps.setString(1, notificationId); - ps.setString(2, username); - ps.setString(3, organization); - ps.setString(4, portalToDisplay); - int rowsAffected = ps.executeUpdate(); - if (rowsAffected > 0) { - String deleteNotification = SQLConstants.PortalNotifications.DELETE_NOTIFICATIONS; - try (PreparedStatement preparedStatement = conn.prepareStatement(deleteNotification)) { - preparedStatement.executeUpdate(); + + try (Connection conn = APIMgtDBUtil.getConnection()) { + conn.setAutoCommit(false); + try (PreparedStatement ps = conn.prepareStatement(sqlQuery)) { + ps.setString(1, notificationId); + ps.setString(2, username); + ps.setString(3, organization); + ps.setString(4, portalToDisplay); + int rowsAffected = ps.executeUpdate(); + if (rowsAffected > 0) { + String deleteNotification = SQLConstants.PortalNotifications.DELETE_NOTIFICATIONS; + try (PreparedStatement preparedStatement = conn.prepareStatement(deleteNotification)) { + preparedStatement.executeUpdate(); + } + conn.commit(); + return true; } - return true; + } catch (SQLException e) { + conn.rollback(); + handleException("Failed to delete notification by id", e); } } catch (SQLException e) { - handleException("Failed to delete notification by id", e); + handleException("Failed to establish database connection", e); } return false; } @@ -355,17 +376,24 @@ public NotificationList markAllNotificationsAsRead(String username, String organ String sqlQuery = SQLConstants.PortalNotifications.MARK_ALL_NOTIFICATIONS_AS_READ; - try (Connection connection = APIMgtDBUtil.getConnection(); - PreparedStatement ps = connection.prepareStatement(sqlQuery)) { - ps.setString(1, username); - ps.setString(2, organization); - ps.setString(3, portalToDisplay); - int rowsAffected = ps.executeUpdate(); - if (rowsAffected > 0) { - return getNotifications(username, organization, portalToDisplay, "desc", 10, 0); + try (Connection connection = APIMgtDBUtil.getConnection()) { + connection.setAutoCommit(false); + try (PreparedStatement ps = connection.prepareStatement(sqlQuery)) { + ps.setString(1, username); + ps.setString(2, organization); + ps.setString(3, portalToDisplay); + int rowsAffected = ps.executeUpdate(); + if (rowsAffected > 0) { + NotificationList notifications = getNotifications(username, organization, portalToDisplay, "desc", 10, 0); + connection.commit(); + return notifications; + } + } catch (SQLException e) { + connection.rollback(); + handleException("Failed to mark all notifications as read", e); } } catch (SQLException e) { - handleException("Failed to mark all notifications as read", e); + handleException("Failed to establish database connection", e); } return null; } @@ -375,6 +403,7 @@ public String getAPIUUIDUsingNameContextVersion(String apiName, String apiContex String apiUUID = null; String sqlQuery = SQLConstants.PortalNotifications.GET_API_UUID_USING_NAME_CONTEXT_VERSION; + try (Connection connection = APIMgtDBUtil.getConnection(); PreparedStatement ps = connection.prepareStatement(sqlQuery)) { ps.setString(1, apiName); @@ -387,10 +416,9 @@ public String getAPIUUIDUsingNameContextVersion(String apiName, String apiContex } } } catch (SQLException e) { - handleException("Failed to retrieve API UUID using name, context and version", e); + handleException("Failed to retrieve API UUID using name, context, and version", e); } return apiUUID; - } public int getUnreadNotificationCount(String username, String organization, String portalToDisplay, Connection conn) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/systemNotifications/NotificationDTO.java similarity index 62% rename from components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationDTO.java rename to components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/systemNotifications/NotificationDTO.java index dd2fe1424e61..753730220d4d 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/systemNotifications/NotificationDTO.java @@ -16,21 +16,21 @@ * under the License. */ -package org.wso2.carbon.apimgt.impl.dto.portalNotifications; +package org.wso2.carbon.apimgt.impl.dto.systemNotifications; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationMetaData; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationType; +import org.wso2.carbon.apimgt.impl.systemNotifications.NotificationMetaData; +import org.wso2.carbon.apimgt.impl.systemNotifications.NotificationType; import java.sql.Timestamp; import java.util.List; -public class PortalNotificationDTO { +public class NotificationDTO { private String notificationId; - private PortalNotificationType notificationType; + private NotificationType notificationType; private Timestamp createdTime; - private PortalNotificationMetaData notificationMetadata; - private List endUsers; + private NotificationMetaData notificationMetadata; + private List endUsers; public String getNotificationId() { return notificationId; @@ -40,11 +40,11 @@ public void setNotificationId(String notificationId) { this.notificationId = notificationId; } - public PortalNotificationType getNotificationType() { + public NotificationType getNotificationType() { return notificationType; } - public void setNotificationType(PortalNotificationType notificationType) { + public void setNotificationType(NotificationType notificationType) { this.notificationType = notificationType; } @@ -56,19 +56,19 @@ public void setCreatedTime(Timestamp createdTime) { this.createdTime = createdTime; } - public PortalNotificationMetaData getNotificationMetadata() { + public NotificationMetaData getNotificationMetadata() { return notificationMetadata; } - public void setNotificationMetadata(PortalNotificationMetaData notificationMetadata) { + public void setNotificationMetadata(NotificationMetaData notificationMetadata) { this.notificationMetadata = notificationMetadata; } - public List getEndUsers() { + public List getEndUsers() { return endUsers; } - public void setEndUsers(List endUsers) { + public void setEndUsers(List endUsers) { this.endUsers = endUsers; } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationEndUserDTO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/systemNotifications/NotificationEndUserDTO.java similarity index 94% rename from components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationEndUserDTO.java rename to components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/systemNotifications/NotificationEndUserDTO.java index e119954ac077..b876b7b1e3dc 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/portalNotifications/PortalNotificationEndUserDTO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dto/systemNotifications/NotificationEndUserDTO.java @@ -16,9 +16,9 @@ * under the License. */ -package org.wso2.carbon.apimgt.impl.dto.portalNotifications; +package org.wso2.carbon.apimgt.impl.dto.systemNotifications; -public class PortalNotificationEndUserDTO { +public class NotificationEndUserDTO { private String notificationId; private String destinationUser; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java deleted file mode 100644 index 039ec2089917..000000000000 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImpl.java +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.apimgt.impl.portalNotifications; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.api.APIManagementException; -import org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage; -import org.wso2.carbon.apimgt.api.model.APIIdentifier; -import org.wso2.carbon.apimgt.api.model.Application; -import org.wso2.carbon.apimgt.api.model.SubscribedAPI; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; -import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; -import org.wso2.carbon.apimgt.impl.dao.PortalNotificationDAO; -import org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO; -import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationDTO; -import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationEndUserDTO; -import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; -import org.wso2.carbon.apimgt.impl.utils.APIUtil; -import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.UserRealm; -import org.wso2.carbon.user.core.UserStoreManager; -import org.wso2.carbon.user.core.common.AbstractUserStoreManager; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; -import org.wso2.carbon.user.core.common.User; -import org.wso2.carbon.user.core.service.RealmService; - -/** - * This class used to insert workflow related notifications to the database, - * whenever admin approves or rejects a workflow request - */ -public class WorkflowNotificationServiceImpl implements PortalNotificationService { - - private static final Log log = LogFactory.getLog(WorkflowNotificationServiceImpl.class); - - /** - * This method will insert workflow related notifications to the database - * - * @param workflowDTO WorkflowDTO object that contains the workflow details - * @param tenantDomainOfUser Tenant domain of the user - */ - public void sendPortalNotifications(WorkflowDTO workflowDTO, String tenantDomainOfUser) { - try { - PortalNotificationDTO portalNotificationsDTO = new PortalNotificationDTO(); - portalNotificationsDTO.setNotificationType(getNotificationType(workflowDTO.getWorkflowType())); - portalNotificationsDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); - portalNotificationsDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); - portalNotificationsDTO.setEndUsers(getDestinationUser(workflowDTO, tenantDomainOfUser)); - - boolean result = PortalNotificationDAO.getInstance().addNotification(portalNotificationsDTO); - - if (!result) { - log.error("Error while adding publisher developer notification - sendPortalNotifications()"); - } - } catch (APIManagementException e) { - log.error("Error while sending portal notifications"); - } - } - - /** - * This method will return the type of the notification - * - * @param workflowType workflow type - * @return PortalNotificationType type of the notification - */ - private PortalNotificationType getNotificationType(String workflowType) { - switch (workflowType) { - case WorkflowConstants.WF_TYPE_AM_API_STATE: - return PortalNotificationType.API_STATE_CHANGE; - case WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE: - return PortalNotificationType.API_PRODUCT_STATE_CHANGE; - case WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION: - return PortalNotificationType.APPLICATION_CREATION; - case WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT: - return PortalNotificationType.API_REVISION_DEPLOYMENT; - case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION: - return PortalNotificationType.APPLICATION_REGISTRATION_PRODUCTION; - case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX: - return PortalNotificationType.APPLICATION_REGISTRATION_SANDBOX; - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION: - return PortalNotificationType.SUBSCRIPTION_CREATION; - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE: - return PortalNotificationType.SUBSCRIPTION_UPDATE; - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION: - return PortalNotificationType.SUBSCRIPTION_DELETION; - } - return null; - } - - /** - * This method will return a list of users that need to send notifications based on the workflow type - * - * @param workflowDTO WorkflowDTO object that contains the workflow details - * @param tenantDomainOfUser Tenant domain of the user - * @return list of PortalNotificationEndUserDTO objects - */ - private List getDestinationUser(WorkflowDTO workflowDTO, String tenantDomainOfUser) - throws APIManagementException { - List destinationUserList = new ArrayList<>(); - String destinationUser = null; - - switch (workflowDTO.getWorkflowType()) { - case WorkflowConstants.WF_TYPE_AM_API_STATE: - case WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE: - destinationUser = workflowDTO.getMetadata("Invoker"); - break; - - case WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION: - case WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT: - case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION: - case WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX: - destinationUser = workflowDTO.getProperties("userName"); - break; - - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION: - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE: - case WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION: - destinationUser = workflowDTO.getProperties("subscriber"); - break; - - case WorkflowConstants.WF_TYPE_AM_USER_SIGNUP: - destinationUser = workflowDTO.getMetadata("userName"); - break; - } - - if (destinationUser != null) { - PortalNotificationEndUserDTO endUser = new PortalNotificationEndUserDTO(); - endUser.setDestinationUser(destinationUser); - endUser.setOrganization(workflowDTO.getTenantDomain()); - endUser.setPortalToDisplay(setPortalToDisplay(workflowDTO.getWorkflowType())); - destinationUserList.add(endUser); - } - - if (workflowDTO.getWorkflowType() - .equals(WorkflowConstants.WF_TYPE_AM_API_STATE) || workflowDTO.getWorkflowType() - .equals(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)) { - if (workflowDTO.getMetadata(APIConstants.PortalNotifications.ACTION_META) - .equals(APIConstants.BLOCK) || workflowDTO.getMetadata(APIConstants.PortalNotifications.ACTION_META) - .equals(APIConstants.DEPRECATE) || workflowDTO.getMetadata( - APIConstants.PortalNotifications.ACTION_META).equals(APIConstants.RETIRE)) { - String apiUUID = null; - String apiName = workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME); - String apiContext = workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META); - String apiVersion = workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION); - String provider = workflowDTO.getMetadata(APIConstants.PortalNotifications.API_PROVIDER); - try { - apiUUID = getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, - workflowDTO.getTenantDomain()); - APIIdentifier apiIdEmailReplaced = new APIIdentifier(APIUtil.replaceEmailDomain(provider), apiName, - apiVersion); - List subscribers = getSubscribersOfAPI(apiUUID, workflowDTO.getTenantDomain(), - apiIdEmailReplaced); - for (SubscribedAPI subscriber : subscribers) { - PortalNotificationEndUserDTO endUser = new PortalNotificationEndUserDTO(); - endUser.setDestinationUser(subscriber.getSubscriber().getName()); - endUser.setOrganization(subscriber.getOrganization()); - endUser.setPortalToDisplay(APIConstants.PortalNotifications.DEV_PORTAL); - destinationUserList.add(endUser); - } - } catch (APIManagementException e) { - APIUtil.handleException("Error while getting subscribers of API - getDestinationUser()", e); - } - } - } - - if (APIUtil.isMultiGroupAppSharingEnabled()) { - try { - List users = getAllUsersBelongToGroup(workflowDTO, tenantDomainOfUser); - for (User user : users) { - PortalNotificationEndUserDTO endUser = new PortalNotificationEndUserDTO(); - if (user.getUsername().equals(destinationUser)) { - continue; - } - endUser.setDestinationUser(user.getUsername()); - endUser.setOrganization(user.getTenantDomain()); - endUser.setPortalToDisplay(APIConstants.PortalNotifications.DEV_PORTAL); - destinationUserList.add(endUser); - } - } catch (APIManagementException e) { - APIUtil.handleException("Error while getting users belong to group - getDestinationUser()", e); - } catch (UserStoreException e) { - APIUtil.handleException("User-Store Exception ", e); - } - } - - return destinationUserList; - } - - /** - * This method will return a PortalNotificationMetaData object containing metadata related to the notification - * - * @param workflowDTO WorkflowDTO object that contains the workflow details - * @return PortalNotificationMetaData object containing metadata related to the notification - */ - private PortalNotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { - PortalNotificationMetaData portalNotificationMetaData = new PortalNotificationMetaData(); - - portalNotificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); - portalNotificationMetaData.setApiVersion( - workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); - portalNotificationMetaData.setAction(workflowDTO.getProperties(APIConstants.PortalNotifications.ACTION)); - portalNotificationMetaData.setApplicationName( - workflowDTO.getProperties(APIConstants.PortalNotifications.APPLICATION_NAME)); - portalNotificationMetaData.setRequestedTier( - workflowDTO.getProperties(APIConstants.PortalNotifications.REQUESTED_TIER)); - portalNotificationMetaData.setRevisionId( - workflowDTO.getProperties(APIConstants.PortalNotifications.REVISION_ID)); - portalNotificationMetaData.setComment(workflowDTO.getComments()); - - if (WorkflowConstants.WF_TYPE_AM_API_STATE.equals( - workflowDTO.getWorkflowType()) || WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE.equals( - workflowDTO.getWorkflowType())) { - portalNotificationMetaData.setApiContext(workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META)); - } - - return portalNotificationMetaData; - } - - /** - * This method will return the portal that the notifications should display - * - * @param workflowType workflow type - * @return the portal that the notifications should display - */ - private String setPortalToDisplay(String workflowType) { - switch (workflowType) { - case WorkflowConstants.WF_TYPE_AM_API_STATE: - case WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE: - case WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT: - return APIConstants.PortalNotifications.PUBLISHER_PORTAL; - default: - return APIConstants.PortalNotifications.DEV_PORTAL; - } - } - - /** - * This method will return the UUID of a given API - * - * @param apiName Name of the API - * @param apiContext Context of the API - * @param apiVersion Version of the API - * @return the UUID of the API - */ - private String getAPIUUIDUsingNameContextVersion(String apiName, String apiContext, String apiVersion, - String organization) throws APIManagementException { - return PortalNotificationDAO.getInstance() - .getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, organization); - } - - /** - * This method will return the list of subscribers of a given API - * - * @param apiUUID UUID of the API - * @param organization Organization of the API - * @param apiIdEmailReplaced APIIdentifier object with email replaced provider name - * @return the subscribers of the API - */ - private List getSubscribersOfAPI(String apiUUID, String organization, - APIIdentifier apiIdEmailReplaced) throws APIManagementException { - List subscribedAPIs = new ArrayList<>(); - Set uniqueUserSet = new HashSet<>(); - try { - UserApplicationAPIUsage[] allApiResult = ApiMgtDAO.getInstance() - .getAllAPIUsageByProviderAndApiId(apiUUID, organization); - for (UserApplicationAPIUsage usage : allApiResult) { - for (SubscribedAPI apiSubscription : usage.getApiSubscriptions()) { - APIIdentifier subsApiId = apiSubscription.getAPIIdentifier(); - APIIdentifier subsApiIdEmailReplaced = new APIIdentifier( - APIUtil.replaceEmailDomain(subsApiId.getProviderName()), subsApiId.getApiName(), - subsApiId.getVersion()); - if (subsApiIdEmailReplaced.equals(apiIdEmailReplaced)) { - String userIdentifier = apiSubscription.getSubscriber() - .getName() + "-" + apiSubscription.getOrganization(); - if (uniqueUserSet.add(userIdentifier)) { - subscribedAPIs.add(apiSubscription); - } - } - } - } - } catch (APIManagementException e) { - APIUtil.handleException("Error while getting API usage by API ID - getAPIUsageByAPIId()", e); - } - return subscribedAPIs; - } - - /** - * This method will return all the users belongs to a given group - * - * @param workflowDTO WorkflowDTO object that contains the workflow details - * @param tenantDomainOfUser Tenant domain of the user - * @return a list of users belongs to a given group - */ - private List getAllUsersBelongToGroup(WorkflowDTO workflowDTO, String tenantDomainOfUser) - throws APIManagementException, UserStoreException { - List users = new ArrayList<>(); - String groupId = null; - if (workflowDTO.getWorkflowType().equals(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION)) { - String applicationId = workflowDTO.getWorkflowReference(); - int appId = Integer.parseInt(applicationId); - ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance(); - Application application = apiMgtDAO.getApplicationById(appId); - groupId = application.getGroupId(); - } else if (workflowDTO.getWorkflowType() - .equals(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION) || workflowDTO.getWorkflowType() - .equals(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE) || workflowDTO.getWorkflowType() - .equals(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION)) { - SubscribedAPI sub = ApiMgtDAO.getInstance() - .getSubscriptionById(Integer.parseInt(workflowDTO.getWorkflowReference())); - groupId = sub.getApplication().getGroupId(); - } else if (workflowDTO.getWorkflowType() - .equals(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION) || workflowDTO.getWorkflowType() - .equals(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX)) { - groupId = ((ApplicationRegistrationWorkflowDTO) workflowDTO).getApplication().getGroupId(); - } - - if (groupId != null) { - int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() - .getTenantId(tenantDomainOfUser); - RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService(); - UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId); - if (realm != null) { - UserStoreManager manager = realm.getUserStoreManager(); - AbstractUserStoreManager abstractManager = (AbstractUserStoreManager) manager; - APIManagerConfiguration config = ServiceReferenceHolder.getInstance() - .getAPIManagerConfigurationService().getAPIManagerConfiguration(); - String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI); - if (StringUtils.isBlank(claim)) { - claim = APIConstants.PortalNotifications.DEFAULT_CLAIM; - } - users = abstractManager.getUserListWithID(claim, groupId, "default"); - } - - } - return users; - } - -} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIProductStateChangeWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIProductStateChangeWFNotifier.java new file mode 100644 index 000000000000..20f2babc460d --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIProductStateChangeWFNotifier.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; + +import java.util.ArrayList; +import java.util.List; + +public class APIProductStateChangeWFNotifier extends AbstractWFNotifier { + private static final Log log = LogFactory.getLog(APIProductStateChangeWFNotifier.class); + + @Override + public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIManagementException { + NotificationDTO notificationDTO = new NotificationDTO(); + notificationDTO.setNotificationType(NotificationType.API_PRODUCT_STATE_CHANGE); + notificationDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + notificationDTO.setEndUsers(getEndUsers(workflowDTO)); + return notificationDTO; + } + + @Override + public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { + NotificationMetaData notificationMetaData = new NotificationMetaData(); + + notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); + notificationMetaData.setApiVersion( + workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setAction(workflowDTO.getProperties(APIConstants.PortalNotifications.ACTION)); + notificationMetaData.setRevisionId( + workflowDTO.getProperties(APIConstants.PortalNotifications.REVISION_ID)); + notificationMetaData.setComment(workflowDTO.getComments()); + notificationMetaData.setApiContext( + workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META)); + + return notificationMetaData; + } + + @Override + public List getEndUsers(WorkflowDTO workflowDTO) throws APIManagementException { + List destinationUserList = new ArrayList<>(); + //add primary user + String destinationUser = workflowDTO.getMetadata("Invoker"); + destinationUserList.add(getPrimaryUser(destinationUser, workflowDTO.getTenantDomain(), + APIConstants.PortalNotifications.PUBLISHER_PORTAL)); + + // add subscribers + String apiName = workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME); + String apiContext = workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META); + String apiVersion = workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION); + String provider = workflowDTO.getMetadata(APIConstants.PortalNotifications.API_PROVIDER); + String tenantDomain = workflowDTO.getTenantDomain(); + String apiAction = workflowDTO.getMetadata(APIConstants.PortalNotifications.ACTION_META); + destinationUserList.addAll( + getSubscriberListOfAPI(apiAction, apiName, apiContext, apiVersion, provider, tenantDomain)); + + return destinationUserList; + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIRevisionDeploymentWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIRevisionDeploymentWFNotifier.java new file mode 100644 index 000000000000..c4126a0cbd22 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIRevisionDeploymentWFNotifier.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; + +import java.util.ArrayList; +import java.util.List; + +public class APIRevisionDeploymentWFNotifier extends AbstractWFNotifier { + private static final Log log = LogFactory.getLog(APIRevisionDeploymentWFNotifier.class); + + @Override + public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) { + NotificationDTO notificationDTO = new NotificationDTO(); + notificationDTO.setNotificationType(NotificationType.API_REVISION_DEPLOYMENT); + notificationDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + notificationDTO.setEndUsers(getEndUsers(workflowDTO)); + return notificationDTO; + } + + @Override + public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { + NotificationMetaData notificationMetaData = new NotificationMetaData(); + notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); + notificationMetaData.setApiVersion( + workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setRevisionId( + workflowDTO.getProperties(APIConstants.PortalNotifications.REVISION_ID)); + notificationMetaData.setComment(workflowDTO.getComments()); + return notificationMetaData; + } + + @Override + public List getEndUsers(WorkflowDTO workflowDTO) { + List destinationUserList = new ArrayList<>(); + //add primary user + String destinationUser = workflowDTO.getProperties("userName"); + destinationUserList.add(getPrimaryUser(destinationUser, workflowDTO.getTenantDomain(), + APIConstants.PortalNotifications.PUBLISHER_PORTAL)); + + return destinationUserList; + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIStateChangeWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIStateChangeWFNotifier.java new file mode 100644 index 000000000000..6d6a48c297b3 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIStateChangeWFNotifier.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; + +import java.util.ArrayList; +import java.util.List; + +public class APIStateChangeWFNotifier extends AbstractWFNotifier { + private static final Log log = LogFactory.getLog(APIStateChangeWFNotifier.class); + + @Override + public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIManagementException { + NotificationDTO notificationDTO = new NotificationDTO(); + notificationDTO.setNotificationType(NotificationType.API_STATE_CHANGE); + notificationDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + notificationDTO.setEndUsers(getEndUsers(workflowDTO)); + return notificationDTO; + } + + @Override + public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { + NotificationMetaData notificationMetaData = new NotificationMetaData(); + + notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); + notificationMetaData.setApiVersion( + workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setAction(workflowDTO.getProperties(APIConstants.PortalNotifications.ACTION)); + notificationMetaData.setComment(workflowDTO.getComments()); + notificationMetaData.setApiContext( + workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META)); + + return notificationMetaData; + } + + @Override + public List getEndUsers(WorkflowDTO workflowDTO) throws APIManagementException { + List destinationUserList = new ArrayList<>(); + //add primary user + String destinationUser = workflowDTO.getMetadata("Invoker"); + destinationUserList.add(getPrimaryUser(destinationUser, workflowDTO.getTenantDomain(), + APIConstants.PortalNotifications.PUBLISHER_PORTAL)); + + // add subscribers + String apiName = workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME); + String apiContext = workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META); + String apiVersion = workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION); + String provider = workflowDTO.getMetadata(APIConstants.PortalNotifications.API_PROVIDER); + String tenantDomain = workflowDTO.getTenantDomain(); + String apiAction = workflowDTO.getMetadata(APIConstants.PortalNotifications.ACTION_META); + destinationUserList.addAll( + getSubscriberListOfAPI(apiAction, apiName, apiContext, apiVersion, provider, tenantDomain)); + + return destinationUserList; + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/AbstractWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/AbstractWFNotifier.java new file mode 100644 index 000000000000..da6973c6bdb2 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/AbstractWFNotifier.java @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage; +import org.wso2.carbon.apimgt.api.model.APIIdentifier; +import org.wso2.carbon.apimgt.api.model.SubscribedAPI; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; +import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; +import org.wso2.carbon.apimgt.impl.dao.NotificationDAO; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.core.UserRealm; +import org.wso2.carbon.user.core.UserStoreManager; +import org.wso2.carbon.user.core.common.AbstractUserStoreManager; +import org.wso2.carbon.user.core.common.User; +import org.wso2.carbon.user.core.service.RealmService; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public abstract class AbstractWFNotifier extends BaseNotifier { + + private static final Log log = LogFactory.getLog(AbstractWFNotifier.class); + public abstract NotificationDTO prepareNotification(WorkflowDTO workflowDTO) + throws APIManagementException; + public abstract NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO); + public abstract List getEndUsers(WorkflowDTO workflowDTO) + throws APIManagementException; + + + /** + * This method will return a NotificationEndUserDTO object contains the primary user details + * + * @param primaryUser username of the primary user who make the workflow request + * @param organization organization of the primary user + * @param portalToDisplay portal to display the notification + * @return a NotificationEndUserDTO object + */ + protected NotificationEndUserDTO getPrimaryUser(String primaryUser, String organization, String portalToDisplay) { + NotificationEndUserDTO endUser = new NotificationEndUserDTO(); + if (primaryUser != null) { + endUser.setDestinationUser(primaryUser); + endUser.setOrganization(organization); + endUser.setPortalToDisplay(portalToDisplay); + } + return endUser; + } + + /** + * This method will return the UUID of a given API + * + * @param apiName Name of the API + * @param apiContext Context of the API + * @param apiVersion Version of the API + * @return the UUID of the API + */ + protected String getAPIUUIDUsingNameContextVersion(String apiName, String apiContext, String apiVersion, + String organization) throws APIManagementException { + return NotificationDAO.getInstance() + .getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, organization); + } + + /** + * This method will return the list of subscribers of a given API + * + * @param apiUUID UUID of the API + * @param organization Organization of the API + * @param apiIdEmailReplaced APIIdentifier object with email replaced provider name + * @return the subscribers of the API + */ + protected List getSubscribersOfAPI(String apiUUID, String organization, + APIIdentifier apiIdEmailReplaced) throws APIManagementException { + List subscribedAPIs = new ArrayList<>(); + Set uniqueUserSet = new HashSet<>(); + try { + UserApplicationAPIUsage[] allApiResult = ApiMgtDAO.getInstance() + .getAllAPIUsageByProviderAndApiId(apiUUID, organization); + for (UserApplicationAPIUsage usage : allApiResult) { + for (SubscribedAPI apiSubscription : usage.getApiSubscriptions()) { + APIIdentifier subsApiId = apiSubscription.getAPIIdentifier(); + APIIdentifier subsApiIdEmailReplaced = new APIIdentifier( + APIUtil.replaceEmailDomain(subsApiId.getProviderName()), subsApiId.getApiName(), + subsApiId.getVersion()); + if (subsApiIdEmailReplaced.equals(apiIdEmailReplaced)) { + String userIdentifier = apiSubscription.getSubscriber() + .getName() + "-" + apiSubscription.getOrganization(); + if (uniqueUserSet.add(userIdentifier)) { + subscribedAPIs.add(apiSubscription); + } + } + } + } + } catch (APIManagementException e) { + APIUtil.handleException("Error while getting API usage by API ID - getAPIUsageByAPIId()", e); + } + return subscribedAPIs; + } + + protected List getSubscriberListOfAPI(String apiAction, String apiName, + String apiContext, String apiVersion, String provider, String tenantDomain) + throws APIManagementException { + List subscriberList = new ArrayList<>(); + + String apiUUID = null; + try { + apiUUID = getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, + tenantDomain); + APIIdentifier apiIdEmailReplaced = new APIIdentifier( + APIUtil.replaceEmailDomain(provider), apiName, apiVersion); + List subscribers = getSubscribersOfAPI(apiUUID, tenantDomain, + apiIdEmailReplaced); + for (SubscribedAPI subscriber : subscribers) { + NotificationEndUserDTO endUser = new NotificationEndUserDTO(); + endUser.setDestinationUser(subscriber.getSubscriber().getName()); + endUser.setOrganization(subscriber.getOrganization()); + endUser.setPortalToDisplay(APIConstants.PortalNotifications.DEV_PORTAL); + subscriberList.add(endUser); + } + } catch (APIManagementException e) { + APIUtil.handleException("Error while getting subscribers of API - getDestinationUser()", + e); + } + + return subscriberList; + } + + /** + * This method will return all the users belongs to a given group + * + * @param workflowDTO WorkflowDTO object that contains the workflow details + * @return a list of users belongs to a given group + */ + protected List getAllUsersBelongToGroup(WorkflowDTO workflowDTO, String groupId) + throws UserStoreException { + String tenantDomainOfUser = workflowDTO.getTenantDomain(); + List users = new ArrayList<>(); + + if (groupId != null) { + int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() + .getTenantId(tenantDomainOfUser); + RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService(); + UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId); + if (realm != null) { + UserStoreManager manager = realm.getUserStoreManager(); + AbstractUserStoreManager abstractManager = (AbstractUserStoreManager) manager; + APIManagerConfiguration config = ServiceReferenceHolder.getInstance() + .getAPIManagerConfigurationService().getAPIManagerConfiguration(); + String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI); + if (StringUtils.isBlank(claim)) { + claim = APIConstants.PortalNotifications.DEFAULT_CLAIM; + } + users = abstractManager.getUserListWithID(claim, groupId, "default"); + } + } + return users; + } + + /** + * This method will return a NotificationEndUserDTO list containing all the users of a given group + * + * @param primaryUser primary user of the workflow + * @param users a list of users belongs to the group + * @return a NotificationEndUserDTO list + */ + protected List getAllUsersBelongToGroupList(String primaryUser, List users){ + List allUsersOfTheGroup = new ArrayList<>(); + + for (User user : users) { + NotificationEndUserDTO endUser = new NotificationEndUserDTO(); + if (user.getUsername().equals(primaryUser)) { + continue; + } + endUser.setDestinationUser(user.getUsername()); + endUser.setOrganization(user.getTenantDomain()); + endUser.setPortalToDisplay(APIConstants.PortalNotifications.DEV_PORTAL); + allUsersOfTheGroup.add(endUser); + } + + return allUsersOfTheGroup; + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationCreationWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationCreationWFNotifier.java new file mode 100644 index 000000000000..a39b3fed3826 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationCreationWFNotifier.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.Application; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.user.api.UserStoreException; + +import java.util.ArrayList; +import java.util.List; + +public class ApplicationCreationWFNotifier extends AbstractWFNotifier { + private static final Log log = LogFactory.getLog(ApplicationCreationWFNotifier.class); + + @Override + public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIManagementException { + NotificationDTO notificationDTO = new NotificationDTO(); + notificationDTO.setNotificationType(NotificationType.APPLICATION_CREATION); + notificationDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + notificationDTO.setEndUsers(getEndUsers(workflowDTO)); + return notificationDTO; + } + + @Override + public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { + NotificationMetaData notificationMetaData = new NotificationMetaData(); + notificationMetaData.setApplicationName( + workflowDTO.getProperties(APIConstants.PortalNotifications.APPLICATION_NAME)); + notificationMetaData.setComment(workflowDTO.getComments()); + return notificationMetaData; + } + + @Override + public List getEndUsers(WorkflowDTO workflowDTO) throws APIManagementException { + List destinationUserList = new ArrayList<>(); + String destinationUser = workflowDTO.getProperties("userName"); + destinationUserList.add(getPrimaryUser(destinationUser, workflowDTO.getTenantDomain(), + APIConstants.PortalNotifications.DEV_PORTAL)); + //add users of the same group + try { + if (APIUtil.isMultiGroupAppSharingEnabled()) { + destinationUserList.addAll(getAllUsersBelongToGroupList(destinationUser, + getAllUsersBelongToGroup(workflowDTO, groupID(workflowDTO)))); + } + } catch (UserStoreException e) { + APIUtil.handleException("Error while getting user list belong to a group ", e); + } + return destinationUserList; + } + + public String groupID(WorkflowDTO workflowDTO) throws APIManagementException { + String applicationId = workflowDTO.getWorkflowReference(); + int appId = Integer.parseInt(applicationId); + ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance(); + Application application = apiMgtDAO.getApplicationById(appId); + return application.getGroupId(); + } + +} \ No newline at end of file diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationProductionWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationProductionWFNotifier.java new file mode 100644 index 000000000000..4be9e9c19977 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationProductionWFNotifier.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.user.api.UserStoreException; + +import java.util.ArrayList; +import java.util.List; + +public class ApplicationRegistrationProductionWFNotifier extends AbstractWFNotifier{ + private static final Log log = LogFactory.getLog(ApplicationRegistrationProductionWFNotifier.class); + + @Override + public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIManagementException { + NotificationDTO notificationDTO = new NotificationDTO(); + notificationDTO.setNotificationType(NotificationType.APPLICATION_REGISTRATION_PRODUCTION); + notificationDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + notificationDTO.setEndUsers(getEndUsers(workflowDTO)); + return notificationDTO; + } + + @Override + public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { + NotificationMetaData notificationMetaData = new NotificationMetaData(); + notificationMetaData.setApplicationName( + workflowDTO.getProperties(APIConstants.PortalNotifications.APPLICATION_NAME)); + notificationMetaData.setComment(workflowDTO.getComments()); + return notificationMetaData; + } + + @Override + public List getEndUsers(WorkflowDTO workflowDTO) throws APIManagementException { + List destinationUserList = new ArrayList<>(); + String destinationUser = workflowDTO.getProperties("userName"); + destinationUserList.add(getPrimaryUser(destinationUser, workflowDTO.getTenantDomain(), + APIConstants.PortalNotifications.DEV_PORTAL)); + //add users of the same group + try { + if (APIUtil.isMultiGroupAppSharingEnabled()) { + destinationUserList.addAll(getAllUsersBelongToGroupList(destinationUser, + getAllUsersBelongToGroup(workflowDTO, groupID(workflowDTO)))); + } + } catch (UserStoreException e) { + APIUtil.handleException("Error while getting user list belong to a group ", e); + } + return destinationUserList; + } + + public String groupID(WorkflowDTO workflowDTO) { + return ((ApplicationRegistrationWorkflowDTO) workflowDTO).getApplication().getGroupId(); + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationSandboxWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationSandboxWFNotifier.java new file mode 100644 index 000000000000..5d686b046ac6 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationSandboxWFNotifier.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.user.api.UserStoreException; + +import java.util.ArrayList; +import java.util.List; + +public class ApplicationRegistrationSandboxWFNotifier extends AbstractWFNotifier{ + private static final Log log = LogFactory.getLog(ApplicationRegistrationSandboxWFNotifier.class); + + @Override + public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIManagementException { + NotificationDTO notificationDTO = new NotificationDTO(); + notificationDTO.setNotificationType(NotificationType.APPLICATION_REGISTRATION_SANDBOX); + notificationDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + notificationDTO.setEndUsers(getEndUsers(workflowDTO)); + return notificationDTO; + } + + @Override + public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { + NotificationMetaData notificationMetaData = new NotificationMetaData(); + notificationMetaData.setApplicationName( + workflowDTO.getProperties(APIConstants.PortalNotifications.APPLICATION_NAME)); + notificationMetaData.setComment(workflowDTO.getComments()); + return notificationMetaData; + } + + @Override + public List getEndUsers(WorkflowDTO workflowDTO) throws APIManagementException { + List destinationUserList = new ArrayList<>(); + String destinationUser = workflowDTO.getProperties("userName"); + destinationUserList.add(getPrimaryUser(destinationUser, workflowDTO.getTenantDomain(), + APIConstants.PortalNotifications.DEV_PORTAL)); + //add users of the same group + try { + if (APIUtil.isMultiGroupAppSharingEnabled()) { + destinationUserList.addAll(getAllUsersBelongToGroupList(destinationUser, + getAllUsersBelongToGroup(workflowDTO, groupID(workflowDTO)))); + } + } catch (UserStoreException e) { + APIUtil.handleException("Error while getting user list belong to a group ", e); + } + return destinationUserList; + } + + public String groupID(WorkflowDTO workflowDTO) { + return ((ApplicationRegistrationWorkflowDTO) workflowDTO).getApplication().getGroupId(); + } +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/BaseNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/BaseNotifier.java new file mode 100644 index 000000000000..3264df94c806 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/BaseNotifier.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.dao.NotificationDAO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; + +public class BaseNotifier implements Notifier{ + + private static final Log log = LogFactory.getLog(BaseNotifier.class); + + @Override + public void sendNotifications(NotificationDTO notificationDTO) { + try { + boolean result = NotificationDAO.getInstance().addNotification(notificationDTO); + if (!result) { + log.error("Error while adding publisher developer notification."); + } + } catch (APIManagementException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/NotificationMetaData.java similarity index 95% rename from components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java rename to components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/NotificationMetaData.java index acb2ab9af273..3de5d0b79d97 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationMetaData.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/NotificationMetaData.java @@ -16,9 +16,9 @@ * under the License. */ -package org.wso2.carbon.apimgt.impl.portalNotifications; +package org.wso2.carbon.apimgt.impl.systemNotifications; -public class PortalNotificationMetaData { +public class NotificationMetaData { private String action; private String api; diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/NotificationType.java similarity index 90% rename from components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java rename to components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/NotificationType.java index d3dfe5b3fb42..9a60696f0026 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationType.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/NotificationType.java @@ -16,9 +16,9 @@ * under the License. */ -package org.wso2.carbon.apimgt.impl.portalNotifications; +package org.wso2.carbon.apimgt.impl.systemNotifications; -public enum PortalNotificationType { +public enum NotificationType { API_STATE_CHANGE, API_PRODUCT_STATE_CHANGE, API_REVISION_DEPLOYMENT, diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/Notifier.java similarity index 75% rename from components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java rename to components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/Notifier.java index f6d962c42eea..544e4b544de4 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/portalNotifications/PortalNotificationService.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/Notifier.java @@ -16,10 +16,12 @@ * under the License. */ -package org.wso2.carbon.apimgt.impl.portalNotifications; +package org.wso2.carbon.apimgt.impl.systemNotifications; -public interface PortalNotificationService { +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; + +public interface Notifier { + + void sendNotifications(NotificationDTO notificationDTO); - void sendPortalNotifications(T notificationObject, String tenantDomain); - } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionCreationWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionCreationWFNotifier.java new file mode 100644 index 000000000000..7d858b2180f3 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionCreationWFNotifier.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.SubscribedAPI; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.user.api.UserStoreException; + +import java.util.ArrayList; +import java.util.List; + +public class SubscriptionCreationWFNotifier extends AbstractWFNotifier { + private static final Log log = LogFactory.getLog(SubscriptionCreationWFNotifier.class); + + @Override + public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIManagementException { + NotificationDTO notificationDTO = new NotificationDTO(); + notificationDTO.setNotificationType(NotificationType.SUBSCRIPTION_CREATION); + notificationDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + notificationDTO.setEndUsers(getEndUsers(workflowDTO)); + return notificationDTO; + } + + @Override + public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { + NotificationMetaData notificationMetaData = new NotificationMetaData(); + notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); + notificationMetaData.setApiVersion( + workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setApplicationName( + workflowDTO.getProperties(APIConstants.PortalNotifications.APPLICATION_NAME)); + notificationMetaData.setComment(workflowDTO.getComments()); + return notificationMetaData; + } + + @Override + public List getEndUsers(WorkflowDTO workflowDTO) throws APIManagementException { + List destinationUserList = new ArrayList<>(); + //add primary user + String destinationUser = workflowDTO.getProperties("subscriber"); + destinationUserList.add(getPrimaryUser(destinationUser, workflowDTO.getTenantDomain(), + APIConstants.PortalNotifications.DEV_PORTAL)); + //add users of the same group + try { + if (APIUtil.isMultiGroupAppSharingEnabled()) { + destinationUserList.addAll(getAllUsersBelongToGroupList(destinationUser, + getAllUsersBelongToGroup(workflowDTO, groupID(workflowDTO)))); + } + + } catch (UserStoreException e) { + APIUtil.handleException("Error while getting user list belong to a group ", e); + } + return destinationUserList; + } + + public String groupID(WorkflowDTO workflowDTO) throws APIManagementException { + SubscribedAPI sub = ApiMgtDAO.getInstance() + .getSubscriptionById(Integer.parseInt(workflowDTO.getWorkflowReference())); + return sub.getApplication().getGroupId(); + } + +} \ No newline at end of file diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionDeletionWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionDeletionWFNotifier.java new file mode 100644 index 000000000000..d2c06a4f806d --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionDeletionWFNotifier.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.Application; +import org.wso2.carbon.apimgt.api.model.SubscribedAPI; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.user.api.UserStoreException; + +import java.util.ArrayList; +import java.util.List; + +public class SubscriptionDeletionWFNotifier extends AbstractWFNotifier{ + private static final Log log = LogFactory.getLog(SubscriptionDeletionWFNotifier.class); + + @Override + public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIManagementException { + NotificationDTO notificationDTO = new NotificationDTO(); + notificationDTO.setNotificationType(NotificationType.SUBSCRIPTION_DELETION); + notificationDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + notificationDTO.setEndUsers(getEndUsers(workflowDTO)); + return notificationDTO; + } + + @Override + public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { + NotificationMetaData notificationMetaData = new NotificationMetaData(); + notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); + notificationMetaData.setApiVersion( + workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setApplicationName( + workflowDTO.getProperties(APIConstants.PortalNotifications.APPLICATION_NAME)); + notificationMetaData.setComment(workflowDTO.getComments()); + return notificationMetaData; + } + + @Override + public List getEndUsers(WorkflowDTO workflowDTO) throws APIManagementException { + List destinationUserList = new ArrayList<>(); + //add primary user + String destinationUser = workflowDTO.getProperties("subscriber"); + destinationUserList.add(getPrimaryUser(destinationUser, workflowDTO.getTenantDomain(), + APIConstants.PortalNotifications.DEV_PORTAL)); + //add users of the same group + try { + if (APIUtil.isMultiGroupAppSharingEnabled()) { + destinationUserList.addAll(getAllUsersBelongToGroupList(destinationUser, + getAllUsersBelongToGroup(workflowDTO, groupID(workflowDTO)))); + } + } catch (UserStoreException e) { + APIUtil.handleException("Error while getting user list belong to a group ", e); + } + return destinationUserList; + } + + public String groupID(WorkflowDTO workflowDTO) throws APIManagementException { + String applicationId = workflowDTO.getProperties("applicationId"); + int appId = Integer.parseInt(applicationId); + ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance(); + Application application = apiMgtDAO.getApplicationById(appId); + return application.getGroupId(); + } +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionUpdateWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionUpdateWFNotifier.java new file mode 100644 index 000000000000..fdf58dc2276f --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionUpdateWFNotifier.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.api.model.SubscribedAPI; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; +import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.user.api.UserStoreException; + +import java.util.ArrayList; +import java.util.List; + +public class SubscriptionUpdateWFNotifier extends AbstractWFNotifier{ + private static final Log log = LogFactory.getLog(SubscriptionUpdateWFNotifier.class); + + public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIManagementException { + NotificationDTO notificationDTO = new NotificationDTO(); + notificationDTO.setNotificationType(NotificationType.SUBSCRIPTION_UPDATE); + notificationDTO.setNotificationMetadata(getNotificationMetaData(workflowDTO)); + notificationDTO.setEndUsers(getEndUsers(workflowDTO)); + return notificationDTO; + } + + @Override + public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { + NotificationMetaData notificationMetaData = new NotificationMetaData(); + notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); + notificationMetaData.setApiVersion( + workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setApplicationName( + workflowDTO.getProperties(APIConstants.PortalNotifications.APPLICATION_NAME)); + notificationMetaData.setRequestedTier( + workflowDTO.getProperties(APIConstants.PortalNotifications.REQUESTED_TIER)); + notificationMetaData.setComment(workflowDTO.getComments()); + + return notificationMetaData; + } + + @Override + public List getEndUsers(WorkflowDTO workflowDTO) throws APIManagementException { + List destinationUserList = new ArrayList<>(); + //add primary user + String destinationUser = workflowDTO.getProperties("subscriber"); + destinationUserList.add(getPrimaryUser(destinationUser, workflowDTO.getTenantDomain(), + APIConstants.PortalNotifications.DEV_PORTAL)); + //add users of the same group + try { + if (APIUtil.isMultiGroupAppSharingEnabled()) { + destinationUserList.addAll(getAllUsersBelongToGroupList(destinationUser, + getAllUsersBelongToGroup(workflowDTO, groupID(workflowDTO)))); + } + } catch (UserStoreException e) { + APIUtil.handleException("Error while getting user list belong to a group ", e); + } + return destinationUserList; + } + + public String groupID(WorkflowDTO workflowDTO) throws APIManagementException { + SubscribedAPI sub = ApiMgtDAO.getInstance() + .getSubscriptionById(Integer.parseInt(workflowDTO.getWorkflowReference())); + return sub.getApplication().getGroupId(); + } + +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/WFNotifierFactory.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/WFNotifierFactory.java new file mode 100644 index 000000000000..623ec58437b9 --- /dev/null +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/WFNotifierFactory.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.apimgt.impl.systemNotifications; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; + +public class WFNotifierFactory { + + private static final Log log = LogFactory.getLog(WFNotifierFactory.class); + public static AbstractWFNotifier getNotifier(String notifierType) { + if (notifierType == null) { + return null; + } + if (notifierType.equals(WorkflowConstants.WF_TYPE_AM_API_STATE)) { + return new APIStateChangeWFNotifier(); + } else if (notifierType.equals(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)) { + return new APIProductStateChangeWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT)) { + return new APIRevisionDeploymentWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION)) { + return new ApplicationCreationWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION)) { + return new ApplicationRegistrationProductionWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX)) { + return new ApplicationRegistrationSandboxWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION)) { + return new SubscriptionCreationWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE)) { + return new SubscriptionUpdateWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION)) { + return new SubscriptionDeletionWFNotifier(); + } + return null; + } +} diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationApprovalWorkflowExecutor.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationApprovalWorkflowExecutor.java index d74e30fb5929..189cabab287b 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationApprovalWorkflowExecutor.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationApprovalWorkflowExecutor.java @@ -65,6 +65,7 @@ public WorkflowResponse execute(WorkflowDTO workflowDTO) throws WorkflowExceptio workflowDTO.setProperties("apiVersion", subsWorkflowDTO.getApiVersion()); workflowDTO.setProperties("subscriber", subsWorkflowDTO.getSubscriber()); workflowDTO.setProperties("applicationName", subsWorkflowDTO.getApplicationName()); + workflowDTO.setProperties("applicationId", String.valueOf(subsWorkflowDTO.getApplicationId())); super.execute(workflowDTO); return new GeneralWorkflowResponse(); diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/NotificationDAOTest.java similarity index 68% rename from components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java rename to components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/NotificationDAOTest.java index 9dc0003766ad..b5ffc76eb306 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/PortalNotificationDAOTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/dao/test/NotificationDAOTest.java @@ -35,11 +35,11 @@ import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationServiceImpl; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; -import org.wso2.carbon.apimgt.impl.dao.PortalNotificationDAO; -import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationDTO; -import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationEndUserDTO; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationMetaData; -import org.wso2.carbon.apimgt.impl.portalNotifications.PortalNotificationType; +import org.wso2.carbon.apimgt.impl.dao.NotificationDAO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; +import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationEndUserDTO; +import org.wso2.carbon.apimgt.impl.systemNotifications.NotificationMetaData; +import org.wso2.carbon.apimgt.impl.systemNotifications.NotificationType; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; import org.wso2.carbon.base.MultitenantConstants; @@ -57,8 +57,8 @@ @RunWith(PowerMockRunner.class) @PowerMockIgnore("javax.management.*") -public class PortalNotificationDAOTest { - public static PortalNotificationDAO portalNotificationDAO; +public class NotificationDAOTest { + public static NotificationDAO notificationDAO; private static final String organization = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; @@ -71,7 +71,7 @@ public void setUp() throws Exception { ServiceReferenceHolder.getInstance() .setAPIManagerConfigurationService(new APIManagerConfigurationServiceImpl(config)); APIMgtDBUtil.initialize(); - portalNotificationDAO = PortalNotificationDAO.getInstance(); + notificationDAO = NotificationDAO.getInstance(); } private static void initializeDatabase(String configFilePath) @@ -110,33 +110,33 @@ private static void initializeDatabase(String configFilePath) @Test public void testAddNotificationSuccess() throws APIManagementException { - PortalNotificationMetaData metaData = getPortalNotificationMetaData(); - PortalNotificationDTO portalNotificationDTO = getPortalNotificationDTO(metaData); + NotificationMetaData metaData = getPortalNotificationMetaData(); + NotificationDTO notificationDTO = getPortalNotificationDTO(metaData); - boolean result = portalNotificationDAO.addNotification(portalNotificationDTO); + boolean result = notificationDAO.addNotification(notificationDTO); Assert.assertTrue(result); } @NotNull - private static PortalNotificationDTO getPortalNotificationDTO(PortalNotificationMetaData metaData) { - PortalNotificationEndUserDTO endUser1 = new PortalNotificationEndUserDTO(); + private static NotificationDTO getPortalNotificationDTO(NotificationMetaData metaData) { + NotificationEndUserDTO endUser1 = new NotificationEndUserDTO(); endUser1.setDestinationUser("Kevin"); endUser1.setOrganization(organization); endUser1.setPortalToDisplay("publisher"); - List endUsersList = new ArrayList<>(); + List endUsersList = new ArrayList<>(); endUsersList.add(endUser1); - PortalNotificationDTO portalNotificationDTO = new PortalNotificationDTO(); - portalNotificationDTO.setNotificationType(PortalNotificationType.API_STATE_CHANGE); - portalNotificationDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); - portalNotificationDTO.setNotificationMetadata(metaData); - portalNotificationDTO.setEndUsers(endUsersList); - return portalNotificationDTO; + NotificationDTO notificationDTO = new NotificationDTO(); + notificationDTO.setNotificationType(NotificationType.API_STATE_CHANGE); + notificationDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); + notificationDTO.setNotificationMetadata(metaData); + notificationDTO.setEndUsers(endUsersList); + return notificationDTO; } @NotNull - private static PortalNotificationMetaData getPortalNotificationMetaData() { - PortalNotificationMetaData metaData = new PortalNotificationMetaData(); + private static NotificationMetaData getPortalNotificationMetaData() { + NotificationMetaData metaData = new NotificationMetaData(); metaData.setApi("Sample_API"); metaData.setApiVersion("1.0"); metaData.setApiContext("/sample"); @@ -150,42 +150,42 @@ private static PortalNotificationMetaData getPortalNotificationMetaData() { @Test public void testGetNotificationsSuccess() throws APIManagementException { - NotificationList notificationList = portalNotificationDAO.getNotifications("helani", organization, + NotificationList notificationList = notificationDAO.getNotifications("helani", organization, "publisher", "desc", 0, 10); Assert.assertNotNull(notificationList); } @Test public void testMarkNotificationAsReadByIdSuccess() throws Exception { - Notification notification = portalNotificationDAO.markNotificationAsReadById("helani", organization, + Notification notification = notificationDAO.markNotificationAsReadById("helani", organization, "1e2736ab-7882-4184-a1ba-6d3c07271b69", "publisher"); Assert.assertEquals(true, notification.getIsRead()); } @Test public void testMarkAllNotificationsAsReadSuccess() throws Exception { - NotificationList notificationList = portalNotificationDAO.markAllNotificationsAsRead("helani", + NotificationList notificationList = notificationDAO.markAllNotificationsAsRead("helani", organization, "publisher"); Assert.assertEquals(true, notificationList.getList().get(0).getIsRead()); } @Test public void testDeleteNotificationByIdSuccess() throws Exception { - boolean result = portalNotificationDAO.deleteNotificationById("helani", organization, + boolean result = notificationDAO.deleteNotificationById("helani", organization, "7dc674f1-2b4c-4826-8e95-fa9b2628b816", "publisher"); Assert.assertTrue(result); } @Test public void testDeleteAllNotificationsSuccess() throws Exception { - boolean result = portalNotificationDAO.deleteAllNotifications("Kevin", organization, + boolean result = notificationDAO.deleteAllNotifications("Kevin", organization, "publisher"); Assert.assertTrue(result); } @Test public void testGetAPIUUIDUsingNameContextVersionSuccess() throws Exception { - String apiUUID = portalNotificationDAO.getAPIUUIDUsingNameContextVersion("testAPI1", + String apiUUID = notificationDAO.getAPIUUIDUsingNameContextVersion("testAPI1", "/sample/api", "1.0.0", organization); Assert.assertEquals("821b9824-eeca-4173-9f56-3dc6d46bd6eb", apiUUID); } @@ -193,7 +193,7 @@ public void testGetAPIUUIDUsingNameContextVersionSuccess() throws Exception { @Test public void testGetUnreadNotificationCountSuccess() throws Exception { Connection connection = APIMgtDBUtil.getConnection(); - int unreadCount = portalNotificationDAO.getUnreadNotificationCount("Nisha", organization, + int unreadCount = notificationDAO.getUnreadNotificationCount("Nisha", organization, "devportal", connection); Assert.assertEquals(1, unreadCount); @@ -201,66 +201,66 @@ public void testGetUnreadNotificationCountSuccess() throws Exception { @Test public void testAddNotificationFailure() { - PortalNotificationMetaData metaData = getPortalNotificationMetaData(); - PortalNotificationEndUserDTO endUser1 = new PortalNotificationEndUserDTO(); + NotificationMetaData metaData = getPortalNotificationMetaData(); + NotificationEndUserDTO endUser1 = new NotificationEndUserDTO(); endUser1.setDestinationUser("Kevin"); endUser1.setOrganization(organization); - List endUsersList = new ArrayList<>(); + List endUsersList = new ArrayList<>(); endUsersList.add(endUser1); - PortalNotificationDTO portalNotificationDTO = new PortalNotificationDTO(); - portalNotificationDTO.setNotificationType(PortalNotificationType.API_STATE_CHANGE); - portalNotificationDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); - portalNotificationDTO.setNotificationMetadata(metaData); - portalNotificationDTO.setEndUsers(endUsersList); + NotificationDTO notificationDTO = new NotificationDTO(); + notificationDTO.setNotificationType(NotificationType.API_STATE_CHANGE); + notificationDTO.setCreatedTime(new java.sql.Timestamp(new java.util.Date().getTime())); + notificationDTO.setNotificationMetadata(metaData); + notificationDTO.setEndUsers(endUsersList); Exception exception = Assert.assertThrows(APIManagementException.class, () -> { - portalNotificationDAO.addNotification(portalNotificationDTO); + notificationDAO.addNotification(notificationDTO); }); - String expectedMessage = "Error while adding end users"; + String expectedMessage = "Error while adding notification"; String actualMessage = exception.getMessage(); Assert.assertEquals(expectedMessage, actualMessage); } @Test public void testGetNotificationsFailure() throws APIManagementException { - NotificationList notificationList = portalNotificationDAO.getNotifications("Rush", organization, + NotificationList notificationList = notificationDAO.getNotifications("Rush", organization, "publisher", "desc", 0, 10); Assert.assertEquals(0, notificationList.getList().size()); } @Test public void testMarkNotificationAsReadByIdFailure() throws Exception { - Notification notification = portalNotificationDAO.markNotificationAsReadById("Rush", organization, + Notification notification = notificationDAO.markNotificationAsReadById("Rush", organization, "1e2736ab-7882-4184-a1ba-6d3c07271b69", "publisher"); Assert.assertNull(notification); } @Test public void testMarkAllNotificationsAsReadFailure() throws Exception { - NotificationList notificationList = portalNotificationDAO.markAllNotificationsAsRead("Rush", + NotificationList notificationList = notificationDAO.markAllNotificationsAsRead("Rush", organization, "publisher"); Assert.assertNull(notificationList); } @Test public void testDeleteNotificationByIdFailure() throws Exception { - boolean result = portalNotificationDAO.deleteNotificationById("Rush", organization, + boolean result = notificationDAO.deleteNotificationById("Rush", organization, "7dc674f1-2b4c-4826-8e95-fa9b2628b816", "publisher"); Assert.assertFalse(result); } @Test public void testDeleteAllNotificationsFailure() throws Exception { - boolean result = portalNotificationDAO.deleteAllNotifications("Rush", organization, + boolean result = notificationDAO.deleteAllNotifications("Rush", organization, "publisher"); Assert.assertFalse(result); } @Test public void testGetAPIUUIDUsingNameContextVersionFailure() throws Exception { - String apiUUID = portalNotificationDAO.getAPIUUIDUsingNameContextVersion("MyApi", "/api", + String apiUUID = notificationDAO.getAPIUUIDUsingNameContextVersion("MyApi", "/api", "1.0.0", organization); Assert.assertNull(apiUUID); } @@ -268,7 +268,7 @@ public void testGetAPIUUIDUsingNameContextVersionFailure() throws Exception { @Test public void testGetUnreadNotificationCountFailure() throws Exception { Connection connection = APIMgtDBUtil.getConnection(); - int unreadCount = portalNotificationDAO.getUnreadNotificationCount("Rush", organization, + int unreadCount = notificationDAO.getUnreadNotificationCount("Rush", organization, "publisher", connection); Assert.assertEquals(0, unreadCount); } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java deleted file mode 100644 index de451118de58..000000000000 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/portalNotifications/WorkflowNotificationServiceImplTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.apimgt.impl.portalNotifications; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.wso2.carbon.apimgt.api.APIManagementException; -import org.wso2.carbon.apimgt.impl.dao.PortalNotificationDAO; -import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; -import org.wso2.carbon.apimgt.impl.dto.portalNotifications.PortalNotificationDTO; -import org.wso2.carbon.apimgt.impl.utils.APIUtil; -import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ APIUtil.class, PortalNotificationDAO.class }) -public class WorkflowNotificationServiceImplTest { - - private WorkflowNotificationServiceImpl notificationService; - private PortalNotificationDAO portalNotificationDAO; - - private WorkflowDTO workflowDTO; - - @Before - public void init() { - notificationService = new WorkflowNotificationServiceImpl(); - portalNotificationDAO = Mockito.mock(PortalNotificationDAO.class); - workflowDTO = createMockWorkflowDTO(); - } - - @Test - public void testSendPortalNotificationsSuccess() throws APIManagementException { - - PowerMockito.mockStatic(APIUtil.class); - PowerMockito.mockStatic(PortalNotificationDAO.class); - String tenantDomainOfUser = "carbonSuper"; - - PowerMockito.when(APIUtil.isMultiGroupAppSharingEnabled()).thenReturn(false); - PowerMockito.when(PortalNotificationDAO.getInstance()).thenReturn(portalNotificationDAO); - Mockito.when(portalNotificationDAO.addNotification(Mockito.any(PortalNotificationDTO.class))).thenReturn(true); - notificationService.sendPortalNotifications(workflowDTO, tenantDomainOfUser); - Mockito.verify(portalNotificationDAO, Mockito.times(1)).addNotification(Mockito.any(PortalNotificationDTO.class)); - } - - private WorkflowDTO createMockWorkflowDTO() { - WorkflowDTO workflowDTO = new WorkflowDTO(); - workflowDTO.setProperties("apiName", "Test API"); - workflowDTO.setProperties("apiVersion", "1.0"); - workflowDTO.setMetadata("Action", "Publish"); - workflowDTO.setMetadata("Provider", "Ali"); - workflowDTO.setProperties("revisionId", "1"); - workflowDTO.setComments("Test Comment"); - workflowDTO.setWorkflowType(WorkflowConstants.WF_TYPE_AM_API_STATE); - workflowDTO.setMetadata("ApiContext", "/test/1.0"); - workflowDTO.setMetadata("Invoker", "Kevin"); - return workflowDTO; - } - -} - diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java index 18ed8ede8c86..6119335f65e1 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationCreationWSWorkflowExecutorTest.java @@ -18,11 +18,8 @@ package org.wso2.carbon.apimgt.impl.workflow; -import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.description.AxisService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -40,7 +37,6 @@ import org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; -import org.wso2.carbon.apimgt.impl.portalNotifications.WorkflowNotificationServiceImpl; import javax.xml.stream.XMLStreamException; import java.util.UUID; @@ -50,13 +46,12 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({ ServiceReferenceHolder.class, ApiMgtDAO.class, ApplicationCreationWSWorkflowExecutor.class, - AXIOMUtil.class, WorkflowNotificationServiceImpl.class }) + AXIOMUtil.class, }) public class ApplicationCreationWSWorkflowExecutorTest { private ApplicationCreationWSWorkflowExecutor applicationCreationWSWorkflowExecutor; private ApiMgtDAO apiMgtDAO; private ServiceClient serviceClient; - WorkflowNotificationServiceImpl workflowsApiService; @Before public void init() { @@ -69,7 +64,6 @@ public void init() { PowerMockito.mockStatic(ApiMgtDAO.class); apiMgtDAO = Mockito.mock(ApiMgtDAO.class); serviceClient = Mockito.mock(ServiceClient.class); - workflowsApiService = PowerMockito.mock(WorkflowNotificationServiceImpl.class); PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO); } @@ -91,8 +85,6 @@ public void testWorkflowApprove() throws APIManagementException, WorkflowExcepti PowerMockito.doNothing().when(apiMgtDAO) .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_APPROVED); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)) @@ -114,8 +106,6 @@ public void testWorkflowReject() throws APIManagementException, WorkflowExceptio PowerMockito.doNothing().when(apiMgtDAO) .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_REJECTED); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)) @@ -136,8 +126,6 @@ public void testWorkflowCreate() throws APIManagementException, WorkflowExceptio PowerMockito.doNothing().when(apiMgtDAO) .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_CREATED); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)) @@ -193,8 +181,6 @@ public void testWorkflowCompleteExceptionWhenStatusUpdateFailed() throws APIMana "Error occurred when updating the status of the Application " + "creation process")).when(apiMgtDAO) .updateApplicationStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.ApplicationStatus.APPLICATION_APPROVED); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); @@ -258,8 +244,6 @@ public void testWorkflowNotAllowedStatus() throws APIManagementException, Workfl Application app = Mockito.mock(Application.class); PowerMockito.doReturn(app).when(apiMgtDAO) .getApplicationById(Integer.parseInt(workflowDTO.getWorkflowReference())); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); applicationCreationWSWorkflowExecutor.complete(workflowDTO); // shouldn't update status diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java index e3d8af62cb67..f107f22d8600 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/ApplicationRegistrationWSWorkflowExecutorTest.java @@ -42,10 +42,8 @@ import org.wso2.carbon.apimgt.impl.TestUtils; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; import org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO; -import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.apimgt.impl.factory.KeyManagerHolder; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; -import org.wso2.carbon.apimgt.impl.portalNotifications.WorkflowNotificationServiceImpl; import org.wso2.carbon.utils.ConfigurationContextService; import javax.xml.stream.XMLStreamException; @@ -55,7 +53,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({ApiMgtDAO.class, ApplicationRegistrationWSWorkflowExecutor.class, - ServiceReferenceHolder.class, AXIOMUtil.class, KeyManagerHolder.class, WorkflowNotificationServiceImpl.class}) + ServiceReferenceHolder.class, AXIOMUtil.class, KeyManagerHolder.class, }) public class ApplicationRegistrationWSWorkflowExecutorTest { private ApplicationRegistrationWSWorkflowExecutor applicationRegistrationWSWorkflowExecutor; @@ -68,7 +66,6 @@ public class ApplicationRegistrationWSWorkflowExecutorTest { private String adminUsername = "admin"; private String adminPassword = "admin"; private String callBaclURL = "http://localhost:8090/playground2.0/oauth2client"; - WorkflowNotificationServiceImpl workflowsApiService; @Before @@ -109,7 +106,6 @@ public void init() throws Exception { kmConfigDTO.setOrganization("carbon.super"); kmConfigDTO.setName("default"); PowerMockito.when(apiMgtDAO.getKeyManagerConfigurationByUUID("default")).thenReturn(kmConfigDTO); - workflowsApiService = PowerMockito.mock(WorkflowNotificationServiceImpl.class); } @Test @@ -194,8 +190,7 @@ public void testCompletingApplicationRegistrationWSWFWhenWFRejected() throws Exc applicationRegistrationWSWorkflowExecutor.setUsername(adminUsername); applicationRegistrationWSWorkflowExecutor.setPassword(adminPassword.toCharArray()); workflowDTO.setStatus(WorkflowStatus.REJECTED); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); + try { Assert.assertNotNull(applicationRegistrationWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { @@ -221,8 +216,7 @@ public void testCompletingApplicationRegistrationWSWFWhenWFApproved() throws Exc applicationRegistrationWSWorkflowExecutor.setPassword(adminPassword.toCharArray()); workflowDTO.setStatus(WorkflowStatus.APPROVED); workflowDTO.setKeyManager("default"); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); + try { Assert.assertNotNull(applicationRegistrationWSWorkflowExecutor.complete(workflowDTO)); } catch (WorkflowException e) { diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java index e19c87a1be45..81f5c56f813d 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/SubscriptionCreationWSWorkflowExecutorTest.java @@ -21,14 +21,7 @@ import java.util.UUID; import org.apache.axiom.om.util.AXIOMUtil; -import org.apache.axis2.AxisFault; -import org.apache.axis2.Constants; -import org.apache.axis2.addressing.EndpointReference; -import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.description.AxisService; -import org.apache.axis2.transport.http.HTTPConstants; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -44,8 +37,7 @@ import org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; -import org.wso2.carbon.apimgt.impl.portalNotifications.WorkflowNotificationServiceImpl; - +import org.wso2.carbon.apimgt.impl.systemNotifications.SubscriptionCreationWFNotifier; import javax.xml.stream.XMLStreamException; /** @@ -53,13 +45,12 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({ ServiceReferenceHolder.class, ApiMgtDAO.class, SubscriptionCreationWSWorkflowExecutor.class, - AXIOMUtil.class, WorkflowNotificationServiceImpl.class}) + AXIOMUtil.class, SubscriptionCreationWFNotifier.class}) public class SubscriptionCreationWSWorkflowExecutorTest { private SubscriptionCreationWSWorkflowExecutor subscriptionCreationWSWorkflowExecutor; private ApiMgtDAO apiMgtDAO; private ServiceClient serviceClient; - WorkflowNotificationServiceImpl workflowsApiService; @Before public void init() { @@ -73,7 +64,6 @@ public void init() { apiMgtDAO = Mockito.mock(ApiMgtDAO.class); serviceClient = Mockito.mock(ServiceClient.class); PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO); - workflowsApiService = PowerMockito.mock(WorkflowNotificationServiceImpl.class); } @Test @@ -90,8 +80,6 @@ public void testWorkflowApprove() throws APIManagementException, WorkflowExcepti PowerMockito.doNothing().when(apiMgtDAO) .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.UNBLOCKED); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)) @@ -109,8 +97,6 @@ public void testWorkflowReject() throws APIManagementException, WorkflowExceptio PowerMockito.doNothing().when(apiMgtDAO) .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); Mockito.verify(apiMgtDAO, Mockito.times(1)) @@ -127,8 +113,6 @@ public void testWorkflowRejectException() throws APIManagementException, Workflo PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO) .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); } @@ -142,8 +126,6 @@ public void testWorkflowApproveException() throws APIManagementException, Workfl PowerMockito.doThrow(new APIManagementException("")).when(apiMgtDAO) .updateSubscriptionStatus(Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.UNBLOCKED); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); } @@ -154,8 +136,6 @@ public void testWorkflowNotAllowedStatus() throws APIManagementException, Workfl workflowDTO.setWorkflowReference("1"); workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString()); workflowDTO.setStatus(WorkflowStatus.CREATED); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); subscriptionCreationWSWorkflowExecutor.complete(workflowDTO); // shouldn't update status Mockito.verify(apiMgtDAO, Mockito.never()) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java index 40f27f4c6b63..04ffce0f1143 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/workflow/UserSignUpWSWorkflowExecutorTest.java @@ -40,7 +40,6 @@ import org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO; import org.wso2.carbon.apimgt.impl.dto.WorkflowDTO; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; -import org.wso2.carbon.apimgt.impl.portalNotifications.WorkflowNotificationServiceImpl; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.utils.SelfSignUpUtil; import org.wso2.carbon.registry.core.utils.UUIDGenerator; @@ -59,7 +58,7 @@ */ @RunWith(PowerMockRunner.class) @PrepareForTest({ServiceReferenceHolder.class, UserSignUpWSWorkflowExecutor.class, ApiMgtDAO.class, APIUtil.class, - AXIOMUtil.class, SelfSignUpUtil.class, CarbonUtils.class, WorkflowNotificationServiceImpl.class}) + AXIOMUtil.class, SelfSignUpUtil.class, CarbonUtils.class, }) public class UserSignUpWSWorkflowExecutorTest { private UserSignUpWSWorkflowExecutor userSignUpWSWorkflowExecutor; @@ -76,7 +75,6 @@ public class UserSignUpWSWorkflowExecutorTest { private String signUpRole = "Internal/subscriber"; private int tenantID = -1234; private String testUsername = "PRIMARY/testuser"; - WorkflowNotificationServiceImpl workflowsApiService; @Before public void init() throws Exception { @@ -115,7 +113,6 @@ public void init() throws Exception { workflowDTO.setTenantDomain(tenantDomain); workflowDTO.setExternalWorkflowReference(externalWFReference); workflowDTO.setWorkflowReference(testUsername + "@carbon.super"); - workflowsApiService = PowerMockito.mock(WorkflowNotificationServiceImpl.class); } @Test @@ -187,8 +184,7 @@ public void testCompletingUserSignUpWorkflowApprovedByAdmin() throws Exception { Mockito.when(userStoreManager.isExistingRole(signUpRole)).thenReturn(true); PowerMockito.doNothing().when(userStoreManager) .updateRoleListOfUser(testUsername, null, new String[] { signUpRole }); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); + //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); try { @@ -208,8 +204,6 @@ public void testFailureToCompleteUserSignUpWorkflowApprovedByAdmin() throws Exce PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); Mockito.when(userStoreManager.isExistingUser(testUsername)).thenReturn(true); Mockito.when(userStoreManager.isExistingRole(signUpRole)).thenReturn(true); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.APPROVED); @@ -253,8 +247,7 @@ public void testCompletingUserSignUpWorkflowRejectedByAdmin() throws Exception { userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); + //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); try { @@ -272,8 +265,7 @@ public void testFailureToCompleteUserSignUpWorkflowRejectedByAdmin() throws Exce userRegistrationConfigDTO.setRoles(roleMap); PowerMockito.when(SelfSignUpUtil.getSignupConfiguration(tenantDomain)).thenReturn(userRegistrationConfigDTO); PowerMockito.doNothing().when(apiMgtDAO).updateWorkflowStatus(workflowDTO); - PowerMockito.doNothing().when(workflowsApiService) - .sendPortalNotifications(Mockito.any(WorkflowDTO.class), Mockito.any(String.class)); + //Set workflow status to be approved workflowDTO.setStatus(WorkflowStatus.REJECTED); Mockito.doThrow(UserStoreException.class).when(userStoreManager).deleteUser(Mockito.anyString()); diff --git a/components/apimgt/org.wso2.carbon.apimgt.internal.service/swagger.json b/components/apimgt/org.wso2.carbon.apimgt.internal.service/swagger.json index a7fa59630d63..8040e385bd35 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.internal.service/swagger.json +++ b/components/apimgt/org.wso2.carbon.apimgt.internal.service/swagger.json @@ -1354,8 +1354,8 @@ "type" : "string", "example" : "EXCHANGED", "description" : "The type of the tokens to be used (exchanged or without exchanged). Accepted values are EXCHANGED, DIRECT or BOTH.", - "enum" : [ "EXCHANGED", "DIRECT", "BOTH" ], - "default" : "DIRECT" + "default" : "DIRECT", + "enum" : [ "EXCHANGED", "DIRECT", "BOTH" ] } } }, diff --git a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java index 1fa1ae1292f6..1aadc6d1ea58 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java +++ b/components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/impl/WorkflowsApiServiceImpl.java @@ -24,12 +24,14 @@ import org.wso2.carbon.apimgt.api.APIConsumer; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; +import org.wso2.carbon.apimgt.api.model.SubscribedAPI; import org.wso2.carbon.apimgt.api.model.Workflow; import org.wso2.carbon.apimgt.impl.APIAdminImpl; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerFactory; import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO; -import org.wso2.carbon.apimgt.impl.portalNotifications.WorkflowNotificationServiceImpl; +import org.wso2.carbon.apimgt.impl.systemNotifications.AbstractWFNotifier; +import org.wso2.carbon.apimgt.impl.systemNotifications.WFNotifierFactory; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.workflow.WorkflowConstants; import org.wso2.carbon.apimgt.impl.workflow.WorkflowException; @@ -204,8 +206,11 @@ public Response workflowsUpdateWorkflowStatusPost(String workflowReferenceId, Wo WorkflowExecutor workflowExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(workflowType); workflowExecutor.complete(workflowDTO); - WorkflowNotificationServiceImpl portalNotification = new WorkflowNotificationServiceImpl(); - portalNotification.sendPortalNotifications(workflowDTO, tenantDomainOfUser); + AbstractWFNotifier notifier = WFNotifierFactory.getNotifier(workflowDTO.getWorkflowType()); + if (notifier != null) { + notifier.sendNotifications(notifier.prepareNotification(workflowDTO)); + } + if (WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) { WorkflowUtils.sendNotificationAfterWFComplete(workflowDTO, workflowType); From 80024b0e3971eb9ae4a3f94b3e8d99408367879e Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Mon, 13 May 2024 17:24:31 +0530 Subject: [PATCH 21/23] Modify the code --- .../carbon/apimgt/impl/dao/NotificationDAO.java | 8 +++++--- .../apimgt/impl/dao/constants/SQLConstants.java | 13 ------------- 2 files changed, 5 insertions(+), 16 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/NotificationDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/NotificationDAO.java index 31456f3e887a..819f7e1ad3ff 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/NotificationDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/NotificationDAO.java @@ -151,8 +151,9 @@ public NotificationList getNotifications(String username, String organization, S notification.setNotificationId(rs.getString("NOTIFICATION_ID")); notification.setNotificationType(rs.getString("NOTIFICATION_TYPE")); notification.setCreatedTime(rs.getTimestamp("CREATED_TIME").toString()); - notification.setComments(getCommentFromMetaData(rs.getString("NOTIFICATION_METADATA"), - rs.getString("NOTIFICATION_TYPE"))); + notification.setComments( + getCommentFromMetaData(rs.getString("NOTIFICATION_METADATA"), + rs.getString("NOTIFICATION_TYPE"))); notification.setIsRead(rs.getBoolean("IS_READ")); list.add(notification); } @@ -384,7 +385,8 @@ public NotificationList markAllNotificationsAsRead(String username, String organ ps.setString(3, portalToDisplay); int rowsAffected = ps.executeUpdate(); if (rowsAffected > 0) { - NotificationList notifications = getNotifications(username, organization, portalToDisplay, "desc", 10, 0); + NotificationList notifications = getNotifications(username, organization, portalToDisplay, "desc", + 10, 0); connection.commit(); return notifications; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java index a9a6c9c87948..f7ad4d91bb49 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/constants/SQLConstants.java @@ -3169,14 +3169,11 @@ public class SQLConstants { " AND API.ORGANIZATION = ?" + " AND SUBS.SUB_STATUS != '" + APIConstants.SubscriptionStatus.REJECTED + "'"; - - /** Portal Notifications related constants **/ public static class PortalNotifications { public static final String ADD_NOTIFICATION = "INSERT INTO AM_NOTIFICATION " + "(NOTIFICATION_ID, NOTIFICATION_TYPE, CREATED_TIME, NOTIFICATION_METADATA) VALUES (?, ?, ?, ?)"; - public static final String ADD_NOTIFICATION_END_USER = "INSERT INTO AM_NOTIFICATION_END_USERS " + "(NOTIFICATION_ID, DESTINATION_USER, ORGANIZATION, PORTAL_TO_DISPLAY) " + "VALUES (?, ?, ?, ?)"; public static final String GET_NOTIFICATIONS_DESC = @@ -3195,7 +3192,6 @@ public static class PortalNotifications { "ORDER BY n.CREATED_TIME DESC " + "LIMIT ? , ?" ; - public static final String GET_NOTIFICATIONS_ASC = "SELECT" + " n.NOTIFICATION_ID," + @@ -3212,10 +3208,8 @@ public static class PortalNotifications { "ORDER BY n.CREATED_TIME ASC " + "LIMIT ? , ?" ; - public static final String DELETE_ALL_NOTIFICATIONS_OF_USER = "DELETE FROM AM_NOTIFICATION_END_USERS " + "WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; - public static final String DELETE_NOTIFICATIONS = "DELETE " + "FROM AM_NOTIFICATION " + @@ -3225,14 +3219,11 @@ public static class PortalNotifications { "FROM AM_NOTIFICATION N " + "LEFT JOIN AM_NOTIFICATION_END_USERS NU ON N.NOTIFICATION_ID = NU.NOTIFICATION_ID " + "WHERE NU.NOTIFICATION_ID IS NULL)"; - public static final String MARK_NOTIFICATION_AS_READ = "UPDATE AM_NOTIFICATION_END_USERS SET IS_READ = TRUE " + "WHERE NOTIFICATION_ID = ? AND DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; - public static final String MARK_ALL_NOTIFICATIONS_AS_READ = "UPDATE AM_NOTIFICATION_END_USERS SET IS_READ = TRUE " + "WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; - public static final String GET_NOTIFICATION_BY_ID = "SELECT" + " n.NOTIFICATION_ID," + @@ -3247,21 +3238,17 @@ public static class PortalNotifications { " AND e.DESTINATION_USER = ?" + " AND e.ORGANIZATION = ?" + " AND e.PORTAL_TO_DISPLAY = ?"; - public static final String DELETE_NOTIFICATION_BY_ID = "DELETE FROM AM_NOTIFICATION_END_USERS " + "WHERE NOTIFICATION_ID = ? AND DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; - public static final String GET_API_UUID_USING_NAME_CONTEXT_VERSION = "SELECT API_UUID FROM AM_API WHERE " + "API_NAME = ? AND CONTEXT = ? AND API_VERSION = ? AND ORGANIZATION = ?"; public static final String GET_NOTIFICATIONS_COUNT = "SELECT COUNT(*) AS NOTIFICATION_COUNT FROM " + "AM_NOTIFICATION_END_USERS WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ?"; - public static final String GET_UNREAD_NOTIFICATION_COUNT = "SELECT COUNT(*) AS UNREAD_NOTIFICATION_COUNT FROM AM_NOTIFICATION_END_USERS " + "WHERE DESTINATION_USER = ? AND ORGANIZATION = ? AND PORTAL_TO_DISPLAY = ? AND IS_READ = FALSE"; } - /** Throttle related constants**/ public static class ThrottleSQLConstants{ From e79744aa628ef5cd6130c9b3a022ede11d678251 Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Mon, 13 May 2024 17:30:36 +0530 Subject: [PATCH 22/23] Format the code --- .../APIProductStateChangeWFNotifier.java | 9 +- .../APIRevisionDeploymentWFNotifier.java | 6 +- .../APIStateChangeWFNotifier.java | 6 +- .../AbstractWFNotifier.java | 291 +++++++++--------- ...ationRegistrationProductionWFNotifier.java | 2 +- ...licationRegistrationSandboxWFNotifier.java | 2 +- .../systemNotifications/BaseNotifier.java | 22 +- .../SubscriptionCreationWFNotifier.java | 3 +- .../SubscriptionDeletionWFNotifier.java | 5 +- .../SubscriptionUpdateWFNotifier.java | 5 +- .../WFNotifierFactory.java | 47 +-- 11 files changed, 192 insertions(+), 206 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIProductStateChangeWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIProductStateChangeWFNotifier.java index 20f2babc460d..7c1331f18900 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIProductStateChangeWFNotifier.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIProductStateChangeWFNotifier.java @@ -46,14 +46,11 @@ public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { NotificationMetaData notificationMetaData = new NotificationMetaData(); notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); - notificationMetaData.setApiVersion( - workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setApiVersion(workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); notificationMetaData.setAction(workflowDTO.getProperties(APIConstants.PortalNotifications.ACTION)); - notificationMetaData.setRevisionId( - workflowDTO.getProperties(APIConstants.PortalNotifications.REVISION_ID)); + notificationMetaData.setRevisionId(workflowDTO.getProperties(APIConstants.PortalNotifications.REVISION_ID)); notificationMetaData.setComment(workflowDTO.getComments()); - notificationMetaData.setApiContext( - workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META)); + notificationMetaData.setApiContext(workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META)); return notificationMetaData; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIRevisionDeploymentWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIRevisionDeploymentWFNotifier.java index c4126a0cbd22..952b63095377 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIRevisionDeploymentWFNotifier.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIRevisionDeploymentWFNotifier.java @@ -44,10 +44,8 @@ public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) { public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { NotificationMetaData notificationMetaData = new NotificationMetaData(); notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); - notificationMetaData.setApiVersion( - workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); - notificationMetaData.setRevisionId( - workflowDTO.getProperties(APIConstants.PortalNotifications.REVISION_ID)); + notificationMetaData.setApiVersion(workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setRevisionId(workflowDTO.getProperties(APIConstants.PortalNotifications.REVISION_ID)); notificationMetaData.setComment(workflowDTO.getComments()); return notificationMetaData; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIStateChangeWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIStateChangeWFNotifier.java index 6d6a48c297b3..76c687f894af 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIStateChangeWFNotifier.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/APIStateChangeWFNotifier.java @@ -46,12 +46,10 @@ public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { NotificationMetaData notificationMetaData = new NotificationMetaData(); notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); - notificationMetaData.setApiVersion( - workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setApiVersion(workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); notificationMetaData.setAction(workflowDTO.getProperties(APIConstants.PortalNotifications.ACTION)); notificationMetaData.setComment(workflowDTO.getComments()); - notificationMetaData.setApiContext( - workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META)); + notificationMetaData.setApiContext(workflowDTO.getMetadata(APIConstants.PortalNotifications.API_CONTEXT_META)); return notificationMetaData; } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/AbstractWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/AbstractWFNotifier.java index da6973c6bdb2..b5314e083223 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/AbstractWFNotifier.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/AbstractWFNotifier.java @@ -48,163 +48,158 @@ public abstract class AbstractWFNotifier extends BaseNotifier { - private static final Log log = LogFactory.getLog(AbstractWFNotifier.class); - public abstract NotificationDTO prepareNotification(WorkflowDTO workflowDTO) - throws APIManagementException; - public abstract NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO); - public abstract List getEndUsers(WorkflowDTO workflowDTO) - throws APIManagementException; - - - /** - * This method will return a NotificationEndUserDTO object contains the primary user details - * - * @param primaryUser username of the primary user who make the workflow request - * @param organization organization of the primary user - * @param portalToDisplay portal to display the notification - * @return a NotificationEndUserDTO object - */ - protected NotificationEndUserDTO getPrimaryUser(String primaryUser, String organization, String portalToDisplay) { - NotificationEndUserDTO endUser = new NotificationEndUserDTO(); - if (primaryUser != null) { - endUser.setDestinationUser(primaryUser); - endUser.setOrganization(organization); - endUser.setPortalToDisplay(portalToDisplay); - } - return endUser; + private static final Log log = LogFactory.getLog(AbstractWFNotifier.class); + + public abstract NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIManagementException; + + public abstract NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO); + + public abstract List getEndUsers(WorkflowDTO workflowDTO) throws APIManagementException; + + /** + * This method will return a NotificationEndUserDTO object contains the primary user details + * + * @param primaryUser username of the primary user who make the workflow request + * @param organization organization of the primary user + * @param portalToDisplay portal to display the notification + * @return a NotificationEndUserDTO object + */ + protected NotificationEndUserDTO getPrimaryUser(String primaryUser, String organization, String portalToDisplay) { + NotificationEndUserDTO endUser = new NotificationEndUserDTO(); + if (primaryUser != null) { + endUser.setDestinationUser(primaryUser); + endUser.setOrganization(organization); + endUser.setPortalToDisplay(portalToDisplay); } - - /** - * This method will return the UUID of a given API - * - * @param apiName Name of the API - * @param apiContext Context of the API - * @param apiVersion Version of the API - * @return the UUID of the API - */ - protected String getAPIUUIDUsingNameContextVersion(String apiName, String apiContext, String apiVersion, - String organization) throws APIManagementException { - return NotificationDAO.getInstance() - .getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, organization); - } - - /** - * This method will return the list of subscribers of a given API - * - * @param apiUUID UUID of the API - * @param organization Organization of the API - * @param apiIdEmailReplaced APIIdentifier object with email replaced provider name - * @return the subscribers of the API - */ - protected List getSubscribersOfAPI(String apiUUID, String organization, - APIIdentifier apiIdEmailReplaced) throws APIManagementException { - List subscribedAPIs = new ArrayList<>(); - Set uniqueUserSet = new HashSet<>(); - try { - UserApplicationAPIUsage[] allApiResult = ApiMgtDAO.getInstance() - .getAllAPIUsageByProviderAndApiId(apiUUID, organization); - for (UserApplicationAPIUsage usage : allApiResult) { - for (SubscribedAPI apiSubscription : usage.getApiSubscriptions()) { - APIIdentifier subsApiId = apiSubscription.getAPIIdentifier(); - APIIdentifier subsApiIdEmailReplaced = new APIIdentifier( - APIUtil.replaceEmailDomain(subsApiId.getProviderName()), subsApiId.getApiName(), - subsApiId.getVersion()); - if (subsApiIdEmailReplaced.equals(apiIdEmailReplaced)) { - String userIdentifier = apiSubscription.getSubscriber() - .getName() + "-" + apiSubscription.getOrganization(); - if (uniqueUserSet.add(userIdentifier)) { - subscribedAPIs.add(apiSubscription); - } - } - } + return endUser; + } + + /** + * This method will return the UUID of a given API + * + * @param apiName Name of the API + * @param apiContext Context of the API + * @param apiVersion Version of the API + * @return the UUID of the API + */ + protected String getAPIUUIDUsingNameContextVersion(String apiName, String apiContext, String apiVersion, + String organization) throws APIManagementException { + return NotificationDAO.getInstance() + .getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, organization); + } + + /** + * This method will return the list of subscribers of a given API + * + * @param apiUUID UUID of the API + * @param organization Organization of the API + * @param apiIdEmailReplaced APIIdentifier object with email replaced provider name + * @return the subscribers of the API + */ + protected List getSubscribersOfAPI(String apiUUID, String organization, + APIIdentifier apiIdEmailReplaced) throws APIManagementException { + List subscribedAPIs = new ArrayList<>(); + Set uniqueUserSet = new HashSet<>(); + try { + UserApplicationAPIUsage[] allApiResult = ApiMgtDAO.getInstance() + .getAllAPIUsageByProviderAndApiId(apiUUID, organization); + for (UserApplicationAPIUsage usage : allApiResult) { + for (SubscribedAPI apiSubscription : usage.getApiSubscriptions()) { + APIIdentifier subsApiId = apiSubscription.getAPIIdentifier(); + APIIdentifier subsApiIdEmailReplaced = new APIIdentifier( + APIUtil.replaceEmailDomain(subsApiId.getProviderName()), subsApiId.getApiName(), + subsApiId.getVersion()); + if (subsApiIdEmailReplaced.equals(apiIdEmailReplaced)) { + String userIdentifier = apiSubscription.getSubscriber() + .getName() + "-" + apiSubscription.getOrganization(); + if (uniqueUserSet.add(userIdentifier)) { + subscribedAPIs.add(apiSubscription); } - } catch (APIManagementException e) { - APIUtil.handleException("Error while getting API usage by API ID - getAPIUsageByAPIId()", e); + } } - return subscribedAPIs; + } + } catch (APIManagementException e) { + APIUtil.handleException("Error while getting API usage by API ID - getAPIUsageByAPIId()", e); } - - protected List getSubscriberListOfAPI(String apiAction, String apiName, - String apiContext, String apiVersion, String provider, String tenantDomain) - throws APIManagementException { - List subscriberList = new ArrayList<>(); - - String apiUUID = null; - try { - apiUUID = getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, - tenantDomain); - APIIdentifier apiIdEmailReplaced = new APIIdentifier( - APIUtil.replaceEmailDomain(provider), apiName, apiVersion); - List subscribers = getSubscribersOfAPI(apiUUID, tenantDomain, - apiIdEmailReplaced); - for (SubscribedAPI subscriber : subscribers) { - NotificationEndUserDTO endUser = new NotificationEndUserDTO(); - endUser.setDestinationUser(subscriber.getSubscriber().getName()); - endUser.setOrganization(subscriber.getOrganization()); - endUser.setPortalToDisplay(APIConstants.PortalNotifications.DEV_PORTAL); - subscriberList.add(endUser); - } - } catch (APIManagementException e) { - APIUtil.handleException("Error while getting subscribers of API - getDestinationUser()", - e); - } - - return subscriberList; + return subscribedAPIs; + } + + protected List getSubscriberListOfAPI(String apiAction, String apiName, String apiContext, + String apiVersion, String provider, String tenantDomain) throws APIManagementException { + List subscriberList = new ArrayList<>(); + + String apiUUID = null; + try { + apiUUID = getAPIUUIDUsingNameContextVersion(apiName, apiContext, apiVersion, tenantDomain); + APIIdentifier apiIdEmailReplaced = new APIIdentifier(APIUtil.replaceEmailDomain(provider), apiName, + apiVersion); + List subscribers = getSubscribersOfAPI(apiUUID, tenantDomain, apiIdEmailReplaced); + for (SubscribedAPI subscriber : subscribers) { + NotificationEndUserDTO endUser = new NotificationEndUserDTO(); + endUser.setDestinationUser(subscriber.getSubscriber().getName()); + endUser.setOrganization(subscriber.getOrganization()); + endUser.setPortalToDisplay(APIConstants.PortalNotifications.DEV_PORTAL); + subscriberList.add(endUser); + } + } catch (APIManagementException e) { + APIUtil.handleException("Error while getting subscribers of API - getDestinationUser()", e); } - /** - * This method will return all the users belongs to a given group - * - * @param workflowDTO WorkflowDTO object that contains the workflow details - * @return a list of users belongs to a given group - */ - protected List getAllUsersBelongToGroup(WorkflowDTO workflowDTO, String groupId) - throws UserStoreException { - String tenantDomainOfUser = workflowDTO.getTenantDomain(); - List users = new ArrayList<>(); - - if (groupId != null) { - int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() - .getTenantId(tenantDomainOfUser); - RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService(); - UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId); - if (realm != null) { - UserStoreManager manager = realm.getUserStoreManager(); - AbstractUserStoreManager abstractManager = (AbstractUserStoreManager) manager; - APIManagerConfiguration config = ServiceReferenceHolder.getInstance() - .getAPIManagerConfigurationService().getAPIManagerConfiguration(); - String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI); - if (StringUtils.isBlank(claim)) { - claim = APIConstants.PortalNotifications.DEFAULT_CLAIM; - } - users = abstractManager.getUserListWithID(claim, groupId, "default"); - } + return subscriberList; + } + + /** + * This method will return all the users belongs to a given group + * + * @param workflowDTO WorkflowDTO object that contains the workflow details + * @return a list of users belongs to a given group + */ + protected List getAllUsersBelongToGroup(WorkflowDTO workflowDTO, String groupId) throws UserStoreException { + String tenantDomainOfUser = workflowDTO.getTenantDomain(); + List users = new ArrayList<>(); + + if (groupId != null) { + int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() + .getTenantId(tenantDomainOfUser); + RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService(); + UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId); + if (realm != null) { + UserStoreManager manager = realm.getUserStoreManager(); + AbstractUserStoreManager abstractManager = (AbstractUserStoreManager) manager; + APIManagerConfiguration config = ServiceReferenceHolder.getInstance() + .getAPIManagerConfigurationService().getAPIManagerConfiguration(); + String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI); + if (StringUtils.isBlank(claim)) { + claim = APIConstants.PortalNotifications.DEFAULT_CLAIM; } - return users; + users = abstractManager.getUserListWithID(claim, groupId, "default"); + } } - - /** - * This method will return a NotificationEndUserDTO list containing all the users of a given group - * - * @param primaryUser primary user of the workflow - * @param users a list of users belongs to the group - * @return a NotificationEndUserDTO list - */ - protected List getAllUsersBelongToGroupList(String primaryUser, List users){ - List allUsersOfTheGroup = new ArrayList<>(); - - for (User user : users) { - NotificationEndUserDTO endUser = new NotificationEndUserDTO(); - if (user.getUsername().equals(primaryUser)) { - continue; - } - endUser.setDestinationUser(user.getUsername()); - endUser.setOrganization(user.getTenantDomain()); - endUser.setPortalToDisplay(APIConstants.PortalNotifications.DEV_PORTAL); - allUsersOfTheGroup.add(endUser); + return users; + } + + /** + * This method will return a NotificationEndUserDTO list containing all the users of a given group + * + * @param primaryUser primary user of the workflow + * @param users a list of users belongs to the group + * @return a NotificationEndUserDTO list + */ + protected List getAllUsersBelongToGroupList(String primaryUser, List users) { + List allUsersOfTheGroup = new ArrayList<>(); + + for (User user : users) { + NotificationEndUserDTO endUser = new NotificationEndUserDTO(); + if (user.getUsername().equals(primaryUser)) { + continue; } - - return allUsersOfTheGroup; + endUser.setDestinationUser(user.getUsername()); + endUser.setOrganization(user.getTenantDomain()); + endUser.setPortalToDisplay(APIConstants.PortalNotifications.DEV_PORTAL); + allUsersOfTheGroup.add(endUser); } + return allUsersOfTheGroup; + } + } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationProductionWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationProductionWFNotifier.java index 4be9e9c19977..94c39a09a14f 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationProductionWFNotifier.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationProductionWFNotifier.java @@ -32,7 +32,7 @@ import java.util.ArrayList; import java.util.List; -public class ApplicationRegistrationProductionWFNotifier extends AbstractWFNotifier{ +public class ApplicationRegistrationProductionWFNotifier extends AbstractWFNotifier { private static final Log log = LogFactory.getLog(ApplicationRegistrationProductionWFNotifier.class); @Override diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationSandboxWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationSandboxWFNotifier.java index 5d686b046ac6..f757458781bb 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationSandboxWFNotifier.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/ApplicationRegistrationSandboxWFNotifier.java @@ -32,7 +32,7 @@ import java.util.ArrayList; import java.util.List; -public class ApplicationRegistrationSandboxWFNotifier extends AbstractWFNotifier{ +public class ApplicationRegistrationSandboxWFNotifier extends AbstractWFNotifier { private static final Log log = LogFactory.getLog(ApplicationRegistrationSandboxWFNotifier.class); @Override diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/BaseNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/BaseNotifier.java index 3264df94c806..a4596133725e 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/BaseNotifier.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/BaseNotifier.java @@ -24,20 +24,20 @@ import org.wso2.carbon.apimgt.impl.dao.NotificationDAO; import org.wso2.carbon.apimgt.impl.dto.systemNotifications.NotificationDTO; -public class BaseNotifier implements Notifier{ +public class BaseNotifier implements Notifier { - private static final Log log = LogFactory.getLog(BaseNotifier.class); + private static final Log log = LogFactory.getLog(BaseNotifier.class); - @Override - public void sendNotifications(NotificationDTO notificationDTO) { - try { - boolean result = NotificationDAO.getInstance().addNotification(notificationDTO); - if (!result) { - log.error("Error while adding publisher developer notification."); - } - } catch (APIManagementException e) { - throw new RuntimeException(e); + @Override + public void sendNotifications(NotificationDTO notificationDTO) { + try { + boolean result = NotificationDAO.getInstance().addNotification(notificationDTO); + if (!result) { + log.error("Error while adding publisher developer notification."); } + } catch (APIManagementException e) { + throw new RuntimeException(e); } + } } diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionCreationWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionCreationWFNotifier.java index 7d858b2180f3..0ff7ea1ceb41 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionCreationWFNotifier.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionCreationWFNotifier.java @@ -49,8 +49,7 @@ public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIMa public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { NotificationMetaData notificationMetaData = new NotificationMetaData(); notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); - notificationMetaData.setApiVersion( - workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setApiVersion(workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); notificationMetaData.setApplicationName( workflowDTO.getProperties(APIConstants.PortalNotifications.APPLICATION_NAME)); notificationMetaData.setComment(workflowDTO.getComments()); diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionDeletionWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionDeletionWFNotifier.java index d2c06a4f806d..f09df5fd8a0b 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionDeletionWFNotifier.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionDeletionWFNotifier.java @@ -34,7 +34,7 @@ import java.util.ArrayList; import java.util.List; -public class SubscriptionDeletionWFNotifier extends AbstractWFNotifier{ +public class SubscriptionDeletionWFNotifier extends AbstractWFNotifier { private static final Log log = LogFactory.getLog(SubscriptionDeletionWFNotifier.class); @Override @@ -50,8 +50,7 @@ public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIMa public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { NotificationMetaData notificationMetaData = new NotificationMetaData(); notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); - notificationMetaData.setApiVersion( - workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setApiVersion(workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); notificationMetaData.setApplicationName( workflowDTO.getProperties(APIConstants.PortalNotifications.APPLICATION_NAME)); notificationMetaData.setComment(workflowDTO.getComments()); diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionUpdateWFNotifier.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionUpdateWFNotifier.java index fdf58dc2276f..10bd5107c84a 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionUpdateWFNotifier.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/SubscriptionUpdateWFNotifier.java @@ -33,7 +33,7 @@ import java.util.ArrayList; import java.util.List; -public class SubscriptionUpdateWFNotifier extends AbstractWFNotifier{ +public class SubscriptionUpdateWFNotifier extends AbstractWFNotifier { private static final Log log = LogFactory.getLog(SubscriptionUpdateWFNotifier.class); public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIManagementException { @@ -48,8 +48,7 @@ public NotificationDTO prepareNotification(WorkflowDTO workflowDTO) throws APIMa public NotificationMetaData getNotificationMetaData(WorkflowDTO workflowDTO) { NotificationMetaData notificationMetaData = new NotificationMetaData(); notificationMetaData.setApi(workflowDTO.getProperties(APIConstants.PortalNotifications.API_NAME)); - notificationMetaData.setApiVersion( - workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); + notificationMetaData.setApiVersion(workflowDTO.getProperties(APIConstants.PortalNotifications.API_VERSION)); notificationMetaData.setApplicationName( workflowDTO.getProperties(APIConstants.PortalNotifications.APPLICATION_NAME)); notificationMetaData.setRequestedTier( diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/WFNotifierFactory.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/WFNotifierFactory.java index 623ec58437b9..63a0a54a8625 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/WFNotifierFactory.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/systemNotifications/WFNotifierFactory.java @@ -25,29 +25,30 @@ public class WFNotifierFactory { private static final Log log = LogFactory.getLog(WFNotifierFactory.class); - public static AbstractWFNotifier getNotifier(String notifierType) { - if (notifierType == null) { - return null; - } - if (notifierType.equals(WorkflowConstants.WF_TYPE_AM_API_STATE)) { - return new APIStateChangeWFNotifier(); - } else if (notifierType.equals(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)) { - return new APIProductStateChangeWFNotifier(); - } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT)) { - return new APIRevisionDeploymentWFNotifier(); - } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION)) { - return new ApplicationCreationWFNotifier(); - } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION)) { - return new ApplicationRegistrationProductionWFNotifier(); - } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX)) { - return new ApplicationRegistrationSandboxWFNotifier(); - } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION)) { - return new SubscriptionCreationWFNotifier(); - } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE)) { - return new SubscriptionUpdateWFNotifier(); - } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION)) { - return new SubscriptionDeletionWFNotifier(); - } + + public static AbstractWFNotifier getNotifier(String notifierType) { + if (notifierType == null) { return null; } + if (notifierType.equals(WorkflowConstants.WF_TYPE_AM_API_STATE)) { + return new APIStateChangeWFNotifier(); + } else if (notifierType.equals(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)) { + return new APIProductStateChangeWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT)) { + return new APIRevisionDeploymentWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION)) { + return new ApplicationCreationWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION)) { + return new ApplicationRegistrationProductionWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX)) { + return new ApplicationRegistrationSandboxWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION)) { + return new SubscriptionCreationWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE)) { + return new SubscriptionUpdateWFNotifier(); + } else if (notifierType.equalsIgnoreCase(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION)) { + return new SubscriptionDeletionWFNotifier(); + } + return null; + } } From b7ef0507a7dd39872787f5c0e8bd1089433658fe Mon Sep 17 00:00:00 2001 From: HelaniUdara Date: Tue, 14 May 2024 13:56:21 +0530 Subject: [PATCH 23/23] Update --- .../main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java index 55683a31126c..a4300eda4f05 100644 --- a/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java +++ b/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java @@ -8719,10 +8719,8 @@ public void populateAppRegistrationWorkflowDTO(ApplicationRegistrationWorkflowDT workflowDTO.setDomainList(rs.getString("ALLOWED_DOMAINS")); workflowDTO.setValidityTime(rs.getLong("VALIDITY_PERIOD")); String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName()); - if (multiGroupAppSharingEnabled) { - if (application.getGroupId() == null || application.getGroupId().isEmpty()) { + if (multiGroupAppSharingEnabled && StringUtils.isEmpty(application.getGroupId())) { application.setGroupId(getGroupId(conn, application.getId())); - } } String keyManagerUUID = rs.getString("KEY_MANAGER"); workflowDTO.setKeyManager(keyManagerUUID);