Improve APPM subscription data retrieving logic

Co-authored-by: Rajitha Kumara <rajitha@entgra.io>
Co-committed-by: Rajitha Kumara <rajitha@entgra.io>
master
Rajitha Kumara 4 months ago committed by Lasantha Dharmakeerthi
parent d53ab7cea2
commit 40c12875ac

@ -0,0 +1,115 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.common;
import java.sql.Timestamp;
public class DeviceSubscription {
private int deviceId;
private int subscriptionId;
private String deviceName;
private String deviceIdentifier;
private String deviceStatus;
private String deviceOwner;
private String deviceType;
private String ownershipType;
private Timestamp dateOfLastUpdate;
private SubscriptionData subscriptionData;
public int getSubscriptionId() {
return subscriptionId;
}
public void setSubscriptionId(int subscriptionId) {
this.subscriptionId = subscriptionId;
}
public int getDeviceId() {
return deviceId;
}
public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getDeviceIdentifier() {
return deviceIdentifier;
}
public void setDeviceIdentifier(String deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
}
public String getDeviceStatus() {
return deviceStatus;
}
public void setDeviceStatus(String deviceStatus) {
this.deviceStatus = deviceStatus;
}
public String getDeviceOwner() {
return deviceOwner;
}
public void setDeviceOwner(String deviceOwner) {
this.deviceOwner = deviceOwner;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public String getOwnershipType() {
return ownershipType;
}
public void setOwnershipType(String ownershipType) {
this.ownershipType = ownershipType;
}
public Timestamp getDateOfLastUpdate() {
return dateOfLastUpdate;
}
public void setDateOfLastUpdate(Timestamp dateOfLastUpdate) {
this.dateOfLastUpdate = dateOfLastUpdate;
}
public SubscriptionData getSubscriptionData() {
return subscriptionData;
}
public void setSubscriptionData(SubscriptionData subscriptionData) {
this.subscriptionData = subscriptionData;
}
}

@ -0,0 +1,68 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.common;
public class DeviceSubscriptionFilterCriteria {
private String name;
private String owner;
private String deviceStatus;
private String filteringDeviceSubscriptionStatus; // COMPLETE, PENDING ...
private String triggeredBy;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getDeviceStatus() {
return deviceStatus;
}
public void setDeviceStatus(String deviceStatus) {
this.deviceStatus = deviceStatus;
}
public String getFilteringDeviceSubscriptionStatus() {
return filteringDeviceSubscriptionStatus;
}
public void setFilteringDeviceSubscriptionStatus(String filteringDeviceSubscriptionStatus) {
this.filteringDeviceSubscriptionStatus = filteringDeviceSubscriptionStatus;
}
public String getTriggeredBy() {
return triggeredBy;
}
public void setTriggeredBy(String triggeredBy) {
this.triggeredBy = triggeredBy;
}
}

@ -0,0 +1,70 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.common;
import java.sql.Timestamp;
public class SubscriptionData {
private String deviceSubscriptionStatus;
private String triggeredBy;
private String subscriptionType;
private Timestamp triggeredAt;
private int subscriptionId;
public String getDeviceSubscriptionStatus() {
return deviceSubscriptionStatus;
}
public void setDeviceSubscriptionStatus(String deviceSubscriptionStatus) {
this.deviceSubscriptionStatus = deviceSubscriptionStatus;
}
public String getTriggeredBy() {
return triggeredBy;
}
public void setTriggeredBy(String triggeredBy) {
this.triggeredBy = triggeredBy;
}
public String getSubscriptionType() {
return subscriptionType;
}
public void setSubscriptionType(String subscriptionType) {
this.subscriptionType = subscriptionType;
}
public Timestamp getTriggeredAt() {
return triggeredAt;
}
public void setTriggeredAt(Timestamp triggeredAt) {
this.triggeredAt = triggeredAt;
}
public int getSubscriptionId() {
return subscriptionId;
}
public void setSubscriptionId(int subscriptionId) {
this.subscriptionId = subscriptionId;
}
}

@ -0,0 +1,88 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.common;
import java.sql.Timestamp;
public class SubscriptionEntity {
private String identity;
private String subscribedBy;
private Timestamp subscribedTimestamp;
private boolean unsubscribed;
private String unsubscribedBy;
private Timestamp unsubscribedTimestamp;
private int applicationReleaseId;
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
public String getSubscribedBy() {
return subscribedBy;
}
public void setSubscribedBy(String subscribedBy) {
this.subscribedBy = subscribedBy;
}
public Timestamp getSubscribedTimestamp() {
return subscribedTimestamp;
}
public void setSubscribedTimestamp(Timestamp subscribedTimestamp) {
this.subscribedTimestamp = subscribedTimestamp;
}
public boolean getUnsubscribed() {
return unsubscribed;
}
public void setUnsubscribed(boolean unsubscribed) {
this.unsubscribed = unsubscribed;
}
public String getUnsubscribedBy() {
return unsubscribedBy;
}
public void setUnsubscribedBy(String unsubscribedBy) {
this.unsubscribedBy = unsubscribedBy;
}
public Timestamp getUnsubscribedTimestamp() {
return unsubscribedTimestamp;
}
public void setUnsubscribedTimestamp(Timestamp unsubscribedTimestamp) {
this.unsubscribedTimestamp = unsubscribedTimestamp;
}
public int getApplicationReleaseId() {
return applicationReleaseId;
}
public void setApplicationReleaseId(int applicationReleaseId) {
this.applicationReleaseId = applicationReleaseId;
}
}

@ -0,0 +1,77 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.common;
public class SubscriptionInfo {
private String applicationUUID;
private String subscriptionType;
private String deviceSubscriptionStatus;
private String identifier;
private String subscriptionStatus;
private DeviceSubscriptionFilterCriteria deviceSubscriptionFilterCriteria;
public String getApplicationUUID() {
return applicationUUID;
}
public void setApplicationUUID(String applicationUUID) {
this.applicationUUID = applicationUUID;
}
public String getSubscriptionType() {
return subscriptionType;
}
public void setSubscriptionType(String subscriptionType) {
this.subscriptionType = subscriptionType;
}
public String getDeviceSubscriptionStatus() {
return deviceSubscriptionStatus;
}
public void setDeviceSubscriptionStatus(String deviceSubscriptionStatus) {
this.deviceSubscriptionStatus = deviceSubscriptionStatus;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getSubscriptionStatus() {
return subscriptionStatus;
}
public void setSubscriptionStatus(String subscriptionStatus) {
this.subscriptionStatus = subscriptionStatus;
}
public DeviceSubscriptionFilterCriteria getDeviceSubscriptionFilterCriteria() {
return deviceSubscriptionFilterCriteria;
}
public void setDeviceSubscriptionFilterCriteria(DeviceSubscriptionFilterCriteria deviceSubscriptionFilterCriteria) {
this.deviceSubscriptionFilterCriteria = deviceSubscriptionFilterCriteria;
}
}

@ -0,0 +1,68 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.common;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SubscriptionMetadata {
public static final class DeviceSubscriptionStatus {
public static final String NEW = "NEW";
public static final String PENDING = "PENDING";
public static final String COMPLETED = "COMPLETED";
public static final String ERROR = "ERROR";
public static final String INVALID = "INVALID";
public static final String UNAUTHORIZED = "UNAUTHORIZED";
public static final String IN_PROGRESS = "IN_PROGRESS";
public static final String REPEAT = "REPEAT";
}
public static final class SubscriptionTypes {
public static final String ROLE = "role";
public static final String DEVICE = "device";
public static final String GROUP = "group";
public static final String USER = "user";
}
public static final class DBSubscriptionStatus {
public static final List<String> COMPLETED_STATUS_LIST =
Collections.singletonList(DeviceSubscriptionStatus.COMPLETED);
public static final List<String> ERROR_STATUS_LIST =
Arrays.asList(DeviceSubscriptionStatus.ERROR, DeviceSubscriptionStatus.INVALID, DeviceSubscriptionStatus.UNAUTHORIZED);
public static final List<String> PENDING_STATUS_LIST =
Arrays.asList(DeviceSubscriptionStatus.PENDING, DeviceSubscriptionStatus.IN_PROGRESS, DeviceSubscriptionStatus.REPEAT);
}
public static Map<String, List<String>> deviceSubscriptionStatusToDBSubscriptionStatusMap;
static {
Map<String, List<String>> statusMap = new HashMap<>();
statusMap.put(DeviceSubscriptionStatus.COMPLETED, DBSubscriptionStatus.COMPLETED_STATUS_LIST);
statusMap.put(DeviceSubscriptionStatus.PENDING, DBSubscriptionStatus.PENDING_STATUS_LIST);
statusMap.put(DeviceSubscriptionStatus.IN_PROGRESS, DBSubscriptionStatus.PENDING_STATUS_LIST);
statusMap.put(DeviceSubscriptionStatus.REPEAT, DBSubscriptionStatus.PENDING_STATUS_LIST);
statusMap.put(DeviceSubscriptionStatus.ERROR, DBSubscriptionStatus.ERROR_STATUS_LIST);
statusMap.put(DeviceSubscriptionStatus.INVALID, DBSubscriptionStatus.ERROR_STATUS_LIST);
statusMap.put(DeviceSubscriptionStatus.UNAUTHORIZED, DBSubscriptionStatus.ERROR_STATUS_LIST);
deviceSubscriptionStatusToDBSubscriptionStatusMap = Collections.unmodifiableMap(statusMap);
}
}

@ -0,0 +1,63 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.common;
import java.util.List;
public class SubscriptionResponse {
private String applicationUUID;
private int count;
private List<?> data;
public SubscriptionResponse(String applicationUUID, int count, List<?> data) {
this.applicationUUID = applicationUUID;
this.count = count;
this.data = data;
}
public SubscriptionResponse(String applicationUUID, List<?> data) {
this.applicationUUID = applicationUUID;
this.data = data;
}
public String getApplicationUUID() {
return applicationUUID;
}
public void setApplicationUUID(String applicationUUID) {
this.applicationUUID = applicationUUID;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<?> getData() {
return data;
}
public void setData(List<?> data) {
this.data = data;
}
}

@ -0,0 +1,68 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.common;
public class SubscriptionStatistics {
private float completedPercentage;
private float failedPercentage;
private float pendingPercentage;
private float newDevicesPercentage;
public SubscriptionStatistics() {}
public SubscriptionStatistics(float completedPercentage, float failedPercentage, float pendingPercentage,
float newDevicesPercentage) {
this.completedPercentage = completedPercentage;
this.failedPercentage = failedPercentage;
this.pendingPercentage = pendingPercentage;
this.newDevicesPercentage = newDevicesPercentage;
}
public float getCompletedPercentage() {
return completedPercentage;
}
public void setCompletedPercentage(float completedPercentage) {
this.completedPercentage = completedPercentage;
}
public float getFailedPercentage() {
return failedPercentage;
}
public void setFailedPercentage(float failedPercentage) {
this.failedPercentage = failedPercentage;
}
public float getPendingPercentage() {
return pendingPercentage;
}
public void setPendingPercentage(float pendingPercentage) {
this.pendingPercentage = pendingPercentage;
}
public float getNewDevicesPercentage() {
return newDevicesPercentage;
}
public void setNewDevicesPercentage(float newDevicesPercentage) {
this.newDevicesPercentage = newDevicesPercentage;
}
}

@ -19,6 +19,7 @@
package io.entgra.device.mgt.core.application.mgt.common.dto;
import java.sql.Timestamp;
import java.util.Objects;
public class DeviceSubscriptionDTO {
@ -34,6 +35,19 @@ public class DeviceSubscriptionDTO {
private int appReleaseId;
private String appUuid;
public DeviceSubscriptionDTO() {
}
public DeviceSubscriptionDTO(int deviceId) {
this.deviceId = deviceId;
}
public DeviceSubscriptionDTO(int deviceId, String status) {
this.deviceId = deviceId;
this.status = status;
}
public int getId() {
return id;
}
@ -121,4 +135,17 @@ public class DeviceSubscriptionDTO {
public void setAppUuid(String appUuid) {
this.appUuid = appUuid;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeviceSubscriptionDTO that = (DeviceSubscriptionDTO) o;
return deviceId == that.deviceId;
}
@Override
public int hashCode() {
return Objects.hash(deviceId);
}
}

@ -0,0 +1,62 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.common.dto;
public class SubscriptionStatisticDTO {
private int completedDeviceCount = 0;
private int pendingDevicesCount = 0;
private int failedDevicesCount = 0;
public void addToComplete(int count) {
completedDeviceCount += count;
}
public void addToPending(int count) {
pendingDevicesCount += count;
}
public void addToFailed(int count) {
failedDevicesCount += count ;
}
public int getCompletedDeviceCount() {
return completedDeviceCount;
}
public void setCompletedDeviceCount(int completedDeviceCount) {
this.completedDeviceCount = completedDeviceCount;
}
public int getPendingDevicesCount() {
return pendingDevicesCount;
}
public void setPendingDevicesCount(int pendingDevicesCount) {
this.pendingDevicesCount = pendingDevicesCount;
}
public int getFailedDevicesCount() {
return failedDevicesCount;
}
public void setFailedDevicesCount(int failedDevicesCount) {
this.failedDevicesCount = failedDevicesCount;
}
}

@ -19,9 +19,16 @@ package io.entgra.device.mgt.core.application.mgt.common.services;
import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstallResponse;
import io.entgra.device.mgt.core.application.mgt.common.CategorizedSubscriptionResult;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscription;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscriptionData;
import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionEntity;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionInfo;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionResponse;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionStatistics;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType;
import io.entgra.device.mgt.core.application.mgt.common.dto.CategorizedSubscriptionCountsDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.ScheduledSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionsDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceOperationDTO;
@ -224,72 +231,34 @@ public interface SubscriptionManager {
Activity getOperationAppDetails(String id) throws SubscriptionManagementException;
/**
* Retrieves the group details associated with a given app release UUID.
*
* @param uuid the UUID of the app release
* @param subscriptionStatus the status of the subscription (subscribed or unsubscribed)
* @param offset the offset for the data set
* @param limit the limit for the data set
* @return {@link SubscriptionsDTO} which contains the details of subscriptions.
* @throws ApplicationManagementException if an error occurs while fetching the group details
*/
public List<SubscriptionsDTO> getGroupsSubscriptionDetailsByUUID(String uuid, String subscriptionStatus,
PaginationRequest request, int offset,
int limit) throws ApplicationManagementException;
/**
* Retrieves the user details associated with a given app release UUID.
*
* @param uuid the UUID of the app release
* @param subscriptionStatus the status of the subscription (subscribed or unsubscribed)
* @param offset the offset for the data set
* @param limit the limit for the data set
* @return {@link SubscriptionsDTO} which contains the details of subscriptions.
* @throws ApplicationManagementException if an error occurs while fetching the user details
*/
List<SubscriptionsDTO> getUserSubscriptionsByUUID(String uuid, String subscriptionStatus, PaginationRequest request,
int offset, int limit) throws ApplicationManagementException;
/**
* Retrieves the Role details associated with a given app release UUID.
*
* @param uuid the UUID of the app release
* @param subscriptionStatus the status of the subscription (subscribed or unsubscribed)
* @param offset the offset for the data set
* @param limit the limit for the data set
* @return {@link SubscriptionsDTO} which contains the details of subscriptions.
* @throws ApplicationManagementException if an error occurs while fetching the role details
* Get subscription data describes by {@link SubscriptionInfo} entity
* @param subscriptionInfo {@link SubscriptionInfo}
* @param limit Limit value
* @param offset Offset value
* @return {@link SubscriptionResponse}
* @throws ApplicationManagementException Throws when error encountered while getting subscription data
*/
List<SubscriptionsDTO> getRoleSubscriptionsByUUID(String uuid, String subscriptionStatus, PaginationRequest request,
int offset, int limit) throws ApplicationManagementException;
SubscriptionResponse getSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException;
/**
* Retrieves the Device Subscription details associated with a given app release UUID.
*
* @param uuid the UUID of the app release
* @param subscriptionStatus the status of the subscription (subscribed or unsubscribed)
* @param offset the offset for the data set
* @param limit the limit for the data set
* @return {@link DeviceSubscriptionResponseDTO} which contains the details of device subscriptions.
* @throws ApplicationManagementException if an error occurs while fetching the device subscription details
* Get status based subscription data describes by {@link SubscriptionInfo} entity
* @param subscriptionInfo {@link SubscriptionInfo}
* @param limit Limit value
* @param offset Offset value
* @return {@link SubscriptionResponse}
* @throws ApplicationManagementException Throws when error encountered while getting subscription data
*/
DeviceSubscriptionResponseDTO getDeviceSubscriptionsDetailsByUUID(String uuid, String subscriptionStatus,
PaginationRequest request, int offset,
int limit) throws ApplicationManagementException;
SubscriptionResponse getStatusBaseSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException;
/**
* Retrieves the All Device details associated with a given app release UUID.
*
* @param uuid the UUID of the app release
* @param subscriptionStatus the status of the subscription (subscribed or unsubscribed)
* @param offset the offset for the data set
* @param limit the limit for the data set
* @return {@link DeviceSubscriptionResponseDTO} which contains the details of device subscriptions.
* @throws ApplicationManagementException if an error occurs while fetching the subscription details
* Get subscription statistics related data describes by the {@link SubscriptionInfo}
* @param subscriptionInfo {@link SubscriptionInfo}
* @return {@link SubscriptionStatistics}
* @throws ApplicationManagementException Throws when error encountered while getting statistics
*/
DeviceSubscriptionResponseDTO getAllSubscriptionDetailsByUUID(String uuid, String subscriptionStatus,
PaginationRequest request, int offset,
int limit) throws ApplicationManagementException;
SubscriptionStatistics getStatistics(SubscriptionInfo subscriptionInfo) throws ApplicationManagementException;
/**
* This method is responsible for retrieving device subscription details related to the given UUID.

@ -19,6 +19,8 @@ package io.entgra.device.mgt.core.application.mgt.core.dao;
import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus;
import io.entgra.device.mgt.core.application.mgt.common.dto.GroupSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionEntity;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionStatisticDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionsDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO;
@ -327,7 +329,7 @@ public interface SubscriptionDAO {
* @return {@link GroupSubscriptionDTO} which contains the details of group subscriptions.
* @throws ApplicationManagementDAOException if connection establishment fails.
*/
List<GroupSubscriptionDTO> getGroupsSubscriptionDetailsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
List<SubscriptionEntity> getGroupsSubscriptionDetailsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException;
/**
@ -341,7 +343,7 @@ public interface SubscriptionDAO {
* @return {@link SubscriptionsDTO} which contains the details of subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
List<SubscriptionsDTO> getUserSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId,
List<SubscriptionEntity> getUserSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId,
int offset, int limit) throws ApplicationManagementDAOException;
/**
@ -355,7 +357,7 @@ public interface SubscriptionDAO {
* @return {@link SubscriptionsDTO} which contains the details of subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
List<SubscriptionsDTO> getRoleSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
List<SubscriptionEntity> getRoleSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException;
/**
@ -398,8 +400,11 @@ public interface SubscriptionDAO {
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
List<DeviceSubscriptionDTO> getSubscriptionDetailsByDeviceIds(int appReleaseId, boolean unsubscribe, int tenantId,
List<Integer> deviceIds, String actionStatus, String actionType,
String actionTriggeredBy, String tabActionStatus) throws ApplicationManagementDAOException;
List<Integer> deviceIds, List<String> actionStatus, String actionType,
String actionTriggeredBy, int limit, int offset) throws ApplicationManagementDAOException;
int getDeviceSubscriptionCount(int appReleaseId, boolean unsubscribe, int tenantId,
List<Integer> deviceIds, List<String> actionStatus, String actionType,
String actionTriggeredBy) throws ApplicationManagementDAOException;
/**
* This method is used to get the details of device subscriptions related to a UUID.
@ -415,9 +420,13 @@ public interface SubscriptionDAO {
* @return {@link DeviceOperationDTO} which contains the details of device subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
List<DeviceSubscriptionDTO> getAllSubscriptionsDetails(int appReleaseId, boolean unsubscribe, int tenantId, String actionStatus, String actionType,
List<DeviceSubscriptionDTO> getAllSubscriptionsDetails(int appReleaseId, boolean unsubscribe, int tenantId, List<String> actionStatus, String actionType,
String actionTriggeredBy, int offset, int limit) throws ApplicationManagementDAOException;
int getAllSubscriptionsCount(int appReleaseId, boolean unsubscribe, int tenantId,
List<String> actionStatus, String actionType, String actionTriggeredBy)
throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of all subscription types related to a UUID.
*
@ -518,6 +527,8 @@ public interface SubscriptionDAO {
*/
int getUserUnsubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
SubscriptionStatisticDTO getSubscriptionStatistic(List<Integer> deviceIds, String subscriptionType, boolean isUnsubscribed,
int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of devices related to a UUID.
*

@ -17,8 +17,11 @@
*/
package io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionMetadata;
import io.entgra.device.mgt.core.application.mgt.common.dto.GroupSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceOperationDTO;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionEntity;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionStatisticDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionsDTO;
import io.entgra.device.mgt.core.application.mgt.core.dao.SubscriptionDAO;
import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl;
@ -43,9 +46,11 @@ import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.stream.Collectors;
@ -1641,20 +1646,27 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
}
@Override
public List<GroupSubscriptionDTO> getGroupsSubscriptionDetailsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
public List<SubscriptionEntity> getGroupsSubscriptionDetailsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get groups related to the given AppReleaseID.");
}
try {
Connection conn = this.getDBConnection();
List<GroupSubscriptionDTO> groupDetails = new ArrayList<>();
List<SubscriptionEntity> subscriptionEntities = new ArrayList<>();
String subscriptionStatusTime = unsubscribe ? "GS.UNSUBSCRIBED_TIMESTAMP" : "GS.SUBSCRIBED_TIMESTAMP";
String sql = "SELECT GS.GROUP_NAME, GS.SUBSCRIBED_BY, GS.SUBSCRIBED_TIMESTAMP, GS.UNSUBSCRIBED, " +
"GS.UNSUBSCRIBED_BY, GS.UNSUBSCRIBED_TIMESTAMP, GS.AP_APP_RELEASE_ID " +
String sql = "SELECT GS.GROUP_NAME, " +
"GS.SUBSCRIBED_BY, " +
"GS.SUBSCRIBED_TIMESTAMP, " +
"GS.UNSUBSCRIBED, " +
"GS.UNSUBSCRIBED_BY, " +
"GS.UNSUBSCRIBED_TIMESTAMP, " +
"GS.AP_APP_RELEASE_ID " +
"FROM AP_GROUP_SUBSCRIPTION GS " +
"WHERE GS.AP_APP_RELEASE_ID = ? AND GS.UNSUBSCRIBED = ? AND GS.TENANT_ID = ? " +
"WHERE GS.AP_APP_RELEASE_ID = ? " +
"AND GS.UNSUBSCRIBED = ? " +
"AND GS.TENANT_ID = ? " +
"ORDER BY " + subscriptionStatusTime + " DESC ";
// Append limit and offset only if limit is not -1
@ -1673,21 +1685,21 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
}
try (ResultSet rs = ps.executeQuery()) {
GroupSubscriptionDTO groupDetail;
SubscriptionEntity subscriptionEntity;
while (rs.next()) {
groupDetail = new GroupSubscriptionDTO();
groupDetail.setGroupName(rs.getString("GROUP_NAME"));
groupDetail.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
groupDetail.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
groupDetail.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
groupDetail.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
groupDetail.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
groupDetail.setAppReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
groupDetails.add(groupDetail);
subscriptionEntity = new SubscriptionEntity();
subscriptionEntity.setIdentity(rs.getString("GROUP_NAME"));
subscriptionEntity.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscriptionEntity.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
subscriptionEntity.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscriptionEntity.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setApplicationReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
subscriptionEntities.add(subscriptionEntity);
}
}
return groupDetails;
return subscriptionEntities;
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get groups for the given UUID.";
@ -1701,20 +1713,27 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
}
@Override
public List<SubscriptionsDTO> getUserSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId,
public List<SubscriptionEntity> getUserSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId,
int offset, int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get user subscriptions related to the given UUID.");
}
try {
Connection conn = this.getDBConnection();
List<SubscriptionsDTO> userSubscriptions = new ArrayList<>();
List<SubscriptionEntity> subscriptionEntities = new ArrayList<>();
String subscriptionStatusTime = unsubscribe ? "US.UNSUBSCRIBED_TIMESTAMP" : "US.SUBSCRIBED_TIMESTAMP";
String sql = "SELECT US.USER_NAME, US.SUBSCRIBED_BY, US.SUBSCRIBED_TIMESTAMP, US.UNSUBSCRIBED, " +
"US.UNSUBSCRIBED_BY, US.UNSUBSCRIBED_TIMESTAMP, US.AP_APP_RELEASE_ID " +
String sql = "SELECT US.USER_NAME, " +
"US.SUBSCRIBED_BY, " +
"US.SUBSCRIBED_TIMESTAMP, " +
"US.UNSUBSCRIBED, " +
"US.UNSUBSCRIBED_BY, " +
"US.UNSUBSCRIBED_TIMESTAMP, " +
"US.AP_APP_RELEASE_ID " +
"FROM AP_USER_SUBSCRIPTION US " +
"WHERE US.AP_APP_RELEASE_ID = ? AND US.UNSUBSCRIBED = ? AND US.TENANT_ID = ? " +
"WHERE US.AP_APP_RELEASE_ID = ? " +
"AND US.UNSUBSCRIBED = ? " +
"AND US.TENANT_ID = ? " +
"ORDER BY " + subscriptionStatusTime + " DESC " +
"LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
@ -1724,21 +1743,21 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
ps.setInt(4, limit);
ps.setInt(5, offset);
try (ResultSet rs = ps.executeQuery()) {
SubscriptionEntity subscriptionEntity;
while (rs.next()) {
SubscriptionsDTO userSubscription;
userSubscription = new SubscriptionsDTO();
userSubscription.setName(rs.getString("USER_NAME"));
userSubscription.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
userSubscription.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
userSubscription.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
userSubscription.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
userSubscription.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
userSubscription.setAppReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
userSubscriptions.add(userSubscription);
subscriptionEntity = new SubscriptionEntity();
subscriptionEntity.setIdentity(rs.getString("USER_NAME"));
subscriptionEntity.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscriptionEntity.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
subscriptionEntity.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscriptionEntity.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setApplicationReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
subscriptionEntities.add(subscriptionEntity);
}
}
return userSubscriptions;
return subscriptionEntities;
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get user subscriptions for the given UUID.";
@ -1752,20 +1771,27 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
}
@Override
public List<SubscriptionsDTO> getRoleSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset,
int limit) throws ApplicationManagementDAOException {
public List<SubscriptionEntity> getRoleSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset,
int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get role subscriptions related to the given AppReleaseID.");
}
try {
Connection conn = this.getDBConnection();
List<SubscriptionsDTO> roleSubscriptions = new ArrayList<>();
List<SubscriptionEntity> subscriptionEntities = new ArrayList<>();
String subscriptionStatusTime = unsubscribe ? "ARS.UNSUBSCRIBED_TIMESTAMP" : "ARS.SUBSCRIBED_TIMESTAMP";
String sql = "SELECT ARS.ROLE_NAME, ARS.SUBSCRIBED_BY, ARS.SUBSCRIBED_TIMESTAMP, ARS.UNSUBSCRIBED, " +
"ARS.UNSUBSCRIBED_BY, ARS.UNSUBSCRIBED_TIMESTAMP, ARS.AP_APP_RELEASE_ID " +
String sql = "SELECT ARS.ROLE_NAME, " +
"ARS.SUBSCRIBED_BY, " +
"ARS.SUBSCRIBED_TIMESTAMP, " +
"ARS.UNSUBSCRIBED, " +
"ARS.UNSUBSCRIBED_BY, " +
"ARS.UNSUBSCRIBED_TIMESTAMP, " +
"ARS.AP_APP_RELEASE_ID " +
"FROM AP_ROLE_SUBSCRIPTION ARS " +
"WHERE ARS.AP_APP_RELEASE_ID = ? AND ARS.UNSUBSCRIBED = ? AND ARS.TENANT_ID = ? " +
"WHERE ARS.AP_APP_RELEASE_ID = ? " +
"AND ARS.UNSUBSCRIBED = ? " +
"AND ARS.TENANT_ID = ? " +
"ORDER BY " + subscriptionStatusTime + " DESC " +
"LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
@ -1775,21 +1801,21 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
ps.setInt(4, limit);
ps.setInt(5, offset);
try (ResultSet rs = ps.executeQuery()) {
SubscriptionsDTO roleSubscription;
SubscriptionEntity subscriptionEntity;
while (rs.next()) {
roleSubscription = new SubscriptionsDTO();
roleSubscription.setName(rs.getString("ROLE_NAME"));
roleSubscription.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
roleSubscription.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
roleSubscription.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
roleSubscription.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
roleSubscription.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
roleSubscription.setAppReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
roleSubscriptions.add(roleSubscription);
subscriptionEntity = new SubscriptionEntity();
subscriptionEntity.setIdentity(rs.getString("ROLE_NAME"));
subscriptionEntity.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscriptionEntity.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
subscriptionEntity.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscriptionEntity.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setApplicationReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
subscriptionEntities.add(subscriptionEntity);
}
}
return roleSubscriptions;
return subscriptionEntities;
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get role subscriptions for the given UUID.";
@ -1918,14 +1944,20 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
}
}
// passed the required list for the action status
@Override
public List<DeviceSubscriptionDTO> getSubscriptionDetailsByDeviceIds(int appReleaseId, boolean unsubscribe, int tenantId,
List<Integer> deviceIds, String actionStatus, String actionType,
String actionTriggeredBy, String tabActionStatus) throws ApplicationManagementDAOException {
List<Integer> deviceIds, List<String> actionStatus, String actionType,
String actionTriggeredBy, int limit, int offset) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting device subscriptions for the application release id " + appReleaseId
+ " and device ids " + deviceIds + " from the database");
}
if (deviceIds == null || deviceIds.isEmpty()) {
return Collections.emptyList();
}
try {
Connection conn = this.getDBConnection();
String subscriptionStatusTime = unsubscribe ? "DS.UNSUBSCRIBED_TIMESTAMP" : "DS.SUBSCRIBED_TIMESTAMP";
@ -1940,11 +1972,15 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
+ "DS.STATUS AS STATUS, "
+ "DS.DM_DEVICE_ID AS DEVICE_ID "
+ "FROM AP_DEVICE_SUBSCRIPTION DS "
+ "WHERE DS.AP_APP_RELEASE_ID = ? AND DS.UNSUBSCRIBED = ? AND DS.TENANT_ID = ? AND DS.DM_DEVICE_ID IN (" +
deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ") ");
+ "WHERE DS.AP_APP_RELEASE_ID = ? "
+ "AND DS.UNSUBSCRIBED = ? "
+ "AND DS.TENANT_ID = ? "
+ "AND DS.DM_DEVICE_ID IN ("
+ deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ") ");
if (actionStatus != null && !actionStatus.isEmpty()) {
sql.append(" AND DS.STATUS = ? ");
sql.append(" AND DS.STATUS IN (").
append(actionStatus.stream().map(status -> "?").collect(Collectors.joining(","))).append(") ");
}
if (actionType != null && !actionType.isEmpty()) {
sql.append(" AND DS.ACTION_TRIGGERED_FROM = ? ");
@ -1953,27 +1989,41 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
sql.append(" AND DS.SUBSCRIBED_BY LIKE ? ");
}
sql.append("ORDER BY ").append(subscriptionStatusTime).append(" DESC");
sql.append("ORDER BY ").append(subscriptionStatusTime).
append(" DESC ");
if (offset >= 0 && limit >= 0) {
sql.append("LIMIT ? OFFSET ?");
}
try (PreparedStatement ps = conn.prepareStatement(sql.toString())) {
int paramIdx = 1;
ps.setInt(paramIdx++, appReleaseId);
ps.setBoolean(paramIdx++, unsubscribe);
ps.setInt(paramIdx++, tenantId);
for (int i = 0; i < deviceIds.size(); i++) {
ps.setInt(paramIdx++, deviceIds.get(i));
for (Integer deviceId : deviceIds) {
ps.setInt(paramIdx++, deviceId);
}
if (actionStatus != null && !actionStatus.isEmpty()) {
ps.setString(paramIdx++, actionStatus);
for (String status : actionStatus) {
ps.setString(paramIdx++, status);
}
}
if (actionType != null && !actionType.isEmpty()) {
ps.setString(paramIdx++, actionType);
}
if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
ps.setString(paramIdx++, "%" + actionTriggeredBy + "%");
}
if (offset >= 0 && limit >= 0) {
ps.setInt(paramIdx++, limit);
ps.setInt(paramIdx, offset);
}
try (ResultSet rs = ps.executeQuery()) {
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved device subscriptions for application release id "
@ -2010,9 +2060,178 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
}
@Override
public int getDeviceSubscriptionCount(int appReleaseId, boolean unsubscribe, int tenantId,
List<Integer> deviceIds, List<String> actionStatus, String actionType,
String actionTriggeredBy) throws ApplicationManagementDAOException {
int deviceCount = 0;
if (deviceIds == null || deviceIds.isEmpty()) return deviceCount;
try {
Connection conn = this.getDBConnection();
StringBuilder sql = new StringBuilder("SELECT COUNT(DISTINCT DS.DM_DEVICE_ID) AS COUNT "
+ "FROM AP_DEVICE_SUBSCRIPTION DS "
+ "WHERE DS.AP_APP_RELEASE_ID = ? "
+ "AND DS.UNSUBSCRIBED = ? "
+ "AND DS.TENANT_ID = ? "
+ "AND DS.DM_DEVICE_ID IN ("
+ deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ") ");
if (actionStatus != null && !actionStatus.isEmpty()) {
sql.append(" AND DS.STATUS IN (").
append(actionStatus.stream().map(status -> "?").collect(Collectors.joining(","))).append(") ");
}
if (actionType != null && !actionType.isEmpty()) {
sql.append(" AND DS.ACTION_TRIGGERED_FROM = ? ");
}
if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
sql.append(" AND DS.SUBSCRIBED_BY LIKE ?");
}
try (PreparedStatement ps = conn.prepareStatement(sql.toString())) {
int paramIdx = 1;
ps.setInt(paramIdx++, appReleaseId);
ps.setBoolean(paramIdx++, unsubscribe);
ps.setInt(paramIdx++, tenantId);
for (Integer deviceId : deviceIds) {
ps.setInt(paramIdx++, deviceId);
}
if (actionStatus != null && !actionStatus.isEmpty()) {
for (String status : actionStatus) {
ps.setString(paramIdx++, status);
}
}
if (actionType != null && !actionType.isEmpty()) {
ps.setString(paramIdx++, actionType);
}
if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
ps.setString(paramIdx, "%" + actionTriggeredBy + "%");
}
try (ResultSet rs = ps.executeQuery()) {
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved device subscriptions for application release id "
+ appReleaseId + " and device ids " + deviceIds);
}
if (rs.next()) {
deviceCount = rs.getInt("COUNT");
}
return deviceCount;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get device subscription data for application ID: " + appReleaseId
+ " and device ids: " + deviceIds + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting device subscriptions for "
+ "application Id: " + appReleaseId + " and device ids: " + deviceIds + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
// @Override
// public List<DeviceSubscriptionDTO> getSubscriptionDetailsByDeviceIds(int appReleaseId, boolean unsubscribe, int tenantId,
// List<Integer> deviceIds, String actionStatus, String actionType,
// String actionTriggeredBy, String tabActionStatus) throws ApplicationManagementDAOException {
// if (log.isDebugEnabled()) {
// log.debug("Getting device subscriptions for the application release id " + appReleaseId
// + " and device ids " + deviceIds + " from the database");
// }
// try {
// Connection conn = this.getDBConnection();
// String subscriptionStatusTime = unsubscribe ? "DS.UNSUBSCRIBED_TIMESTAMP" : "DS.SUBSCRIBED_TIMESTAMP";
// StringBuilder sql = new StringBuilder("SELECT "
// + "DS.ID AS ID, "
// + "DS.SUBSCRIBED_BY AS SUBSCRIBED_BY, "
// + "DS.SUBSCRIBED_TIMESTAMP AS SUBSCRIBED_AT, "
// + "DS.UNSUBSCRIBED AS IS_UNSUBSCRIBED, "
// + "DS.UNSUBSCRIBED_BY AS UNSUBSCRIBED_BY, "
// + "DS.UNSUBSCRIBED_TIMESTAMP AS UNSUBSCRIBED_AT, "
// + "DS.ACTION_TRIGGERED_FROM AS ACTION_TRIGGERED_FROM, "
// + "DS.STATUS AS STATUS, "
// + "DS.DM_DEVICE_ID AS DEVICE_ID "
// + "FROM AP_DEVICE_SUBSCRIPTION DS "
// + "WHERE DS.AP_APP_RELEASE_ID = ? AND DS.UNSUBSCRIBED = ? AND DS.TENANT_ID = ? AND DS.DM_DEVICE_ID IN (" +
// deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ") ");
//
// if (actionStatus != null && !actionStatus.isEmpty()) {
// sql.append(" AND DS.STATUS = ? ");
// }
// if (actionType != null && !actionType.isEmpty()) {
// sql.append(" AND DS.ACTION_TRIGGERED_FROM = ? ");
// }
// if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
// sql.append(" AND DS.SUBSCRIBED_BY LIKE ? ");
// }
//
// sql.append("ORDER BY ").append(subscriptionStatusTime).append(" DESC");
//
// try (PreparedStatement ps = conn.prepareStatement(sql.toString())) {
// int paramIdx = 1;
// ps.setInt(paramIdx++, appReleaseId);
// ps.setBoolean(paramIdx++, unsubscribe);
// ps.setInt(paramIdx++, tenantId);
// for (int i = 0; i < deviceIds.size(); i++) {
// ps.setInt(paramIdx++, deviceIds.get(i));
// }
//
// if (actionStatus != null && !actionStatus.isEmpty()) {
// ps.setString(paramIdx++, actionStatus);
// }
// if (actionType != null && !actionType.isEmpty()) {
// ps.setString(paramIdx++, actionType);
// }
// if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
// ps.setString(paramIdx++, "%" + actionTriggeredBy + "%");
// }
//
// try (ResultSet rs = ps.executeQuery()) {
// if (log.isDebugEnabled()) {
// log.debug("Successfully retrieved device subscriptions for application release id "
// + appReleaseId + " and device ids " + deviceIds);
// }
// List<DeviceSubscriptionDTO> subscriptions = new ArrayList<>();
// while (rs.next()) {
// DeviceSubscriptionDTO subscription = new DeviceSubscriptionDTO();
// subscription.setId(rs.getInt("ID"));
// subscription.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
// subscription.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_AT"));
// subscription.setUnsubscribed(rs.getBoolean("IS_UNSUBSCRIBED"));
// subscription.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
// subscription.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_AT"));
// subscription.setActionTriggeredFrom(rs.getString("ACTION_TRIGGERED_FROM"));
// subscription.setStatus(rs.getString("STATUS"));
// subscription.setDeviceId(rs.getInt("DEVICE_ID"));
// subscriptions.add(subscription);
// }
// return subscriptions;
// }
// } catch (SQLException e) {
// String msg = "Error occurred while running SQL to get device subscription data for application ID: " + appReleaseId
// + " and device ids: " + deviceIds + ".";
// log.error(msg, e);
// throw new ApplicationManagementDAOException(msg, e);
// }
// } catch (DBConnectionException e) {
// String msg = "Error occurred while obtaining the DB connection for getting device subscriptions for "
// + "application Id: " + appReleaseId + " and device ids: " + deviceIds + ".";
// log.error(msg, e);
// throw new ApplicationManagementDAOException(msg, e);
// }
//
// }
@Override
public List<DeviceSubscriptionDTO> getAllSubscriptionsDetails(int appReleaseId, boolean unsubscribe, int tenantId,
String actionStatus, String actionType, String actionTriggeredBy,
List<String> actionStatus, String actionType, String actionTriggeredBy,
int offset, int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting device subscriptions for the application release id " + appReleaseId
@ -2032,11 +2251,15 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
+ "DS.STATUS AS STATUS, "
+ "DS.DM_DEVICE_ID AS DEVICE_ID "
+ "FROM AP_DEVICE_SUBSCRIPTION DS "
+ "WHERE DS.AP_APP_RELEASE_ID = ? AND DS.UNSUBSCRIBED = ? AND DS.TENANT_ID = ? ");
+ "WHERE DS.AP_APP_RELEASE_ID = ? "
+ "AND DS.UNSUBSCRIBED = ? "
+ "AND DS.TENANT_ID = ? ");
if (actionStatus != null && !actionStatus.isEmpty()) {
sql.append(" AND DS.STATUS = ? ");
sql.append(" AND DS.STATUS IN (").
append(actionStatus.stream().map(status -> "?").collect(Collectors.joining(","))).append(") ");
}
if (actionType != null && !actionType.isEmpty()) {
sql.append(" AND DS.ACTION_TRIGGERED_FROM = ? ");
}
@ -2044,8 +2267,11 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
sql.append(" AND ").append(actionTriggeredColumn).append(" LIKE ? ");
}
sql.append("ORDER BY ").append(subscriptionStatusTime).append(" DESC ")
.append("LIMIT ? OFFSET ?");
sql.append("ORDER BY ").append(subscriptionStatusTime).append(" DESC ");
if (limit >= 0 && offset >= 0) {
sql.append("LIMIT ? OFFSET ?");
}
try {
Connection conn = this.getDBConnection();
@ -2056,17 +2282,23 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
ps.setInt(paramIdx++, tenantId);
if (actionStatus != null && !actionStatus.isEmpty()) {
ps.setString(paramIdx++, actionStatus);
for (String status : actionStatus) {
ps.setString(paramIdx++, status);
}
}
if (actionType != null && !actionType.isEmpty()) {
ps.setString(paramIdx++, actionType);
}
if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
ps.setString(paramIdx++, "%" + actionTriggeredBy + "%");
}
ps.setInt(paramIdx++, limit);
ps.setInt(paramIdx++, offset);
if (limit >= 0 && offset >= 0) {
ps.setInt(paramIdx++, limit);
ps.setInt(paramIdx, offset);
}
try (ResultSet rs = ps.executeQuery()) {
if (log.isDebugEnabled()) {
@ -2104,6 +2336,70 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
}
}
@Override
public int getAllSubscriptionsCount(int appReleaseId, boolean unsubscribe, int tenantId,
List<String> actionStatus, String actionType, String actionTriggeredBy)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting device subscriptions for the application release id " + appReleaseId
+ " from the database");
}
String actionTriggeredColumn = unsubscribe ? "DS.UNSUBSCRIBED_BY" : "DS.SUBSCRIBED_BY";
StringBuilder sql = new StringBuilder("SELECT COUNT(DISTINCT DS.DM_DEVICE_ID) AS COUNT "
+ "FROM AP_DEVICE_SUBSCRIPTION DS "
+ "WHERE DS.AP_APP_RELEASE_ID = ? "
+ "AND DS.UNSUBSCRIBED = ? "
+ "AND DS.TENANT_ID = ? ");
if (actionStatus != null && !actionStatus.isEmpty()) {
sql.append(" AND DS.STATUS IN (").
append(actionStatus.stream().map(status -> "?").collect(Collectors.joining(","))).append(") ");
}
if (actionType != null && !actionType.isEmpty()) {
sql.append(" AND DS.ACTION_TRIGGERED_FROM = ? ");
}
if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
sql.append(" AND ").append(actionTriggeredColumn).append(" LIKE ?");
}
try {
Connection conn = this.getDBConnection();
try (PreparedStatement ps = conn.prepareStatement(sql.toString())) {
int paramIdx = 1;
ps.setInt(paramIdx++, appReleaseId);
ps.setBoolean(paramIdx++, unsubscribe);
ps.setInt(paramIdx++, tenantId);
if (actionStatus != null && !actionStatus.isEmpty()) {
for (String status : actionStatus) {
ps.setString(paramIdx++, status);
}
}
if (actionType != null && !actionType.isEmpty()) {
ps.setString(paramIdx++, actionType);
}
if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
ps.setString(paramIdx++, "%" + actionTriggeredBy + "%");
}
try (ResultSet rs = ps.executeQuery()) {
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved device subscriptions for application release id "
+ appReleaseId);
}
return rs.next() ? rs.getInt("COUNT") : 0;
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting device subscription for "
+ "application Id: " + appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get device subscription data for application ID: " + appReleaseId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int getAllSubscriptionCount(int appReleaseId, int tenantId)
throws ApplicationManagementDAOException {
@ -2496,13 +2792,85 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
}
}
// todo: fixed the status
@Override
public SubscriptionStatisticDTO getSubscriptionStatistic(List<Integer> deviceIds, String subscriptionType,
boolean isUnsubscribed, int tenantId)
throws ApplicationManagementDAOException {
SubscriptionStatisticDTO subscriptionStatisticDTO = new SubscriptionStatisticDTO();
if (deviceIds == null || deviceIds.isEmpty()) return subscriptionStatisticDTO;
boolean doesAllEntriesRequired = true;
try {
Connection connection = getDBConnection();
String sql = "SELECT COUNT(DISTINCT ID) AS COUNT, " +
"STATUS FROM AP_DEVICE_SUBSCRIPTION " +
"WHERE TENANT_ID = ? " +
"AND UNSUBSCRIBED = ?" +
"AND DM_DEVICE_ID IN (" +
deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ")";
if (!Objects.equals(subscriptionType, SubscriptionMetadata.SubscriptionTypes.DEVICE)) {
sql += " AND ACTION_TRIGGERED_FROM = ?";
doesAllEntriesRequired = false;
}
sql += " GROUP BY (STATUS)";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int idx = 1;
preparedStatement.setInt(idx++, tenantId);
preparedStatement.setBoolean(idx++, isUnsubscribed);
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(idx++, deviceId);
}
if (!doesAllEntriesRequired) {
preparedStatement.setString(idx, subscriptionType);
}
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
// add the error and in progress
int count = resultSet.getInt("COUNT");
String status = resultSet.getString("STATUS");
if (SubscriptionMetadata.DBSubscriptionStatus.COMPLETED_STATUS_LIST.contains(status)) {
subscriptionStatisticDTO.addToComplete(count);
}
if (SubscriptionMetadata.DBSubscriptionStatus.PENDING_STATUS_LIST.contains(status)) {
subscriptionStatisticDTO.addToPending(count);
}
if (SubscriptionMetadata.DBSubscriptionStatus.ERROR_STATUS_LIST.contains(status)) {
subscriptionStatisticDTO.addToFailed(count);
}
}
}
}
return subscriptionStatisticDTO;
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting subscription statistics";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while running SQL for getting subscription statistics";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
public int countSubscriptionsByStatus(int appReleaseId, int tenantId, String actionStatus, String actionTriggeredFrom) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to count device subscriptions by status and actionTriggeredFrom for the given AppReleaseID.");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT COUNT(*) FROM AP_DEVICE_SUBSCRIPTION WHERE AP_APP_RELEASE_ID = ? AND TENANT_ID = ? AND STATUS = ? AND ACTION_TRIGGERED_FROM = ?";
String sql = "SELECT COUNT(*) FROM AP_DEVICE_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " +
"AND STATUS = ?" +
" AND ACTION_TRIGGERED_FROM = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
@ -2525,4 +2893,5 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
}
return 0;
}
}

