Compare commits

Invalid templates have been ignored

1 invalid template(s) found pull_request_template.md: frontmatter must start with a separator line

..

41 Commits

Author SHA1 Message Date
Nipuni Kavindya 829e1ed8a4 Add operation log of a subscription
5 months ago
Lasantha Dharmakeerthi 0aea6a9fa1 Sync master with appm_improvement branch
5 months ago
prathabanKavin e1216d898a Limit device percentages to two decimals
5 months ago
Nipuni Kavindya 6e4dbee81f Initialize OperationManagementDAOFactory with data source
5 months ago
Nipuni Kavindya b95c795606 Generalize JSON keys of application subscription APIs.
5 months ago
prathabanKavin 332b2f2f91 Change subscriptionType format
5 months ago
Nipuni Kavindya 664c1e9e5a Generalize application subscription APIs
5 months ago
Nipuni Kavindya 74e52e46b7 DAO and Services for APIs to populate the installation details static UI.
5 months ago
Nipuni Kavindya 86bed7b83a Feature to manage subscription type base subscriptions and Installation Percentage Calculation based on groups, users and roles
5 months ago
Kavin Prathaban 0790aa609a Modify methods to categorize device subscriptions
5 months ago
Lasantha Dharmakeerthi 47ac0774ad Sync master branch changes into appm_improvement branch
5 months ago
Kavin Prathaban fb3ee6d6f3 Merge branch 'appm_improvement' into appmnewsyncbranch
5 months ago
Sasini Sandamali faa9cea80a Add necessary improvements and configs for grafana version 10.3.3 (#396)
5 months ago
Amalka Subasinghe 0de768cee0 scopes and related permissions added when scope is not attached to an api
5 months ago
Pasindu Rupasinghe 43a6c289c5 Change scope key not found log to debug level log
5 months ago
Gimhan Wijayawardana 922c775cfa Modify permission of operation status update
5 months ago
Pramila Niroshan cc602a03bd Add missing test cases for DevicePersistTests and GroupPersistTests
5 months ago
Lasantha Dharmakeerthi 3c06059873 Fix SQL error
5 months ago
Ashvini Wegodapola 49bc317d20 Add filter to get Web apps in Enrollment Application Install
5 months ago
Lasantha Dharmakeerthi ec463cfb5c Limit device percentages to two decimals
5 months ago
Kavin Prathaban c0729cfab2 Merge branch 'appm_improvement' into devicepercentageissue
5 months ago
prathabanKavin 128682ce77 Limit device percentages to two decimals
5 months ago
Lasantha Dharmakeerthi 4a9496f78a Initialize OperationManagementDAOFactory with data source
5 months ago
Nipuni Kavindya 998b4e2c7c Initialize OperationManagementDAOFactory with data source
5 months ago
Nipuni Kavindya 6db42a0f4b Generalize JSON keys of application subscription APIs.
5 months ago
Lasantha Dharmakeerthi ddbf312c6a Change subscriptionType format
5 months ago
Lasantha Dharmakeerthi 02d2a8c22f Generalize JSON keys of application subscription APIs
5 months ago
Nipuni Kavindya 6c92c626af Generalize JSON keys of application subscription APIs.
5 months ago
prathabanKavin e3e0e6de3d Change subscriptionType format
5 months ago
prathabanKavin 1b74cf9a03 Fix devices of a group not loading
5 months ago
Lasantha Dharmakeerthi fa59590dfe Generalize application subscription APIs
5 months ago
Nipuni Kavindya f50abeeca1 Generalize application subscription APIs
5 months ago
Lasantha Dharmakeerthi 8c4f8bda4d DAO and Services for APIs to populate the installation details static UI.
6 months ago
Nipuni Kavindya e5cd6c40ce DAO and Services for APIs to populate the installation details static UI.
6 months ago
Lasantha Dharmakeerthi 918c604d72 Sync with master branch
6 months ago
Kavin Prathaban cb6af45a07 Merge branch 'appm_improvement' into appmsyncmaster
6 months ago
Nipuni Kavindya e3da56f793 Feature to manage subscription type base subscriptions and Installation Percentage Calculation based on groups, users and roles
6 months ago
Kavin Prathaban 2da954275a Modify methods to categorize device subscriptions
6 months ago
Lasantha Dharmakeerthi c8c3c79dad Add feature to manage subscription type base subscriptions and Installation Percentage of devices based on completed, pending, error and new
6 months ago
Nipuni Kavindya aff18e1ceb Feature to manage subscription type base subscriptions and Installation Percentage Calculation based on groups, users and roles
6 months ago
Kavin Prathaban 1ea3a44859 Modify methods to categorize device subscriptions
6 months ago

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>grafana-mgt</artifactId> <artifactId>grafana-mgt</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>grafana-mgt</artifactId> <artifactId>grafana-mgt</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>grafana-mgt</artifactId> <artifactId>grafana-mgt</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>analytics-mgt</artifactId> <artifactId>analytics-mgt</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>io.entgra.device.mgt.core.parent</artifactId> <artifactId>io.entgra.device.mgt.core.parent</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -20,7 +20,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.parent</artifactId> <artifactId>io.entgra.device.mgt.core.parent</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -25,52 +25,16 @@ public class ApplicationArtifact {
private String installerName; private String installerName;
private InputStream installerStream; private InputStream installerStream;
private String installerPath;
private String bannerName; private String bannerName;
private InputStream bannerStream; private InputStream bannerStream;
private String bannerPath;
private String iconName; private String iconName;
private InputStream iconStream; private InputStream iconStream;
private String iconPath;
private Map<String , InputStream> screenshots; private Map<String , InputStream> screenshots;
private Map<String, String> screenshotPaths;
public String getInstallerPath() {
return installerPath;
}
public void setInstallerPath(String installerPath) {
this.installerPath = installerPath;
}
public String getBannerPath() {
return bannerPath;
}
public void setBannerPath(String bannerPath) {
this.bannerPath = bannerPath;
}
public String getIconPath() {
return iconPath;
}
public void setIconPath(String iconPath) {
this.iconPath = iconPath;
}
public Map<String, String> getScreenshotPaths() {
return screenshotPaths;
}
public void setScreenshotPaths(Map<String, String> screenshotPaths) {
this.screenshotPaths = screenshotPaths;
}
public String getInstallerName() { public String getInstallerName() {
return installerName; return installerName;

@ -18,20 +18,14 @@
package io.entgra.device.mgt.core.application.mgt.common; package io.entgra.device.mgt.core.application.mgt.common;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class CategorizedSubscriptionResult { public class CategorizedSubscriptionResult {
private List<DeviceSubscriptionData> installedDevices; private List<DeviceSubscriptionData> installedDevices;
private int installedDevicesCount;
private List<DeviceSubscriptionData> pendingDevices; private List<DeviceSubscriptionData> pendingDevices;
private int pendingDevicesCount;
private List<DeviceSubscriptionData> errorDevices; private List<DeviceSubscriptionData> errorDevices;
private int errorDevicesCount;
private List<DeviceSubscriptionData> newDevices; private List<DeviceSubscriptionData> newDevices;
private int newDevicesCount;
private List<DeviceSubscriptionData> subscribedDevices; private List<DeviceSubscriptionData> subscribedDevices;
private int subscribedDevicesCount;
public CategorizedSubscriptionResult(List<DeviceSubscriptionData> installedDevices, public CategorizedSubscriptionResult(List<DeviceSubscriptionData> installedDevices,
List<DeviceSubscriptionData> pendingDevices, List<DeviceSubscriptionData> pendingDevices,
@ -66,75 +60,6 @@ public class CategorizedSubscriptionResult {
this.subscribedDevices = subscribedDevices; this.subscribedDevices = subscribedDevices;
} }
public CategorizedSubscriptionResult(List<DeviceSubscriptionData> installedDevices,
List<DeviceSubscriptionData> pendingDevices,
List<DeviceSubscriptionData> errorDevices,
List<DeviceSubscriptionData> newDevices,
int installedDevicesCount,
int pendingDevicesCount,
int errorDevicesCount,
int newDevicesCount
) {
this.installedDevices = installedDevices;
this.pendingDevices = pendingDevices;
this.errorDevices = errorDevices;
this.newDevices = newDevices;
this.subscribedDevices = null;
this.installedDevicesCount = installedDevicesCount;
this.pendingDevicesCount = pendingDevicesCount;
this.errorDevicesCount = errorDevicesCount;
this.newDevicesCount = newDevicesCount;
this.subscribedDevicesCount = 0;
}
public CategorizedSubscriptionResult(List<DeviceSubscriptionData> installedDevices,
List<DeviceSubscriptionData> pendingDevices,
List<DeviceSubscriptionData> errorDevices,
List<DeviceSubscriptionData> newDevices,
List<DeviceSubscriptionData> subscribedDevices, int installedDevicesCount,
int pendingDevicesCount,
int errorDevicesCount,
int newDevicesCount,
int subscribedDevicesCount) {
this.installedDevices = installedDevices;
this.pendingDevices = pendingDevices;
this.errorDevices = errorDevices;
this.newDevices = newDevices;
this.subscribedDevices = subscribedDevices;
this.installedDevicesCount = installedDevicesCount;
this.pendingDevicesCount = pendingDevicesCount;
this.errorDevicesCount = errorDevicesCount;
this.newDevicesCount = newDevicesCount;
this.subscribedDevicesCount = subscribedDevicesCount;
}
public CategorizedSubscriptionResult(List<DeviceSubscriptionData> devices, String tabActionStatus) {
switch (tabActionStatus) {
case "COMPLETED":
this.installedDevices = devices;
break;
case "PENDING":
this.pendingDevices = devices;
break;
case "ERROR":
this.errorDevices = devices;
break;
case "NEW":
this.newDevices = devices;
break;
case "SUBSCRIBED":
this.subscribedDevices = devices;
break;
default:
this.installedDevices = new ArrayList<>();
this.pendingDevices = new ArrayList<>();
this.errorDevices = new ArrayList<>();
this.newDevices = new ArrayList<>();
this.subscribedDevices = new ArrayList<>();
break;
}
}
public List<DeviceSubscriptionData> getInstalledDevices() { public List<DeviceSubscriptionData> getInstalledDevices() {
return installedDevices; return installedDevices;
} }
@ -174,44 +99,5 @@ public class CategorizedSubscriptionResult {
public void setSubscribedDevices(List<DeviceSubscriptionData> subscribedDevices) { public void setSubscribedDevices(List<DeviceSubscriptionData> subscribedDevices) {
this.subscribedDevices = subscribedDevices; this.subscribedDevices = subscribedDevices;
} }
public int getInstalledDevicesCount() {
return installedDevicesCount;
}
public void setInstalledDevicesCount(int installedDevicesCount) {
this.installedDevicesCount = installedDevicesCount;
}
public int getPendingDevicesCount() {
return pendingDevicesCount;
}
public void setPendingDevicesCount(int pendingDevicesCount) {
this.pendingDevicesCount = pendingDevicesCount;
}
public int getErrorDevicesCount() {
return errorDevicesCount;
}
public void setErrorDevicesCount(int errorDevicesCount) {
this.errorDevicesCount = errorDevicesCount;
}
public int getNewDevicesCount() {
return newDevicesCount;
}
public void setNewDevicesCount(int newDevicesCount) {
this.newDevicesCount = newDevicesCount;
}
public int getSubscribedDevicesCount() {
return subscribedDevicesCount;
}
public void setSubscribedDevicesCount(int subscribedDevicesCount) {
this.subscribedDevicesCount = subscribedDevicesCount;
}
} }

@ -1,115 +0,0 @@
/*
* 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;
}
}

@ -40,8 +40,6 @@ public class DeviceSubscriptionData {
private String unsubscribedBy; private String unsubscribedBy;
private Timestamp unsubscribedTimestamp; private Timestamp unsubscribedTimestamp;
private String deviceName; private String deviceName;
private String deviceIdentifier;
private String type;
public String getAction() { public String getAction() {
return action; return action;
@ -170,20 +168,4 @@ public class DeviceSubscriptionData {
public void setDeviceName(String deviceName) { public void setDeviceName(String deviceName) {
this.deviceName = deviceName; this.deviceName = deviceName;
} }
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDeviceIdentifier() {
return deviceIdentifier;
}
public void setDeviceIdentifier(String deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
}
} }

@ -1,68 +0,0 @@
/*
* 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;
}
}

@ -1,70 +0,0 @@
/*
* 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;
}
}

@ -1,88 +0,0 @@
/*
* 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;
}
}

@ -1,77 +0,0 @@
/*
* 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;
}
}

@ -1,69 +0,0 @@
/*
* 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 String SUBSCRIPTION_STATUS_UNSUBSCRIBED = "unsubscribed";
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 REPEATED = "REPEATED";
}
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.REPEATED);
}
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, Collections.singletonList(DeviceSubscriptionStatus.IN_PROGRESS));
statusMap.put(DeviceSubscriptionStatus.REPEATED, Collections.singletonList(DeviceSubscriptionStatus.REPEATED));
statusMap.put(DeviceSubscriptionStatus.ERROR, DBSubscriptionStatus.ERROR_STATUS_LIST);
statusMap.put(DeviceSubscriptionStatus.INVALID,Collections.singletonList(DeviceSubscriptionStatus.INVALID));
statusMap.put(DeviceSubscriptionStatus.UNAUTHORIZED,Collections.singletonList(DeviceSubscriptionStatus.UNAUTHORIZED));
deviceSubscriptionStatusToDBSubscriptionStatusMap = Collections.unmodifiableMap(statusMap);
}
}

@ -1,63 +0,0 @@
/*
* 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;
}
}

@ -1,68 +0,0 @@
/*
* 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,7 +19,6 @@
package io.entgra.device.mgt.core.application.mgt.common.dto; package io.entgra.device.mgt.core.application.mgt.common.dto;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.Objects;
public class DeviceSubscriptionDTO { public class DeviceSubscriptionDTO {
@ -35,19 +34,6 @@ public class DeviceSubscriptionDTO {
private int appReleaseId; private int appReleaseId;
private String appUuid; 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() { public int getId() {
return id; return id;
} }
@ -135,17 +121,4 @@ public class DeviceSubscriptionDTO {
public void setAppUuid(String appUuid) { public void setAppUuid(String appUuid) {
this.appUuid = 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);
}
} }

@ -1,21 +1,3 @@
/*
* 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; package io.entgra.device.mgt.core.application.mgt.common.dto;
import io.entgra.device.mgt.core.application.mgt.common.CategorizedSubscriptionResult; import io.entgra.device.mgt.core.application.mgt.common.CategorizedSubscriptionResult;

@ -1,21 +1,3 @@
/*
* 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; package io.entgra.device.mgt.core.application.mgt.common.dto;
import java.util.List; import java.util.List;

@ -1,62 +0,0 @@
/*
* 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;
}
}

@ -546,20 +546,5 @@ public interface ApplicationManager {
* @throws ApplicationManagementException thrown if an error occurs when deleting data * @throws ApplicationManagementException thrown if an error occurs when deleting data
*/ */
void deleteApplicationDataOfTenant(int tenantId) throws ApplicationManagementException; void deleteApplicationDataOfTenant(int tenantId) throws ApplicationManagementException;
/**
* Delete all application related data of a tenant by tenant Domain
*
* @param tenantDomain Domain of the Tenant
* @throws ApplicationManagementException thrown if an error occurs when deleting data
*/
void deleteApplicationDataByTenantDomain(String tenantDomain) throws ApplicationManagementException; void deleteApplicationDataByTenantDomain(String tenantDomain) throws ApplicationManagementException;
/**
* Delete all Application artifacts related to a tenant by Tenant Domain
*
* @param tenantDomain Domain of the Tenant
* @throws ApplicationManagementException thrown if an error occurs when deleting app folders
*/
void deleteApplicationArtifactsByTenantDomain(String tenantDomain) throws ApplicationManagementException;
} }

@ -140,14 +140,4 @@ public interface ApplicationStorageManager {
* @throws ApplicationStorageManagementException thrown if * @throws ApplicationStorageManagementException thrown if
*/ */
void deleteAppFolderOfTenant(int tenantId) throws ApplicationStorageManagementException; void deleteAppFolderOfTenant(int tenantId) throws ApplicationStorageManagementException;
/**
* Get absolute path of a file describe by hashVal, folder, file name and tenantId
* @param hashVal Hash value of the application release.
* @param folderName Folder name file resides.
* @param fileName File name of the file.
* @param tenantId Tenant ID
* @return Absolute path
*/
String getAbsolutePathOfFile(String hashVal, String folderName, String fileName, int tenantId);
} }

@ -19,16 +19,9 @@ 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.ApplicationInstallResponse;
import io.entgra.device.mgt.core.application.mgt.common.CategorizedSubscriptionResult; 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.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.SubscriptionType;
import io.entgra.device.mgt.core.application.mgt.common.dto.CategorizedSubscriptionCountsDTO; 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.ScheduledSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionsDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionsDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceOperationDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceOperationDTO;
@ -231,44 +224,81 @@ public interface SubscriptionManager {
Activity getOperationAppDetails(String id) throws SubscriptionManagementException; Activity getOperationAppDetails(String id) throws SubscriptionManagementException;
/** /**
* Get subscription data describes by {@link SubscriptionInfo} entity * Retrieves the group details associated with a given app release UUID.
* @param subscriptionInfo {@link SubscriptionInfo} *
* @param limit Limit value * @param uuid the UUID of the app release
* @param offset Offset value * @param subscriptionStatus the status of the subscription (subscribed or unsubscribed)
* @return {@link SubscriptionResponse} * @param offset the offset for the data set
* @throws ApplicationManagementException Throws when error encountered while getting subscription data * @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
*/ */
SubscriptionResponse getSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset) List<SubscriptionsDTO> getGroupsSubscriptionDetailsByUUID(String uuid, String subscriptionStatus, int offset, int limit)
throws ApplicationManagementException; throws ApplicationManagementException;
/** /**
* Get status based subscription data describes by {@link SubscriptionInfo} entity * Retrieves the user details associated with a given app release UUID.
* @param subscriptionInfo {@link SubscriptionInfo} *
* @param limit Limit value * @param uuid the UUID of the app release
* @param offset Offset value * @param subscriptionStatus the status of the subscription (subscribed or unsubscribed)
* @return {@link SubscriptionResponse} * @param offset the offset for the data set
* @throws ApplicationManagementException Throws when error encountered while getting subscription data * @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, 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
*/ */
SubscriptionResponse getStatusBaseSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset) List<SubscriptionsDTO> getRoleSubscriptionsByUUID(String uuid, String subscriptionStatus, int offset, int limit)
throws ApplicationManagementException; throws ApplicationManagementException;
/** /**
* Get subscription statistics related data describes by the {@link SubscriptionInfo} * Retrieves the Device Subscription details associated with a given app release UUID.
* @param subscriptionInfo {@link SubscriptionInfo} *
* @return {@link SubscriptionStatistics} * @param uuid the UUID of the app release
* @throws ApplicationManagementException Throws when error encountered while getting statistics * @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
*/ */
SubscriptionStatistics getStatistics(SubscriptionInfo subscriptionInfo) throws ApplicationManagementException; DeviceSubscriptionResponseDTO getDeviceSubscriptionsDetailsByUUID(String uuid, String subscriptionStatus, int offset, int limit)
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
*/
DeviceSubscriptionResponseDTO getAllSubscriptionDetailsByUUID(String uuid, String subscriptionStatus, int offset, int limit)
throws ApplicationManagementException;
/** /**
* This method is responsible for retrieving device subscription details related to the given UUID. * This method is responsible for retrieving device subscription details related to the given UUID.
* *
* @param deviceId the deviceId of the device that need to get operation details. * @param deviceId the deviceId of the device that need to get operation details.
* @param uuid the UUID of the application release. * @param uuid the UUID of the application release.
* @param offset the offset for the data set
* @param limit the limit for the data set
* @return {@link DeviceOperationDTO} which contains the details of device subscriptions. * @return {@link DeviceOperationDTO} which contains the details of device subscriptions.
* @throws SubscriptionManagementException if there is an error while fetching the details. * @throws SubscriptionManagementException if there is an error while fetching the details.
*/ */
List<DeviceOperationDTO> getSubscriptionOperationsByUUIDAndDeviceID(int deviceId, String uuid) List<DeviceOperationDTO> getSubscriptionOperationsByUUIDAndDeviceID(int deviceId, String uuid, int offset, int limit)
throws ApplicationManagementException; throws ApplicationManagementException;
/** /**

@ -21,7 +21,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -81,7 +81,6 @@
com.dd.*, com.dd.*,
io.entgra.device.mgt.core.identity.jwt.client.extension.*, io.entgra.device.mgt.core.identity.jwt.client.extension.*,
io.entgra.device.mgt.core.apimgt.application.extension.*, io.entgra.device.mgt.core.apimgt.application.extension.*,
io.entgra.device.mgt.core.tenant.mgt.common.*,
org.apache.commons.httpclient, org.apache.commons.httpclient,
org.apache.commons.httpclient.methods, org.apache.commons.httpclient.methods,
org.apache.commons.validator.routines org.apache.commons.validator.routines
@ -390,10 +389,6 @@
<artifactId>org.wso2.carbon.tenant.mgt</artifactId> <artifactId>org.wso2.carbon.tenant.mgt</artifactId>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.tenant.mgt.common</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

@ -19,8 +19,6 @@ 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.ExecutionStatus;
import io.entgra.device.mgt.core.application.mgt.common.dto.GroupSubscriptionDTO; 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.SubscriptionsDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO;
@ -329,7 +327,7 @@ public interface SubscriptionDAO {
* @return {@link GroupSubscriptionDTO} which contains the details of group subscriptions. * @return {@link GroupSubscriptionDTO} which contains the details of group subscriptions.
* @throws ApplicationManagementDAOException if connection establishment fails. * @throws ApplicationManagementDAOException if connection establishment fails.
*/ */
List<SubscriptionEntity> getGroupsSubscriptionDetailsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit) List<GroupSubscriptionDTO> getGroupsSubscriptionDetailsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException; throws ApplicationManagementDAOException;
/** /**
@ -343,7 +341,7 @@ public interface SubscriptionDAO {
* @return {@link SubscriptionsDTO} which contains the details of subscriptions. * @return {@link SubscriptionsDTO} which contains the details of subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails. * @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/ */
List<SubscriptionEntity> getUserSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, List<SubscriptionsDTO> getUserSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId,
int offset, int limit) throws ApplicationManagementDAOException; int offset, int limit) throws ApplicationManagementDAOException;
/** /**
@ -357,7 +355,7 @@ public interface SubscriptionDAO {
* @return {@link SubscriptionsDTO} which contains the details of subscriptions. * @return {@link SubscriptionsDTO} which contains the details of subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails. * @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/ */
List<SubscriptionEntity> getRoleSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit) List<SubscriptionsDTO> getRoleSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException; throws ApplicationManagementDAOException;
/** /**
@ -380,10 +378,12 @@ public interface SubscriptionDAO {
* @param appReleaseId the appReleaseId of the application release. * @param appReleaseId the appReleaseId of the application release.
* @param deviceId the deviceId of the device that need to get operation details. * @param deviceId the deviceId of the device that need to get operation details.
* @param tenantId id of the current tenant. * @param tenantId id of the current tenant.
* @param offset the offset for the data set
* @param limit the limit for the data set
* @return {@link DeviceOperationDTO} which contains the details of device subscriptions. * @return {@link DeviceOperationDTO} which contains the details of device subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails. * @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/ */
List<DeviceOperationDTO> getSubscriptionOperationsByAppReleaseIDAndDeviceID(int appReleaseId, int deviceId, int tenantId) List<DeviceOperationDTO> getSubscriptionOperationsByAppReleaseIDAndDeviceID(int appReleaseId, int deviceId, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException; throws ApplicationManagementDAOException;
/** /**
@ -392,19 +392,12 @@ public interface SubscriptionDAO {
* @param appReleaseId the appReleaseId of the application release. * @param appReleaseId the appReleaseId of the application release.
* @param unsubscribe the Status of the subscription. * @param unsubscribe the Status of the subscription.
* @param tenantId id of the current tenant. * @param tenantId id of the current tenant.
* @param actionStatus Status of the action
* @param actionType type of the action
* @param actionTriggeredBy subscribed by
* @param deviceIds deviceIds deviceIds to retrieve data. * @param deviceIds deviceIds deviceIds to retrieve data.
* @return {@link DeviceOperationDTO} which contains the details of device subscriptions. * @return {@link DeviceOperationDTO} which contains the details of device subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails. * @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/ */
List<DeviceSubscriptionDTO> getSubscriptionDetailsByDeviceIds(int appReleaseId, boolean unsubscribe, int tenantId, List<DeviceSubscriptionDTO> getSubscriptionDetailsByDeviceIds(int appReleaseId, boolean unsubscribe, int tenantId, List<Integer> deviceIds)
List<Integer> deviceIds, List<String> actionStatus, String actionType, throws ApplicationManagementDAOException;
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. * This method is used to get the details of device subscriptions related to a UUID.
@ -412,19 +405,12 @@ public interface SubscriptionDAO {
* @param appReleaseId the appReleaseId of the application release. * @param appReleaseId the appReleaseId of the application release.
* @param unsubscribe the Status of the subscription. * @param unsubscribe the Status of the subscription.
* @param tenantId id of the current tenant. * @param tenantId id of the current tenant.
* @param actionStatus Status of the action
* @param actionType type of the action
* @param actionTriggeredBy subscribed by
* @param offset the offset for the data set * @param offset the offset for the data set
* @param limit the limit for the data set * @param limit the limit for the data set
* @return {@link DeviceOperationDTO} which contains the details of device subscriptions. * @return {@link DeviceOperationDTO} which contains the details of device subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails. * @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/ */
List<DeviceSubscriptionDTO> getAllSubscriptionsDetails(int appReleaseId, boolean unsubscribe, int tenantId, List<String> actionStatus, String actionType, List<DeviceSubscriptionDTO> getAllSubscriptionsDetails(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
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; throws ApplicationManagementDAOException;
/** /**
@ -526,18 +512,4 @@ public interface SubscriptionDAO {
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails. * @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/ */
int getUserUnsubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException; int getUserUnsubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
SubscriptionStatisticDTO getSubscriptionStatistic(List<Integer> deviceIds, boolean isUnsubscribed,
int tenantId, int appReleaseId) throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of devices related to a UUID.
*
* @param appReleaseId the UUID of the application release.
* @param tenantId id of the current tenant.
* @param actionStatus categorized status.
* @param actionTriggeredFrom type of the action.
* @return {@link int} which contains the count of the subscription type
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
int countSubscriptionsByStatus(int appReleaseId, int tenantId, String actionStatus, String actionTriggeredFrom) throws ApplicationManagementDAOException;
} }

@ -313,7 +313,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
sql += " AND AP_APP_RELEASE.CURRENT_STATE = ?"; sql += " AND AP_APP_RELEASE.CURRENT_STATE = ?";
} }
if (deviceTypeId != -1) { if (deviceTypeId != -1) {
sql += " AND (AP_APP.DEVICE_TYPE_ID = ? "; sql += "AND (AP_APP.DEVICE_TYPE_ID = ? ";
if (filter.isWithWebApps()) { if (filter.isWithWebApps()) {
sql += "OR AP_APP.DEVICE_TYPE_ID = 0 "; sql += "OR AP_APP.DEVICE_TYPE_ID = 0 ";
} }

@ -17,19 +17,14 @@
*/ */
package io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription; 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.dto.DeviceOperationDTO;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionEntity; import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionsDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionStatisticDTO;
import io.entgra.device.mgt.core.application.mgt.core.dao.SubscriptionDAO; import io.entgra.device.mgt.core.application.mgt.core.dao.SubscriptionDAO;
import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl; import io.entgra.device.mgt.core.application.mgt.core.dao.impl.AbstractDAOImpl;
import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.device.mgt.core.application.mgt.core.exception.UnexpectedServerErrorException;
import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil; import io.entgra.device.mgt.core.application.mgt.core.util.DAOUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity; import io.entgra.device.mgt.core.device.mgt.common.operation.mgt.Activity;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus; import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus;
@ -48,11 +43,9 @@ import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner; import java.util.StringJoiner;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -1456,13 +1449,13 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
+ "AR.PACKAGE_NAME, " + "AR.PACKAGE_NAME, "
+ "AR.VERSION, " + "AR.VERSION, "
+ "DS.SUBSCRIBED_BY, " + "DS.SUBSCRIBED_BY, "
+ "DS.STATUS, "
+ "DS.ACTION_TRIGGERED_FROM " + "DS.ACTION_TRIGGERED_FROM "
+ "FROM AP_APP_SUB_OP_MAPPING SOP " + "FROM AP_APP_SUB_OP_MAPPING SOP "
+ "JOIN AP_DEVICE_SUBSCRIPTION DS ON SOP.AP_DEVICE_SUBSCRIPTION_ID = DS.ID " + "JOIN AP_DEVICE_SUBSCRIPTION DS ON SOP.AP_DEVICE_SUBSCRIPTION_ID = DS.ID "
+ "JOIN AP_APP_RELEASE AR ON DS.AP_APP_RELEASE_ID = AR.ID " + "JOIN AP_APP_RELEASE AR ON DS.AP_APP_RELEASE_ID = AR.ID "
+ "JOIN AP_APP AP ON AP.ID = AR.AP_APP_ID " + "JOIN AP_APP AP ON AP.ID = AR.AP_APP_ID "
+ "WHERE SOP.OPERATION_ID = ? AND SOP.TENANT_ID = ? " + " WHERE SOP.OPERATION_ID = ? AND SOP.TENANT_ID = ?";
+ "LIMIT 1";
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
@ -1648,60 +1641,45 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
} }
@Override @Override
public List<SubscriptionEntity> getGroupsSubscriptionDetailsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit) public List<GroupSubscriptionDTO> getGroupsSubscriptionDetailsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get groups related to the given AppReleaseID."); log.debug("Request received in DAO Layer to get groups related to the given AppReleaseID.");
} }
try { try {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
List<SubscriptionEntity> subscriptionEntities = new ArrayList<>(); List<GroupSubscriptionDTO> groupDetails = new ArrayList<>();
String subscriptionStatusTime = unsubscribe ? "GS.UNSUBSCRIBED_TIMESTAMP" : "GS.SUBSCRIBED_TIMESTAMP"; String subscriptionStatusTime = unsubscribe ? "GS.UNSUBSCRIBED_TIMESTAMP" : "GS.SUBSCRIBED_TIMESTAMP";
String sql = "SELECT GS.GROUP_NAME, " + String sql = "SELECT GS.GROUP_NAME, GS.SUBSCRIBED_BY, GS.SUBSCRIBED_TIMESTAMP, GS.UNSUBSCRIBED, " +
"GS.SUBSCRIBED_BY, " + "GS.UNSUBSCRIBED_BY, GS.UNSUBSCRIBED_TIMESTAMP, GS.AP_APP_RELEASE_ID " +
"GS.SUBSCRIBED_TIMESTAMP, " +
"GS.UNSUBSCRIBED, " +
"GS.UNSUBSCRIBED_BY, " +
"GS.UNSUBSCRIBED_TIMESTAMP, " +
"GS.AP_APP_RELEASE_ID " +
"FROM AP_GROUP_SUBSCRIPTION GS " + "FROM AP_GROUP_SUBSCRIPTION GS " +
"WHERE GS.AP_APP_RELEASE_ID = ? " + "WHERE GS.AP_APP_RELEASE_ID = ? AND GS.UNSUBSCRIBED = ? AND GS.TENANT_ID = ? " +
"AND GS.UNSUBSCRIBED = ? " + "ORDER BY " + subscriptionStatusTime + " DESC " +
"AND GS.TENANT_ID = ? " + "LIMIT ? OFFSET ?";
"ORDER BY " + subscriptionStatusTime + " DESC ";
// Append limit and offset only if limit is not -1
if (limit != -1) {
sql = sql + " LIMIT ? OFFSET ?";
}
try (PreparedStatement ps = conn.prepareStatement(sql)) { try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId); ps.setInt(1, appReleaseId);
ps.setBoolean(2, unsubscribe); ps.setBoolean(2, unsubscribe);
ps.setInt(3, tenantId); ps.setInt(3, tenantId);
ps.setInt(4, limit);
// Set limit and offset parameters only if limit is not -1 ps.setInt(5, offset);
if (limit != -1) {
ps.setInt(4, limit);
ps.setInt(5, offset);
}
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
SubscriptionEntity subscriptionEntity; GroupSubscriptionDTO groupDetail;
while (rs.next()) { while (rs.next()) {
subscriptionEntity = new SubscriptionEntity(); groupDetail = new GroupSubscriptionDTO();
subscriptionEntity.setIdentity(rs.getString("GROUP_NAME")); groupDetail.setGroupName(rs.getString("GROUP_NAME"));
subscriptionEntity.setSubscribedBy(rs.getString("SUBSCRIBED_BY")); groupDetail.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscriptionEntity.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP")); groupDetail.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED")); groupDetail.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
subscriptionEntity.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY")); groupDetail.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscriptionEntity.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP")); groupDetail.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setApplicationReleaseId(rs.getInt("AP_APP_RELEASE_ID")); groupDetail.setAppReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
subscriptionEntities.add(subscriptionEntity); groupDetails.add(groupDetail);
} }
} }
return subscriptionEntities; return groupDetails;
} }
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get groups for the given UUID."; String msg = "Error occurred while obtaining the DB connection to get groups for the given UUID.";
@ -1715,27 +1693,20 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
} }
@Override @Override
public List<SubscriptionEntity> getUserSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, public List<SubscriptionsDTO> getUserSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId,
int offset, int limit) throws ApplicationManagementDAOException { int offset, int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get user subscriptions related to the given UUID."); log.debug("Request received in DAO Layer to get user subscriptions related to the given UUID.");
} }
try { try {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
List<SubscriptionEntity> subscriptionEntities = new ArrayList<>(); List<SubscriptionsDTO> userSubscriptions = new ArrayList<>();
String subscriptionStatusTime = unsubscribe ? "US.UNSUBSCRIBED_TIMESTAMP" : "US.SUBSCRIBED_TIMESTAMP"; String subscriptionStatusTime = unsubscribe ? "US.UNSUBSCRIBED_TIMESTAMP" : "US.SUBSCRIBED_TIMESTAMP";
String sql = "SELECT US.USER_NAME, " + String sql = "SELECT US.USER_NAME, US.SUBSCRIBED_BY, US.SUBSCRIBED_TIMESTAMP, US.UNSUBSCRIBED, " +
"US.SUBSCRIBED_BY, " + "US.UNSUBSCRIBED_BY, US.UNSUBSCRIBED_TIMESTAMP, US.AP_APP_RELEASE_ID " +
"US.SUBSCRIBED_TIMESTAMP, " +
"US.UNSUBSCRIBED, " +
"US.UNSUBSCRIBED_BY, " +
"US.UNSUBSCRIBED_TIMESTAMP, " +
"US.AP_APP_RELEASE_ID " +
"FROM AP_USER_SUBSCRIPTION US " + "FROM AP_USER_SUBSCRIPTION US " +
"WHERE US.AP_APP_RELEASE_ID = ? " + "WHERE US.AP_APP_RELEASE_ID = ? AND US.UNSUBSCRIBED = ? AND US.TENANT_ID = ? " +
"AND US.UNSUBSCRIBED = ? " +
"AND US.TENANT_ID = ? " +
"ORDER BY " + subscriptionStatusTime + " DESC " + "ORDER BY " + subscriptionStatusTime + " DESC " +
"LIMIT ? OFFSET ?"; "LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) { try (PreparedStatement ps = conn.prepareStatement(sql)) {
@ -1745,21 +1716,21 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
ps.setInt(4, limit); ps.setInt(4, limit);
ps.setInt(5, offset); ps.setInt(5, offset);
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
SubscriptionEntity subscriptionEntity;
while (rs.next()) { while (rs.next()) {
subscriptionEntity = new SubscriptionEntity(); SubscriptionsDTO userSubscription;
subscriptionEntity.setIdentity(rs.getString("USER_NAME")); userSubscription = new SubscriptionsDTO();
subscriptionEntity.setSubscribedBy(rs.getString("SUBSCRIBED_BY")); userSubscription.setName(rs.getString("USER_NAME"));
subscriptionEntity.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP")); userSubscription.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscriptionEntity.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED")); userSubscription.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY")); userSubscription.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
subscriptionEntity.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP")); userSubscription.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscriptionEntity.setApplicationReleaseId(rs.getInt("AP_APP_RELEASE_ID")); userSubscription.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
userSubscription.setAppReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
subscriptionEntities.add(subscriptionEntity);
userSubscriptions.add(userSubscription);
} }
} }
return subscriptionEntities; return userSubscriptions;
} }
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get user subscriptions for the given UUID."; String msg = "Error occurred while obtaining the DB connection to get user subscriptions for the given UUID.";
@ -1773,27 +1744,20 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
} }
@Override @Override
public List<SubscriptionEntity> getRoleSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, public List<SubscriptionsDTO> getRoleSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset,
int limit) throws ApplicationManagementDAOException { int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get role subscriptions related to the given AppReleaseID."); log.debug("Request received in DAO Layer to get role subscriptions related to the given AppReleaseID.");
} }
try { try {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
List<SubscriptionEntity> subscriptionEntities = new ArrayList<>(); List<SubscriptionsDTO> roleSubscriptions = new ArrayList<>();
String subscriptionStatusTime = unsubscribe ? "ARS.UNSUBSCRIBED_TIMESTAMP" : "ARS.SUBSCRIBED_TIMESTAMP"; String subscriptionStatusTime = unsubscribe ? "ARS.UNSUBSCRIBED_TIMESTAMP" : "ARS.SUBSCRIBED_TIMESTAMP";
String sql = "SELECT ARS.ROLE_NAME, " + String sql = "SELECT ARS.ROLE_NAME, ARS.SUBSCRIBED_BY, ARS.SUBSCRIBED_TIMESTAMP, ARS.UNSUBSCRIBED, " +
"ARS.SUBSCRIBED_BY, " + "ARS.UNSUBSCRIBED_BY, ARS.UNSUBSCRIBED_TIMESTAMP, ARS.AP_APP_RELEASE_ID " +
"ARS.SUBSCRIBED_TIMESTAMP, " +
"ARS.UNSUBSCRIBED, " +
"ARS.UNSUBSCRIBED_BY, " +
"ARS.UNSUBSCRIBED_TIMESTAMP, " +
"ARS.AP_APP_RELEASE_ID " +
"FROM AP_ROLE_SUBSCRIPTION ARS " + "FROM AP_ROLE_SUBSCRIPTION ARS " +
"WHERE ARS.AP_APP_RELEASE_ID = ? " + "WHERE ARS.AP_APP_RELEASE_ID = ? AND ARS.UNSUBSCRIBED = ? AND ARS.TENANT_ID = ? " +
"AND ARS.UNSUBSCRIBED = ? " +
"AND ARS.TENANT_ID = ? " +
"ORDER BY " + subscriptionStatusTime + " DESC " + "ORDER BY " + subscriptionStatusTime + " DESC " +
"LIMIT ? OFFSET ?"; "LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) { try (PreparedStatement ps = conn.prepareStatement(sql)) {
@ -1803,21 +1767,21 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
ps.setInt(4, limit); ps.setInt(4, limit);
ps.setInt(5, offset); ps.setInt(5, offset);
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
SubscriptionEntity subscriptionEntity; SubscriptionsDTO roleSubscription;
while (rs.next()) { while (rs.next()) {
subscriptionEntity = new SubscriptionEntity(); roleSubscription = new SubscriptionsDTO();
subscriptionEntity.setIdentity(rs.getString("ROLE_NAME")); roleSubscription.setName(rs.getString("ROLE_NAME"));
subscriptionEntity.setSubscribedBy(rs.getString("SUBSCRIBED_BY")); roleSubscription.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscriptionEntity.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP")); roleSubscription.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED")); roleSubscription.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
subscriptionEntity.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY")); roleSubscription.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscriptionEntity.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP")); roleSubscription.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
subscriptionEntity.setApplicationReleaseId(rs.getInt("AP_APP_RELEASE_ID")); roleSubscription.setAppReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
subscriptionEntities.add(subscriptionEntity); roleSubscriptions.add(roleSubscription);
} }
} }
return subscriptionEntities; return roleSubscriptions;
} }
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get role subscriptions for the given UUID."; String msg = "Error occurred while obtaining the DB connection to get role subscriptions for the given UUID.";
@ -1893,7 +1857,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
@Override @Override
public List<DeviceOperationDTO> getSubscriptionOperationsByAppReleaseIDAndDeviceID( public List<DeviceOperationDTO> getSubscriptionOperationsByAppReleaseIDAndDeviceID(
int appReleaseId, int deviceId, int tenantId) throws ApplicationManagementDAOException { int appReleaseId, int deviceId, int tenantId, int offset, int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get device subscriptions related to the given AppReleaseID and DeviceID."); log.debug("Request received in DAO Layer to get device subscriptions related to the given AppReleaseID and DeviceID.");
} }
@ -1913,12 +1877,13 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
"WHERE ads.AP_APP_RELEASE_ID = ? " + "WHERE ads.AP_APP_RELEASE_ID = ? " +
"AND ads.DM_DEVICE_ID = ? " + "AND ads.DM_DEVICE_ID = ? " +
"AND ads.TENANT_ID = ? " + "AND ads.TENANT_ID = ? " +
"ORDER BY aasom.OPERATION_ID DESC " + "LIMIT ? OFFSET ?";
"LIMIT 1";
try (PreparedStatement ps = conn.prepareStatement(sql)) { try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId); ps.setInt(1, appReleaseId);
ps.setInt(2, deviceId); ps.setInt(2, deviceId);
ps.setInt(3, tenantId); ps.setInt(3, tenantId);
ps.setInt(4, limit);
ps.setInt(5, offset);
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
DeviceOperationDTO deviceSubscription; DeviceOperationDTO deviceSubscription;
while (rs.next()) { while (rs.next()) {
@ -1946,24 +1911,17 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
} }
} }
// passed the required list for the action status
@Override @Override
public List<DeviceSubscriptionDTO> getSubscriptionDetailsByDeviceIds(int appReleaseId, boolean unsubscribe, int tenantId, public List<DeviceSubscriptionDTO> getSubscriptionDetailsByDeviceIds(int appReleaseId, boolean unsubscribe, int tenantId, List<Integer> deviceIds)
List<Integer> deviceIds, List<String> actionStatus, String actionType, throws ApplicationManagementDAOException {
String actionTriggeredBy, int limit, int offset) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting device subscriptions for the application release id " + appReleaseId log.debug("Getting device subscriptions for the application release id " + appReleaseId
+ " and device ids " + deviceIds + " from the database"); + " and device ids " + deviceIds + " from the database");
} }
if (deviceIds == null || deviceIds.isEmpty()) {
return Collections.emptyList();
}
try { try {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
String subscriptionStatusTime = unsubscribe ? "DS.UNSUBSCRIBED_TIMESTAMP" : "DS.SUBSCRIBED_TIMESTAMP"; String subscriptionStatusTime = unsubscribe ? "DS.UNSUBSCRIBED_TIMESTAMP" : "DS.SUBSCRIBED_TIMESTAMP";
StringBuilder sql = new StringBuilder("SELECT " String sql = "SELECT "
+ "DS.ID AS ID, " + "DS.ID AS ID, "
+ "DS.SUBSCRIBED_BY AS SUBSCRIBED_BY, " + "DS.SUBSCRIBED_BY AS SUBSCRIBED_BY, "
+ "DS.SUBSCRIBED_TIMESTAMP AS SUBSCRIBED_AT, " + "DS.SUBSCRIBED_TIMESTAMP AS SUBSCRIBED_AT, "
@ -1974,58 +1932,17 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
+ "DS.STATUS AS STATUS, " + "DS.STATUS AS STATUS, "
+ "DS.DM_DEVICE_ID AS DEVICE_ID " + "DS.DM_DEVICE_ID AS DEVICE_ID "
+ "FROM AP_DEVICE_SUBSCRIPTION DS " + "FROM AP_DEVICE_SUBSCRIPTION DS "
+ "WHERE DS.AP_APP_RELEASE_ID = ? " + "WHERE DS.AP_APP_RELEASE_ID = ? AND DS.UNSUBSCRIBED = ? AND DS.TENANT_ID = ? AND DS.DM_DEVICE_ID IN (" +
+ "AND DS.UNSUBSCRIBED = ? " deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ") "
+ "AND DS.TENANT_ID = ? " + "ORDER BY " + subscriptionStatusTime + " DESC";
+ "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("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 (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()) { try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(paramIdx++, "%" + actionTriggeredBy + "%"); ps.setInt(1, appReleaseId);
} ps.setBoolean(2, unsubscribe);
ps.setInt(3, tenantId);
if (offset >= 0 && limit >= 0) { for (int i = 0; i < deviceIds.size(); i++) {
ps.setInt(paramIdx++, limit); ps.setInt(4 + i, deviceIds.get(i));
ps.setInt(paramIdx, offset);
} }
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Successfully retrieved device subscriptions for application release id " log.debug("Successfully retrieved device subscriptions for application release id "
@ -2062,178 +1979,8 @@ 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 @Override
public List<DeviceSubscriptionDTO> getAllSubscriptionsDetails(int appReleaseId, boolean unsubscribe, int tenantId, public List<DeviceSubscriptionDTO> getAllSubscriptionsDetails(int appReleaseId, boolean unsubscribe, int tenantId,
List<String> actionStatus, String actionType, String actionTriggeredBy,
int offset, int limit) throws ApplicationManagementDAOException { int offset, int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting device subscriptions for the application release id " + appReleaseId log.debug("Getting device subscriptions for the application release id " + appReleaseId
@ -2241,8 +1988,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
} }
String subscriptionStatusTime = unsubscribe ? "DS.UNSUBSCRIBED_TIMESTAMP" : "DS.SUBSCRIBED_TIMESTAMP"; String subscriptionStatusTime = unsubscribe ? "DS.UNSUBSCRIBED_TIMESTAMP" : "DS.SUBSCRIBED_TIMESTAMP";
String actionTriggeredColumn = unsubscribe ? "DS.UNSUBSCRIBED_BY" : "DS.SUBSCRIBED_BY"; String sql = "SELECT "
StringBuilder sql = new StringBuilder("SELECT "
+ "DS.ID AS ID, " + "DS.ID AS ID, "
+ "DS.SUBSCRIBED_BY AS SUBSCRIBED_BY, " + "DS.SUBSCRIBED_BY AS SUBSCRIBED_BY, "
+ "DS.SUBSCRIBED_TIMESTAMP AS SUBSCRIBED_AT, " + "DS.SUBSCRIBED_TIMESTAMP AS SUBSCRIBED_AT, "
@ -2250,58 +1996,21 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
+ "DS.UNSUBSCRIBED_BY AS UNSUBSCRIBED_BY, " + "DS.UNSUBSCRIBED_BY AS UNSUBSCRIBED_BY, "
+ "DS.UNSUBSCRIBED_TIMESTAMP AS UNSUBSCRIBED_AT, " + "DS.UNSUBSCRIBED_TIMESTAMP AS UNSUBSCRIBED_AT, "
+ "DS.ACTION_TRIGGERED_FROM AS ACTION_TRIGGERED_FROM, " + "DS.ACTION_TRIGGERED_FROM AS ACTION_TRIGGERED_FROM, "
+ "DS.STATUS AS STATUS, " + "DS.STATUS AS STATUS,"
+ "DS.DM_DEVICE_ID AS DEVICE_ID " + "DS.DM_DEVICE_ID AS DEVICE_ID "
+ "FROM AP_DEVICE_SUBSCRIPTION DS " + "FROM AP_DEVICE_SUBSCRIPTION DS "
+ "WHERE DS.AP_APP_RELEASE_ID = ? " + "WHERE DS.AP_APP_RELEASE_ID = ? AND DS.UNSUBSCRIBED = ? AND DS.TENANT_ID=? "
+ "AND DS.UNSUBSCRIBED = ? " + "ORDER BY " + subscriptionStatusTime + " DESC "
+ "AND DS.TENANT_ID = ? "); + "LIMIT ? OFFSET ?";
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("LIMIT ? OFFSET ?");
}
try { try {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
try (PreparedStatement ps = conn.prepareStatement(sql.toString())) { try (PreparedStatement ps = conn.prepareStatement(sql)) {
int paramIdx = 1; ps.setInt(1, appReleaseId);
ps.setInt(paramIdx++, appReleaseId); ps.setBoolean(2, unsubscribe);
ps.setBoolean(paramIdx++, unsubscribe); ps.setInt(3, tenantId);
ps.setInt(paramIdx++, tenantId); ps.setInt(4, limit);
ps.setInt(5, offset);
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++, limit);
ps.setInt(paramIdx, offset);
}
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Successfully retrieved device subscriptions for application release id " log.debug("Successfully retrieved device subscriptions for application release id "
@ -2332,112 +2041,30 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
log.error(msg, e); log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e); throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while running SQL to get device subscription data for application ID: " + appReleaseId; String msg = "Error occurred while while running SQL to get device subscription data for application ID: " + appReleaseId;
log.error(msg, e); log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e); throw new ApplicationManagementDAOException(msg, e);
} }
} }
@Override @Override
public int getAllSubscriptionsCount(int appReleaseId, boolean unsubscribe, int tenantId, public int getAllSubscriptionCount(int appReleaseId, int tenantId)
List<String> actionStatus, String actionType, String actionTriggeredBy)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting device subscriptions for the application release id " + appReleaseId log.debug("Getting all subscriptions count for the application appReleaseId " + appReleaseId
+ " from the database"); + " 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 {
if (log.isDebugEnabled()) {
log.debug("Getting all subscriptions count for the application appReleaseId " + appReleaseId + " from the database");
}
List<String> allowingDeviceStatuses = new ArrayList<>();
allowingDeviceStatuses.add(EnrolmentInfo.Status.ACTIVE.toString());
allowingDeviceStatuses.add(EnrolmentInfo.Status.INACTIVE.toString());
allowingDeviceStatuses.add(EnrolmentInfo.Status.UNREACHABLE.toString());
DeviceManagementProviderService deviceManagementProviderService = HelperUtil.getDeviceManagementProviderService();
try { try {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
List<Integer> deviceIds = deviceManagementProviderService.getDeviceIdsByStatus(allowingDeviceStatuses);
if (deviceIds.isEmpty()) {
return 0;
}
StringBuilder idList = new StringBuilder();
for (int i = 0; i < deviceIds.size(); i++) {
idList.append("?");
if (i < deviceIds.size() - 1) {
idList.append(",");
}
}
String sql = "SELECT COUNT(*) AS count " + String sql = "SELECT COUNT(*) AS count " +
"FROM AP_DEVICE_SUBSCRIPTION " + "FROM AP_DEVICE_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " + "WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " + "AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = FALSE " + "AND UNSUBSCRIBED = FALSE";
"AND DM_DEVICE_ID IN (" + idList.toString() + ")";
try (PreparedStatement ps = conn.prepareStatement(sql)) { try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId); ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId); ps.setInt(2, tenantId);
for (int i = 0; i < deviceIds.size(); i++) {
ps.setInt(3 + i, deviceIds.get(i));
}
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) { if (rs.next()) {
@ -2451,7 +2078,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
log.error(msg, e); log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e); throw new ApplicationManagementDAOException(msg, e);
} }
} catch (DBConnectionException | DeviceManagementException e) { } catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting all subscriptions count for appReleaseId: " String msg = "Error occurred while obtaining the DB connection for getting all subscriptions count for appReleaseId: "
+ appReleaseId + "."; + appReleaseId + ".";
log.error(msg, e); log.error(msg, e);
@ -2460,41 +2087,23 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
} }
@Override @Override
public int getAllUnsubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException { public int getAllUnsubscriptionCount(int appReleaseId, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting all unsubscription count for the application appReleaseId " + appReleaseId + " from the database"); log.debug("Getting all unsubscription count for the application appReleaseId " + appReleaseId
+ " from the database");
} }
List<String> allowingDeviceStatuses = new ArrayList<>();
allowingDeviceStatuses.add(EnrolmentInfo.Status.ACTIVE.toString());
allowingDeviceStatuses.add(EnrolmentInfo.Status.INACTIVE.toString());
allowingDeviceStatuses.add(EnrolmentInfo.Status.UNREACHABLE.toString());
DeviceManagementProviderService deviceManagementProviderService = HelperUtil.getDeviceManagementProviderService();
try { try {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
List<Integer> deviceIds = deviceManagementProviderService.getDeviceIdsByStatus(allowingDeviceStatuses);
if (deviceIds.isEmpty()) {
return 0;
}
StringBuilder idList = new StringBuilder();
for (int i = 0; i < deviceIds.size(); i++) {
idList.append("?");
if (i < deviceIds.size() - 1) {
idList.append(",");
}
}
String sql = "SELECT COUNT(*) AS count " + String sql = "SELECT COUNT(*) AS count " +
"FROM AP_DEVICE_SUBSCRIPTION " + "FROM AP_DEVICE_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " + "WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " + "AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = TRUE " + "AND UNSUBSCRIBED = TRUE";
"AND DM_DEVICE_ID IN (" + idList.toString() + ")";
try (PreparedStatement ps = conn.prepareStatement(sql)) { try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId); ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId); ps.setInt(2, tenantId);
for (int i = 0; i < deviceIds.size(); i++) {
ps.setInt(3 + i, deviceIds.get(i));
}
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) { if (rs.next()) {
@ -2508,7 +2117,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
log.error(msg, e); log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e); throw new ApplicationManagementDAOException(msg, e);
} }
} catch (DBConnectionException | DeviceManagementException e) { } catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting all unsubscription count for appReleaseId: " String msg = "Error occurred while obtaining the DB connection for getting all unsubscription count for appReleaseId: "
+ appReleaseId + "."; + appReleaseId + ".";
log.error(msg, e); log.error(msg, e);
@ -2829,97 +2438,4 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
throw new ApplicationManagementDAOException(msg, e); throw new ApplicationManagementDAOException(msg, e);
} }
} }
@Override
public SubscriptionStatisticDTO getSubscriptionStatistic(List<Integer> deviceIds, boolean isUnsubscribed, int tenantId, int appReleaseId)
throws ApplicationManagementDAOException {
SubscriptionStatisticDTO subscriptionStatisticDTO = new SubscriptionStatisticDTO();
if (deviceIds == null || deviceIds.isEmpty()) return subscriptionStatisticDTO;
try {
Connection connection = getDBConnection();
String sql = "SELECT COUNT(DISTINCT ID) AS COUNT, " +
"STATUS FROM AP_DEVICE_SUBSCRIPTION " +
"WHERE TENANT_ID = ? " +
"AND AP_APP_RELEASE_ID = ? " +
"AND UNSUBSCRIBED = ? " +
"AND DM_DEVICE_ID IN (" +
deviceIds.stream().map(id -> "?").collect(Collectors.joining(",")) + ") " +
"GROUP BY (STATUS)";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int idx = 1;
preparedStatement.setInt(idx++, tenantId);
preparedStatement.setInt(idx++, appReleaseId);
preparedStatement.setBoolean(idx++, isUnsubscribed);
for (Integer deviceId : deviceIds) {
preparedStatement.setInt(idx++, deviceId);
}
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 = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
ps.setString(3, actionStatus);
ps.setString(4, actionTriggeredFrom);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt(1);
}
}
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to count device subscriptions by status and action trigger.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "SQL Error occurred while counting device subscriptions by status and action trigger.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
return 0;
}
} }

@ -18,8 +18,6 @@
package io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription; 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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException; import io.entgra.device.mgt.core.application.mgt.common.exception.DBConnectionException;
@ -30,9 +28,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
/** /**
* This handles Application subscribing operations which are specific to Oracle. * This handles Application subscribing operations which are specific to Oracle.
@ -161,379 +157,4 @@ public class OracleSubscriptionDAOImpl extends GenericSubscriptionDAOImpl {
throw new ApplicationManagementDAOException(msg, e); 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);
}
}
} }

@ -30,7 +30,6 @@ import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.Metadata;
import io.entgra.device.mgt.core.tenant.mgt.common.exception.TenantMgtException;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringEscapeUtils;
@ -97,19 +96,17 @@ import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementEx
import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType; import io.entgra.device.mgt.core.device.mgt.core.dto.DeviceType;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.stratos.common.beans.TenantInfoBean;
import org.wso2.carbon.tenant.mgt.services.TenantMgtAdminService;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
@ -726,29 +723,24 @@ public class ApplicationManagerImpl implements ApplicationManager {
* @throws ResourceManagementException if error occurred while uploading * @throws ResourceManagementException if error occurred while uploading
*/ */
private ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, private ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact,
String deviceType) String deviceType)
throws ResourceManagementException, ApplicationManagementException { throws ResourceManagementException, ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try { byte[] content = getByteContentOfApp(applicationArtifact);
String md5OfApp = applicationStorageManager. String md5OfApp = generateMD5OfApp(applicationArtifact, content);
getMD5(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath()))); validateReleaseBinaryFileHash(md5OfApp);
validateReleaseBinaryFileHash(md5OfApp); releaseDTO.setUuid(UUID.randomUUID().toString());
releaseDTO.setUuid(UUID.randomUUID().toString()); releaseDTO.setAppHashValue(md5OfApp);
releaseDTO.setAppHashValue(md5OfApp); releaseDTO.setInstallerName(applicationArtifact.getInstallerName());
releaseDTO.setInstallerName(applicationArtifact.getInstallerName());
try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) {
applicationStorageManager.uploadReleaseArtifact(releaseDTO, deviceType, applicationStorageManager.uploadReleaseArtifact(releaseDTO, deviceType,
Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), tenantId); binaryDuplicate, tenantId);
} catch (IOException e) { } catch (IOException e) {
String msg = "Error occurred when uploading release artifact into the server"; String msg = "Error occurred when uploading release artifact into the server";
log.error(msg); log.error(msg);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch (StorageManagementException e) {
String msg = "Error occurred while md5sum value retrieving process: application UUID "
+ releaseDTO.getUuid();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} }
return addImageArtifacts(releaseDTO, applicationArtifact, tenantId); return addImageArtifacts(releaseDTO, applicationArtifact, tenantId);
} }
@ -777,8 +769,6 @@ public class ApplicationManagerImpl implements ApplicationManager {
return Constants.GOOGLE_PLAY_STORE_URL; return Constants.GOOGLE_PLAY_STORE_URL;
} else if (DeviceTypes.IOS.toString().equalsIgnoreCase(deviceType)) { } else if (DeviceTypes.IOS.toString().equalsIgnoreCase(deviceType)) {
return Constants.APPLE_STORE_URL; return Constants.APPLE_STORE_URL;
} else if (DeviceTypes.WINDOWS.toString().equalsIgnoreCase(deviceType)) {
return Constants.MICROSOFT_STORE_URL;
} else { } else {
throw new IllegalArgumentException("No such device with the name " + deviceType); throw new IllegalArgumentException("No such device with the name " + deviceType);
} }
@ -866,77 +856,82 @@ public class ApplicationManagerImpl implements ApplicationManager {
String uuid = UUID.randomUUID().toString(); String uuid = UUID.randomUUID().toString();
applicationReleaseDTO.setUuid(uuid); applicationReleaseDTO.setUuid(uuid);
// The application executable artifacts such as apks are uploaded. // The application executable artifacts such as apks are uploaded.
try { try {
byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
applicationReleaseDTO.setInstallerName(applicationArtifact.getInstallerName()); applicationReleaseDTO.setInstallerName(applicationArtifact.getInstallerName());
if (!DeviceTypes.WINDOWS.toString().equalsIgnoreCase(deviceType)) { try (ByteArrayInputStream binary = new ByteArrayInputStream(content)) {
ApplicationInstaller applicationInstaller = applicationStorageManager if (!DeviceTypes.WINDOWS.toString().equalsIgnoreCase(deviceType)) {
.getAppInstallerData(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), deviceType); ApplicationInstaller applicationInstaller = applicationStorageManager
applicationReleaseDTO.setVersion(applicationInstaller.getVersion()); .getAppInstallerData(binary, deviceType);
applicationReleaseDTO.setPackageName(applicationInstaller.getPackageName()); applicationReleaseDTO.setVersion(applicationInstaller.getVersion());
} else { applicationReleaseDTO.setPackageName(applicationInstaller.getPackageName());
String windowsInstallerName = applicationArtifact.getInstallerName(); } else {
String extension = windowsInstallerName.substring(windowsInstallerName.lastIndexOf(".") + 1); String windowsInstallerName = applicationArtifact.getInstallerName();
if (!extension.equalsIgnoreCase(Constants.MSI) && String extension = windowsInstallerName.substring(windowsInstallerName.lastIndexOf(".") + 1);
!extension.equalsIgnoreCase(Constants.APPX)) { if (!extension.equalsIgnoreCase(Constants.MSI) &&
String msg = "Application Type doesn't match with supporting application types of " + !extension.equalsIgnoreCase(Constants.APPX)) {
deviceType + "platform which are APPX and MSI"; String msg = "Application Type doesn't match with supporting application types of " +
log.error(msg); deviceType + "platform which are APPX and MSI";
throw new BadRequestException(msg); log.error(msg);
throw new BadRequestException(msg);
}
} }
}
String packageName = applicationReleaseDTO.getPackageName(); String packageName = applicationReleaseDTO.getPackageName();
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
if (!isNewRelease && applicationReleaseDAO if (!isNewRelease && applicationReleaseDAO
.isActiveReleaseExisitForPackageName(packageName, tenantId, .isActiveReleaseExisitForPackageName(packageName, tenantId,
lifecycleStateManager.getEndState())) { lifecycleStateManager.getEndState())) {
String msg = "Application release is already exist for the package name: " + packageName String msg = "Application release is already exist for the package name: " + packageName
+ ". Either you can delete all application releases for package " + packageName + " or " + ". Either you can delete all application releases for package " + packageName + " or "
+ "you can add this app release as an new application release, under the existing " + "you can add this app release as an new application release, under the existing "
+ "application."; + "application.";
log.error(msg); log.error(msg);
throw new ApplicationManagementException(msg); throw new ApplicationManagementException(msg);
} }
String md5OfApp = applicationStorageManager. String md5OfApp = applicationStorageManager.getMD5(new ByteArrayInputStream(content));
getMD5(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath()))); if (md5OfApp == null) {
if (md5OfApp == null) { String msg = "Error occurred while md5sum value retrieving process: application UUID "
+ applicationReleaseDTO.getUuid();
log.error(msg);
throw new ApplicationStorageManagementException(msg);
}
if (this.applicationReleaseDAO.verifyReleaseExistenceByHash(md5OfApp, tenantId)) {
String msg =
"Application release exists for the uploaded binary file. Device Type: " + deviceType;
log.error(msg);
throw new BadRequestException(msg);
}
applicationReleaseDTO.setAppHashValue(md5OfApp);
try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) {
applicationStorageManager
.uploadReleaseArtifact(applicationReleaseDTO, deviceType, binaryDuplicate, tenantId);
}
} catch (StorageManagementException e) {
String msg = "Error occurred while md5sum value retrieving process: application UUID " String msg = "Error occurred while md5sum value retrieving process: application UUID "
+ applicationReleaseDTO.getUuid(); + applicationReleaseDTO.getUuid();
log.error(msg); log.error(msg, e);
throw new ApplicationStorageManagementException(msg); throw new ApplicationStorageManagementException(msg, e);
} } catch (DBConnectionException e) {
if (this.applicationReleaseDAO.verifyReleaseExistenceByHash(md5OfApp, tenantId)) { String msg = "Error occurred when getting database connection for verifying app release data.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg = String msg =
"Application release exists for the uploaded binary file. Device Type: " + deviceType; "Error occurred when executing the query for verifying application release existence for "
log.error(msg); + "the package.";
throw new BadRequestException(msg); log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
} }
applicationReleaseDTO.setAppHashValue(md5OfApp);
applicationStorageManager
.uploadReleaseArtifact(applicationReleaseDTO, deviceType,
Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), tenantId);
} catch (StorageManagementException e) {
String msg = "Error occurred while md5sum value retrieving process: application UUID "
+ applicationReleaseDTO.getUuid();
log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "Error occurred when getting database connection for verifying app release data.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg =
"Error occurred when executing the query for verifying application release existence for "
+ "the package.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
} }
} catch (IOException e) { } catch (IOException e) {
String msg = "Error occurred when getting file input stream. Installer name: " + applicationArtifact String msg = "Error occurred when getting byte array of binary file. Installer name: " + applicationArtifact
.getInstallerName(); .getInstallerName();
log.error(msg, e); log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e); throw new ApplicationStorageManagementException(msg, e);
@ -962,64 +957,73 @@ public class ApplicationManagerImpl implements ApplicationManager {
// The application executable artifacts such as apks are uploaded. // The application executable artifacts such as apks are uploaded.
try { try {
String md5OfApp = applicationStorageManager.getMD5(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath()))); byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
if (md5OfApp == null) {
String msg = "Error occurred while retrieving md5sum value from the binary file for application "
+ "release UUID " + applicationReleaseDTO.getUuid();
log.error(msg);
throw new ApplicationStorageManagementException(msg);
}
if (!applicationReleaseDTO.getAppHashValue().equals(md5OfApp)) { try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) {
applicationReleaseDTO.setInstallerName(applicationArtifact.getInstallerName()); String md5OfApp = applicationStorageManager.getMD5(binaryClone);
ApplicationInstaller applicationInstaller = applicationStorageManager
.getAppInstallerData(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), deviceType);
String packageName = applicationInstaller.getPackageName();
try { if (md5OfApp == null) {
ConnectionManagerUtil.getDBConnection(); String msg = "Error occurred while retrieving md5sum value from the binary file for application "
if (this.applicationReleaseDAO.verifyReleaseExistenceByHash(md5OfApp, tenantId)) { + "release UUID " + applicationReleaseDTO.getUuid();
String msg = "Same binary file is in the server. Hence you can't add same file into the " log.error(msg);
+ "server. Device Type: " + deviceType + " and package name: " + packageName; throw new ApplicationStorageManagementException(msg);
log.error(msg); }
throw new BadRequestException(msg); if (!applicationReleaseDTO.getAppHashValue().equals(md5OfApp)) {
} applicationReleaseDTO.setInstallerName(applicationArtifact.getInstallerName());
if (applicationReleaseDTO.getPackageName() == null) {
String msg = "Found null value for application release package name for application "
+ "release which has UUID: " + applicationReleaseDTO.getUuid();
log.error(msg);
throw new ApplicationManagementException(msg);
}
if (!applicationReleaseDTO.getPackageName().equals(packageName)) {
String msg = "Package name of the new artifact does not match with the package name of "
+ "the exiting application release. Package name of the existing app release "
+ applicationReleaseDTO.getPackageName() + " and package name of the new "
+ "application release " + packageName;
log.error(msg);
throw new BadRequestException(msg);
}
applicationReleaseDTO.setVersion(applicationInstaller.getVersion()); try (ByteArrayInputStream binary = new ByteArrayInputStream(content)) {
applicationReleaseDTO.setPackageName(packageName); ApplicationInstaller applicationInstaller = applicationStorageManager
String deletingAppHashValue = applicationReleaseDTO.getAppHashValue(); .getAppInstallerData(binary, deviceType);
applicationReleaseDTO.setAppHashValue(md5OfApp); String packageName = applicationInstaller.getPackageName();
applicationStorageManager.uploadReleaseArtifact(applicationReleaseDTO, deviceType,
Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), try {
tenantId); ConnectionManagerUtil.getDBConnection();
applicationStorageManager.copyImageArtifactsAndDeleteInstaller(deletingAppHashValue, if (this.applicationReleaseDAO.verifyReleaseExistenceByHash(md5OfApp, tenantId)) {
applicationReleaseDTO, tenantId); String msg = "Same binary file is in the server. Hence you can't add same file into the "
} catch (DBConnectionException e) { + "server. Device Type: " + deviceType + " and package name: " + packageName;
String msg = "Error occurred when getting database connection for verifying application " log.error(msg);
+ "release existing for new app hash value."; throw new BadRequestException(msg);
log.error(msg, e); }
throw new ApplicationManagementException(msg, e); if (applicationReleaseDTO.getPackageName() == null){
} catch (ApplicationManagementDAOException e) { String msg = "Found null value for application release package name for application "
String msg = "Error occurred when executing the query for verifying application release " + "release which has UUID: " + applicationReleaseDTO.getUuid();
+ "existence for the new app hash value."; log.error(msg);
log.error(msg, e); throw new ApplicationManagementException(msg);
throw new ApplicationManagementException(msg, e); }
} finally { if (!applicationReleaseDTO.getPackageName().equals(packageName)){
ConnectionManagerUtil.closeDBConnection(); String msg = "Package name of the new artifact does not match with the package name of "
+ "the exiting application release. Package name of the existing app release "
+ applicationReleaseDTO.getPackageName() + " and package name of the new "
+ "application release " + packageName;
log.error(msg);
throw new BadRequestException(msg);
}
applicationReleaseDTO.setVersion(applicationInstaller.getVersion());
applicationReleaseDTO.setPackageName(packageName);
String deletingAppHashValue = applicationReleaseDTO.getAppHashValue();
applicationReleaseDTO.setAppHashValue(md5OfApp);
try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) {
applicationStorageManager
.uploadReleaseArtifact(applicationReleaseDTO, deviceType, binaryDuplicate,
tenantId);
applicationStorageManager.copyImageArtifactsAndDeleteInstaller(deletingAppHashValue,
applicationReleaseDTO, tenantId);
}
} catch (DBConnectionException e) {
String msg = "Error occurred when getting database connection for verifying application "
+ "release existing for new app hash value.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg = "Error occurred when executing the query for verifying application release "
+ "existence for the new app hash value.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
} }
} }
} catch (StorageManagementException e) { } catch (StorageManagementException e) {
@ -1028,7 +1032,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg, e); log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e); throw new ApplicationStorageManagementException(msg, e);
} catch (IOException e) { } catch (IOException e) {
String msg = "Error occurred when getting file input stream. Installer name: " + applicationArtifact String msg = "Error occurred when getting byte array of binary file. Installer name: " + applicationArtifact
.getInstallerName(); .getInstallerName();
log.error(msg, e); log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e); throw new ApplicationStorageManagementException(msg, e);
@ -3603,49 +3607,52 @@ public class ApplicationManagerImpl implements ApplicationManager {
DeviceType deviceTypeObj = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); DeviceType deviceTypeObj = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId());
// The application executable artifacts such as deb are uploaded. // The application executable artifacts such as deb are uploaded.
try { try {
String md5OfApp = applicationStorageManager.getMD5( byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath()))); try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) {
if (md5OfApp == null) { String md5OfApp = applicationStorageManager.getMD5(binaryClone);
String msg = "Error occurred while retrieving md5sum value from the binary file for " if (md5OfApp == null) {
+ "application release UUID " + applicationReleaseDTO.get().getUuid(); String msg = "Error occurred while retrieving md5sum value from the binary file for "
log.error(msg); + "application release UUID " + applicationReleaseDTO.get().getUuid();
throw new ApplicationStorageManagementException(msg); log.error(msg);
} throw new ApplicationStorageManagementException(msg);
}
if (!applicationReleaseDTO.get().getAppHashValue().equals(md5OfApp)) {
try {
ConnectionManagerUtil.getDBConnection();
if (this.applicationReleaseDAO.verifyReleaseExistenceByHash(md5OfApp, tenantId)) {
String msg =
"Same binary file is in the server. Hence you can't add same file into the "
+ "server. Device Type: " + deviceTypeObj.getName()
+ " and package name: " + applicationDTO.getApplicationReleaseDTOs()
.get(0).getPackageName();
log.error(msg);
throw new BadRequestException(msg);
}
if (!applicationReleaseDTO.get().getAppHashValue().equals(md5OfApp)) { applicationReleaseDTO.get().setInstallerName(applicationArtifact.getInstallerName());
try { String deletingAppHashValue = applicationReleaseDTO.get().getAppHashValue();
ConnectionManagerUtil.getDBConnection(); applicationReleaseDTO.get().setAppHashValue(md5OfApp);
if (this.applicationReleaseDAO.verifyReleaseExistenceByHash(md5OfApp, tenantId)) { try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) {
applicationStorageManager
.uploadReleaseArtifact(applicationReleaseDTO.get(), deviceTypeObj.getName(),
binaryDuplicate, tenantId);
applicationStorageManager.copyImageArtifactsAndDeleteInstaller(deletingAppHashValue,
applicationReleaseDTO.get(), tenantId);
}
} catch (DBConnectionException e) {
String msg = "Error occurred when getting database connection for verifying application"
+ " release existing for new app hash value.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg = String msg =
"Same binary file is in the server. Hence you can't add same file into the " "Error occurred when executing the query for verifying application release "
+ "server. Device Type: " + deviceTypeObj.getName() + "existence for the new app hash value.";
+ " and package name: " + applicationDTO.getApplicationReleaseDTOs() log.error(msg, e);
.get(0).getPackageName(); throw new ApplicationManagementException(msg, e);
log.error(msg); } finally {
throw new BadRequestException(msg); ConnectionManagerUtil.closeDBConnection();
} }
applicationReleaseDTO.get().setInstallerName(applicationArtifact.getInstallerName());
String deletingAppHashValue = applicationReleaseDTO.get().getAppHashValue();
applicationReleaseDTO.get().setAppHashValue(md5OfApp);
applicationStorageManager.
uploadReleaseArtifact(applicationReleaseDTO.get(), deviceTypeObj.getName(),
Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), tenantId);
applicationStorageManager.copyImageArtifactsAndDeleteInstaller(deletingAppHashValue,
applicationReleaseDTO.get(), tenantId);
} catch (DBConnectionException e) {
String msg = "Error occurred when getting database connection for verifying application"
+ " release existing for new app hash value.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg =
"Error occurred when executing the query for verifying application release "
+ "existence for the new app hash value.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
} }
} }
} catch (StorageManagementException e) { } catch (StorageManagementException e) {
@ -4417,6 +4424,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
spApplicationDAO.deleteSPApplicationMappingByTenant(tenantId); spApplicationDAO.deleteSPApplicationMappingByTenant(tenantId);
spApplicationDAO.deleteIdentityServerByTenant(tenantId); spApplicationDAO.deleteIdentityServerByTenant(tenantId);
applicationDAO.deleteApplicationsByTenant(tenantId); applicationDAO.deleteApplicationsByTenant(tenantId);
APIUtil.getApplicationStorageManager().deleteAppFolderOfTenant(tenantId);
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
@ -4441,6 +4449,12 @@ public class ApplicationManagerImpl implements ApplicationManager {
+ " of tenant ID: " + tenantId ; + " of tenant ID: " + tenantId ;
log.error(msg, e); log.error(msg, e);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch (ApplicationStorageManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred while deleting App folder of tenant"
+ " of tenant ID: " + tenantId ;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -4449,9 +4463,19 @@ public class ApplicationManagerImpl implements ApplicationManager {
@Override @Override
public void deleteApplicationDataByTenantDomain(String tenantDomain) throws ApplicationManagementException { public void deleteApplicationDataByTenantDomain(String tenantDomain) throws ApplicationManagementException {
int tenantId; int tenantId;
try { try{
tenantId = DataHolder.getInstance().getTenantManagerAdminService().getTenantId(tenantDomain); TenantMgtAdminService tenantMgtAdminService = new TenantMgtAdminService();
TenantInfoBean tenantInfoBean = tenantMgtAdminService.getTenant(tenantDomain);
tenantId = tenantInfoBean.getTenantId();
} catch (Exception e) {
String msg = "Error getting tenant ID from domain: "
+ tenantDomain;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
}
try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
vppApplicationDAO.deleteAssociationByTenant(tenantId); vppApplicationDAO.deleteAssociationByTenant(tenantId);
@ -4475,54 +4499,40 @@ public class ApplicationManagerImpl implements ApplicationManager {
spApplicationDAO.deleteSPApplicationMappingByTenant(tenantId); spApplicationDAO.deleteSPApplicationMappingByTenant(tenantId);
spApplicationDAO.deleteIdentityServerByTenant(tenantId); spApplicationDAO.deleteIdentityServerByTenant(tenantId);
applicationDAO.deleteApplicationsByTenant(tenantId); applicationDAO.deleteApplicationsByTenant(tenantId);
APIUtil.getApplicationStorageManager().deleteAppFolderOfTenant(tenantId);
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
String msg = "Error occurred while observing the database connection to delete applications for tenant with " + String msg = "Error occurred while observing the database connection to delete applications for tenant with ID: "
"domain: " + tenantDomain; + tenantId;
log.error(msg, e); log.error(msg, e);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Database access error is occurred when getting applications for tenant with domain: " String msg = "Database access error is occurred when getting applications for tenant with ID: " + tenantId;
+ tenantDomain;
log.error(msg, e); log.error(msg, e);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch (LifeCycleManagementDAOException e) { } catch (LifeCycleManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred while deleting life-cycle state data of application releases of the tenant" String msg = "Error occurred while deleting life-cycle state data of application releases of the tenant"
+ " of domain: " + tenantDomain ; + " of ID: " + tenantId ;
log.error(msg, e); log.error(msg, e);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch (ReviewManagementDAOException e) { } catch (ReviewManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred while deleting reviews of application releases of the applications" String msg = "Error occurred while deleting reviews of application releases of the applications"
+ " of tenant of domain: " + tenantDomain ; + " of tenant ID: " + tenantId ;
log.error(msg, e); log.error(msg, e);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch (Exception e) { } catch (ApplicationStorageManagementException e) {
String msg = "Error getting tenant ID from domain: " ConnectionManagerUtil.rollbackDBTransaction();
+ tenantDomain; String msg = "Error occurred while deleting App folder of tenant"
+ " of tenant ID: " + tenantId ;
log.error(msg, e); log.error(msg, e);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
} }
}
@Override
public void deleteApplicationArtifactsByTenantDomain(String tenantDomain) throws ApplicationManagementException {
int tenantId;
try {
tenantId = DataHolder.getInstance().getTenantManagerAdminService().getTenantId(tenantDomain);
DataHolder.getInstance().getApplicationStorageManager().deleteAppFolderOfTenant(tenantId);
} catch (ApplicationStorageManagementException e) {
String msg = "Error deleting app artifacts of tenant of domain: " + tenantDomain ;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (TenantMgtException e) {
String msg = "Error getting tenant ID from domain: "
+ tenantDomain + " when trying to delete application artifacts of tenant";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
}
} }
} }

@ -37,7 +37,6 @@ import io.entgra.device.mgt.core.device.mgt.core.common.exception.StorageManagem
import io.entgra.device.mgt.core.device.mgt.core.common.util.StorageManagementUtil; import io.entgra.device.mgt.core.device.mgt.core.common.util.StorageManagementUtil;
import java.io.*; import java.io.*;
import java.nio.file.Paths;
import java.util.List; import java.util.List;
import static io.entgra.device.mgt.core.device.mgt.core.common.util.StorageManagementUtil.saveFile; import static io.entgra.device.mgt.core.device.mgt.core.common.util.StorageManagementUtil.saveFile;
@ -156,12 +155,13 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
public void uploadReleaseArtifact(ApplicationReleaseDTO applicationReleaseDTO, public void uploadReleaseArtifact(ApplicationReleaseDTO applicationReleaseDTO,
String deviceType, InputStream binaryFile, int tenantId) throws ResourceManagementException { String deviceType, InputStream binaryFile, int tenantId) throws ResourceManagementException {
try { try {
byte [] content = IOUtils.toByteArray(binaryFile);
String artifactDirectoryPath = String artifactDirectoryPath =
storagePath + tenantId + File.separator + applicationReleaseDTO.getAppHashValue() + File.separator storagePath + tenantId + File.separator + applicationReleaseDTO.getAppHashValue() + File.separator
+ Constants.APP_ARTIFACT; + Constants.APP_ARTIFACT;
StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath); StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
String artifactPath = artifactDirectoryPath + File.separator + applicationReleaseDTO.getInstallerName(); String artifactPath = artifactDirectoryPath + File.separator + applicationReleaseDTO.getInstallerName();
saveFile(binaryFile, artifactPath); saveFile(new ByteArrayInputStream(content), artifactPath);
} catch (IOException e) { } catch (IOException e) {
String msg = "IO Exception while saving the release artifacts in the server for the application UUID " String msg = "IO Exception while saving the release artifacts in the server for the application UUID "
+ applicationReleaseDTO.getUuid(); + applicationReleaseDTO.getUuid();
@ -324,12 +324,4 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
} }
} }
} }
@Override
public String getAbsolutePathOfFile(String hashVal, String folderName, String fileName, int tenantId) {
String filePath =
storagePath + tenantId + File.separator + hashVal + File.separator + folderName + File.separator
+ fileName;
return Paths.get(filePath).toAbsolutePath().toString();
}
} }

@ -31,7 +31,6 @@ import io.entgra.device.mgt.core.device.mgt.common.exceptions.NotFoundException;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL; import java.net.URL;
import java.nio.file.FileSystems; import java.nio.file.FileSystems;
@ -104,13 +103,8 @@ public class FileTransferServiceImpl implements FileTransferService {
@Override @Override
public boolean isExistsOnLocal(URL downloadUrl) throws FileTransferServiceException { public boolean isExistsOnLocal(URL downloadUrl) throws FileTransferServiceException {
try { try {
FileDescriptor fileDescriptor = FileTransferServiceHelperUtil.resolve(downloadUrl); return FileTransferServiceHelperUtil.resolve(downloadUrl) != null;
if (fileDescriptor != null && fileDescriptor.getFile() != null) { } catch (FileTransferServiceHelperUtilException e) {
fileDescriptor.getFile().close();
return true;
}
return false;
} catch (FileTransferServiceHelperUtilException | IOException e) {
String msg = "Error occurred while checking the existence of artifact on the local environment"; String msg = "Error occurred while checking the existence of artifact on the local environment";
log.error(msg, e); log.error(msg, e);
throw new FileTransferServiceException(msg, e); throw new FileTransferServiceException(msg, e);

@ -33,9 +33,7 @@ import io.entgra.device.mgt.core.application.mgt.core.impl.FileTransferServiceIm
import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager;
import io.entgra.device.mgt.core.application.mgt.core.task.ScheduledAppSubscriptionTaskManager; import io.entgra.device.mgt.core.application.mgt.core.task.ScheduledAppSubscriptionTaskManager;
import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil; import io.entgra.device.mgt.core.application.mgt.core.util.ApplicationManagementUtil;
import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerAdminService;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
@ -73,12 +71,6 @@ import java.util.List;
* policy="dynamic" * policy="dynamic"
* bind="setTaskService" * bind="setTaskService"
* unbind="unsetTaskService" * unbind="unsetTaskService"
* @scr.reference name="io.entgra.device.mgt.core.tenant.manager"
* interface="io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerAdminService"
* cardinality="0..1"
* policy="dynamic"
* bind="setTenantManagementAdminService"
* unbind="unsetTenantManagementAdminService"
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class ApplicationManagementServiceComponent { public class ApplicationManagementServiceComponent {
@ -204,20 +196,4 @@ public class ApplicationManagementServiceComponent {
} }
DataHolder.getInstance().setTaskService(null); DataHolder.getInstance().setTaskService(null);
} }
@SuppressWarnings("unused")
protected void setTenantManagementAdminService(TenantManagerAdminService tenantManagerAdminService) {
if (log.isDebugEnabled()) {
log.debug("Setting Tenant management admin Service");
}
DataHolder.getInstance().setTenantManagerAdminService(tenantManagerAdminService);
}
@SuppressWarnings("unused")
protected void unsetTenantManagementAdminService(TenantManagerAdminService tenantManagerAdminService) {
if (log.isDebugEnabled()) {
log.debug("Un setting Tenant management admin service");
}
DataHolder.getInstance().setTenantManagerAdminService(null);
}
} }

@ -27,8 +27,6 @@ import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionMan
import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.VPPApplicationManager;
import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.device.mgt.core.application.mgt.core.lifecycle.LifecycleStateManager;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService; import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerAdminService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
@ -59,7 +57,6 @@ public class DataHolder {
private TaskService taskService; private TaskService taskService;
private FileTransferService fileTransferService; private FileTransferService fileTransferService;
private TenantManagerAdminService tenantManagerAdminService;
private static final DataHolder applicationMgtDataHolder = new DataHolder(); private static final DataHolder applicationMgtDataHolder = new DataHolder();
@ -166,12 +163,4 @@ public class DataHolder {
public void setFileTransferService(FileTransferService fileTransferService) { public void setFileTransferService(FileTransferService fileTransferService) {
this.fileTransferService = fileTransferService; this.fileTransferService = fileTransferService;
} }
public TenantManagerAdminService getTenantManagerAdminService() {
return tenantManagerAdminService;
}
public void setTenantManagerAdminService(TenantManagerAdminService tenantManagerAdminService) {
this.tenantManagerAdminService = tenantManagerAdminService;
}
} }

@ -181,7 +181,6 @@ public class ApplicationManagementUtil {
fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(artifactLinkUrl).download(artifactLinkUrl); fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(artifactLinkUrl).download(artifactLinkUrl);
applicationArtifact.setInstallerName(fileDescriptor.getFullQualifiedName()); applicationArtifact.setInstallerName(fileDescriptor.getFullQualifiedName());
applicationArtifact.setInstallerStream(fileDescriptor.getFile()); applicationArtifact.setInstallerStream(fileDescriptor.getFile());
applicationArtifact.setInstallerPath(fileDescriptor.getAbsolutePath());
} }
if (iconLink != null) { if (iconLink != null) {
@ -189,7 +188,6 @@ public class ApplicationManagementUtil {
fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(iconLinkUrl).download(iconLinkUrl); fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(iconLinkUrl).download(iconLinkUrl);
applicationArtifact.setIconName(fileDescriptor.getFullQualifiedName()); applicationArtifact.setIconName(fileDescriptor.getFullQualifiedName());
applicationArtifact.setIconStream(fileDescriptor.getFile()); applicationArtifact.setIconStream(fileDescriptor.getFile());
applicationArtifact.setIconPath(fileDescriptor.getAbsolutePath());
} }
if (bannerLink != null) { if (bannerLink != null) {
@ -197,12 +195,10 @@ public class ApplicationManagementUtil {
fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(bannerLinkUrl).download(bannerLinkUrl); fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(bannerLinkUrl).download(bannerLinkUrl);
applicationArtifact.setBannerName(fileDescriptor.getFullQualifiedName()); applicationArtifact.setBannerName(fileDescriptor.getFullQualifiedName());
applicationArtifact.setBannerStream(fileDescriptor.getFile()); applicationArtifact.setBannerStream(fileDescriptor.getFile());
applicationArtifact.setBannerPath(fileDescriptor.getAbsolutePath());
} }
if (screenshotLinks != null) { if (screenshotLinks != null) {
Map<String, InputStream> screenshotData = new TreeMap<>(); Map<String, InputStream> screenshotData = new TreeMap<>();
Map<String, String> screenshotPaths = new TreeMap<>();
// This is to handle cases in which multiple screenshots have the same name // This is to handle cases in which multiple screenshots have the same name
Map<String, Integer> screenshotNameCount = new HashMap<>(); Map<String, Integer> screenshotNameCount = new HashMap<>();
URL screenshotLinkUrl; URL screenshotLinkUrl;
@ -213,7 +209,6 @@ public class ApplicationManagementUtil {
screenshotNameCount.put(screenshotName, screenshotNameCount.getOrDefault(screenshotName, 0) + 1); screenshotNameCount.put(screenshotName, screenshotNameCount.getOrDefault(screenshotName, 0) + 1);
screenshotName = FileUtil.generateDuplicateFileName(screenshotName, screenshotNameCount.get(screenshotName)); screenshotName = FileUtil.generateDuplicateFileName(screenshotName, screenshotNameCount.get(screenshotName));
screenshotData.put(screenshotName, fileDescriptor.getFile()); screenshotData.put(screenshotName, fileDescriptor.getFile());
screenshotPaths.put(screenshotName, fileDescriptor.getAbsolutePath());
} }
applicationArtifact.setScreenshots(screenshotData); applicationArtifact.setScreenshots(screenshotData);
} }

@ -74,7 +74,6 @@ public class Constants {
public static final String IS_USER_ABLE_TO_VIEW_ALL_ROLES = "isUserAbleToViewAllRoles"; public static final String IS_USER_ABLE_TO_VIEW_ALL_ROLES = "isUserAbleToViewAllRoles";
public static final String GOOGLE_PLAY_STORE_URL = "https://play.google.com/store/apps/details?id="; public static final String GOOGLE_PLAY_STORE_URL = "https://play.google.com/store/apps/details?id=";
public static final String APPLE_STORE_URL = "https://itunes.apple.com/country/app/app-name/id"; public static final String APPLE_STORE_URL = "https://itunes.apple.com/country/app/app-name/id";
public static final String MICROSOFT_STORE_URL = "https://apps.microsoft.com/detail/";
public static final String GOOGLE_PLAY_SYNCED_APP = "GooglePlaySyncedApp"; public static final String GOOGLE_PLAY_SYNCED_APP = "GooglePlaySyncedApp";
// Subscription task related constants // Subscription task related constants

@ -383,6 +383,7 @@ public class DAOUtil {
activity.setAppType(rs.getString("TYPE")); activity.setAppType(rs.getString("TYPE"));
activity.setUsername(rs.getString("SUBSCRIBED_BY")); activity.setUsername(rs.getString("SUBSCRIBED_BY"));
activity.setPackageName(rs.getString("PACKAGE_NAME")); activity.setPackageName(rs.getString("PACKAGE_NAME"));
activity.setStatus(rs.getString("STATUS"));
activity.setVersion(rs.getString("VERSION")); activity.setVersion(rs.getString("VERSION"));
activity.setTriggeredBy(rs.getString("ACTION_TRIGGERED_FROM")); activity.setTriggeredBy(rs.getString("ACTION_TRIGGERED_FROM"));
activities.add(activity); activities.add(activity);

@ -23,9 +23,7 @@ import com.google.gson.Gson;
import io.entgra.device.mgt.core.application.mgt.common.ChunkDescriptor; import io.entgra.device.mgt.core.application.mgt.common.ChunkDescriptor;
import io.entgra.device.mgt.core.application.mgt.common.FileDescriptor; import io.entgra.device.mgt.core.application.mgt.common.FileDescriptor;
import io.entgra.device.mgt.core.application.mgt.common.FileMetaEntry; import io.entgra.device.mgt.core.application.mgt.common.FileMetaEntry;
import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationStorageManagementException;
import io.entgra.device.mgt.core.application.mgt.core.exception.FileTransferServiceHelperUtilException; import io.entgra.device.mgt.core.application.mgt.core.exception.FileTransferServiceHelperUtilException;
import io.entgra.device.mgt.core.application.mgt.core.internal.DataHolder;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.NotFoundException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.NotFoundException;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -177,12 +175,6 @@ public class FileTransferServiceHelperUtil {
} }
String []urlPathSegments = downloadUrl.getPath().split("/"); String []urlPathSegments = downloadUrl.getPath().split("/");
FileDescriptor fileDescriptorResolvedFromRelease = resolve(urlPathSegments);
if (fileDescriptorResolvedFromRelease != null) {
return fileDescriptorResolvedFromRelease;
}
if (urlPathSegments.length < 2) { if (urlPathSegments.length < 2) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("URL patch segments contain less than 2 segments"); log.debug("URL patch segments contain less than 2 segments");
@ -242,54 +234,4 @@ public class FileTransferServiceHelperUtil {
throw new FileTransferServiceHelperUtilException("Error encountered while creating artifact file", e); throw new FileTransferServiceHelperUtilException("Error encountered while creating artifact file", e);
} }
} }
private static FileDescriptor resolve(String []urlSegments) throws FileTransferServiceHelperUtilException {
// check the possibility of url is pointing to a file resides in the default storage path
if (urlSegments.length < 4) {
if (log.isDebugEnabled()) {
log.debug("URL path segments contain less than 4 segments");
}
return null;
}
int tenantId;
try {
tenantId = Integer.parseInt(urlSegments[urlSegments.length - 4]);
} catch (NumberFormatException e) {
if (log.isDebugEnabled()) {
log.debug("URL isn't pointing to a file resides in the default storage path");
}
return null;
}
String fileName = urlSegments[urlSegments.length - 1];
String folderName = urlSegments[urlSegments.length - 2];
String appHash = urlSegments[urlSegments.length - 3];
try {
InputStream fileStream = DataHolder.getInstance().
getApplicationStorageManager().getFileStream(appHash, folderName, fileName, tenantId);
if (fileStream == null) {
if (log.isDebugEnabled()) {
log.debug("Could not found the file " + fileName);
}
return null;
}
String []fileNameSegments = fileName.split("\\.(?=[^.]+$)");
if (fileNameSegments.length < 2) {
throw new FileTransferServiceHelperUtilException("Invalid full qualified name encountered :" + fileName);
}
FileDescriptor fileDescriptor = new FileDescriptor();
fileDescriptor.setFile(fileStream);
fileDescriptor.setFullQualifiedName(fileName);
fileDescriptor.setExtension(fileNameSegments[fileNameSegments.length - 1]);
fileDescriptor.setFileName(fileNameSegments[fileNameSegments.length - 2]);
fileDescriptor.setAbsolutePath(DataHolder.getInstance().
getApplicationStorageManager().getAbsolutePathOfFile(appHash, folderName, fileName, tenantId));
return fileDescriptor;
} catch (ApplicationStorageManagementException e) {
throw new FileTransferServiceHelperUtilException("Error encountered while getting file input stream", e);
}
}
} }