@ -18,6 +18,8 @@
package io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionEntity;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException;
@ -28,7 +30,9 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* This handles Application subscribing operations which are specific to Oracle.
@ -157,4 +161,379 @@ public class OracleSubscriptionDAOImpl extends GenericSubscriptionDAOImpl {
throw new ApplicationManagementDAOException(msg, e);
}
}
// passed the required list for the action status
@Override
public List<DeviceSubscriptionDTO> getSubscriptionDetailsByDeviceIds(int appReleaseId, boolean unsubscribe, int tenantId,
List<Integer> deviceIds, List<String> actionStatus, String actionType,
String actionTriggeredBy, int limit, int offset) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting device subscriptions for the application release id " + appReleaseId
+ " and device ids " + deviceIds + " from the database");
}
if (deviceIds == null || deviceIds.isEmpty()) {
return Collections.emptyList();
}
try {
Connection conn = this.getDBConnection();
String subscriptionStatusTime = unsubscribe ? "DS.UNSUBSCRIBED_TIMESTAMP" : "DS.SUBSCRIBED_TIMESTAMP";
StringBuilder sql = new StringBuilder("SELECT "
+ "DS.ID AS ID, "
+ "DS.SUBSCRIBED_BY AS SUBSCRIBED_BY, "
+ "DS.SUBSCRIBED_TIMESTAMP AS SUBSCRIBED_AT, "
+ "DS.UNSUBSCRIBED AS IS_UNSUBSCRIBED, "
+ "DS.UNSUBSCRIBED_BY AS UNSUBSCRIBED_BY, "
+ "DS.UNSUBSCRIBED_TIMESTAMP AS UNSUBSCRIBED_AT, "
+ "DS.ACTION_TRIGGERED_FROM AS ACTION_TRIGGERED_FROM, "
+ "DS.STATUS AS STATUS, "
+ "DS.DM_DEVICE_ID AS DEVICE_ID "
+ "FROM AP_DEVICE_SUBSCRIPTION DS "
+ "WHERE DS.AP_APP_RELEASE_ID = ? "
+ "AND DS.UNSUBSCRIBED = ? "
+ "AND DS.TENANT_ID = ? "
+ "AND DS.DM_DEVICE_ID IN ("
+ deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ") ");
if (actionStatus != null && !actionStatus.isEmpty()) {
sql.append(" AND DS.STATUS IN (").
append(actionStatus.stream().map(status -> "?").collect(Collectors.joining(","))).append(") ");
}
if (actionType != null && !actionType.isEmpty()) {
sql.append(" AND DS.ACTION_TRIGGERED_FROM = ? ");
}
if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
sql.append(" AND DS.SUBSCRIBED_BY LIKE ? ");
}
sql.append("ORDER BY ").append(subscriptionStatusTime).
append(" DESC ");
if (offset >= 0 && limit >= 0) {
sql.append("OFFSET ? ROWS FETCH NEXT ? ROWS ONLY");
}
try (PreparedStatement ps = conn.prepareStatement(sql.toString())) {
int paramIdx = 1;
ps.setInt(paramIdx++, appReleaseId);
ps.setBoolean(paramIdx++, unsubscribe);
ps.setInt(paramIdx++, tenantId);
for (Integer deviceId : deviceIds) {
ps.setInt(paramIdx++, deviceId);
}
if (actionStatus != null && !actionStatus.isEmpty()) {
for (String status : actionStatus) {
ps.setString(paramIdx++, status);
}
}
if (actionType != null && !actionType.isEmpty()) {
ps.setString(paramIdx++, actionType);
}
if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
ps.setString(paramIdx++, "%" + actionTriggeredBy + "%");
}
if (offset >= 0 && limit >= 0) {
ps.setInt(paramIdx++, offset);
ps.setInt(paramIdx, limit);
}
try (ResultSet rs = ps.executeQuery()) {
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved device subscriptions for application release id "
+ appReleaseId + " and device ids " + deviceIds);
}
List<DeviceSubscriptionDTO> subscriptions = new ArrayList<>();
while (rs.next()) {
DeviceSubscriptionDTO subscription = new DeviceSubscriptionDTO();
subscription.setId(rs.getInt("ID"));
subscription.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscription.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_AT"));
subscription.setUnsubscribed(rs.getBoolean("IS_UNSUBSCRIBED"));
subscription.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscription.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_AT"));
subscription.setActionTriggeredFrom(rs.getString("ACTION_TRIGGERED_FROM"));
subscription.setStatus(rs.getString("STATUS"));
subscription.setDeviceId(rs.getInt("DEVICE_ID"));
subscriptions.add(subscription);
}
return subscriptions;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get device subscription data for application ID: " + appReleaseId
+ " and device ids: " + deviceIds + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting device subscriptions for "
+ "application Id: " + appReleaseId + " and device ids: " + deviceIds + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public List<SubscriptionEntity> getRoleSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset,
int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get role subscriptions related to the given AppReleaseID.");
}
try {
Connection conn = this.getDBConnection();
List<SubscriptionEntity> subscriptionEntities = new ArrayList<>();
String subscriptionStatusTime = unsubscribe ? "ARS.UNSUBSCRIBED_TIMESTAMP" : "ARS.SUBSCRIBED_TIMESTAMP";
String sql = "SELECT ARS.ROLE_NAME, " +
"ARS.SUBSCRIBED_BY, " +
"ARS.SUBSCRIBED_TIMESTAMP, " +
"ARS.UNSUBSCRIBED, " +
"ARS.UNSUBSCRIBED_BY, " +
"ARS.UNSUBSCRIBED_TIMESTAMP, " +
"ARS.AP_APP_RELEASE_ID " +
"FROM AP_ROLE_SUBSCRIPTION ARS " +
"WHERE ARS.AP_APP_RELEASE_ID = ? " +
"AND ARS.UNSUBSCRIBED = ? " +
"AND ARS.TENANT_ID = ? " +
"ORDER BY " + subscriptionStatusTime + " DESC " +
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setBoolean(2, unsubscribe);
ps.setInt(3, tenantId);
ps.setInt(4, offset);
ps.setInt(5, limit);
try (ResultSet rs = ps.executeQuery()) {
SubscriptionEntity subscriptionEntity;
while (rs.next()) {
subscriptionEntity = new SubscriptionEntity();
subscriptionEntity.setIdentity(rs.getString("ROLE_NAME"));
subscriptionEntity.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscriptionEntity.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
subscriptionEntity.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscriptionEntity.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setApplicationReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
subscriptionEntities.add(subscriptionEntity);
}
}
return subscriptionEntities;
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get role subscriptions for the given UUID.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "SQL Error occurred while getting role subscriptions for the given UUID.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public List<SubscriptionEntity> getUserSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId,
int offset, int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get user subscriptions related to the given UUID.");
}
try {
Connection conn = this.getDBConnection();
List<SubscriptionEntity> subscriptionEntities = new ArrayList<>();
String subscriptionStatusTime = unsubscribe ? "US.UNSUBSCRIBED_TIMESTAMP" : "US.SUBSCRIBED_TIMESTAMP";
String sql = "SELECT US.USER_NAME, " +
"US.SUBSCRIBED_BY, " +
"US.SUBSCRIBED_TIMESTAMP, " +
"US.UNSUBSCRIBED, " +
"US.UNSUBSCRIBED_BY, " +
"US.UNSUBSCRIBED_TIMESTAMP, " +
"US.AP_APP_RELEASE_ID " +
"FROM AP_USER_SUBSCRIPTION US " +
"WHERE US.AP_APP_RELEASE_ID = ? " +
"AND US.UNSUBSCRIBED = ? " +
"AND US.TENANT_ID = ? " +
"ORDER BY " + subscriptionStatusTime + " DESC " +
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setBoolean(2, unsubscribe);
ps.setInt(3, tenantId);
ps.setInt(4, offset);
ps.setInt(5, limit);
try (ResultSet rs = ps.executeQuery()) {
SubscriptionEntity subscriptionEntity;
while (rs.next()) {
subscriptionEntity = new SubscriptionEntity();
subscriptionEntity.setIdentity(rs.getString("USER_NAME"));
subscriptionEntity.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscriptionEntity.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
subscriptionEntity.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscriptionEntity.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setApplicationReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
subscriptionEntities.add(subscriptionEntity);
}
}
return subscriptionEntities;
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get user subscriptions for the given UUID.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "SQL Error occurred while getting user subscriptions for the given UUID.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public List<SubscriptionEntity> getGroupsSubscriptionDetailsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get groups related to the given AppReleaseID.");
}
try {
Connection conn = this.getDBConnection();
List<SubscriptionEntity> subscriptionEntities = new ArrayList<>();
String subscriptionStatusTime = unsubscribe ? "GS.UNSUBSCRIBED_TIMESTAMP" : "GS.SUBSCRIBED_TIMESTAMP";
String sql = "SELECT GS.GROUP_NAME, " +
"GS.SUBSCRIBED_BY, " +
"GS.SUBSCRIBED_TIMESTAMP, " +
"GS.UNSUBSCRIBED, " +
"GS.UNSUBSCRIBED_BY, " +
"GS.UNSUBSCRIBED_TIMESTAMP, " +
"GS.AP_APP_RELEASE_ID " +
"FROM AP_GROUP_SUBSCRIPTION GS " +
"WHERE GS.AP_APP_RELEASE_ID = ? " +
"AND GS.UNSUBSCRIBED = ? AND GS.TENANT_ID = ? " +
"ORDER BY " + subscriptionStatusTime + " DESC " +
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setBoolean(2, unsubscribe);
ps.setInt(3, tenantId);
ps.setInt(4, offset);
ps.setInt(5, limit);
try (ResultSet rs = ps.executeQuery()) {
SubscriptionEntity subscriptionEntity;
while (rs.next()) {
subscriptionEntity = new SubscriptionEntity();
subscriptionEntity.setIdentity(rs.getString("GROUP_NAME"));
subscriptionEntity.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscriptionEntity.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
subscriptionEntity.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscriptionEntity.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setApplicationReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
subscriptionEntities.add(subscriptionEntity);
}
}
return subscriptionEntities;
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get groups for the given UUID.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "SQL Error occurred while getting groups for the given UUID.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public List<DeviceSubscriptionDTO> getAllSubscriptionsDetails(int appReleaseId, boolean unsubscribe, int tenantId,
List<String> actionStatus, String actionType, String actionTriggeredBy,
int offset, int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting device subscriptions for the application release id " + appReleaseId + " from the database");
}
String subscriptionStatusTime = unsubscribe ? "DS.UNSUBSCRIBED_TIMESTAMP" : "DS.SUBSCRIBED_TIMESTAMP";
String actionTriggeredColumn = unsubscribe ? "DS.UNSUBSCRIBED_BY" : "DS.SUBSCRIBED_BY";
StringBuilder sql = new StringBuilder("SELECT "
+ "DS.ID AS ID, "
+ "DS.SUBSCRIBED_BY AS SUBSCRIBED_BY, "
+ "DS.SUBSCRIBED_TIMESTAMP AS SUBSCRIBED_AT, "
+ "DS.UNSUBSCRIBED AS IS_UNSUBSCRIBED, "
+ "DS.UNSUBSCRIBED_BY AS UNSUBSCRIBED_BY, "
+ "DS.UNSUBSCRIBED_TIMESTAMP AS UNSUBSCRIBED_AT, "
+ "DS.ACTION_TRIGGERED_FROM AS ACTION_TRIGGERED_FROM, "
+ "DS.STATUS AS STATUS, "
+ "DS.DM_DEVICE_ID AS DEVICE_ID "
+ "FROM AP_DEVICE_SUBSCRIPTION DS "
+ "WHERE DS.AP_APP_RELEASE_ID = ? "
+ "AND DS.UNSUBSCRIBED = ? "
+ "AND DS.TENANT_ID = ? ");
if (actionStatus != null && !actionStatus.isEmpty()) {
sql.append(" AND DS.STATUS IN (")
.append(actionStatus.stream().map(status -> "?").collect(Collectors.joining(","))).append(") ");
}
if (actionType != null && !actionType.isEmpty()) {
sql.append(" AND DS.ACTION_TRIGGERED_FROM = ? ");
}
if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
sql.append(" AND ").append(actionTriggeredColumn).append(" LIKE ? ");
}
sql.append("ORDER BY ").append(subscriptionStatusTime).append(" DESC ");
if (limit >= 0 && offset >= 0) {
sql.append("OFFSET ? ROWS FETCH NEXT ? ROWS ONLY");
}
try {
Connection conn = this.getDBConnection();
try (PreparedStatement ps = conn.prepareStatement(sql.toString())) {
int paramIdx = 1;
ps.setInt(paramIdx++, appReleaseId);
ps.setBoolean(paramIdx++, unsubscribe);
ps.setInt(paramIdx++, tenantId);
if (actionStatus != null && !actionStatus.isEmpty()) {
for (String status : actionStatus) {
ps.setString(paramIdx++, status);
}
}
if (actionType != null && !actionType.isEmpty()) {
ps.setString(paramIdx++, actionType);
}
if (actionTriggeredBy != null && !actionTriggeredBy.isEmpty()) {
ps.setString(paramIdx++, "%" + actionTriggeredBy + "%");
}
if (limit >= 0 && offset >= 0) {
ps.setInt(paramIdx++, offset);
ps.setInt(paramIdx, limit);
}
try (ResultSet rs = ps.executeQuery()) {
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved device subscriptions for application release id "
+ appReleaseId);
}
List<DeviceSubscriptionDTO> deviceSubscriptions = new ArrayList<>();
while (rs.next()) {
DeviceSubscriptionDTO subscription = new DeviceSubscriptionDTO();
subscription.setId(rs.getInt("ID"));
subscription.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscription.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_AT"));
subscription.setUnsubscribed(rs.getBoolean("IS_UNSUBSCRIBED"));
subscription.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscription.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_AT"));
subscription.setActionTriggeredFrom(rs.getString("ACTION_TRIGGERED_FROM"));
subscription.setStatus(rs.getString("STATUS"));
subscription.setDeviceId(rs.getInt("DEVICE_ID"));
deviceSubscriptions.add(subscription);
}
return deviceSubscriptions;
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting device subscription for application Id: "
+ appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get device subscription data for application ID: " + appReleaseId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
}

@ -0,0 +1,29 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.core.util;
public class SubscriptionManagementUtil {
public static final class DeviceSubscriptionStatus {
public static final String COMPLETED = "COMPLETED";
public static final String ERROR ="ERROR";
public static final String NEW = "NEW";
public static final String SUBSCRIBED = "SUBSCRIBED";
}
}

@ -0,0 +1,207 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscription;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscriptionFilterCriteria;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionData;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionInfo;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionMetadata;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionStatistics;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionStatisticDTO;
import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class SubscriptionManagementHelperUtil {
/**
* Retrieves device subscription data based on the provided filters.
*
* @param deviceSubscriptionDTOS List of DeviceSubscriptionDTO objects.
* @param deviceSubscriptionFilterCriteria Filter criteria for device subscription.
* @param isUnsubscribed Boolean indicating whether to filter unsubscribed devices.
* @param deviceTypeId Device type ID.
* @param limit Limit for pagination.
* @param offset Offset for pagination.
* @return List of DeviceSubscription objects.
* @throws DeviceManagementException If an error occurs during device management.
*/
public static List<DeviceSubscription> getDeviceSubscriptionData(List<DeviceSubscriptionDTO> deviceSubscriptionDTOS,
DeviceSubscriptionFilterCriteria deviceSubscriptionFilterCriteria,
boolean isUnsubscribed, int deviceTypeId, int limit, int offset)
throws DeviceManagementException {
List<Integer> deviceIds = deviceSubscriptionDTOS.stream().map(DeviceSubscriptionDTO::getDeviceId).collect(Collectors.toList());
PaginationRequest paginationRequest = new PaginationRequest(offset, limit);
paginationRequest.setDeviceName(deviceSubscriptionFilterCriteria.getName());
paginationRequest.setDeviceStatus(deviceSubscriptionFilterCriteria.getDeviceStatus());
paginationRequest.setOwner(deviceSubscriptionFilterCriteria.getOwner());
paginationRequest.setDeviceTypeId(deviceTypeId);
List<Device> devices = HelperUtil.getDeviceManagementProviderService().getDevicesByDeviceIds(paginationRequest, deviceIds);
return populateDeviceData(deviceSubscriptionDTOS, devices, isUnsubscribed);
}
/**
* Retrieves the total count of device subscriptions based on the provided filters.
*
* @param deviceSubscriptionDTOS List of DeviceSubscriptionDTO objects.
* @param deviceSubscriptionFilterCriteria Filter criteria for device subscription.
* @param deviceTypeId Device type ID.
* @return int Total count of device subscriptions.
* @throws DeviceManagementException If an error occurs during device management.
*/
public static int getTotalDeviceSubscriptionCount(List<DeviceSubscriptionDTO> deviceSubscriptionDTOS,
DeviceSubscriptionFilterCriteria deviceSubscriptionFilterCriteria, int deviceTypeId)
throws DeviceManagementException {
List<Integer> deviceIds = deviceSubscriptionDTOS.stream().map(DeviceSubscriptionDTO::getDeviceId).collect(Collectors.toList());
PaginationRequest paginationRequest = new PaginationRequest(-1, -1);
paginationRequest.setDeviceName(deviceSubscriptionFilterCriteria.getName());
paginationRequest.setDeviceStatus(deviceSubscriptionFilterCriteria.getDeviceStatus());
paginationRequest.setOwner(deviceSubscriptionFilterCriteria.getOwner());
paginationRequest.setDeviceTypeId(deviceTypeId);
return HelperUtil.getDeviceManagementProviderService().getDeviceCountByDeviceIds(paginationRequest, deviceIds);
}
/**
* Populates device subscription data based on the provided devices and subscription DTOs.
*
* @param deviceSubscriptionDTOS List of DeviceSubscriptionDTO objects.
* @param devices List of Device objects.
* @param isUnsubscribed Boolean indicating whether to filter unsubscribed devices.
* @return List of DeviceSubscription objects.
*/
private static List<DeviceSubscription> populateDeviceData(List<DeviceSubscriptionDTO> deviceSubscriptionDTOS,
List<Device> devices, boolean isUnsubscribed) {
List<DeviceSubscription> deviceSubscriptions = new ArrayList<>();
for (Device device : devices) {
int idx = deviceSubscriptionDTOS.indexOf(new DeviceSubscriptionDTO(device.getId()));
if (idx >= 0) {
DeviceSubscriptionDTO deviceSubscriptionDTO = deviceSubscriptionDTOS.get(idx);
DeviceSubscription deviceSubscription = new DeviceSubscription();
deviceSubscription.setDeviceId(device.getId());
deviceSubscription.setDeviceIdentifier(device.getDeviceIdentifier());
deviceSubscription.setDeviceOwner(device.getEnrolmentInfo().getOwner());
deviceSubscription.setDeviceType(device.getType());
deviceSubscription.setDeviceName(device.getName());
deviceSubscription.setDeviceStatus(device.getEnrolmentInfo().getStatus().name());
deviceSubscription.setOwnershipType(device.getEnrolmentInfo().getOwnership().name());
deviceSubscription.setDateOfLastUpdate(new Timestamp(device.getEnrolmentInfo().getDateOfLastUpdate()));
SubscriptionData subscriptionData = getSubscriptionData(isUnsubscribed, deviceSubscriptionDTO);
deviceSubscription.setSubscriptionData(subscriptionData);
deviceSubscriptions.add(deviceSubscription);
}
}
return deviceSubscriptions;
}
/**
* Creates a SubscriptionData object based on the provided subscription DTO.
*
* @param isUnsubscribed Boolean indicating whether to filter unsubscribed devices.
* @param deviceSubscriptionDTO DeviceSubscriptionDTO object.
* @return SubscriptionData object.
*/
private static SubscriptionData getSubscriptionData(boolean isUnsubscribed, DeviceSubscriptionDTO deviceSubscriptionDTO) {
SubscriptionData subscriptionData = new SubscriptionData();
subscriptionData.setTriggeredBy(isUnsubscribed ? deviceSubscriptionDTO.getUnsubscribedBy() :
deviceSubscriptionDTO.getSubscribedBy());
subscriptionData.setTriggeredAt(deviceSubscriptionDTO.getSubscribedTimestamp());
subscriptionData.setDeviceSubscriptionStatus(deviceSubscriptionDTO.getStatus());
subscriptionData.setSubscriptionType(deviceSubscriptionDTO.getActionTriggeredFrom());
subscriptionData.setSubscriptionId(deviceSubscriptionDTO.getId());
return subscriptionData;
}
/**
* Retrieves the device subscription status based on the provided subscription info.
*
* @param subscriptionInfo SubscriptionInfo object.
* @return Device subscription status.
*/
public static String getDeviceSubscriptionStatus(SubscriptionInfo subscriptionInfo) {
return getDeviceSubscriptionStatus(subscriptionInfo.getDeviceSubscriptionFilterCriteria().
getFilteringDeviceSubscriptionStatus(), subscriptionInfo.getDeviceSubscriptionStatus());
}
/**
* Retrieves the device subscription status based on the provided filter and status.
*
* @param deviceSubscriptionStatusFilter Filtered device subscription status.
* @param deviceSubscriptionStatus Device subscription status.
* @return Device subscription status.
*/
public static String getDeviceSubscriptionStatus(String deviceSubscriptionStatusFilter, String deviceSubscriptionStatus) {
return (deviceSubscriptionStatusFilter != null && !deviceSubscriptionStatusFilter.isEmpty()) ?
deviceSubscriptionStatusFilter : deviceSubscriptionStatus;
}
/**
* Retrieves subscription statistics based on the provided subscription statistics DTO and device count.
*
* @param subscriptionStatisticDTO SubscriptionStatisticDTO object.
* @param allDeviceCount Total count of all devices.
* @return SubscriptionStatistics object.
*/
public static SubscriptionStatistics getSubscriptionStatistics(SubscriptionStatisticDTO subscriptionStatisticDTO, int allDeviceCount) {
SubscriptionStatistics subscriptionStatistics = new SubscriptionStatistics();
subscriptionStatistics.setCompletedPercentage(
getPercentage(subscriptionStatisticDTO.getCompletedDeviceCount(), allDeviceCount));
subscriptionStatistics.setPendingPercentage(
getPercentage(subscriptionStatisticDTO.getPendingDevicesCount(), allDeviceCount));
subscriptionStatistics.setFailedPercentage(
getPercentage(subscriptionStatisticDTO.getFailedDevicesCount(), allDeviceCount));
subscriptionStatistics.setNewDevicesPercentage(getPercentage((allDeviceCount -
subscriptionStatisticDTO.getCompletedDeviceCount() -
subscriptionStatisticDTO.getPendingDevicesCount() -
subscriptionStatisticDTO.getFailedDevicesCount()), allDeviceCount));
return subscriptionStatistics;
}
/**
* Calculates the percentages.
*
* @param numerator Numerator value.
* @param denominator Denominator value.
* @return Calculated percentage.
*/
public static float getPercentage(int numerator, int denominator) {
if (denominator <= 0) {
return 0.0f;
}
return ((float) numerator / (float) denominator) * 100;
}
/**
* Retrieves database subscription statuses based on the provided device subscription status.
*
* @param deviceSubscriptionStatus Device subscription status.
* @return List of database subscription statuses.
*/
public static List<String> getDBSubscriptionStatus(String deviceSubscriptionStatus) {
return SubscriptionMetadata.deviceSubscriptionStatusToDBSubscriptionStatusMap.get(deviceSubscriptionStatus);
}
}