@ -1,207 +0,0 @@
/*
* 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);
}
}

@ -1,71 +0,0 @@
/*
* 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() {
}
public static SubscriptionManagementServiceProvider getInstance() {
return SubscriptionManagementProviderServiceHolder.INSTANCE;
}
/**
* 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();
}
}

@ -1,143 +0,0 @@
/*
* 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.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(SubscriptionMetadata.SUBSCRIPTION_STATUS_UNSUBSCRIBED, 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);
deviceSubscriptionDTOS = newDeviceIds.stream().map(DeviceSubscriptionDTO::new).collect(Collectors.toList());
} 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();
}
}

@ -1,230 +0,0 @@
/*
* 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.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(SubscriptionMetadata.SUBSCRIPTION_STATUS_UNSUBSCRIBED, 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> newDeviceIds = deviceManagementProviderService.getDevicesInGivenIdList(allDeviceIdsOwnByGroup);
deviceSubscriptionDTOS = newDeviceIds.stream().map(DeviceSubscriptionDTO::new).collect(Collectors.toList());
} 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 {
return null;
}
@Override
public SubscriptionStatistics getSubscriptionStatistics(SubscriptionInfo subscriptionInfo) throws ApplicationManagementException {
return null;
}
// @Override
// public SubscriptionResponse getSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
// throws ApplicationManagementException {
// final boolean isUnsubscribe = Objects.equals(SubscriptionMetadata.SUBSCRIPTION_STATUS_UNSUBSCRIBED, 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(SubscriptionMetadata.SUBSCRIPTION_STATUS_UNSUBSCRIBED, subscriptionInfo.getSubscriptionStatus());
// 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<Device> devices = HelperUtil.getGroupManagementProviderService().
// getAllDevicesOfGroup(subscriptionInfo.getIdentifier(), false);
// List<Integer> deviceIdsOwnByGroup = devices.stream().map(Device::getId).collect(Collectors.toList());
// SubscriptionStatisticDTO subscriptionStatisticDTO = subscriptionDAO.
// getSubscriptionStatistic(deviceIdsOwnByGroup, isUnsubscribe, tenantId, applicationReleaseDTO.getId());
// 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();
}
}

@ -1,237 +0,0 @@
/*
* 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(SubscriptionMetadata.SUBSCRIPTION_STATUS_UNSUBSCRIBED, 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> newDeviceIds = deviceManagementProviderService.getDevicesInGivenIdList(deviceIdsOwnByRole);
deviceSubscriptionDTOS = newDeviceIds.stream().map(DeviceSubscriptionDTO::new).collect(Collectors.toList());
} 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 {
return null;
}
@Override
public SubscriptionStatistics getSubscriptionStatistics(SubscriptionInfo subscriptionInfo) throws ApplicationManagementException {
return null;
}
// @Override
// public SubscriptionResponse getSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
// throws ApplicationManagementException {
// final boolean isUnsubscribe = Objects.equals(SubscriptionMetadata.SUBSCRIPTION_STATUS_UNSUBSCRIBED, 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(SubscriptionMetadata.SUBSCRIPTION_STATUS_UNSUBSCRIBED, subscriptionInfo.getSubscriptionStatus());
// 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<Integer> deviceIdsOwnByRole = getDeviceIdsOwnByRole(subscriptionInfo.getIdentifier(), tenantId);
// SubscriptionStatisticDTO subscriptionStatisticDTO = subscriptionDAO.
// getSubscriptionStatistic(deviceIdsOwnByRole, isUnsubscribe, tenantId, applicationReleaseDTO.getId());
// 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();
}
}

@ -1,222 +0,0 @@
/*
* 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(SubscriptionMetadata.SUBSCRIPTION_STATUS_UNSUBSCRIBED, 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> newDeviceIds = deviceManagementProviderService.getDevicesInGivenIdList(deviceIdsOwnByUser);
deviceSubscriptionDTOS = newDeviceIds.stream().map(DeviceSubscriptionDTO::new).collect(Collectors.toList());
} 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 {
return null;
}
@Override
public SubscriptionStatistics getSubscriptionStatistics(SubscriptionInfo subscriptionInfo) throws ApplicationManagementException {
return null;
}
// @Override
// public SubscriptionResponse getSubscriptions(SubscriptionInfo subscriptionInfo, int limit, int offset)
// throws ApplicationManagementException {
// final boolean isUnsubscribe = Objects.equals(SubscriptionMetadata.SUBSCRIPTION_STATUS_UNSUBSCRIBED, 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(SubscriptionMetadata.SUBSCRIPTION_STATUS_UNSUBSCRIBED, subscriptionInfo.getSubscriptionStatus());
// 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<Integer> deviceIdsOwnByUser = getDeviceIdsOwnByUser(subscriptionInfo.getIdentifier());
// SubscriptionStatisticDTO subscriptionStatisticDTO = subscriptionDAO.
// getSubscriptionStatistic(deviceIdsOwnByUser, isUnsubscribe, tenantId, applicationReleaseDTO.getId());
// 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();
}
}

@ -1,44 +0,0 @@
/*
* 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;
}

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.parent</artifactId> <artifactId>io.entgra.device.mgt.core.parent</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>cea-mgt</artifactId> <artifactId>cea-mgt</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -23,7 +23,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>cea-mgt</artifactId> <artifactId>cea-mgt</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>cea-mgt</artifactId> <artifactId>cea-mgt</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>cea-mgt</artifactId> <artifactId>cea-mgt</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.parent</artifactId> <artifactId>io.entgra.device.mgt.core.parent</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>certificate-mgt</artifactId> <artifactId>certificate-mgt</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>certificate-mgt</artifactId> <artifactId>certificate-mgt</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>certificate-mgt</artifactId> <artifactId>certificate-mgt</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<artifactId>io.entgra.device.mgt.core.parent</artifactId> <artifactId>io.entgra.device.mgt.core.parent</artifactId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -329,7 +329,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED
DEVICE_ID INT NOT NULL, DEVICE_ID INT NOT NULL,
ENROLMENT_ID INT(11) NOT NULL, ENROLMENT_ID INT(11) NOT NULL,
POLICY_ID INT NOT NULL, POLICY_ID INT NOT NULL,
POLICY_CONTENT TEXT NULL, POLICY_CONTENT BLOB NULL,
TENANT_ID INT NOT NULL, TENANT_ID INT NOT NULL,
APPLIED TINYINT(1) NULL, APPLIED TINYINT(1) NULL,
CREATED_TIME TIMESTAMP NULL, CREATED_TIME TIMESTAMP NULL,

@ -336,7 +336,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED (
DEVICE_ID INT NOT NULL , DEVICE_ID INT NOT NULL ,
ENROLMENT_ID INT(11) NOT NULL, ENROLMENT_ID INT(11) NOT NULL,
POLICY_ID INT NOT NULL , POLICY_ID INT NOT NULL ,
POLICY_CONTENT TEXT NULL , POLICY_CONTENT BLOB NULL ,
TENANT_ID INT NOT NULL, TENANT_ID INT NOT NULL,
APPLIED TINYINT(1) NULL , APPLIED TINYINT(1) NULL ,
CREATED_TIME TIMESTAMP NULL , CREATED_TIME TIMESTAMP NULL ,

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -111,46 +111,6 @@
<groupId>org.wso2.carbon.analytics-common</groupId> <groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId> <artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.orbit.com.google.http-client</groupId>
<artifactId>google-http-client</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.com.google.auth-library-oauth2-http</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.io.opencensus</groupId>
<artifactId>opencensus</artifactId>
</dependency>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-api</artifactId>
</dependency>
<dependency>
<groupId>io.opencensus</groupId>
<artifactId>opencensus-contrib-http-util</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.io.grpc</groupId>
<artifactId>grpc-context</artifactId>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>failureaccess</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -177,27 +137,12 @@
com.google.gson, com.google.gson,
org.osgi.framework.*;version="${imp.package.version.osgi.framework}", org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}", org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.wso2.carbon.utils.*,
io.entgra.device.mgt.core.device.mgt.common.operation.mgt, io.entgra.device.mgt.core.device.mgt.common.operation.mgt,
io.entgra.device.mgt.core.device.mgt.common.push.notification, io.entgra.device.mgt.core.device.mgt.common.push.notification,
org.apache.commons.logging, org.apache.commons.logging,
io.entgra.device.mgt.core.device.mgt.common.*, io.entgra.device.mgt.core.device.mgt.common.*,
io.entgra.device.mgt.core.device.mgt.core.service, io.entgra.device.mgt.core.device.mgt.core.service
io.entgra.device.mgt.core.device.mgt.core.config.*,
io.entgra.device.mgt.core.device.mgt.core.config.push.notification.*,
io.entgra.device.mgt.core.device.mgt.extensions.logger.spi,
io.entgra.device.mgt.core.notification.logger.*,
com.google.auth.oauth2.*
</Import-Package> </Import-Package>
<Embed-Dependency>
google-auth-library-oauth2-http;scope=compile|runtime,
google-http-client;scope=compile|runtime,
grpc-context;scope=compile|runtime,
guava;scope=compile|runtime,
opencensus;scope=compile|runtime,
failureaccess;scope=compile|runtime
</Embed-Dependency>
<Embed-Transitive>true</Embed-Transitive>
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>

@ -32,9 +32,7 @@ public class FCMBasedPushNotificationProvider implements PushNotificationProvide
@Override @Override
public NotificationStrategy getNotificationStrategy(PushNotificationConfig config) { public NotificationStrategy getNotificationStrategy(PushNotificationConfig config) {
FCMNotificationStrategy fcmNotificationStrategy = new FCMNotificationStrategy(config); return new FCMNotificationStrategy(config);
fcmNotificationStrategy.init();
return fcmNotificationStrategy;
} }
} }

@ -17,8 +17,9 @@
*/ */
package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm; package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.util.FCMUtil; import com.google.gson.JsonPrimitive;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.device.mgt.common.Device; import io.entgra.device.mgt.core.device.mgt.common.Device;
@ -38,13 +39,14 @@ import java.util.List;
public class FCMNotificationStrategy implements NotificationStrategy { public class FCMNotificationStrategy implements NotificationStrategy {
private static final Log log = LogFactory.getLog(FCMNotificationStrategy.class); private static final Log log = LogFactory.getLog(FCMNotificationStrategy.class);
private static final String NOTIFIER_TYPE_FCM = "FCM"; private static final String NOTIFIER_TYPE_FCM = "FCM";
private static final String FCM_TOKEN = "FCM_TOKEN"; private static final String FCM_TOKEN = "FCM_TOKEN";
private static final String FCM_ENDPOINT = "https://fcm.googleapis.com/fcm/send";
private static final String FCM_API_KEY = "fcmAPIKey"; private static final String FCM_API_KEY = "fcmAPIKey";
private static final int TIME_TO_LIVE = 2419199; // 1 second less than 28 days private static final int TIME_TO_LIVE = 2419199; // 1 second less that 28 days
private static final int HTTP_STATUS_CODE_OK = 200; private static final int HTTP_STATUS_CODE_OK = 200;
private final PushNotificationConfig config; private final PushNotificationConfig config;
private static final String FCM_ENDPOINT_KEY = "FCM_SERVER_ENDPOINT";
public FCMNotificationStrategy(PushNotificationConfig config) { public FCMNotificationStrategy(PushNotificationConfig config) {
this.config = config; this.config = config;
@ -62,14 +64,12 @@ public class FCMNotificationStrategy implements NotificationStrategy {
Device device = FCMDataHolder.getInstance().getDeviceManagementProviderService() Device device = FCMDataHolder.getInstance().getDeviceManagementProviderService()
.getDeviceWithTypeProperties(ctx.getDeviceId()); .getDeviceWithTypeProperties(ctx.getDeviceId());
if(device.getProperties() != null && getFCMToken(device.getProperties()) != null) { if(device.getProperties() != null && getFCMToken(device.getProperties()) != null) {
FCMUtil.getInstance().getDefaultApplication().refresh(); this.sendWakeUpCall(ctx.getOperation().getCode(), device);
sendWakeUpCall(FCMUtil.getInstance().getDefaultApplication().getAccessToken().getTokenValue(),
getFCMToken(device.getProperties()));
} }
} else { } else {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Not using FCM notifier as notifier type is set to " + config.getType() + log.debug("Not using FCM notifier as notifier type is set to " + config.getType() +
" in Platform Configurations."); " in Platform Configurations.");
} }
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
@ -79,73 +79,69 @@ public class FCMNotificationStrategy implements NotificationStrategy {
} }
} }
@Override
public NotificationContext buildContext() {
return null;
}
/** @Override
* Send FCM message to the FCM server to initiate the push notification public void undeploy() {
* @param accessToken Access token to authenticate with the FCM server
* @param registrationId Registration ID of the device
* @throws IOException If an error occurs while sending the request
* @throws PushNotificationExecutionFailedException If an error occurs while sending the push notification
*/
private void sendWakeUpCall(String accessToken, String registrationId) throws IOException,
PushNotificationExecutionFailedException {
HttpURLConnection conn = null;
String fcmServerEndpoint = FCMUtil.getInstance().getContextMetadataProperties()
.getProperty(FCM_ENDPOINT_KEY);
if(fcmServerEndpoint == null) {
String msg = "Encountered configuration issue. " + FCM_ENDPOINT_KEY + " is not defined";
log.error(msg);
throw new PushNotificationExecutionFailedException(msg);
}
try { }
byte[] bytes = getFCMRequest(registrationId).getBytes();
URL url = new URL(fcmServerEndpoint); private void sendWakeUpCall(String message, Device device) throws IOException,
conn = (HttpURLConnection) url.openConnection(); PushNotificationExecutionFailedException {
conn.setRequestProperty("Content-Type", "application/json"); if (device.getProperties() != null) {
conn.setRequestProperty("Authorization", "Bearer " + accessToken); OutputStream os = null;
conn.setRequestMethod("POST"); byte[] bytes = getFCMRequest(message, getFCMToken(device.getProperties())).getBytes();
conn.setDoOutput(true);
HttpURLConnection conn = null;
try (OutputStream os = conn.getOutputStream()) { try {
conn = (HttpURLConnection) new URL(FCM_ENDPOINT).openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key=" + config.getProperty(FCM_API_KEY));
conn.setRequestMethod("POST");
conn.setDoOutput(true);
os = conn.getOutputStream();
os.write(bytes); os.write(bytes);
} finally {
if (os != null) {
os.close();
}
if (conn != null) {
conn.disconnect();
}
} }
int status = conn.getResponseCode(); int status = conn.getResponseCode();
if (status != 200) { if (log.isDebugEnabled()) {
log.error("Response Status: " + status + ", Response Message: " + conn.getResponseMessage()); log.debug("Result code: " + status + ", Message: " + conn.getResponseMessage());
} }
} finally { if (status != HTTP_STATUS_CODE_OK) {
if (conn != null) { throw new PushNotificationExecutionFailedException("Push notification sending failed with the HTTP " +
conn.disconnect(); "error code '" + status + "'");
} }
} }
} }
/** private static String getFCMRequest(String message, String registrationId) {
* Get the FCM request as a JSON string
* @param registrationId Registration ID of the device
* @return FCM request as a JSON string
*/
private static String getFCMRequest(String registrationId) {
JsonObject messageObject = new JsonObject();
messageObject.addProperty("token", registrationId);
JsonObject fcmRequest = new JsonObject(); JsonObject fcmRequest = new JsonObject();
fcmRequest.add("message", messageObject); fcmRequest.addProperty("delay_while_idle", false);
fcmRequest.addProperty("time_to_live", TIME_TO_LIVE);
return fcmRequest.toString(); fcmRequest.addProperty("priority", "high");
}
//Add message to FCM request
@Override JsonObject data = new JsonObject();
public NotificationContext buildContext() { if (message != null && !message.isEmpty()) {
return null; data.addProperty("data", message);
} fcmRequest.add("data", data);
}
@Override //Set device reg-id
public void undeploy() { JsonArray regIds = new JsonArray();
regIds.add(new JsonPrimitive(registrationId));
fcmRequest.add("registration_ids", regIds);
return fcmRequest.toString();
} }
private static String getFCMToken(List<Device.Property> properties) { private static String getFCMToken(List<Device.Property> properties) {
@ -163,4 +159,5 @@ public class FCMNotificationStrategy implements NotificationStrategy {
public PushNotificationConfig getConfig() { public PushNotificationConfig getConfig() {
return config; return config;
} }
} }

@ -1,108 +0,0 @@
/*
* 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.device.mgt.extensions.push.notification.provider.fcm.util;
import com.google.auth.oauth2.GoogleCredentials;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager;
import io.entgra.device.mgt.core.device.mgt.core.config.push.notification.ContextMetadata;
import io.entgra.device.mgt.core.device.mgt.core.config.push.notification.PushNotificationConfiguration;
import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.FCMNotificationStrategy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;
public class FCMUtil {
private static final Log log = LogFactory.getLog(FCMUtil.class);
private static volatile FCMUtil instance;
private static GoogleCredentials defaultApplication;
private static final String FCM_SERVICE_ACCOUNT_PATH = CarbonUtils.getCarbonHome() + File.separator +
"repository" + File.separator + "resources" + File.separator + "service-account.json";
private static final String[] FCM_SCOPES = { "https://www.googleapis.com/auth/firebase.messaging" };
private Properties contextMetadataProperties;
private FCMUtil() {
initContextConfigs();
initDefaultOAuthApplication();
}
private void initDefaultOAuthApplication() {
if (defaultApplication == null) {
Path serviceAccountPath = Paths.get(FCM_SERVICE_ACCOUNT_PATH);
try {
defaultApplication = GoogleCredentials.
fromStream(Files.newInputStream(serviceAccountPath)).
createScoped(FCM_SCOPES);
} catch (IOException e) {
String msg = "Fail to initialize default OAuth application for FCM communication";
log.error(msg);
throw new IllegalStateException(msg, e);
}
}
}
/**
* Initialize the context metadata properties from the cdm-config.xml. This file includes the fcm server URL
* to be invoked when sending the wakeup call to the device.
*/
private void initContextConfigs() {
PushNotificationConfiguration pushNotificationConfiguration = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig().getPushNotificationConfiguration();
List<ContextMetadata> contextMetadata = pushNotificationConfiguration.getContextMetadata();
Properties properties = new Properties();
if (contextMetadata != null) {
for (ContextMetadata metadata : contextMetadata) {
properties.setProperty(metadata.getKey(), metadata.getValue());
}
}
contextMetadataProperties = properties;
}
/**
* Get the instance of FCMUtil. FCMUtil is a singleton class which should not be
* instantiating more than once. Instantiating the class requires to read the service account file from
* the filesystem and instantiation of the GoogleCredentials object which are costly operations.
* @return FCMUtil instance
*/
public static FCMUtil getInstance() {
if (instance == null) {
synchronized (FCMUtil.class) {
if (instance == null) {
instance = new FCMUtil();
}
}
}
return instance;
}
public GoogleCredentials getDefaultApplication() {
return defaultApplication;
}
public Properties getContextMetadataProperties() {
return contextMetadataProperties;
}
}

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>io.entgra.device.mgt.core.parent</artifactId> <artifactId>io.entgra.device.mgt.core.parent</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -18,7 +18,6 @@
package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans; package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans;
import com.google.gson.Gson;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
@ -114,8 +113,4 @@ public class ApplicationUninstallation {
public void setType(String type) { public void setType(String type) {
this.type = type; this.type = type;
} }
public String toJson() {
return new Gson().toJson(this);
}
} }