@ -0,0 +1,67 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionInfo;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionMetadata;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.impl.DeviceBasedSubscriptionManagementHelperServiceImpl;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.impl.GroupBasedSubscriptionManagementHelperServiceImpl;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.impl.RoleBasedSubscriptionManagementHelperServiceImpl;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.impl.UserBasedSubscriptionManagementHelperServiceImpl;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.service.SubscriptionManagementHelperService;
import java.util.Objects;
public class SubscriptionManagementServiceProvider {
private SubscriptionManagementServiceProvider() {
}
/**
* Retrieves the appropriate SubscriptionManagementHelperService based on the provided SubscriptionInfo.
*
* @param subscriptionInfo SubscriptionInfo object containing the subscription type.
* @return SubscriptionManagementHelperService implementation based on the subscription type.
*/
public SubscriptionManagementHelperService getSubscriptionManagementHelperService(SubscriptionInfo subscriptionInfo) {
return getSubscriptionManagementHelperService(subscriptionInfo.getSubscriptionType());
}
/**
* Retrieves the appropriate SubscriptionManagementHelperService based on the subscription type.
*
* @param subscriptionType Type of the subscription.
* @return SubscriptionManagementHelperService implementation based on the subscription type.
*/
private SubscriptionManagementHelperService getSubscriptionManagementHelperService(String subscriptionType) {
if (Objects.equals(subscriptionType, SubscriptionMetadata.SubscriptionTypes.ROLE))
return RoleBasedSubscriptionManagementHelperServiceImpl.getInstance();
if (Objects.equals(subscriptionType, SubscriptionMetadata.SubscriptionTypes.GROUP))
return GroupBasedSubscriptionManagementHelperServiceImpl.getInstance();
if (Objects.equals(subscriptionType, SubscriptionMetadata.SubscriptionTypes.USER))
return UserBasedSubscriptionManagementHelperServiceImpl.getInstance();
if (Objects.equals(subscriptionType, SubscriptionMetadata.SubscriptionTypes.DEVICE))
return DeviceBasedSubscriptionManagementHelperServiceImpl.getInstance();
throw new UnsupportedOperationException("Subscription type: " + subscriptionType + " not supports");
}
private static class SubscriptionManagementProviderServiceHolder {
private static final SubscriptionManagementServiceProvider INSTANCE = new SubscriptionManagementServiceProvider();
}
}

@ -0,0 +1,147 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.impl;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscription;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscriptionFilterCriteria;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionInfo;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionMetadata;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionResponse;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionStatistics;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException;
import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException;
import io.entgra.device.mgt.core.application.mgt.core.exception.NotFoundException;
import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.SubscriptionManagementHelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.service.SubscriptionManagementHelperService;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class DeviceBasedSubscriptionManagementHelperServiceImpl implements SubscriptionManagementHelperService {
private static final Log log = LogFactory.getLog(DeviceBasedSubscriptionManagementHelperServiceImpl.class);
private DeviceBasedSubscriptionManagementHelperServiceImpl() {
}
public static DeviceBasedSubscriptionManagementHelperServiceImpl getInstance() {
return DeviceBasedSubscriptionManagementHelperServiceImpl.DeviceBasedSubscriptionManagementHelperServiceImplHolder.INSTANCE;
}
@Override
public SubscriptionResponse getStatusBaseSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException {
final boolean isUnsubscribe = Objects.equals("unsubscribe", subscriptionInfo.getSubscriptionStatus());
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS;
int deviceCount = 0;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
ApplicationReleaseDTO applicationReleaseDTO = applicationReleaseDAO.
getReleaseByUUID(subscriptionInfo.getApplicationUUID(), tenantId);
if (applicationReleaseDTO == null) {
String msg = "Couldn't find an application release for application release UUID: " +
subscriptionInfo.getApplicationUUID();
log.error(msg);
throw new NotFoundException(msg);
}
ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(subscriptionInfo.getApplicationUUID(), tenantId);
if (applicationDTO == null) {
String msg = "Application not found for the release UUID: " + subscriptionInfo.getApplicationUUID();
log.error(msg);
throw new NotFoundException(msg);
}
String deviceSubscriptionStatus = SubscriptionManagementHelperUtil.getDeviceSubscriptionStatus(subscriptionInfo);
DeviceSubscriptionFilterCriteria deviceSubscriptionFilterCriteria = subscriptionInfo.getDeviceSubscriptionFilterCriteria();
DeviceManagementProviderService deviceManagementProviderService = HelperUtil.getDeviceManagementProviderService();
List<String> dbSubscriptionStatus = SubscriptionManagementHelperUtil.getDBSubscriptionStatus(subscriptionInfo.getDeviceSubscriptionStatus());
if (Objects.equals(SubscriptionMetadata.DeviceSubscriptionStatus.NEW, deviceSubscriptionStatus)) {
deviceSubscriptionDTOS = subscriptionDAO.getAllSubscriptionsDetails(applicationReleaseDTO.
getId(), isUnsubscribe, tenantId, null, null,
deviceSubscriptionFilterCriteria.getTriggeredBy(), -1, -1);
List<Integer> deviceIdsOfSubscription = deviceSubscriptionDTOS.stream().
map(DeviceSubscriptionDTO::getDeviceId).collect(Collectors.toList());
List<Integer> newDeviceIds = deviceManagementProviderService.getDevicesNotInGivenIdList(deviceIdsOfSubscription,
new PaginationRequest(offset, limit));
deviceSubscriptionDTOS = newDeviceIds.stream().map(DeviceSubscriptionDTO::new).collect(Collectors.toList());
deviceCount = deviceManagementProviderService.getDeviceCountNotInGivenIdList(deviceIdsOfSubscription);
} else {
deviceSubscriptionDTOS = subscriptionDAO.getAllSubscriptionsDetails(applicationReleaseDTO.
getId(), isUnsubscribe, tenantId, dbSubscriptionStatus, null,
deviceSubscriptionFilterCriteria.getTriggeredBy(), -1, -1);
deviceCount = SubscriptionManagementHelperUtil.getTotalDeviceSubscriptionCount(deviceSubscriptionDTOS,
subscriptionInfo.getDeviceSubscriptionFilterCriteria(), applicationDTO.getDeviceTypeId());
}
List<DeviceSubscription> deviceSubscriptions = SubscriptionManagementHelperUtil.getDeviceSubscriptionData(deviceSubscriptionDTOS,
subscriptionInfo.getDeviceSubscriptionFilterCriteria(), isUnsubscribe, applicationDTO.getDeviceTypeId(), limit, offset);
return new SubscriptionResponse(subscriptionInfo.getApplicationUUID(), deviceCount, deviceSubscriptions);
} catch (DeviceManagementException e) {
String msg = "Error encountered while getting device details";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException | DBConnectionException e) {
String msg = "Error encountered while connecting to the database";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public SubscriptionResponse getSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException {
return new SubscriptionResponse(subscriptionInfo.getApplicationUUID(), Collections.emptyList());
}
@Override
public SubscriptionStatistics getSubscriptionStatistics(SubscriptionInfo subscriptionInfo)
throws ApplicationManagementException {
return null;
}
private static class DeviceBasedSubscriptionManagementHelperServiceImplHolder {
private static final DeviceBasedSubscriptionManagementHelperServiceImpl INSTANCE
= new DeviceBasedSubscriptionManagementHelperServiceImpl();
}
}

@ -0,0 +1,215 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.impl;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscription;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscriptionFilterCriteria;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionEntity;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionInfo;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionMetadata;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionResponse;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionStatistics;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionStatisticDTO;
import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException;
import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException;
import io.entgra.device.mgt.core.application.mgt.core.exception.NotFoundException;
import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.SubscriptionManagementHelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.service.SubscriptionManagementHelperService;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException;
import io.entgra.device.mgt.core.device.mgt.core.dto.GroupDetailsDTO;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import io.entgra.device.mgt.core.device.mgt.core.service.GroupManagementProviderService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class GroupBasedSubscriptionManagementHelperServiceImpl implements SubscriptionManagementHelperService {
private static final Log log = LogFactory.getLog(GroupBasedSubscriptionManagementHelperServiceImpl.class);
private GroupBasedSubscriptionManagementHelperServiceImpl() {
}
public static GroupBasedSubscriptionManagementHelperServiceImpl getInstance() {
return GroupBasedSubscriptionManagementHelperServiceImplHolder.INSTANCE;
}
@Override
public SubscriptionResponse getStatusBaseSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException {
final boolean isUnsubscribe = Objects.equals("unsubscribe", subscriptionInfo.getSubscriptionStatus());
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS;
int deviceCount = 0;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
ApplicationReleaseDTO applicationReleaseDTO = applicationReleaseDAO.
getReleaseByUUID(subscriptionInfo.getApplicationUUID(), tenantId);
if (applicationReleaseDTO == null) {
String msg = "Couldn't find an application release for application release UUID: " +
subscriptionInfo.getApplicationUUID();
log.error(msg);
throw new NotFoundException(msg);
}
ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(subscriptionInfo.getApplicationUUID(), tenantId);
if (applicationDTO == null) {
String msg = "Application not found for the release UUID: " + subscriptionInfo.getApplicationUUID();
log.error(msg);
throw new NotFoundException(msg);
}
String deviceSubscriptionStatus = SubscriptionManagementHelperUtil.getDeviceSubscriptionStatus(subscriptionInfo);
DeviceSubscriptionFilterCriteria deviceSubscriptionFilterCriteria = subscriptionInfo.getDeviceSubscriptionFilterCriteria();
DeviceManagementProviderService deviceManagementProviderService = HelperUtil.getDeviceManagementProviderService();
GroupManagementProviderService groupManagementProviderService = HelperUtil.getGroupManagementProviderService();
GroupDetailsDTO groupDetailsDTO;
List<String> dbSubscriptionStatus = SubscriptionManagementHelperUtil.getDBSubscriptionStatus(subscriptionInfo.getDeviceSubscriptionStatus());
if (Objects.equals(SubscriptionMetadata.DeviceSubscriptionStatus.NEW, deviceSubscriptionStatus)) {
List<Integer> allDeviceIdsOwnByGroup = groupManagementProviderService.getGroupDetailsWithDevices(subscriptionInfo.getIdentifier(),
applicationDTO.getDeviceTypeId(), deviceSubscriptionFilterCriteria.getOwner(), deviceSubscriptionFilterCriteria.getName(),
deviceSubscriptionFilterCriteria.getDeviceStatus(), -1, -1).getDeviceIds();
deviceSubscriptionDTOS = subscriptionDAO.getSubscriptionDetailsByDeviceIds(applicationReleaseDTO.getId(),
isUnsubscribe, tenantId, allDeviceIdsOwnByGroup, null,
null, deviceSubscriptionFilterCriteria.getTriggeredBy(), -1, -1);
List<Integer> deviceIdsOfSubscription = deviceSubscriptionDTOS.stream().
map(DeviceSubscriptionDTO::getDeviceId).collect(Collectors.toList());
for (Integer deviceId : deviceIdsOfSubscription) {
allDeviceIdsOwnByGroup.remove(deviceId);
}
List<Integer> paginatedNewDeviceIds = deviceManagementProviderService.getDevicesInGivenIdList(allDeviceIdsOwnByGroup,
new PaginationRequest(offset, limit));
deviceSubscriptionDTOS = paginatedNewDeviceIds.stream().map(DeviceSubscriptionDTO::new).collect(Collectors.toList());
deviceCount = allDeviceIdsOwnByGroup.size();
} else {
groupDetailsDTO = groupManagementProviderService.getGroupDetailsWithDevices(subscriptionInfo.getIdentifier(),
applicationDTO.getDeviceTypeId(), deviceSubscriptionFilterCriteria.getOwner(), deviceSubscriptionFilterCriteria.getName(),
deviceSubscriptionFilterCriteria.getDeviceStatus(), offset, limit);
List<Integer> paginatedDeviceIdsOwnByGroup = groupDetailsDTO.getDeviceIds();
deviceSubscriptionDTOS = subscriptionDAO.getSubscriptionDetailsByDeviceIds(applicationReleaseDTO.getId(),
isUnsubscribe, tenantId, paginatedDeviceIdsOwnByGroup, dbSubscriptionStatus,
null, deviceSubscriptionFilterCriteria.getTriggeredBy(), -1, -1);
deviceCount = SubscriptionManagementHelperUtil.getTotalDeviceSubscriptionCount(deviceSubscriptionDTOS,
subscriptionInfo.getDeviceSubscriptionFilterCriteria(), applicationDTO.getDeviceTypeId());
}
List<DeviceSubscription> deviceSubscriptions = SubscriptionManagementHelperUtil.getDeviceSubscriptionData(deviceSubscriptionDTOS,
subscriptionInfo.getDeviceSubscriptionFilterCriteria(), isUnsubscribe, applicationDTO.getDeviceTypeId(), limit, offset);
return new SubscriptionResponse(subscriptionInfo.getApplicationUUID(), deviceCount, deviceSubscriptions);
} catch (GroupManagementException e) {
String msg = "Error encountered while retrieving group details for group: " + subscriptionInfo.getIdentifier();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException | DBConnectionException e) {
String msg = "Error encountered while connecting to the database";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (DeviceManagementException e) {
throw new RuntimeException(e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public SubscriptionResponse getSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException {
final boolean isUnsubscribe = Objects.equals("unsubscribe", subscriptionInfo.getSubscriptionStatus());
final int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
ApplicationReleaseDTO applicationReleaseDTO = applicationReleaseDAO.
getReleaseByUUID(subscriptionInfo.getApplicationUUID(), tenantId);
if (applicationReleaseDTO == null) {
String msg = "Couldn't find an application release for application release UUID: " +
subscriptionInfo.getApplicationUUID();
log.error(msg);
throw new NotFoundException(msg);
}
List<SubscriptionEntity> subscriptionEntities = subscriptionDAO.
getGroupsSubscriptionDetailsByAppReleaseID(applicationReleaseDTO.getId(), isUnsubscribe, tenantId, offset, limit);
int subscriptionCount = isUnsubscribe ? subscriptionDAO.getGroupUnsubscriptionCount(applicationReleaseDTO.getId(), tenantId) :
subscriptionDAO.getGroupSubscriptionCount(applicationReleaseDTO.getId(), tenantId);
return new SubscriptionResponse(subscriptionInfo.getApplicationUUID(), subscriptionCount, subscriptionEntities);
} catch (DBConnectionException | ApplicationManagementDAOException e) {
String msg = "Error encountered while connecting to the database";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public SubscriptionStatistics getSubscriptionStatistics(SubscriptionInfo subscriptionInfo)
throws ApplicationManagementException {
final boolean isUnsubscribe = Objects.equals("unsubscribe", subscriptionInfo.getSubscriptionStatus());
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
List<Device> devices = HelperUtil.getGroupManagementProviderService().
getAllDevicesOfGroup(subscriptionInfo.getIdentifier(), false);
List<Integer> deviceIdsOwnByGroup = devices.stream().map(Device::getId).collect(Collectors.toList());
SubscriptionStatisticDTO subscriptionStatisticDTO = subscriptionDAO.
getSubscriptionStatistic(deviceIdsOwnByGroup, null, isUnsubscribe, tenantId);
int allDeviceCount = HelperUtil.getGroupManagementProviderService().getDeviceCount(subscriptionInfo.getIdentifier());
return SubscriptionManagementHelperUtil.getSubscriptionStatistics(subscriptionStatisticDTO, allDeviceCount);
} catch (ApplicationManagementDAOException e) {
String msg = "Error encountered while getting subscription statistics for group: " + subscriptionInfo.getIdentifier();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (GroupManagementException e) {
String msg = "Error encountered while getting device subscription for group: " + subscriptionInfo.getIdentifier();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
private static class GroupBasedSubscriptionManagementHelperServiceImplHolder {
private static final GroupBasedSubscriptionManagementHelperServiceImpl INSTANCE
= new GroupBasedSubscriptionManagementHelperServiceImpl();
}
}

@ -0,0 +1,221 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.impl;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscription;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscriptionFilterCriteria;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionEntity;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionInfo;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionMetadata;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionResponse;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionStatistics;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionStatisticDTO;
import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException;
import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException;
import io.entgra.device.mgt.core.application.mgt.core.exception.NotFoundException;
import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder;
import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.SubscriptionManagementHelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.service.SubscriptionManagementHelperService;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.PaginationResult;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class RoleBasedSubscriptionManagementHelperServiceImpl implements SubscriptionManagementHelperService {
private static final Log log = LogFactory.getLog(RoleBasedSubscriptionManagementHelperServiceImpl.class);
private RoleBasedSubscriptionManagementHelperServiceImpl() {
}
public static RoleBasedSubscriptionManagementHelperServiceImpl getInstance() {
return RoleBasedSubscriptionManagementHelperServiceImplHolder.INSTANCE;
}
@Override
public SubscriptionResponse getStatusBaseSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException {
final boolean isUnsubscribe = Objects.equals("unsubscribe", subscriptionInfo.getSubscriptionStatus());
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS;
int deviceCount = 0;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
List<Integer> deviceIdsOwnByRole = getDeviceIdsOwnByRole(subscriptionInfo.getIdentifier(), tenantId);
ApplicationReleaseDTO applicationReleaseDTO = applicationReleaseDAO.
getReleaseByUUID(subscriptionInfo.getApplicationUUID(), tenantId);
if (applicationReleaseDTO == null) {
String msg = "Couldn't find an application release for application release UUID: " +
subscriptionInfo.getApplicationUUID();
log.error(msg);
throw new NotFoundException(msg);
}
ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(subscriptionInfo.getApplicationUUID(), tenantId);
if (applicationDTO == null) {
String msg = "Application not found for the release UUID: " + subscriptionInfo.getApplicationUUID();
log.error(msg);
throw new NotFoundException(msg);
}
String deviceSubscriptionStatus = SubscriptionManagementHelperUtil.getDeviceSubscriptionStatus(subscriptionInfo);
DeviceSubscriptionFilterCriteria deviceSubscriptionFilterCriteria = subscriptionInfo.getDeviceSubscriptionFilterCriteria();
DeviceManagementProviderService deviceManagementProviderService = HelperUtil.getDeviceManagementProviderService();
List<String> dbSubscriptionStatus = SubscriptionManagementHelperUtil.getDBSubscriptionStatus(subscriptionInfo.getDeviceSubscriptionStatus());
if (Objects.equals(SubscriptionMetadata.DeviceSubscriptionStatus.NEW, deviceSubscriptionStatus)) {
deviceSubscriptionDTOS = subscriptionDAO.getSubscriptionDetailsByDeviceIds(applicationReleaseDTO.getId(),
isUnsubscribe, tenantId, deviceIdsOwnByRole, null,
null, deviceSubscriptionFilterCriteria.getTriggeredBy(), -1, -1);
List<Integer> deviceIdsOfSubscription = deviceSubscriptionDTOS.stream().
map(DeviceSubscriptionDTO::getDeviceId).collect(Collectors.toList());
for (Integer deviceId : deviceIdsOfSubscription) {
deviceIdsOwnByRole.remove(deviceId);
}
List<Integer> paginatedNewDeviceIds = deviceManagementProviderService.getDevicesInGivenIdList(deviceIdsOwnByRole,
new PaginationRequest(offset, limit));
deviceSubscriptionDTOS = paginatedNewDeviceIds.stream().map(DeviceSubscriptionDTO::new).collect(Collectors.toList());
deviceCount = deviceIdsOwnByRole.size();
} else {
deviceSubscriptionDTOS = subscriptionDAO.getSubscriptionDetailsByDeviceIds(applicationReleaseDTO.getId(),
isUnsubscribe, tenantId, deviceIdsOwnByRole, dbSubscriptionStatus,
subscriptionInfo.getSubscriptionType(), deviceSubscriptionFilterCriteria.getTriggeredBy(), -1, -1);
deviceCount = SubscriptionManagementHelperUtil.getTotalDeviceSubscriptionCount(deviceSubscriptionDTOS,
subscriptionInfo.getDeviceSubscriptionFilterCriteria(), applicationDTO.getDeviceTypeId());
}
List<DeviceSubscription> deviceSubscriptions = SubscriptionManagementHelperUtil.
getDeviceSubscriptionData(deviceSubscriptionDTOS,
subscriptionInfo.getDeviceSubscriptionFilterCriteria(), isUnsubscribe, applicationDTO.getDeviceTypeId(), limit, offset);
return new SubscriptionResponse(subscriptionInfo.getApplicationUUID(), deviceCount, deviceSubscriptions);
} catch (UserStoreException e) {
String msg = "Error encountered while getting the user management store for tenant id " + tenantId;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (DeviceManagementException e) {
String msg = "Error encountered while getting device details";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException | DBConnectionException e) {
String msg = "Error encountered while connecting to the database";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public SubscriptionResponse getSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException {
final boolean isUnsubscribe = Objects.equals("unsubscribe", subscriptionInfo.getSubscriptionStatus());
final int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
ApplicationReleaseDTO applicationReleaseDTO = applicationReleaseDAO.
getReleaseByUUID(subscriptionInfo.getApplicationUUID(), tenantId);
if (applicationReleaseDTO == null) {
String msg = "Couldn't find an application release for application release UUID: " +
subscriptionInfo.getApplicationUUID();
log.error(msg);
throw new NotFoundException(msg);
}
List<SubscriptionEntity> subscriptionEntities = subscriptionDAO.
getRoleSubscriptionsByAppReleaseID(applicationReleaseDTO.getId(), isUnsubscribe, tenantId, offset, limit);
int subscriptionCount = isUnsubscribe ? subscriptionDAO.getRoleUnsubscriptionCount(applicationReleaseDTO.getId(), tenantId) :
subscriptionDAO.getRoleSubscriptionCount(applicationReleaseDTO.getId(), tenantId);
return new SubscriptionResponse(subscriptionInfo.getApplicationUUID(), subscriptionCount, subscriptionEntities);
} catch (DBConnectionException | ApplicationManagementDAOException e) {
String msg = "Error encountered while connecting to the database";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public SubscriptionStatistics getSubscriptionStatistics(SubscriptionInfo subscriptionInfo) throws ApplicationManagementException {
final boolean isUnsubscribe = Objects.equals("unsubscribe", subscriptionInfo.getSubscriptionStatus());
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
List<Integer> deviceIdsOwnByRole = getDeviceIdsOwnByRole(subscriptionInfo.getIdentifier(), tenantId);
SubscriptionStatisticDTO subscriptionStatisticDTO = subscriptionDAO.
getSubscriptionStatistic(deviceIdsOwnByRole, null, isUnsubscribe, tenantId);
int allDeviceCount = deviceIdsOwnByRole.size();
return SubscriptionManagementHelperUtil.getSubscriptionStatistics(subscriptionStatisticDTO, allDeviceCount);
} catch (DeviceManagementException | ApplicationManagementDAOException | UserStoreException e) {
String msg = "Error encountered while getting subscription statistics for role: " + subscriptionInfo.getIdentifier();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@SuppressWarnings("unchecked")
private List<Integer> getDeviceIdsOwnByRole(String roleName, int tenantId) throws UserStoreException, DeviceManagementException {
UserStoreManager userStoreManager = DataHolder.getInstance().getRealmService().
getTenantUserRealm(tenantId).getUserStoreManager();
String[] usersWithRole =
userStoreManager.getUserListOfRole(roleName);
List<Device> deviceListOwnByRole = new ArrayList<>();
for (String user : usersWithRole) {
PaginationRequest paginationRequest = new PaginationRequest(-1, -1);
paginationRequest.setOwner(user);
paginationRequest.setStatusList(Arrays.asList("ACTIVE", "INACTIVE", "UNREACHABLE"));
PaginationResult ownDeviceIds = HelperUtil.getDeviceManagementProviderService().
getAllDevicesIdList(paginationRequest);
if (ownDeviceIds.getData() != null) {
deviceListOwnByRole.addAll((List<Device>) ownDeviceIds.getData());
}
}
return deviceListOwnByRole.stream().map(Device::getId).collect(Collectors.toList());
}
private static class RoleBasedSubscriptionManagementHelperServiceImplHolder {
private static final RoleBasedSubscriptionManagementHelperServiceImpl INSTANCE
= new RoleBasedSubscriptionManagementHelperServiceImpl();
}
}

@ -0,0 +1,206 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.impl;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscription;
import io.entgra.device.mgt.core.application.mgt.common.DeviceSubscriptionFilterCriteria;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionEntity;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionInfo;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionMetadata;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionResponse;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionStatistics;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionStatisticDTO;
import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException;
import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException;
import io.entgra.device.mgt.core.application.mgt.core.exception.NotFoundException;
import io.entgra.device.mgt.core.application.mgt.core.util.ConnectionManagerUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.SubscriptionManagementHelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.service.SubscriptionManagementHelperService;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.PaginationResult;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class UserBasedSubscriptionManagementHelperServiceImpl implements SubscriptionManagementHelperService {
private static final Log log = LogFactory.getLog(UserBasedSubscriptionManagementHelperServiceImpl.class);
private UserBasedSubscriptionManagementHelperServiceImpl() {
}
public static UserBasedSubscriptionManagementHelperServiceImpl getInstance() {
return UserBasedSubscriptionManagementHelperServiceImpl.UserBasedSubscriptionManagementHelperServiceImplHolder.INSTANCE;
}
@Override
public SubscriptionResponse getStatusBaseSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException {
final boolean isUnsubscribe = Objects.equals("unsubscribe", subscriptionInfo.getSubscriptionStatus());
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS;
int deviceCount = 0;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
List<Integer> deviceIdsOwnByUser = getDeviceIdsOwnByUser(subscriptionInfo.getIdentifier());
ApplicationReleaseDTO applicationReleaseDTO = applicationReleaseDAO.
getReleaseByUUID(subscriptionInfo.getApplicationUUID(), tenantId);
if (applicationReleaseDTO == null) {
String msg = "Couldn't find an application release for application release UUID: " +
subscriptionInfo.getApplicationUUID();
log.error(msg);
throw new NotFoundException(msg);
}
ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(subscriptionInfo.getApplicationUUID(), tenantId);
if (applicationDTO == null) {
String msg = "Application not found for the release UUID: " + subscriptionInfo.getApplicationUUID();
log.error(msg);
throw new NotFoundException(msg);
}
String deviceSubscriptionStatus = SubscriptionManagementHelperUtil.getDeviceSubscriptionStatus(subscriptionInfo);
DeviceSubscriptionFilterCriteria deviceSubscriptionFilterCriteria = subscriptionInfo.getDeviceSubscriptionFilterCriteria();
DeviceManagementProviderService deviceManagementProviderService = HelperUtil.getDeviceManagementProviderService();
List<String> dbSubscriptionStatus = SubscriptionManagementHelperUtil.getDBSubscriptionStatus(subscriptionInfo.getDeviceSubscriptionStatus());
if (Objects.equals(SubscriptionMetadata.DeviceSubscriptionStatus.NEW, deviceSubscriptionStatus)) {
deviceSubscriptionDTOS = subscriptionDAO.getSubscriptionDetailsByDeviceIds(applicationReleaseDTO.getId(),
isUnsubscribe, tenantId, deviceIdsOwnByUser, null,
null, deviceSubscriptionFilterCriteria.getTriggeredBy(), -1, -1);
List<Integer> deviceIdsOfSubscription = deviceSubscriptionDTOS.stream().
map(DeviceSubscriptionDTO::getDeviceId).collect(Collectors.toList());
for (Integer deviceId : deviceIdsOfSubscription) {
deviceIdsOwnByUser.remove(deviceId);
}
List<Integer> paginatedNewDeviceIds = deviceManagementProviderService.getDevicesInGivenIdList(deviceIdsOwnByUser,
new PaginationRequest(offset, limit));
deviceSubscriptionDTOS = paginatedNewDeviceIds.stream().map(DeviceSubscriptionDTO::new).collect(Collectors.toList());
deviceCount = deviceIdsOwnByUser.size();
} else {
deviceSubscriptionDTOS = subscriptionDAO.getSubscriptionDetailsByDeviceIds(applicationReleaseDTO.getId(),
isUnsubscribe, tenantId, deviceIdsOwnByUser, dbSubscriptionStatus,
null, deviceSubscriptionFilterCriteria.getTriggeredBy(), -1, -1);
deviceCount = SubscriptionManagementHelperUtil.getTotalDeviceSubscriptionCount(deviceSubscriptionDTOS,
subscriptionInfo.getDeviceSubscriptionFilterCriteria(), applicationDTO.getDeviceTypeId());
}
List<DeviceSubscription> deviceSubscriptions = SubscriptionManagementHelperUtil.getDeviceSubscriptionData(deviceSubscriptionDTOS,
subscriptionInfo.getDeviceSubscriptionFilterCriteria(), isUnsubscribe, applicationDTO.getDeviceTypeId(), limit, offset);
return new SubscriptionResponse(subscriptionInfo.getApplicationUUID(), deviceCount, deviceSubscriptions);
} catch (DeviceManagementException e) {
String msg = "Error encountered while getting device details";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException | DBConnectionException e) {
String msg = "Error encountered while connecting to the database";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public SubscriptionResponse getSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException {
final boolean isUnsubscribe = Objects.equals("unsubscribe", subscriptionInfo.getSubscriptionStatus());
final int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
ApplicationReleaseDTO applicationReleaseDTO = applicationReleaseDAO.
getReleaseByUUID(subscriptionInfo.getApplicationUUID(), tenantId);
if (applicationReleaseDTO == null) {
String msg = "Couldn't find an application release for application release UUID: " +
subscriptionInfo.getApplicationUUID();
log.error(msg);
throw new NotFoundException(msg);
}
List<SubscriptionEntity> subscriptionEntities = subscriptionDAO.
getUserSubscriptionsByAppReleaseID(applicationReleaseDTO.getId(), isUnsubscribe, tenantId, offset, limit);
int subscriptionCount = isUnsubscribe ? subscriptionDAO.getUserUnsubscriptionCount(applicationReleaseDTO.getId(), tenantId) :
subscriptionDAO.getUserSubscriptionCount(applicationReleaseDTO.getId(), tenantId);
return new SubscriptionResponse(subscriptionInfo.getApplicationUUID(), subscriptionCount, subscriptionEntities);
} catch (DBConnectionException | ApplicationManagementDAOException e) {
String msg = "Error encountered while connecting to the database";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public SubscriptionStatistics getSubscriptionStatistics(SubscriptionInfo subscriptionInfo) throws ApplicationManagementException {
final boolean isUnsubscribe = Objects.equals("unsubscribe", subscriptionInfo.getSubscriptionStatus());
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
ConnectionManagerUtil.openDBConnection();
List<Integer> deviceIdsOwnByUser = getDeviceIdsOwnByUser(subscriptionInfo.getIdentifier());
SubscriptionStatisticDTO subscriptionStatisticDTO = subscriptionDAO.
getSubscriptionStatistic(deviceIdsOwnByUser, null, isUnsubscribe, tenantId);
int allDeviceCount = deviceIdsOwnByUser.size();
return SubscriptionManagementHelperUtil.getSubscriptionStatistics(subscriptionStatisticDTO, allDeviceCount);
} catch (DeviceManagementException | ApplicationManagementDAOException e) {
String msg = "Error encountered while getting subscription statistics for user: " + subscriptionInfo.getIdentifier();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@SuppressWarnings("unchecked")
private List<Integer> getDeviceIdsOwnByUser(String username) throws DeviceManagementException {
List<Device> deviceListOwnByUser = new ArrayList<>();
PaginationRequest paginationRequest = new PaginationRequest(-1, -1);
paginationRequest.setOwner(username);
paginationRequest.setStatusList(Arrays.asList("ACTIVE", "INACTIVE", "UNREACHABLE"));
PaginationResult ownDeviceIds = HelperUtil.getDeviceManagementProviderService().
getAllDevicesIdList(paginationRequest);
if (ownDeviceIds.getData() != null) {
deviceListOwnByUser.addAll((List<Device>) ownDeviceIds.getData());
}
return deviceListOwnByUser.stream().map(Device::getId).collect(Collectors.toList());
}
private static class UserBasedSubscriptionManagementHelperServiceImplHolder {
private static final UserBasedSubscriptionManagementHelperServiceImpl INSTANCE
= new UserBasedSubscriptionManagementHelperServiceImpl();
}
}

@ -0,0 +1,44 @@
/*
* Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.service;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionInfo;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionResponse;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionStatistics;
import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationDAO;
import io.entgra.device.mgt.core.application.mgt.core.dao.ApplicationReleaseDAO;
import io.entgra.device.mgt.core.application.mgt.core.dao.SubscriptionDAO;
import io.entgra.device.mgt.core.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
public interface SubscriptionManagementHelperService {
SubscriptionDAO subscriptionDAO = ApplicationManagementDAOFactory.getSubscriptionDAO();
ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
ApplicationReleaseDAO applicationReleaseDAO = ApplicationManagementDAOFactory.getApplicationReleaseDAO();
SubscriptionResponse getStatusBaseSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException;
SubscriptionResponse getSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
throws ApplicationManagementException;
SubscriptionStatistics getSubscriptionStatistics(SubscriptionInfo subscriptionInfo)
throws ApplicationManagementException;
}

@ -97,6 +97,10 @@ public class Device implements Serializable {
public Device() {
}
public Device(int id) {
this.id = id;
}
public Device(String name, String type, String description, String deviceId, EnrolmentInfo enrolmentInfo,
List<Feature> features, List<Property> properties) {
this.name = name;
@ -268,7 +272,9 @@ public class Device implements Serializable {
Device device = (Device) o;
return getDeviceIdentifier().equals(device.getDeviceIdentifier());
if (getDeviceIdentifier().equals(device.getDeviceIdentifier())) return true;
return getId() == device.getId();
}

@ -54,6 +54,7 @@ public class PaginationRequest {
private List<String> statusList = new ArrayList<>();
private OperationLogFilters operationLogFilters = new OperationLogFilters();
private List<SortColumn> sortColumn = new ArrayList<>();
private int deviceTypeId;
public OperationLogFilters getOperationLogFilters() {
return operationLogFilters;
}
@ -292,4 +293,12 @@ public class PaginationRequest {
public void setTabActionStatus(String tabActionStatus) {
this.tabActionStatus = tabActionStatus;
}
public int getDeviceTypeId() {
return deviceTypeId;
}
public void setDeviceTypeId(int deviceTypeId) {
this.deviceTypeId = deviceTypeId;
}
}

@ -864,4 +864,19 @@ public interface DeviceDAO {
* @throws DeviceManagementDAOException
*/
int getCountOfDevicesNotInGroup(PaginationRequest request, int tenantId) throws DeviceManagementDAOException;
List<Integer> getDevicesNotInGivenIdList(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException;
List<Integer> getDevicesInGivenIdList(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException;
int getDeviceCountNotInGivenIdList(List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException;
List<Device> getDevicesByDeviceIds(PaginationRequest paginationRequest, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException;
int getDeviceCountByDeviceIds(PaginationRequest paginationRequest, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException;
}

@ -488,4 +488,5 @@ public interface GroupDAO {
int tenantId, String deviceOwner, String deviceName, String deviceStatus, int offset, int limit)
throws GroupManagementDAOException;
int getDeviceCount(String groupName, int tenantId) throws GroupManagementDAOException;
}

@ -54,6 +54,7 @@ import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.Random;
import java.util.stream.Collectors;
public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
@ -3298,4 +3299,278 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public List<Integer> getDevicesNotInGivenIdList(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
List<Integer> filteredDeviceIds = new ArrayList<>();
try {
Connection connection = getConnection();
String sql = "SELECT ID AS DEVICE_ID FROM DM_DEVICE WHERE TENANT_ID = ?";
if (deviceIds != null && !deviceIds.isEmpty()) {
sql += " AND ID NOT IN ( " + deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ")";
}
sql += " LIMIT ? OFFSET ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int paraIdx = 1;
preparedStatement.setInt(paraIdx++, tenantId);
if (deviceIds != null && !deviceIds.isEmpty()) {
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(paraIdx++, deviceId);
}
}
preparedStatement.setInt(paraIdx++, request.getRowCount());
preparedStatement.setInt(paraIdx, request.getStartIndex());
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
filteredDeviceIds.add(resultSet.getInt("DEVICE_ID"));
}
}
return filteredDeviceIds;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving device ids not in: " + filteredDeviceIds;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public List<Integer> getDevicesInGivenIdList(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
List<Integer> filteredDeviceIds = new ArrayList<>();
if (deviceIds == null || deviceIds.isEmpty()) return filteredDeviceIds;
String deviceIdStringList = deviceIds.stream().map(id -> "?").collect(Collectors.joining(","));
try {
Connection connection = getConnection();
String sql = "SELECT ID AS DEVICE_ID " +
"FROM DM_DEVICE " +
"WHERE ID IN (" + deviceIdStringList + ")" +
" AND TENANT_ID = ? " +
"LIMIT ? " +
"OFFSET ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int paraIdx = 1;
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(paraIdx++, deviceId);
}
preparedStatement.setInt(paraIdx++, tenantId);
preparedStatement.setInt(paraIdx++, request.getRowCount());
preparedStatement.setInt(paraIdx, request.getStartIndex());
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
filteredDeviceIds.add(resultSet.getInt("DEVICE_ID"));
}
}
return filteredDeviceIds;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving device ids in: " + filteredDeviceIds;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public int getDeviceCountNotInGivenIdList(List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
int deviceCount = 0;
try {
Connection connection = getConnection();
String sql = "SELECT COUNT(ID) AS COUNT " +
"FROM DM_DEVICE " +
"WHERE TENANT_ID = ?";
if (deviceIds != null && !deviceIds.isEmpty()) {
sql += " AND ID NOT IN ( " + deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ")";
}
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int paraIdx = 1;
preparedStatement.setInt(paraIdx++, tenantId);
if (deviceIds != null && !deviceIds.isEmpty()) {
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(paraIdx++, deviceId);
}
}
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
deviceCount = resultSet.getInt("COUNT");
}
}
return deviceCount;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving device count";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public List<Device> getDevicesByDeviceIds(PaginationRequest paginationRequest, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
List<Device> devices = new ArrayList<>();
if (deviceIds == null || deviceIds.isEmpty()) return devices;
String deviceIdStringList = deviceIds.stream().map(id -> "?").collect(Collectors.joining(","));
boolean isOwnerProvided = false;
boolean isDeviceStatusProvided = false;
boolean isDeviceNameProvided = false;
try {
Connection connection = getConnection();
String sql = "SELECT e.DEVICE_ID, " +
"d.DEVICE_IDENTIFICATION, " +
"e.STATUS, " +
"e.OWNER, " +
"d.NAME AS DEVICE_NAME, " +
"e.DEVICE_TYPE, " +
"e.OWNERSHIP, " +
"e.DATE_OF_LAST_UPDATE " +
"FROM DM_DEVICE d " +
"INNER JOIN DM_ENROLMENT e " +
"ON d.ID = e.DEVICE_ID " +
"WHERE d.DEVICE_TYPE_ID = ? " +
"AND d.TENANT_ID = ? " +
"AND e.DEVICE_ID IN (" + deviceIdStringList+ ") " +
"AND e.STATUS NOT IN ('DELETED', 'REMOVED')";
if (paginationRequest.getOwner() != null) {
sql = sql + " AND e.OWNER LIKE ?";
isOwnerProvided = true;
}
if (paginationRequest.getDeviceStatus() != null) {
sql = sql + " AND e.STATUS = ?";
isDeviceStatusProvided = true;
}
if (paginationRequest.getDeviceName() != null) {
sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true;
}
sql = sql + " LIMIT ? OFFSET ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int parameterIdx = 1;
preparedStatement.setInt(parameterIdx++, paginationRequest.getDeviceTypeId());
preparedStatement.setInt(parameterIdx++, tenantId);
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(parameterIdx++, deviceId);
}
if (isOwnerProvided)
preparedStatement.setString(parameterIdx++, "%" + paginationRequest.getOwner() + "%");
if (isDeviceStatusProvided)
preparedStatement.setString(parameterIdx++, paginationRequest.getDeviceStatus());
if (isDeviceNameProvided)
preparedStatement.setString(parameterIdx++, "%" + paginationRequest.getDeviceName() + "%");
preparedStatement.setInt(parameterIdx++, paginationRequest.getRowCount());
preparedStatement.setInt(parameterIdx, paginationRequest.getStartIndex());
try(ResultSet resultSet = preparedStatement.executeQuery()) {
Device device;
while(resultSet.next()) {
device = new Device();
device.setId(resultSet.getInt("DEVICE_ID"));
device.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFICATION"));
device.setName(resultSet.getString("DEVICE_NAME"));
device.setType(resultSet.getString("DEVICE_TYPE"));
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(resultSet.getString("STATUS")));
enrolmentInfo.setOwner(resultSet.getString("OWNER"));
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(resultSet.getString("OWNERSHIP")));
enrolmentInfo.setDateOfLastUpdate(resultSet.getTimestamp("DATE_OF_LAST_UPDATE").getTime());
device.setEnrolmentInfo(enrolmentInfo);
devices.add(device);
}
}
}
return devices;
} catch (SQLException e) {
String msg = "Error occurred while retrieving devices for device ids in: " + deviceIds;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
// todo: fix the join query
@Override
public int getDeviceCountByDeviceIds(PaginationRequest paginationRequest, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
int deviceCount = 0;
if (deviceIds == null || deviceIds.isEmpty()) return deviceCount;
String deviceIdStringList = deviceIds.stream().map(id -> "?").collect(Collectors.joining(","));
boolean isOwnerProvided = false;
boolean isDeviceStatusProvided = false;
boolean isDeviceNameProvided = false;
try {
Connection connection = getConnection();
String sql = "SELECT COUNT(DISTINCT e.DEVICE_ID) AS COUNT " +
"FROM DM_DEVICE d " +
"INNER JOIN DM_ENROLMENT e " +
"ON d.ID = e.DEVICE_ID " +
"WHERE e.TENANT_ID = ? " +
"AND e.DEVICE_ID IN (" + deviceIdStringList+ ") " +
"AND d.DEVICE_TYPE_ID = ? " +
"AND e.STATUS NOT IN ('DELETED', 'REMOVED')";
if (paginationRequest.getOwner() != null) {
sql = sql + " AND e.OWNER LIKE ?";
isOwnerProvided = true;
}
if (paginationRequest.getDeviceStatus() != null) {
sql = sql + " AND e.STATUS = ?";
isDeviceStatusProvided = true;
}
if (paginationRequest.getDeviceName() != null) {
sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true;
}
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int parameterIdx = 1;
preparedStatement.setInt(parameterIdx++, tenantId);
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(parameterIdx++, deviceId);
}
preparedStatement.setInt(parameterIdx++, paginationRequest.getDeviceTypeId());
if (isOwnerProvided)
preparedStatement.setString(parameterIdx++, "%" + paginationRequest.getOwner() + "%");
if (isDeviceStatusProvided)
preparedStatement.setString(parameterIdx++, paginationRequest.getDeviceStatus());
if (isDeviceNameProvided)
preparedStatement.setString(parameterIdx, "%" + paginationRequest.getDeviceName() + "%");
try(ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
deviceCount = resultSet.getInt("COUNT");
}
}
}
return deviceCount;
} catch (SQLException e) {
String msg = "Error occurred while retrieving device count for device ids in: " + deviceIds;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
}

@ -587,9 +587,9 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
"d.NAME AS DEVICE_NAME, " +
"e.DEVICE_TYPE AS DEVICE_TYPE, " +
"e.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION " +
"FROM DM_ENROLMENT e " +
"JOIN DM_DEVICE d ON e.DEVICE_ID = d.ID " +
"WHERE e.OWNER = ? AND e.TENANT_ID = ? AND e.STATUS IN (" + deviceFilters + ")");
"FROM DM_ENROLMENT e " +
"JOIN DM_DEVICE d ON e.DEVICE_ID = d.ID " +
"WHERE e.OWNER = ? AND e.TENANT_ID = ? AND e.STATUS IN (" + deviceFilters + ")");
if (deviceTypeId != 0) {
sql.append(" AND d.DEVICE_TYPE_ID = ?");
@ -629,13 +629,6 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
if (ownerDetails.getUserName() == null) {
ownerDetails.setUserName(rs.getString("OWNER"));
}
ownerDetails.setDeviceStatus(rs.getString("DEVICE_STATUS"));
ownerDetails.setDeviceNames(rs.getString("DEVICE_NAME"));
ownerDetails.setDeviceTypes(rs.getString("DEVICE_TYPE"));
ownerDetails.setDeviceIdentifiers(rs.getString("DEVICE_IDENTIFICATION"));
deviceIds.add(rs.getInt("DEVICE_ID"));
deviceCount++;
}
@ -646,11 +639,95 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
ownerDetails.setUserName(deviceOwner);
ownerDetails.setDeviceIds(deviceIds);
ownerDetails.setDeviceCount(deviceCount);
return ownerDetails;
}
// @Override
// public OwnerWithDeviceDTO getOwnersWithDevices(String owner, List<String> allowingDeviceStatuses, int tenantId,
// int deviceTypeId, String deviceOwner, String deviceName,
// String deviceStatus) throws DeviceManagementDAOException {
// Connection conn = null;
// OwnerWithDeviceDTO ownerDetails = new OwnerWithDeviceDTO();
// List<Integer> deviceIds = new ArrayList<>();
// int deviceCount = 0;
//
// StringBuilder deviceFilters = new StringBuilder();
// for (int i = 0; i < allowingDeviceStatuses.size(); i++) {
// deviceFilters.append("?");
// if (i < allowingDeviceStatuses.size() - 1) {
// deviceFilters.append(",");
// }
// }
//
// StringBuilder sql = new StringBuilder(
// "SELECT e.DEVICE_ID, " +
// "e.OWNER, " +
// "e.STATUS AS DEVICE_STATUS, " +
// "d.NAME AS DEVICE_NAME, " +
// "e.DEVICE_TYPE AS DEVICE_TYPE, " +
// "e.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION " +
// "FROM DM_ENROLMENT e " +
// "JOIN DM_DEVICE d ON e.DEVICE_ID = d.ID " +
// "WHERE e.OWNER = ? AND e.TENANT_ID = ? AND d.DEVICE_TYPE_ID = ? AND e.STATUS IN (" + deviceFilters + ")");
//
// if (deviceOwner != null && !deviceOwner.isEmpty()) {
// sql.append(" AND e.OWNER LIKE ?");
// }
// if (deviceName != null && !deviceName.isEmpty()) {
// sql.append(" AND d.NAME LIKE ?");
// }
// if (deviceStatus != null && !deviceStatus.isEmpty()) {
// sql.append(" AND e.STATUS = ?");
// }
//
// try {
// conn = this.getConnection();
// try (PreparedStatement stmt = conn.prepareStatement(sql.toString())) {
// int index = 1;
// stmt.setString(index++, owner);
// stmt.setInt(index++, tenantId);
// stmt.setInt(index++, deviceTypeId);
// for (String status : allowingDeviceStatuses) {
// stmt.setString(index++, status);
// }
//
// if (deviceOwner != null && !deviceOwner.isEmpty()) {
// stmt.setString(index++, "%" + deviceOwner + "%");
// }
// if (deviceName != null && !deviceName.isEmpty()) {
// stmt.setString(index++, "%" + deviceName + "%");
// }
// if (deviceStatus != null && !deviceStatus.isEmpty()) {
// stmt.setString(index++, deviceStatus);
// }
//
// try (ResultSet rs = stmt.executeQuery()) {
// while (rs.next()) {
// if (ownerDetails.getUserName() == null) {
// ownerDetails.setUserName(rs.getString("OWNER"));
// }
// ownerDetails.setDeviceStatus(rs.getString("DEVICE_STATUS"));
// ownerDetails.setDeviceNames(rs.getString("DEVICE_NAME"));
// ownerDetails.setDeviceTypes(rs.getString("DEVICE_TYPE"));
// ownerDetails.setDeviceIdentifiers(rs.getString("DEVICE_IDENTIFICATION"));
// deviceIds.add(rs.getInt("DEVICE_ID"));
// deviceCount++;
// }
// }
// }
// } catch (SQLException e) {
// String msg = "Error occurred while retrieving owners and device IDs for owner: " + owner;
// log.error(msg, e);
// throw new DeviceManagementDAOException(msg, e);
// }
// ownerDetails.setDeviceIds(deviceIds);
// ownerDetails.setDeviceCount(deviceCount);
// return ownerDetails;
// }
@Override
public OwnerWithDeviceDTO getOwnerWithDeviceByDeviceId(int deviceId, int tenantId, String deviceOwner, String deviceName,
String deviceStatus) throws DeviceManagementDAOException {

@ -1496,9 +1496,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
if (deviceStatus != null && !deviceStatus.isEmpty()) {
sql.append(" AND e.STATUS = ?");
}
// Append limit and offset only if limit is not -1
if (limit != -1) {
if (limit >= 0 && offset >=0 ) {
sql.append(" LIMIT ? OFFSET ?");
}
@ -1525,8 +1523,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
stmt.setString(index++, deviceStatus);
}
// Set limit and offset parameters only if limit is not -1
if (limit != -1) {
if (limit >= 0 && offset >=0 ) {
stmt.setInt(index++, limit);
stmt.setInt(index++, offset);
}
@ -1562,4 +1559,29 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
throw new GroupManagementDAOException(msg, e);
}
}
@Override
public int getDeviceCount(String groupName, int tenantId) throws GroupManagementDAOException {
int deviceCount = 0;
try {
Connection connection = GroupManagementDAOFactory.getConnection();
String sql = "SELECT COUNT(d.ID) AS COUNT FROM DM_GROUP d INNER JOIN " +
"DM_DEVICE_GROUP_MAP m ON " +
"d.ID = m.GROUP_ID WHERE d.TENANT_ID = ? AND d.GROUP_NAME = ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setInt(1, tenantId);
preparedStatement.setString(2, groupName);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
deviceCount = resultSet.getInt("COUNT");
}
}
}
return deviceCount;
} catch (SQLException e) {
String msg = "Error occurred while retrieving device count for the group: " + groupName;
log.error(msg, e);
throw new GroupManagementDAOException(msg, e);
}
}
}