@ -310,12 +310,6 @@ public interface DeviceManagementService {
required = false) required = false)
@QueryParam("groupId") @QueryParam("groupId")
int groupId, int groupId,
@ApiParam(
name = "excludeGroupId",
value = "Id of the group that needs to get the devices that are not belong.",
required = false)
@QueryParam("excludeGroupId")
int excludeGroupId,
@ApiParam( @ApiParam(
name = "since", name = "since",
value = "Checks if the requested variant was created since the specified date-time.\n" + value = "Checks if the requested variant was created since the specified date-time.\n" +

@ -934,12 +934,6 @@ public interface PolicyManagementService {
required = false) required = false)
@QueryParam("status") @QueryParam("status")
String status, String status,
@ApiParam(
name = "deviceType",
value = "The device type of the policy that needs filtering.",
required = false)
@QueryParam("deviceType")
String deviceType,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" + value = "Checks if the requested variant was modified, since the specified date-time. \n" +

@ -298,13 +298,8 @@ public interface UserManagementAdminService {
name = "tenantDomain", name = "tenantDomain",
value = "The domain of the tenant to be deleted.", value = "The domain of the tenant to be deleted.",
required = true) required = true)
@PathParam("tenantDomain") @PathParam("tenantDomain")
String tenantDomain, String tenantDomain);
@ApiParam(
name = "deleteAppArtifacts",
value = "Flag to indicate whether to delete application artifacts.",
required = false)
@QueryParam("deleteAppArtifacts")
@DefaultValue("false")
boolean deleteAppArtifacts);
} }

@ -175,6 +175,7 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
activity.setUsername(appActivity.getUsername()); activity.setUsername(appActivity.getUsername());
activity.setPackageName(appActivity.getPackageName()); activity.setPackageName(appActivity.getPackageName());
activity.setAppName(appActivity.getAppName()); activity.setAppName(appActivity.getAppName());
activity.setStatus(appActivity.getStatus());
activity.setAppType(appActivity.getAppType()); activity.setAppType(appActivity.getAppType());
activity.setVersion(appActivity.getVersion()); activity.setVersion(appActivity.getVersion());
activity.setTriggeredBy(appActivity.getTriggeredBy()); activity.setTriggeredBy(appActivity.getTriggeredBy());

@ -19,6 +19,7 @@
package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl; package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstallResponse; import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstallResponse;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType; import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType;
import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException;
@ -43,7 +44,6 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.*;
import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application;
import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException;
import io.entgra.device.mgt.core.device.mgt.common.app.mgt.MobileAppTypes;
import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException; import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationService; import io.entgra.device.mgt.core.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceData; import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceData;
@ -147,7 +147,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@QueryParam("customProperty") String customProperty, @QueryParam("customProperty") String customProperty,
@QueryParam("status") List<String> status, @QueryParam("status") List<String> status,
@QueryParam("groupId") int groupId, @QueryParam("groupId") int groupId,
@QueryParam("excludeGroupId") int excludeGroupId,
@QueryParam("since") String since, @QueryParam("since") String since,
@HeaderParam("If-Modified-Since") String ifModifiedSince, @HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("requireDeviceInfo") boolean requireDeviceInfo, @QueryParam("requireDeviceInfo") boolean requireDeviceInfo,
@ -210,22 +209,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
request.setStatusList(status); request.setStatusList(status);
} }
} }
// this is the user who initiates the request
if (excludeGroupId != 0) {
request.setGroupId(excludeGroupId);
if (user != null && !user.isEmpty()) {
request.setOwner(MultitenantUtils.getTenantAwareUsername(user));
} else if (userPattern != null && !userPattern.isEmpty()) {
request.setOwnerPattern(userPattern);
}
result = dms.getDevicesNotInGroup(request, requireDeviceInfo);
devices.setList((List<Device>) result.getData());
devices.setCount(result.getRecordsTotal());
return Response.status(Response.Status.OK).entity(devices).build();
}
String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
if (groupId != 0) { if (groupId != 0) {
@ -557,49 +541,22 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@Path("/type/{deviceType}/id/{deviceId}/rename") @Path("/type/{deviceType}/id/{deviceId}/rename")
public Response renameDevice(Device device, @PathParam("deviceType") String deviceType, public Response renameDevice(Device device, @PathParam("deviceType") String deviceType,
@PathParam("deviceId") String deviceId) { @PathParam("deviceId") String deviceId) {
if (device == null) {
String msg = "Required values are not set to rename device";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
if (StringUtils.isEmpty(device.getName())) {
String msg = "Device name is not set to rename device";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
try { try {
Device updatedDevice = deviceManagementProviderService.updateDeviceName(device, deviceType, deviceId); Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier
if (updatedDevice != null) { (deviceId, deviceType), true);
boolean notificationResponse = deviceManagementProviderService.sendDeviceNameChangedNotification(updatedDevice); persistedDevice.setName(device.getName());
if (notificationResponse) { System.out.println("This is rename device");
return Response.status(Response.Status.CREATED).entity(updatedDevice).build(); boolean responseOfmodifyEnrollment = deviceManagementProviderService.modifyEnrollment(persistedDevice);
} else { boolean responseOfDeviceNameChanged = deviceManagementProviderService.sendDeviceNameChangedNotification(
String msg = "Device updated successfully, but failed to send notification."; persistedDevice);
log.warn(msg); boolean response = responseOfmodifyEnrollment && responseOfDeviceNameChanged;
return Response.status(Response.Status.CREATED).entity(updatedDevice).header("Warning", msg).build();
} return Response.status(Response.Status.CREATED).entity(response).build();
} else {
String msg = "Device update failed for device of type : " + deviceType;
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
} catch (BadRequestException e) {
String msg = "Bad request: " + e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (DeviceNotFoundException e) {
String msg = "Device not found: " + e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error encountered while updating requested device of type : " + deviceType; String msg = "Error encountered while updating requested device of type : " + deviceType ;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ConflictException e) {
String msg = "Conflict encountered while updating requested device of type : " + deviceType;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.CONFLICT).entity(msg).build(); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} }
} }
@ -1112,6 +1069,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@QueryParam("version") String version, @QueryParam("version") String version,
@QueryParam("user") String user) { @QueryParam("user") String user) {
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>(); List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
Operation operation = new Operation();
try { try {
RequestValidationUtil.validateDeviceIdentifier(type, id); RequestValidationUtil.validateDeviceIdentifier(type, id);
Device device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id, false); Device device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id, false);
@ -1132,12 +1090,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
//if the applications not installed via entgra store //if the applications not installed via entgra store
} else { } else {
if (Constants.ANDROID.equals(type)) { if (Constants.ANDROID.equals(type)) {
ApplicationUninstallation applicationUninstallation = new ApplicationUninstallation(packageName, ApplicationUninstallation applicationUninstallation = new ApplicationUninstallation(packageName, "PUBLIC", name, platform, version, user);
MobileAppTypes.PUBLIC.toString(), name, platform, version, user); Gson gson = new Gson();
ProfileOperation operation = new ProfileOperation();
operation.setCode(MDMAppConstants.AndroidConstants.UNMANAGED_APP_UNINSTALL); operation.setCode(MDMAppConstants.AndroidConstants.UNMANAGED_APP_UNINSTALL);
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(applicationUninstallation.toJson()); operation.setPayLoad(gson.toJson(applicationUninstallation));
DeviceManagementProviderService deviceManagementProviderService = HelperUtil DeviceManagementProviderService deviceManagementProviderService = HelperUtil
.getDeviceManagementProviderService(); .getDeviceManagementProviderService();
Activity activity = deviceManagementProviderService.addOperation( Activity activity = deviceManagementProviderService.addOperation(

@ -488,7 +488,6 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
@QueryParam("name") String name, @QueryParam("name") String name,
@QueryParam("type") String type, @QueryParam("type") String type,
@QueryParam("status") String status, @QueryParam("status") String status,
@QueryParam("deviceType") String deviceType,
@HeaderParam("If-Modified-Since") String ifModifiedSince, @HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("offset") int offset, @QueryParam("offset") int offset,
@QueryParam("limit") int limit) { @QueryParam("limit") int limit) {
@ -506,9 +505,6 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
if (status != null){ if (status != null){
request.setStatus(status); request.setStatus(status);
} }
if (deviceType != null) {
request.setDeviceType(deviceType);
}
try { try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
policies = policyAdministratorPoint.getPolicyList(request); policies = policyAdministratorPoint.getPolicyList(request);

@ -19,7 +19,6 @@ package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.admin;
import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException; import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import io.entgra.device.mgt.core.tenant.mgt.common.exception.TenantMgtException;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
@ -30,6 +29,9 @@ import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.CredentialManagementR
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils; import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.stratos.common.exception.StratosException;
import org.wso2.carbon.tenant.mgt.services.TenantMgtAdminService;
import org.wso2.carbon.user.api.UserStoreException;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.ws.rs.*; import javax.ws.rs.*;
@ -89,7 +91,7 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic
@DELETE @DELETE
@Path("/domain/{tenantDomain}") @Path("/domain/{tenantDomain}")
@Override @Override
public Response deleteTenantByDomain(@PathParam("tenantDomain") String tenantDomain, @QueryParam("deleteAppArtifacts") boolean deleteAppArtifacts) { public Response deleteTenantByDomain(@PathParam("tenantDomain") String tenantDomain) {
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
if (tenantId != MultitenantConstants.SUPER_TENANT_ID){ if (tenantId != MultitenantConstants.SUPER_TENANT_ID){
@ -97,20 +99,15 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic
log.error(msg); log.error(msg);
return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build(); return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build();
} else { } else {
if (deleteAppArtifacts) {
DeviceMgtAPIUtils.getApplicationManager().deleteApplicationArtifactsByTenantDomain(tenantDomain);
}
DeviceMgtAPIUtils.getApplicationManager().deleteApplicationDataByTenantDomain(tenantDomain); DeviceMgtAPIUtils.getApplicationManager().deleteApplicationDataByTenantDomain(tenantDomain);
DeviceMgtAPIUtils.getDeviceManagementService().deleteDeviceDataByTenantDomain(tenantDomain); DeviceMgtAPIUtils.getDeviceManagementService().deleteDeviceDataByTenantDomain(tenantDomain);
DeviceMgtAPIUtils.getTenantManagerAdminService().deleteTenant(tenantDomain); TenantMgtAdminService tenantMgtAdminService = new TenantMgtAdminService();
tenantMgtAdminService.deleteTenant(tenantDomain);
String msg = "Tenant Deletion process has been initiated for tenant:" + tenantDomain; String msg = "Tenant Deletion process has been initiated for tenant:" + tenantDomain;
if (log.isDebugEnabled()) {
log.debug(msg);
}
return Response.status(Response.Status.OK).entity(msg).build(); return Response.status(Response.Status.OK).entity(msg).build();
} }
} catch (TenantMgtException e) { } catch (StratosException | UserStoreException e) {
String msg = "Error deleting tenant: " + tenantDomain; String msg = "Error deleting tenant: " + tenantDomain;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();

@ -23,8 +23,6 @@ import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONObject;
import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.device.mgt.common.Base64File;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import io.entgra.device.mgt.core.device.mgt.common.Feature; import io.entgra.device.mgt.core.device.mgt.common.Feature;
@ -823,30 +821,6 @@ public class RequestValidationUtil {
new ErrorResponse.ErrorResponseBuilder() new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build()); .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
} }
if (metadata.getMetaKey().equals("PER_DEVICE_COST")) {
String metaValue = metadata.getMetaValue();
JSONArray jsonArray = new JSONArray(metaValue);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.has("cost")) {
Object costObj = jsonObject.get("cost");
if (costObj == JSONObject.NULL || (costObj instanceof Number && ((Number) costObj).doubleValue() < 0)) {
String msg = "Billing cost cannot be a minus value or null.";
log.error(msg);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
} else {
String msg = "Billing cost is missing.";
log.error(msg);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
}
}
if (metadata.getMetaValue() == null) { if (metadata.getMetaValue() == null) {
String msg = "Request parameter metaValue should be non empty."; String msg = "Request parameter metaValue should be non empty.";
log.error(msg); log.error(msg);

@ -24,7 +24,6 @@ import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionMan
import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuthorizationService; import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuthorizationService;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService;
import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerAdminService;
import org.apache.axis2.AxisFault; import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Options; import org.apache.axis2.client.Options;
import org.apache.axis2.java.security.SSLProtocolSocketFactory; import org.apache.axis2.java.security.SSLProtocolSocketFactory;
@ -164,7 +163,6 @@ public class DeviceMgtAPIUtils {
private static volatile ApplicationManager applicationManager; private static volatile ApplicationManager applicationManager;
private static volatile APIPublisherService apiPublisher; private static volatile APIPublisherService apiPublisher;
private static volatile TenantManagerAdminService tenantManagerAdminService;
static { static {
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
@ -1245,21 +1243,4 @@ public class DeviceMgtAPIUtils {
} }
return isPermitted; return isPermitted;
} }
public static TenantManagerAdminService getTenantManagerAdminService(){
if(tenantManagerAdminService == null) {
synchronized (DeviceMgtAPIUtils.class) {
if (tenantManagerAdminService == null) {
tenantManagerAdminService = (TenantManagerAdminService) PrivilegedCarbonContext.getThreadLocalCarbonContext().
getOSGiService(TenantManagerAdminService.class, null);
if (tenantManagerAdminService == null) {
String msg = "Tenant Manager Admin Service is null";
log.error(msg);
throw new IllegalStateException(msg);
}
}
}
}
return tenantManagerAdminService;
}
} }

@ -157,7 +157,7 @@ public class DeviceManagementServiceImplTest {
.toReturn(this.deviceAccessAuthorizationService); .toReturn(this.deviceAccessAuthorizationService);
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, null, null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} }
@ -177,22 +177,22 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null,null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, null,null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, null, null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, null, null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, true, null, null, DEFAULT_STATUS_LIST, 1, null, null, true,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
} }
@ -307,7 +307,7 @@ public class DeviceManagementServiceImplTest {
Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true);
deviceManagementService.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, deviceManagementService.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null,
DEFAULT_ROLE, DEFAULT_OWNERSHIP, null,null, DEFAULT_STATUS_LIST, 1, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null,null, DEFAULT_STATUS_LIST, 1,
0, null, null, false, 10, 5); null, null, false, 10, 5);
} }
@Test(description = "Testing get devices when user is the device admin") @Test(description = "Testing get devices when user is the device admin")
@ -326,11 +326,11 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP
, null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, 10, 5); , null, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP .getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP
, null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, 10, 5); , null, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
} }
@ -352,7 +352,7 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 0, 0, null, null, false, null, null, DEFAULT_STATUS_LIST, 0, null, null, false,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode());
Mockito.reset(this.deviceAccessAuthorizationService); Mockito.reset(this.deviceAccessAuthorizationService);
@ -374,17 +374,17 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 0, 0, null, ifModifiedSince, false, null, null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, false,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 0, 0, null, ifModifiedSince, true, null, null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, true,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 0, 0, null, "ErrorModifiedSince", null, null, DEFAULT_STATUS_LIST, 0, null, "ErrorModifiedSince",
false, 10, 5); false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} }
@ -405,17 +405,17 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null,DEFAULT_STATUS_LIST, 0, 0, since, null, false, null, null,DEFAULT_STATUS_LIST, 0, since, null, false,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null,DEFAULT_STATUS_LIST, 0, 0, since, null, true, null, null,DEFAULT_STATUS_LIST, 0, since, null, true,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null,DEFAULT_STATUS_LIST, 0, 0, "ErrorSince", null, false, null, null,DEFAULT_STATUS_LIST, 0, "ErrorSince", null, false,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} }
@ -438,7 +438,7 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, null, null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Mockito.reset(this.deviceManagementProviderService); Mockito.reset(this.deviceManagementProviderService);
@ -461,7 +461,7 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, null, null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5); 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Mockito.reset(this.deviceAccessAuthorizationService); Mockito.reset(this.deviceAccessAuthorizationService);

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>io.entgra.device.mgt.core</groupId> <groupId>io.entgra.device.mgt.core</groupId>
<version>5.2.4-SNAPSHOT</version> <version>5.0.42-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

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