@ -42,6 +42,7 @@ import java.util.Date;
import java.util.List;
import java.util.StringJoiner;
import java.util.Map;
import java.util.stream.Collectors;
/**
* This class holds the generic implementation of DeviceDAO which can be used to support ANSI db syntax.
@ -457,6 +458,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT d.ID, " +
"d.LAST_UPDATED_TIMESTAMP, " +
"d.DEVICE_IDENTIFICATION " +
"FROM DM_DEVICE d WHERE d.TENANT_ID = ?) d1 " +
"WHERE d1.ID = e.DEVICE_ID AND e.TENANT_ID = ? ";
@ -1857,4 +1859,156 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
@Override
public List<Device> getDevicesByDeviceIds(PaginationRequest paginationRequest, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
List<Device> devices = new ArrayList<>();
if (deviceIds == null || deviceIds.isEmpty()) return devices;
String deviceIdStringList = deviceIds.stream().map(id -> "?").collect(Collectors.joining(","));
boolean isOwnerProvided = false;
boolean isDeviceStatusProvided = false;
boolean isDeviceNameProvided = false;
try {
Connection connection = getConnection();
String sql = "SELECT e.DEVICE_ID, " +
"d.DEVICE_IDENTIFICATION, " +
"e.STATUS, " +
"e.OWNER, " +
"d.NAME AS DEVICE_NAME, " +
"e.DEVICE_TYPE, " +
"e.OWNERSHIP, " +
"e.DATE_OF_LAST_UPDATE " +
"FROM DM_DEVICE d " +
"INNER JOIN DM_ENROLMENT e " +
"WHERE d.ID = e.DEVICE_ID " +
"AND d.TENANT_ID = ? " +
"AND e.DEVICE_ID IN (" + deviceIdStringList+ ") " +
"AND e.STATUS NOT IN ('DELETED', 'REMOVED')";
if (paginationRequest.getOwner() != null) {
sql = sql + " AND e.OWNER LIKE ?";
isOwnerProvided = true;
}
if (paginationRequest.getDeviceStatus() != null) {
sql = sql + " AND e.STATUS = ?";
isDeviceStatusProvided = true;
}
if (paginationRequest.getDeviceName() != null) {
sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true;
}
sql = sql + " LIMIT ? OFFSET ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int parameterIdx = 1;
preparedStatement.setInt(parameterIdx++, tenantId);
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(parameterIdx++, deviceId);
}
if (isOwnerProvided)
preparedStatement.setString(parameterIdx++, "%" + paginationRequest.getOwner() + "%");
if (isDeviceStatusProvided)
preparedStatement.setString(parameterIdx++, paginationRequest.getDeviceStatus());
if (isDeviceNameProvided)
preparedStatement.setString(parameterIdx++, "%" + paginationRequest.getDeviceName() + "%");
preparedStatement.setInt(parameterIdx++, paginationRequest.getRowCount());
preparedStatement.setInt(parameterIdx, paginationRequest.getStartIndex());
try(ResultSet resultSet = preparedStatement.executeQuery()) {
Device device;
while(resultSet.next()) {
device = new Device();
device.setId(resultSet.getInt("DEVICE_ID"));
device.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFICATION"));
device.setName(resultSet.getString("DEVICE_NAME"));
device.setType(resultSet.getString("DEVICE_TYPE"));
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(resultSet.getString("STATUS")));
enrolmentInfo.setOwner(resultSet.getString("OWNER"));
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(resultSet.getString("OWNERSHIP")));
enrolmentInfo.setDateOfLastUpdate(resultSet.getTimestamp("DATE_OF_LAST_UPDATE").getTime());
device.setEnrolmentInfo(enrolmentInfo);
devices.add(device);
}
}
}
return devices;
} catch (SQLException e) {
String msg = "Error occurred while retrieving devices for device ids in: " + deviceIds;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public List<Integer> getDevicesInGivenIdList(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
List<Integer> filteredDeviceIds = new ArrayList<>();
if (deviceIds == null || deviceIds.isEmpty()) return filteredDeviceIds;
String deviceIdStringList = deviceIds.stream().map(id -> "?").collect(Collectors.joining(","));
try {
Connection connection = getConnection();
String sql = "SELECT ID AS DEVICE_ID " +
"FROM DM_DEVICE WHERE ID IN " +
"(" + deviceIdStringList + ") " +
"AND TENANT_ID = ? " +
"LIMIT ? " +
"OFFSET ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int paraIdx = 1;
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(paraIdx++, deviceId);
}
preparedStatement.setInt(paraIdx++, tenantId);
preparedStatement.setInt(paraIdx++, request.getRowCount());
preparedStatement.setInt(paraIdx, request.getStartIndex());
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
filteredDeviceIds.add(resultSet.getInt("DEVICE_ID"));
}
}
return filteredDeviceIds;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving device ids in: " + filteredDeviceIds;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public List<Integer> getDevicesNotInGivenIdList(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
List<Integer> filteredDeviceIds = new ArrayList<>();
try {
Connection connection = getConnection();
String sql = "SELECT ID AS DEVICE_ID " +
"FROM DM_DEVICE" +
" WHERE TENANT_ID = ?";
if (deviceIds != null && !deviceIds.isEmpty()) {
sql += " AND ID NOT IN ( " + deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ")";
}
sql += " LIMIT ? OFFSET ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int paraIdx = 1;
preparedStatement.setInt(paraIdx++, tenantId);
if (deviceIds != null && !deviceIds.isEmpty()) {
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(paraIdx++, deviceId);
}
}
preparedStatement.setInt(paraIdx++, request.getRowCount());
preparedStatement.setInt(paraIdx, request.getStartIndex());
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
filteredDeviceIds.add(resultSet.getInt("DEVICE_ID"));
}
}
return filteredDeviceIds;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving device ids not in: " + filteredDeviceIds;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
}

@ -20,6 +20,7 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.device;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -28,7 +29,9 @@ 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.stream.Collectors;
/**
* This class holds the generic implementation of DeviceDAO which can be used to support ANSI db syntax.
@ -69,4 +72,162 @@ public class OracleDeviceDAOImpl extends SQLServerDeviceDAOImpl {
}
}
@Override
public List<Device> getDevicesByDeviceIds(PaginationRequest paginationRequest, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
List<Device> devices = new ArrayList<>();
if (deviceIds == null || deviceIds.isEmpty()) return devices;
String deviceIdStringList = deviceIds.stream().map(id -> "?").collect(Collectors.joining(","));
boolean isOwnerProvided = false;
boolean isDeviceStatusProvided = false;
boolean isDeviceNameProvided = false;
try {
Connection connection = getConnection();
String sql = "SELECT e.DEVICE_ID, " +
"d.DEVICE_IDENTIFICATION, " +
"e.STATUS, " +
"e.OWNER, " +
"d.NAME AS DEVICE_NAME, " +
"e.DEVICE_TYPE, " +
"e.OWNERSHIP, " +
"e.DATE_OF_LAST_UPDATE " +
"FROM DM_DEVICE d " +
"INNER JOIN DM_ENROLMENT e " +
"ON d.ID = e.DEVICE_ID " +
"WHERE d.TENANT_ID = ? " +
"AND e.DEVICE_ID IN (" + deviceIdStringList + ") " +
"AND e.STATUS NOT IN ('DELETED', 'REMOVED')";
if (paginationRequest.getOwner() != null) {
sql += " AND e.OWNER LIKE ?";
isOwnerProvided = true;
}
if (paginationRequest.getDeviceStatus() != null) {
sql += " AND e.STATUS = ?";
isDeviceStatusProvided = true;
}
if (paginationRequest.getDeviceName() != null) {
sql += " AND d.NAME LIKE ?";
isDeviceNameProvided = true;
}
sql += " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int parameterIdx = 1;
preparedStatement.setInt(parameterIdx++, tenantId);
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(parameterIdx++, deviceId);
}
if (isOwnerProvided) {
preparedStatement.setString(parameterIdx++, "%" + paginationRequest.getOwner() + "%");
}
if (isDeviceStatusProvided) {
preparedStatement.setString(parameterIdx++, paginationRequest.getDeviceStatus());
}
if (isDeviceNameProvided) {
preparedStatement.setString(parameterIdx++, "%" + paginationRequest.getDeviceName() + "%");
}
preparedStatement.setInt(parameterIdx++, paginationRequest.getStartIndex());
preparedStatement.setInt(parameterIdx, paginationRequest.getRowCount());
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
Device device = new Device();
device.setId(resultSet.getInt("DEVICE_ID"));
device.setDeviceIdentifier(resultSet.getString("DEVICE_IDENTIFICATION"));
device.setName(resultSet.getString("DEVICE_NAME"));
device.setType(resultSet.getString("DEVICE_TYPE"));
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(resultSet.getString("STATUS")));
enrolmentInfo.setOwner(resultSet.getString("OWNER"));
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(resultSet.getString("OWNERSHIP")));
enrolmentInfo.setDateOfLastUpdate(resultSet.getTimestamp("DATE_OF_LAST_UPDATE").getTime());
device.setEnrolmentInfo(enrolmentInfo);
devices.add(device);
}
}
}
return devices;
} catch (SQLException e) {
String msg = "Error occurred while retrieving devices for device ids in: " + deviceIds;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public List<Integer> getDevicesInGivenIdList(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
List<Integer> filteredDeviceIds = new ArrayList<>();
if (deviceIds == null || deviceIds.isEmpty()) return filteredDeviceIds;
String deviceIdStringList = deviceIds.stream().map(id -> "?").collect(Collectors.joining(","));
try {
Connection connection = getConnection();
String sql = "SELECT ID AS DEVICE_ID " +
"FROM DM_DEVICE WHERE ID IN " +
"(" + deviceIdStringList + ") " +
"AND TENANT_ID = ? " +
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int paraIdx = 1;
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(paraIdx++, deviceId);
}
preparedStatement.setInt(paraIdx++, tenantId);
preparedStatement.setInt(paraIdx++, request.getStartIndex());
preparedStatement.setInt(paraIdx, request.getRowCount());
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
filteredDeviceIds.add(resultSet.getInt("DEVICE_ID"));
}
}
return filteredDeviceIds;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving device ids in: " + deviceIds;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public List<Integer> getDevicesNotInGivenIdList(PaginationRequest request, List<Integer> deviceIds, int tenantId)
throws DeviceManagementDAOException {
List<Integer> filteredDeviceIds = new ArrayList<>();
try {
Connection connection = getConnection();
String sql = "SELECT ID AS DEVICE_ID " +
"FROM DM_DEVICE " +
"WHERE TENANT_ID = ?";
if (deviceIds != null && !deviceIds.isEmpty()) {
sql += " AND ID NOT IN (" + deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ")";
}
sql += "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int paraIdx = 1;
preparedStatement.setInt(paraIdx++, tenantId);
if (deviceIds != null && !deviceIds.isEmpty()) {
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(paraIdx++, deviceId);
}
}
preparedStatement.setInt(paraIdx++, request.getStartIndex());
preparedStatement.setInt(paraIdx, request.getRowCount());
try (ResultSet resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
filteredDeviceIds.add(resultSet.getInt("DEVICE_ID"));
}
}
return filteredDeviceIds;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving device ids not in: " + deviceIds;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
}

@ -1152,4 +1152,16 @@ public interface DeviceManagementProviderService {
*/
Device updateDeviceName(Device device, String deviceType, String deviceId)
throws DeviceManagementException, DeviceNotFoundException, ConflictException;
List<Integer> getDevicesNotInGivenIdList(List<Integer> deviceIds, PaginationRequest paginationRequest)
throws DeviceManagementException;
List<Integer> getDevicesInGivenIdList(List<Integer> deviceIds, PaginationRequest paginationRequest)
throws DeviceManagementException;
int getDeviceCountNotInGivenIdList(List<Integer> deviceIds) throws DeviceManagementException;
List<Device> getDevicesByDeviceIds(PaginationRequest paginationRequest, List<Integer> deviceIds)
throws DeviceManagementException;
public int getDeviceCountByDeviceIds(PaginationRequest paginationRequest, List<Integer> deviceIds)
throws DeviceManagementException;
}

@ -161,6 +161,7 @@ import javax.xml.bind.Marshaller;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.sql.Array;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
@ -5359,25 +5360,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
OwnerWithDeviceDTO ownerWithDeviceDTO;
List<String> allowingDeviceStatuses = new ArrayList<>();
allowingDeviceStatuses.add(EnrolmentInfo.Status.ACTIVE.toString());
allowingDeviceStatuses.add(EnrolmentInfo.Status.INACTIVE.toString());
allowingDeviceStatuses.add(EnrolmentInfo.Status.UNREACHABLE.toString());
List<String> allowingDeviceStatuses = Arrays.asList(EnrolmentInfo.Status.ACTIVE.toString(),
EnrolmentInfo.Status.INACTIVE.toString(), EnrolmentInfo.Status.UNREACHABLE.toString());
try {
DeviceManagementDAOFactory.openConnection();
ownerWithDeviceDTO = this.enrollmentDAO.getOwnersWithDevices(owner, allowingDeviceStatuses, tenantId, deviceTypeId, deviceOwner, deviceName, deviceStatus);
if (ownerWithDeviceDTO == null) {
String msg = "No data found for owner: " + owner;
log.error(msg);
throw new DeviceManagementDAOException(msg);
}
List<Integer> deviceIds = ownerWithDeviceDTO.getDeviceIds();
if (deviceIds != null) {
ownerWithDeviceDTO.setDeviceCount(deviceIds.size());
} else {
ownerWithDeviceDTO.setDeviceCount(0);
}
ownerWithDeviceDTO = this.enrollmentDAO.getOwnersWithDevices(owner, allowingDeviceStatuses,
tenantId, deviceTypeId, deviceOwner, deviceName, deviceStatus);
} catch (DeviceManagementDAOException | SQLException e) {
String msg = "Error occurred while retrieving device IDs for owner: " + owner;
log.error(msg, e);
@ -5388,6 +5377,41 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return ownerWithDeviceDTO;
}
// @Override
// public OwnerWithDeviceDTO getOwnersWithDeviceIds(String owner, int deviceTypeId, String deviceOwner, String deviceName, String deviceStatus)
// throws DeviceManagementDAOException {
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// OwnerWithDeviceDTO ownerWithDeviceDTO;
//
// List<String> allowingDeviceStatuses = new ArrayList<>();
// allowingDeviceStatuses.add(EnrolmentInfo.Status.ACTIVE.toString());
// allowingDeviceStatuses.add(EnrolmentInfo.Status.INACTIVE.toString());
// allowingDeviceStatuses.add(EnrolmentInfo.Status.UNREACHABLE.toString());
//
// try {
// DeviceManagementDAOFactory.openConnection();
// ownerWithDeviceDTO = this.enrollmentDAO.getOwnersWithDevices(owner, allowingDeviceStatuses, tenantId, deviceTypeId, deviceOwner, deviceName, deviceStatus);
// if (ownerWithDeviceDTO == null) {
// String msg = "No data found for owner: " + owner;
// log.error(msg);
// throw new DeviceManagementDAOException(msg);
// }
// List<Integer> deviceIds = ownerWithDeviceDTO.getDeviceIds();
// if (deviceIds != null) {
// ownerWithDeviceDTO.setDeviceCount(deviceIds.size());
// } else {
// ownerWithDeviceDTO.setDeviceCount(0);
// }
// } catch (DeviceManagementDAOException | SQLException e) {
// String msg = "Error occurred while retrieving device IDs for owner: " + owner;
// log.error(msg, e);
// throw new DeviceManagementDAOException(msg, e);
// } finally {
// DeviceManagementDAOFactory.closeConnection();
// }
// return ownerWithDeviceDTO;
// }
@Override
public OwnerWithDeviceDTO getOwnerWithDeviceByDeviceId(int deviceId, String deviceOwner, String deviceName, String deviceStatus)
@ -5568,4 +5592,130 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public List<Integer> getDevicesNotInGivenIdList(List<Integer> deviceIds, PaginationRequest paginationRequest)
throws DeviceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
if (paginationRequest == null) {
String msg = "Received null for pagination request";
log.error(msg);
throw new DeviceManagementException(msg);
}
try {
DeviceManagementDAOFactory.openConnection();
return deviceDAO.getDevicesNotInGivenIdList(paginationRequest, deviceIds, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error encountered while getting device ids";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error encountered while getting the database connection";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public List<Integer> getDevicesInGivenIdList(List<Integer> deviceIds, PaginationRequest paginationRequest)
throws DeviceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
if (paginationRequest == null) {
String msg = "Received null for pagination request";
log.error(msg);
throw new DeviceManagementException(msg);
}
try {
DeviceManagementDAOFactory.openConnection();
return deviceDAO.getDevicesInGivenIdList(paginationRequest, deviceIds, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error encountered while getting device ids";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error encountered while getting the database connection";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public int getDeviceCountNotInGivenIdList(List<Integer> deviceIds)
throws DeviceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
DeviceManagementDAOFactory.openConnection();
return deviceDAO.getDeviceCountNotInGivenIdList(deviceIds, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error encountered while getting device ids";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error encountered while getting the database connection";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public List<Device> getDevicesByDeviceIds(PaginationRequest paginationRequest, List<Integer> deviceIds)
throws DeviceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
if (paginationRequest == null) {
String msg = "Received null for pagination request";
log.error(msg);
throw new DeviceManagementException(msg);
}
try {
DeviceManagementDAOFactory.openConnection();
return deviceDAO.getDevicesByDeviceIds(paginationRequest, deviceIds, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error encountered while getting devices for device ids in " + deviceIds;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error encountered while getting the database connection";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public int getDeviceCountByDeviceIds(PaginationRequest paginationRequest, List<Integer> deviceIds)
throws DeviceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
if (paginationRequest == null) {
String msg = "Received null for pagination request";
log.error(msg);
throw new DeviceManagementException(msg);
}
try {
DeviceManagementDAOFactory.openConnection();
return deviceDAO.getDeviceCountByDeviceIds(paginationRequest, deviceIds, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error encountered while getting devices for device ids in " + deviceIds;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error encountered while getting the database connection";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
}

@ -30,6 +30,7 @@ import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupAlreadyExistEx
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupNotExistException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.RoleDoesNotExistException;
import io.entgra.device.mgt.core.device.mgt.core.dao.GroupManagementDAOException;
import io.entgra.device.mgt.core.device.mgt.core.dto.GroupDetailsDTO;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.UserStoreManager;
@ -389,4 +390,6 @@ public interface GroupManagementProviderService {
GroupDetailsDTO getGroupDetailsWithDevices(String groupName, int deviceTypeId, String deviceOwner, String deviceName, String deviceStatus,
int offset, int limit) throws GroupManagementException;
int getDeviceCount(String groupName) throws GroupManagementException;
}

@ -1725,4 +1725,18 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
return groupDetailsWithDevices;
}
@Override
public int getDeviceCount(String groupName) throws GroupManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
GroupManagementDAOFactory.openConnection();
return groupDAO.getDeviceCount(groupName, tenantId);
} catch (SQLException | GroupManagementDAOException e) {
String msg = "Error occurred while retrieving device count.";
log.error(msg, e);
throw new GroupManagementException(msg, e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
}
}

Loading…
Cancel
Save