@ -58,10 +58,6 @@ public class MDMAppConstants {
} }
public static final String INSTALL_ENTERPRISE_APPLICATION = "INSTALL_ENTERPRISE_APPLICATION"; public static final String INSTALL_ENTERPRISE_APPLICATION = "INSTALL_ENTERPRISE_APPLICATION";
public static final String UNINSTALL_ENTERPRISE_APPLICATION = "UNINSTALL_ENTERPRISE_APPLICATION"; public static final String UNINSTALL_ENTERPRISE_APPLICATION = "UNINSTALL_ENTERPRISE_APPLICATION";
public static final String INSTALL_STORE_APPLICATION = "INSTALL_STORE_APPLICATION";
public static final String UNINSTALL_STORE_APPLICATION = "UNINSTALL_STORE_APPLICATION";
public static final String INSTALL_WEB_CLIP_APPLICATION = "INSTALL_WEB_CLIP";
public static final String UNINSTALL_WEB_CLIP_APPLICATION = "UNINSTALL_WEB_CLIP";
//App type constants related to window device type //App type constants related to window device type
public static final String MSI = "MSI"; public static final String MSI = "MSI";
public static final String APPX = "APPX"; public static final String APPX = "APPX";

@ -41,20 +41,11 @@ public class PaginationRequest {
private Date since; private Date since;
private String filter; private String filter;
private String serialNumber; private String serialNumber;
private String groupName;
private String roleName;
private String userName;
private String deviceStatus;
private String tabActionStatus;
private String actionStatus;
private String actionType;
private String actionTriggeredBy;
private Map<String, String> customProperty = new HashMap<>(); private Map<String, String> customProperty = new HashMap<>();
private Map<String, Object> property = new HashMap<>(); private Map<String, Object> property = new HashMap<>();
private List<String> statusList = new ArrayList<>(); private List<String> statusList = new ArrayList<>();
private OperationLogFilters operationLogFilters = new OperationLogFilters(); private OperationLogFilters operationLogFilters = new OperationLogFilters();
private List<SortColumn> sortColumn = new ArrayList<>(); private List<SortColumn> sortColumn = new ArrayList<>();
private int deviceTypeId;
public OperationLogFilters getOperationLogFilters() { public OperationLogFilters getOperationLogFilters() {
return operationLogFilters; return operationLogFilters;
} }
@ -229,76 +220,4 @@ public class PaginationRequest {
+ this.ownership + "' Status '" + this.statusList + "' owner '" + this.owner + "' groupId: " + this.groupId + this.ownership + "' Status '" + this.statusList + "' owner '" + this.owner + "' groupId: " + this.groupId
+ " start index: " + this.startIndex + ", SortColumns: " + this.sortColumn; + " start index: " + this.startIndex + ", SortColumns: " + this.sortColumn;
} }
public String getDeviceStatus() {
return deviceStatus;
}
public void setDeviceStatus(String deviceStatus) {
this.deviceStatus = deviceStatus;
}
public String getActionStatus() {
return actionStatus;
}
public void setActionStatus(String actionStatus) {
this.actionStatus = actionStatus;
}
public String getActionType() {
return actionType;
}
public void setActionType(String actionType) {
this.actionType = actionType;
}
public String getActionTriggeredBy() {
return actionTriggeredBy;
}
public void setActionTriggeredBy(String actionTriggeredBy) {
this.actionTriggeredBy = actionTriggeredBy;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getTabActionStatus() {
return tabActionStatus;
}
public void setTabActionStatus(String tabActionStatus) {
this.tabActionStatus = tabActionStatus;
}
public int getDeviceTypeId() {
return deviceTypeId;
}
public void setDeviceTypeId(int deviceTypeId) {
this.deviceTypeId = deviceTypeId;
}
} }

@ -24,7 +24,6 @@ public class PolicyPaginationRequest {
private String name; private String name;
private String type; private String type;
private String status; private String status;
private String deviceType;
public PolicyPaginationRequest(int start, int rowCount) { public PolicyPaginationRequest(int start, int rowCount) {
this.startIndex = start; this.startIndex = start;
@ -71,14 +70,6 @@ public class PolicyPaginationRequest {
this.status = status; this.status = status;
} }
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
@Override @Override
public String toString() { public String toString() {
return "Group Name '" + this.name + "' num of rows: " + this.rowCount + " start index: " + this.startIndex; return "Group Name '" + this.name + "' num of rows: " + this.rowCount + " start index: " + this.startIndex;

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save