Add Windows Updates Scope

pull/406/head
Subodhinie 4 months ago
commit 502f579432

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

@ -107,6 +107,23 @@ public interface GrafanaAPIProxyService {
)
Response frontendMetrics(JsonObject body, @Context HttpHeaders headers, @Context UriInfo requestUriInfo);
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/user/auth-tokens/rotate")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Rotate authentication tokens",
tags = "Analytics",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "grafana:api:view")
})
}
)
Response rotateAuthToken(JsonObject body, @Context HttpHeaders headers, @Context UriInfo requestUriInfo);
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/dashboards/uid/{uid}")
@ -123,6 +140,22 @@ public interface GrafanaAPIProxyService {
)
Response getDashboard(@Context HttpHeaders headers, @Context UriInfo requestUriInfo) throws ClassNotFoundException;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/folders/{uid}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Grafana dashboard folder information",
tags = "Analytics",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "grafana:api:view")
})
}
)
Response getFolders(@Context HttpHeaders headers, @Context UriInfo requestUriInfo) throws ClassNotFoundException;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ -140,6 +173,23 @@ public interface GrafanaAPIProxyService {
)
Response getAnnotations(@Context HttpHeaders headers, @Context UriInfo requestUriInfo) throws ClassNotFoundException;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/prometheus/grafana/api/v1/rules")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Accessing Grafana Prometheus rule information",
tags = "Analytics",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "grafana:api:view")
})
}
)
Response prometheusRuleInfo(@Context HttpHeaders headers, @Context UriInfo requestUriInfo) throws ClassNotFoundException;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/alerts/states-for-dashboard")

@ -26,6 +26,8 @@ import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.impl.util.Grafa
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.impl.util.GrafanaRequestHandlerUtil;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.exception.GrafanaManagementException;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.bean.GrafanaPanelIdentifier;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.GrafanaConfiguration;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.GrafanaConfigurationManager;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.exception.MaliciousQueryAttempt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -56,9 +58,13 @@ public class GrafanaAPIProxyServiceImpl implements GrafanaAPIProxyService {
@Override
public Response queryDatasource(JsonObject body, @Context HttpHeaders headers, @Context UriInfo requestUriInfo) {
try {
GrafanaConfiguration configuration = GrafanaConfigurationManager.getInstance().getGrafanaConfiguration();
GrafanaPanelIdentifier panelIdentifier = GrafanaRequestHandlerUtil.getPanelIdentifier(headers);
GrafanaMgtAPIUtils.getGrafanaQueryService().buildSafeQuery(body, panelIdentifier.getDashboardId(),
panelIdentifier.getPanelId(), requestUriInfo.getRequestUri());
boolean queryValidationConfig = configuration.getValidationConfig().getDSQueryValidation();
if (queryValidationConfig) {
GrafanaMgtAPIUtils.getGrafanaQueryService().buildSafeQuery(body, panelIdentifier.getDashboardId(),
panelIdentifier.getPanelId(), requestUriInfo.getRequestUri());
}
return GrafanaRequestHandlerUtil.proxyPassPostRequest(body, requestUriInfo, panelIdentifier.getOrgId());
} catch (MaliciousQueryAttempt e) {
return Response.status(Response.Status.BAD_REQUEST).entity(
@ -83,6 +89,15 @@ public class GrafanaAPIProxyServiceImpl implements GrafanaAPIProxyService {
return proxyPassPostRequest(body, headers, requestUriInfo);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/user/auth-tokens/rotate")
@Override
public Response rotateAuthToken(JsonObject body, @Context HttpHeaders headers, @Context UriInfo requestUriInfo) {
return proxyPassPostRequest(body, headers, requestUriInfo);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/dashboards/uid/{uid}")
@ -91,6 +106,14 @@ public class GrafanaAPIProxyServiceImpl implements GrafanaAPIProxyService {
return proxyPassGetRequest(headers, requestUriInfo);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/folders/{uid}")
@Override
public Response getFolders(@Context HttpHeaders headers, @Context UriInfo requestUriInfo) {
return proxyPassGetRequest(headers, requestUriInfo);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ -99,6 +122,16 @@ public class GrafanaAPIProxyServiceImpl implements GrafanaAPIProxyService {
public Response getAnnotations(@Context HttpHeaders headers, @Context UriInfo requestUriInfo) {
return proxyPassGetRequest(headers, requestUriInfo);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/prometheus/grafana/api/v1/rules")
@Override
public Response prometheusRuleInfo(@Context HttpHeaders headers, @Context UriInfo requestUriInfo) {
return proxyPassGetRequest(headers, requestUriInfo);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/alerts/states-for-dashboard")

@ -22,6 +22,8 @@ import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.bean.ErrorRespo
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.api.exception.RefererNotValid;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.common.exception.GrafanaManagementException;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.bean.GrafanaPanelIdentifier;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.GrafanaConfiguration;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.GrafanaConfigurationManager;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.exception.GrafanaEnvVariablesNotDefined;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.util.GrafanaConstants;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.util.GrafanaUtil;
@ -120,19 +122,23 @@ public class GrafanaRequestHandlerUtil {
return path;
}
public static GrafanaPanelIdentifier getPanelIdentifier(HttpHeaders headers) throws RefererNotValid {
public static GrafanaPanelIdentifier getPanelIdentifier(HttpHeaders headers) throws RefererNotValid, GrafanaManagementException {
String referer = headers.getHeaderString(GrafanaConstants.REFERER_HEADER);
if(referer == null) {
if (referer == null) {
String errMsg = "Request does not contain Referer header";
log.error(errMsg);
throw new RefererNotValid(errMsg);
}
GrafanaConfiguration configuration = GrafanaConfigurationManager.getInstance().getGrafanaConfiguration();
boolean dashboardIntegrationConfig = configuration.getValidationConfig().getDashboardIntegration();
GrafanaPanelIdentifier panelIdentifier = GrafanaUtil.getPanelIdentifierFromReferer(referer);
if(panelIdentifier.getDashboardId() == null ||
panelIdentifier.getPanelId() == null || panelIdentifier.getOrgId() == null) {
String errMsg = "Referer must contain dashboardId, panelId and orgId";
log.error(errMsg);
throw new RefererNotValid(errMsg);
if (!dashboardIntegrationConfig) {
if (panelIdentifier.getDashboardId() == null ||
panelIdentifier.getPanelId() == null || panelIdentifier.getOrgId() == null) {
String errMsg = "Referer must contain dashboardId, panelId, and orgId";
log.error(errMsg);
throw new RefererNotValid(errMsg);
}
}
return panelIdentifier;
}

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

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

@ -19,6 +19,7 @@
package io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.xml.bean.CacheConfiguration;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.xml.bean.ValidationConfig;
import io.entgra.device.mgt.core.analytics.mgt.grafana.proxy.core.config.xml.bean.User;
import javax.xml.bind.annotation.XmlElement;
@ -30,6 +31,7 @@ import java.util.List;
public class GrafanaConfiguration {
private User adminUser;
private ValidationConfig validationConfig;
private List<CacheConfiguration> caches;
@XmlElement(name = "AdminUser")
@ -37,6 +39,15 @@ public class GrafanaConfiguration {
return adminUser;
}
@XmlElement(name = "ValidationConfig")
public ValidationConfig getValidationConfig() {
return validationConfig;
}
public void setValidationConfig(ValidationConfig validationConfig) {
this.validationConfig = validationConfig;
}
public void setAdminUser(User user) {
this.adminUser = user;
}

@ -0,0 +1,45 @@
/*
* 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.analytics.mgt.grafana.proxy.core.config.xml.bean;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ValidationConfig")
public class ValidationConfig {
private boolean dsQueryValidation;
private boolean dashboardIntegration;
@XmlElement(name = "DSQueryValidation")
public boolean getDSQueryValidation() {
return dsQueryValidation;
}
public void setDSQueryValidation(boolean dsQueryValidation) {
this.dsQueryValidation = dsQueryValidation;
}
@XmlElement(name = "DashboardIntegration")
public boolean getDashboardIntegration() {
return dashboardIntegration;
}
public void setDashboardIntegration(boolean dashboardIntegration) {
this.dashboardIntegration = dashboardIntegration;
}
}

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

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

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

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

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

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

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

@ -120,7 +120,9 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices {
throw new BadRequestException(msg);
} else if (HttpStatus.SC_NOT_FOUND == response.code()) {
String msg = "Shared scope key not found : " + key;
log.info(msg);
if (log.isDebugEnabled()) {
log.debug(msg);
}
return false;
} else {
String msg = "Response : " + response.code() + response.body();

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

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

@ -22,7 +22,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.42-SNAPSHOT</version>
<version>5.1.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -205,7 +205,9 @@
org.wso2.carbon.utils;version="4.6",
org.wso2.carbon.utils.multitenancy;version="4.6",
org.apache.commons.lang,
org.json
org.json,
io.entgra.device.mgt.core.device.mgt.common.permission.mgt,
io.entgra.device.mgt.core.device.mgt.core.permission.mgt
</Import-Package>
<Embed-Dependency>
jsr311-api;scope=compile|runtime;inline=false

@ -46,6 +46,7 @@ import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig;
import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermission;
import io.entgra.device.mgt.core.device.mgt.core.config.permission.DefaultPermissions;
import io.entgra.device.mgt.core.device.mgt.core.config.permission.ScopeMapping;
import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -68,6 +69,8 @@ import org.wso2.carbon.user.core.tenant.TenantSearchResult;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils;
import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException;
import java.io.BufferedReader;
import java.io.File;
@ -610,9 +613,17 @@ public class APIPublisherServiceImpl implements APIPublisherService {
if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getName())) {
publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope);
// todo: permission changed in update path, is not handled yet.
} else {
// todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list
log.warn(scope.getName() + " not available as shared scope");
// This scope doesn't have an api attached.
log.warn(scope.getName() + " not available as shared, add as new scope");
publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
// add permission if not exist
try {
PermissionUtils.putPermission(permission);
} catch(PermissionManagementException e) {
log.error("Error when adding permission ", e);
}
}
}
for (String role : rolePermissions.keySet()) {

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

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

@ -25,16 +25,52 @@ public class ApplicationArtifact {
private String installerName;
private InputStream installerStream;
private String installerPath;
private String bannerName;
private InputStream bannerStream;
private String bannerPath;
private String iconName;
private InputStream iconStream;
private String iconPath;
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() {
return installerName;

@ -0,0 +1,103 @@
/*
* 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 CategorizedSubscriptionResult {
private List<DeviceSubscriptionData> installedDevices;
private List<DeviceSubscriptionData> pendingDevices;
private List<DeviceSubscriptionData> errorDevices;
private List<DeviceSubscriptionData> newDevices;
private List<DeviceSubscriptionData> subscribedDevices;
public CategorizedSubscriptionResult(List<DeviceSubscriptionData> installedDevices,
List<DeviceSubscriptionData> pendingDevices,
List<DeviceSubscriptionData> errorDevices) {
this.installedDevices = installedDevices;
this.pendingDevices = pendingDevices;
this.errorDevices = errorDevices;
this.newDevices = null;
this.subscribedDevices = null;
}
public CategorizedSubscriptionResult(List<DeviceSubscriptionData> installedDevices,
List<DeviceSubscriptionData> pendingDevices,
List<DeviceSubscriptionData> errorDevices,
List<DeviceSubscriptionData> newDevices) {
this.installedDevices = installedDevices;
this.pendingDevices = pendingDevices;
this.errorDevices = errorDevices;
this.newDevices = newDevices;
this.subscribedDevices = null;
}
public CategorizedSubscriptionResult(List<DeviceSubscriptionData> installedDevices,
List<DeviceSubscriptionData> pendingDevices,
List<DeviceSubscriptionData> errorDevices,
List<DeviceSubscriptionData> newDevices,
List<DeviceSubscriptionData> subscribedDevices) {
this.installedDevices = installedDevices;
this.pendingDevices = pendingDevices;
this.errorDevices = errorDevices;
this.newDevices = newDevices;
this.subscribedDevices = subscribedDevices;
}
public List<DeviceSubscriptionData> getInstalledDevices() {
return installedDevices;
}
public void setInstalledDevices(List<DeviceSubscriptionData> installedDevices) {
this.installedDevices = installedDevices;
}
public List<DeviceSubscriptionData> getPendingDevices() {
return pendingDevices;
}
public void setPendingDevices(List<DeviceSubscriptionData> pendingDevices) {
this.pendingDevices = pendingDevices;
}
public List<DeviceSubscriptionData> getErrorDevices() {
return errorDevices;
}
public void setErrorDevices(List<DeviceSubscriptionData> errorDevices) {
this.errorDevices = errorDevices;
}
public List<DeviceSubscriptionData> getNewDevices() {
return newDevices;
}
public void setNewDevices(List<DeviceSubscriptionData> newDevices) {
this.newDevices = newDevices;
}
public List<DeviceSubscriptionData> getSubscribedDevices() {
return subscribedDevices;
}
public void setSubscribedDevices(List<DeviceSubscriptionData> subscribedDevices) {
this.subscribedDevices = subscribedDevices;
}
}

@ -26,12 +26,22 @@ public class DeviceSubscriptionData {
private int subId;
private String action;
private long actionTriggeredTimestamp;
private Timestamp actionTriggeredTimestamp;
private String actionTriggeredFrom;
private String actionTriggeredBy;
private String actionType;
private String status;
private Device device;
private String currentInstalledVersion;
private int deviceId;
private String deviceOwner;
private String deviceStatus;
private boolean unsubscribed;
private String unsubscribedBy;
private Timestamp unsubscribedTimestamp;
private String deviceName;
private String deviceIdentifier;
private String type;
public String getAction() {
return action;
@ -41,14 +51,6 @@ public class DeviceSubscriptionData {
this.action = action;
}
public long getActionTriggeredTimestamp() {
return actionTriggeredTimestamp;
}
public void setActionTriggeredTimestamp(long actionTriggeredTimestamp) {
this.actionTriggeredTimestamp = actionTriggeredTimestamp;
}
public String getActionTriggeredBy() {
return actionTriggeredBy;
}
@ -81,9 +83,13 @@ public class DeviceSubscriptionData {
this.device = device;
}
public String getCurrentInstalledVersion() { return currentInstalledVersion; }
public String getCurrentInstalledVersion() {
return currentInstalledVersion;
}
public void setCurrentInstalledVersion(String currentInstalledVersion) { this.currentInstalledVersion = currentInstalledVersion; }
public void setCurrentInstalledVersion(String currentInstalledVersion) {
this.currentInstalledVersion = currentInstalledVersion;
}
public int getSubId() {
return subId;
@ -92,4 +98,92 @@ public class DeviceSubscriptionData {
public void setSubId(int subId) {
this.subId = subId;
}
public int getDeviceId() {
return deviceId;
}
public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}
public String getActionTriggeredFrom() {
return actionTriggeredFrom;
}
public void setActionTriggeredFrom(String actionTriggeredFrom) {
this.actionTriggeredFrom = actionTriggeredFrom;
}
public Timestamp getActionTriggeredTimestamp() {
return actionTriggeredTimestamp;
}
public void setActionTriggeredTimestamp(Timestamp actionTriggeredTimestamp) {
this.actionTriggeredTimestamp = actionTriggeredTimestamp;
}
public String getDeviceOwner() {
return deviceOwner;
}
public void setDeviceOwner(String deviceOwner) {
this.deviceOwner = deviceOwner;
}
public String getDeviceStatus() {
return deviceStatus;
}
public void setDeviceStatus(String deviceStatus) {
this.deviceStatus = deviceStatus;
}
public boolean isUnsubscribed() {
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 String getDeviceName() {
return deviceName;
}
public void setDeviceName(String 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;
}
}

@ -118,6 +118,11 @@ public class Filter {
*/
private boolean isNotRetired;
/**
* To check whether web applications should be returned
*/
private boolean withWebApps;
public int getLimit() {
return limit;
}
@ -221,4 +226,12 @@ public class Filter {
public void setNotRetired(boolean notRetired) {
isNotRetired = notRetired;
}
public boolean isWithWebApps() {
return withWebApps;
}
public void setWithWebApps(boolean withWebApps) {
this.withWebApps = withWebApps;
}
}

@ -0,0 +1,55 @@
/*
* 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 CategorizedSubscriptionCountsDTO {
private String subscriptionType;
private int subscriptionCount;
private int unsubscriptionCount;
public CategorizedSubscriptionCountsDTO(String subscriptionType, int subscriptionCount, int unsubscriptionCount) {
this.subscriptionType = subscriptionType;
this.subscriptionCount = subscriptionCount;
this.unsubscriptionCount = unsubscriptionCount;
}
public String getSubscriptionType() {
return subscriptionType;
}
public void setSubscriptionType(String subscriptionType) {
this.subscriptionType = subscriptionType;
}
public int getSubscriptionCount() {
return subscriptionCount;
}
public void setSubscriptionCount(int subscriptionCount) {
this.subscriptionCount = subscriptionCount;
}
public int getUnsubscriptionCount() {
return unsubscriptionCount;
}
public void setUnsubscriptionCount(int unsubscriptionCount) {
this.unsubscriptionCount = unsubscriptionCount;
}
}

@ -0,0 +1,126 @@
/*
* 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;
import io.entgra.device.mgt.core.device.mgt.core.dto.OperationResponseDTO;
import java.sql.Timestamp;
import java.util.List;
public class DeviceOperationDTO {
private int deviceId;
private String uuid;
private String status;
private int operationId;
private String actionTriggeredFrom;
private Timestamp actionTriggeredAt;
private int appReleaseId;
private String operationCode;
private Object operationDetails;
private Object operationProperties;
private List<OperationResponseDTO> operationResponses;
public int getDeviceId() {
return deviceId;
}
public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getOperationId() {
return operationId;
}
public void setOperationId(int operationId) {
this.operationId = operationId;
}
public String getActionTriggeredFrom() {
return actionTriggeredFrom;
}
public void setActionTriggeredFrom(String actionTriggeredFrom) {
this.actionTriggeredFrom = actionTriggeredFrom;
}
public Timestamp getActionTriggeredAt() {
return actionTriggeredAt;
}
public void setActionTriggeredAt(Timestamp actionTriggeredAt) {
this.actionTriggeredAt = actionTriggeredAt;
}
public int getAppReleaseId() {
return appReleaseId;
}
public void setAppReleaseId(int appReleaseId) {
this.appReleaseId = appReleaseId;
}
public String getOperationCode() {
return operationCode;
}
public void setOperationCode(String operationCode) {
this.operationCode = operationCode;
}
public Object getOperationDetails() {
return operationDetails;
}
public void setOperationDetails(Object operationDetails) {
this.operationDetails = operationDetails;
}
public Object getOperationProperties() {
return operationProperties;
}
public void setOperationProperties(Object operationProperties) {
this.operationProperties = operationProperties;
}
public List<OperationResponseDTO> getOperationResponses() {
return operationResponses;
}
public void setOperationResponses(List<OperationResponseDTO> operationResponses) {
this.operationResponses = operationResponses;
}
}

@ -31,44 +31,94 @@ public class DeviceSubscriptionDTO {
private String actionTriggeredFrom;
private String status;
private int deviceId;
private int appReleaseId;
private String appUuid;
public int getId() { return id; }
public int getId() {
return id;
}
public void setId(int id) { this.id = id; }
public void setId(int id) {
this.id = id;
}
public String getSubscribedBy() { return subscribedBy; }
public String getSubscribedBy() {
return subscribedBy;
}
public void setSubscribedBy(String subscribedBy) { this.subscribedBy = subscribedBy; }
public void setSubscribedBy(String subscribedBy) {
this.subscribedBy = subscribedBy;
}
public Timestamp getSubscribedTimestamp() { return subscribedTimestamp; }
public Timestamp getSubscribedTimestamp() {
return subscribedTimestamp;
}
public void setSubscribedTimestamp(Timestamp subscribedTimestamp) {
this.subscribedTimestamp = subscribedTimestamp;
}
public boolean isUnsubscribed() { return isUnsubscribed; }
public boolean isUnsubscribed() {
return isUnsubscribed;
}
public void setUnsubscribed(boolean unsubscribed) { isUnsubscribed = unsubscribed; }
public void setUnsubscribed(boolean unsubscribed) {
isUnsubscribed = unsubscribed;
}
public String getUnsubscribedBy() { return unsubscribedBy; }
public String getUnsubscribedBy() {
return unsubscribedBy;
}
public void setUnsubscribedBy(String unsubscribedBy) { this.unsubscribedBy = unsubscribedBy; }
public void setUnsubscribedBy(String unsubscribedBy) {
this.unsubscribedBy = unsubscribedBy;
}
public Timestamp getUnsubscribedTimestamp() { return unsubscribedTimestamp; }
public Timestamp getUnsubscribedTimestamp() {
return unsubscribedTimestamp;
}
public void setUnsubscribedTimestamp(Timestamp unsubscribedTimestamp) {
this.unsubscribedTimestamp = unsubscribedTimestamp;
}
public String getActionTriggeredFrom() { return actionTriggeredFrom; }
public String getActionTriggeredFrom() {
return actionTriggeredFrom;
}
public void setActionTriggeredFrom(String actionTriggeredFrom) {
this.actionTriggeredFrom = actionTriggeredFrom;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getDeviceId() {
return deviceId;
}
public void setActionTriggeredFrom(String actionTriggeredFrom) { this.actionTriggeredFrom = actionTriggeredFrom; }
public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}
public String getStatus() { return status; }
public int getAppReleaseId() {
return appReleaseId;
}
public void setStatus(String status) { this.status = status; }
public void setAppReleaseId(int appReleaseId) {
this.appReleaseId = appReleaseId;
}
public int getDeviceId() { return deviceId; }
public String getAppUuid() {
return appUuid;
}
public void setDeviceId(int deviceId) { this.deviceId = deviceId; }
public void setAppUuid(String appUuid) {
this.appUuid = appUuid;
}
}

@ -0,0 +1,60 @@
/*
* 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;
import io.entgra.device.mgt.core.application.mgt.common.CategorizedSubscriptionResult;
import java.util.Map;
public class DeviceSubscriptionResponseDTO {
private int deviceCount;
private Map<String, Double> statusPercentages;
private CategorizedSubscriptionResult devices;
public DeviceSubscriptionResponseDTO(int deviceCount, Map<String, Double> statusPercentages,
CategorizedSubscriptionResult devices) {
this.deviceCount = deviceCount;
this.statusPercentages = statusPercentages;
this.devices = devices;
}
public int getDeviceCount() {
return deviceCount;
}
public void setDeviceCount(int deviceCount) {
this.deviceCount = deviceCount;
}
public Map<String, Double> getStatusPercentages() {
return statusPercentages;
}
public void setStatusPercentages(Map<String, Double> statusPercentages) {
this.statusPercentages = statusPercentages;
}
public CategorizedSubscriptionResult getDevices() {
return devices;
}
public void setDevices(CategorizedSubscriptionResult devices) {
this.devices = devices;
}
}

@ -22,6 +22,7 @@ import java.sql.Timestamp;
public class GroupSubscriptionDTO {
private int id;
private String groupName;
private String subscribedBy;
private Timestamp subscribedTimestamp;
private boolean isUnsubscribed;
@ -29,6 +30,7 @@ public class GroupSubscriptionDTO {
private Timestamp unsubscribedTimestamp;
private String subscribedFrom;
private int groupdId;
private int appReleaseId;
public int getId() { return id; }
@ -61,4 +63,20 @@ public class GroupSubscriptionDTO {
public int getGroupdId() { return groupdId; }
public void setGroupdId(int groupdId) { this.groupdId = groupdId; }
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public int getAppReleaseId() {
return appReleaseId;
}
public void setAppReleaseId(int appReleaseId) {
this.appReleaseId = appReleaseId;
}
}

@ -18,51 +18,115 @@
package io.entgra.device.mgt.core.application.mgt.common.dto;
import io.entgra.device.mgt.core.application.mgt.common.CategorizedSubscriptionResult;
import java.sql.Timestamp;
import java.util.Map;
public class RoleSubscriptionDTO {
private int id;
private String subscribedBy;
private Timestamp subscribedTimestamp;
private boolean isUnsubscribed;
private boolean unsubscribed;
private String unsubscribedBy;
private Timestamp unsubscribedTimestamp;
private String subscribedFrom;
private String roleName;
private int appReleaseId;
private int deviceCount;
private Map<String, Double> statusPercentages;
private CategorizedSubscriptionResult devices;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getSubscribedBy() { return subscribedBy; }
public String getSubscribedBy() {
return subscribedBy;
}
public void setSubscribedBy(String subscribedBy) { this.subscribedBy = subscribedBy; }
public void setSubscribedBy(String subscribedBy) {
this.subscribedBy = subscribedBy;
}
public Timestamp getSubscribedTimestamp() { return subscribedTimestamp; }
public Timestamp getSubscribedTimestamp() {
return subscribedTimestamp;
}
public void setSubscribedTimestamp(Timestamp subscribedTimestamp) {
this.subscribedTimestamp = subscribedTimestamp;
}
public boolean isUnsubscribed() { return isUnsubscribed; }
public boolean getUnsubscribed() {
return unsubscribed;
}
public void setUnsubscribed(boolean unsubscribed) { isUnsubscribed = unsubscribed; }
public void setUnsubscribed(boolean unsubscribed) {
this.unsubscribed = unsubscribed;
}
public String getUnsubscribedBy() { return unsubscribedBy; }
public boolean isUnsubscribed() {
return isUnsubscribed;
}
public void setUnsubscribedBy(String unsubscribedBy) { this.unsubscribedBy = unsubscribedBy; }
public String getUnsubscribedBy() {
return unsubscribedBy;
}
public void setUnsubscribedBy(String unsubscribedBy) {
this.unsubscribedBy = unsubscribedBy;
}
public Timestamp getUnsubscribedTimestamp() { return unsubscribedTimestamp; }
public Timestamp getUnsubscribedTimestamp() {
return unsubscribedTimestamp;
}
public void setUnsubscribedTimestamp(Timestamp unsubscribedTimestamp) {
this.unsubscribedTimestamp = unsubscribedTimestamp;
}
public String getSubscribedFrom() { return subscribedFrom; }
public String getSubscribedFrom() {
return subscribedFrom;
}
public void setSubscribedFrom(String subscribedFrom) {
this.subscribedFrom = subscribedFrom;
}
public String getRoleName() {
return roleName;
}
public void setSubscribedFrom(String subscribedFrom) { this.subscribedFrom = subscribedFrom; }
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleName() { return roleName; }
public int getAppReleaseId() {
return appReleaseId;
}
public void setAppReleaseId(int appReleaseId) {
this.appReleaseId = appReleaseId;
}
public int getDeviceCount() {
return deviceCount;
}
public void setDeviceCount(int deviceCount) {
this.deviceCount = deviceCount;
}
public Map<String, Double> getStatusPercentages() {
return statusPercentages;
}
public void setStatusPercentages(Map<String, Double> statusPercentages) {
this.statusPercentages = statusPercentages;
}
public CategorizedSubscriptionResult getDevices() {
return devices;
}
public void setDevices(CategorizedSubscriptionResult devices) {
this.devices = devices;
}
public void setRoleName(String roleName) { this.roleName = roleName; }
}

@ -0,0 +1,52 @@
/*
* 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;
import java.util.List;
public class SubscriptionResponseDTO {
private String UUID;
private List<SubscriptionsDTO> subscriptions;
private List<DeviceOperationDTO> DevicesOperations;
public String getUUID() {
return UUID;
}
public void setUUID(String UUID) {
this.UUID = UUID;
}
public List<DeviceOperationDTO> getDevicesOperations() {
return DevicesOperations;
}
public void setDevicesOperations(List<DeviceOperationDTO> devicesOperations) {
DevicesOperations = devicesOperations;
}
public List<SubscriptionsDTO> getSubscriptions() {
return subscriptions;
}
public void setSubscriptions(List<SubscriptionsDTO> subscriptions) {
this.subscriptions = subscriptions;
}
}

@ -0,0 +1,162 @@
/*
* 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;
import io.entgra.device.mgt.core.application.mgt.common.CategorizedSubscriptionResult;
import java.sql.Timestamp;
import java.util.Map;
public class SubscriptionsDTO {
private int id;
private String owner;
private String name;
private String subscribedBy;
private Timestamp subscribedTimestamp;
private boolean unsubscribed;
private String unsubscribedBy;
private Timestamp unsubscribedTimestamp;
private String subscribedFrom;
private int appReleaseId;
private int deviceCount;
private String deviceOwner;
private String deviceStatus;
private Map<String, Double> statusPercentages;
private CategorizedSubscriptionResult devices;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 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 String getSubscribedFrom() {
return subscribedFrom;
}
public void setSubscribedFrom(String subscribedFrom) {
this.subscribedFrom = subscribedFrom;
}
public int getAppReleaseId() {
return appReleaseId;
}
public void setAppReleaseId(int appReleaseId) {
this.appReleaseId = appReleaseId;
}
public int getDeviceCount() {
return deviceCount;
}
public void setDeviceCount(int deviceCount) {
this.deviceCount = deviceCount;
}
public String getDeviceOwner() {
return deviceOwner;
}
public void setDeviceOwner(String deviceOwner) {
this.deviceOwner = deviceOwner;
}
public String getDeviceStatus() {
return deviceStatus;
}
public void setDeviceStatus(String deviceStatus) {
this.deviceStatus = deviceStatus;
}
public Map<String, Double> getStatusPercentages() {
return statusPercentages;
}
public void setStatusPercentages(Map<String, Double> statusPercentages) {
this.statusPercentages = statusPercentages;
}
public CategorizedSubscriptionResult getDevices() {
return devices;
}
public void setDevices(CategorizedSubscriptionResult devices) {
this.devices = devices;
}
public boolean getUnsubscribed() {
return unsubscribed;
}
public void setUnsubscribed(boolean unsubscribed) {
this.unsubscribed = unsubscribed;
}
}

@ -546,5 +546,20 @@ public interface ApplicationManager {
* @throws ApplicationManagementException thrown if an error occurs when deleting data
*/
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;
/**
* 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,4 +140,14 @@ public interface ApplicationStorageManager {
* @throws ApplicationStorageManagementException thrown if
*/
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);
}

@ -18,11 +18,16 @@
package io.entgra.device.mgt.core.application.mgt.common.services;
import io.entgra.device.mgt.core.application.mgt.common.ApplicationInstallResponse;
import io.entgra.device.mgt.core.application.mgt.common.CategorizedSubscriptionResult;
import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus;
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.ScheduledSubscriptionDTO;
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.DeviceSubscriptionResponseDTO;
import io.entgra.device.mgt.core.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException;
import io.entgra.device.mgt.core.application.mgt.common.SubscriptionType;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.PaginationResult;
@ -194,7 +199,7 @@ public interface SubscriptionManager {
* application release for given UUID, if an error occurred while getting device details of subscribed device ids,
* if an error occurred while getting subscription details of given application release UUID.
*/
PaginationResult getAppSubscriptionDetails(PaginationRequest request, String appUUID, String actionStatus, String action, String installedVersion)
CategorizedSubscriptionResult getAppSubscriptionDetails(PaginationRequest request, String appUUID, String actionStatus, String action, String installedVersion)
throws ApplicationManagementException;
/***
@ -217,4 +222,92 @@ public interface SubscriptionManager {
* @throws {@link SubscriptionManagementException} Exception of the subscription management
*/
Activity getOperationAppDetails(String id) throws SubscriptionManagementException;
/**
* Retrieves the group details associated with a given app release UUID.
*
* @param uuid the UUID of the app release
* @param subscriptionStatus the status of the subscription (subscribed or unsubscribed)
* @param offset the offset for the data set
* @param limit the limit for the data set
* @return {@link SubscriptionsDTO} which contains the details of subscriptions.
* @throws ApplicationManagementException if an error occurs while fetching the group details
*/
List<SubscriptionsDTO> getGroupsSubscriptionDetailsByUUID(String uuid, String subscriptionStatus, int offset, int limit)
throws ApplicationManagementException;
/**
* Retrieves the user details associated with a given app release UUID.
*
* @param uuid the UUID of the app release
* @param subscriptionStatus the status of the subscription (subscribed or unsubscribed)
* @param offset the offset for the data set
* @param limit the limit for the data set
* @return {@link SubscriptionsDTO} which contains the details of subscriptions.
* @throws ApplicationManagementException if an error occurs while fetching the user details
*/
List<SubscriptionsDTO> getUserSubscriptionsByUUID(String uuid, String subscriptionStatus, 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
*/
List<SubscriptionsDTO> getRoleSubscriptionsByUUID(String uuid, String subscriptionStatus, int offset, int limit)
throws ApplicationManagementException;
/**
* Retrieves the Device Subscription details associated with a given app release UUID.
*
* @param uuid the UUID of the app release
* @param subscriptionStatus the status of the subscription (subscribed or unsubscribed)
* @param offset the offset for the data set
* @param limit the limit for the data set
* @return {@link DeviceSubscriptionResponseDTO} which contains the details of device subscriptions.
* @throws ApplicationManagementException if an error occurs while fetching the device subscription details
*/
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.
*
* @param deviceId the deviceId of the device that need to get operation details.
* @param uuid the UUID of the application release.
* @return {@link DeviceOperationDTO} which contains the details of device subscriptions.
* @throws SubscriptionManagementException if there is an error while fetching the details.
*/
List<DeviceOperationDTO> getSubscriptionOperationsByUUIDAndDeviceID(int deviceId, String uuid)
throws ApplicationManagementException;
/**
* This method is responsible for retrieving device counts details related to the given UUID.
*
* @param uuid the UUID of the application release.
* @return {@link List<CategorizedSubscriptionCountsDTO>} which contains counts of subscriptions
and unsubscription for each subscription type.
* @throws SubscriptionManagementException if there is an error while fetching the details.
*/
List<CategorizedSubscriptionCountsDTO> getSubscriptionCountsByUUID(String uuid)
throws ApplicationManagementException;
}

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

@ -18,8 +18,11 @@
package io.entgra.device.mgt.core.application.mgt.core.dao;
import io.entgra.device.mgt.core.application.mgt.common.ExecutionStatus;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.GroupSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.SubscriptionsDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.ApplicationReleaseDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.DeviceOperationDTO;
import io.entgra.device.mgt.core.application.mgt.common.dto.ScheduledSubscriptionDTO;
import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionManagementException;
import io.entgra.device.mgt.core.application.mgt.core.exception.ApplicationManagementDAOException;
@ -312,4 +315,199 @@ public interface SubscriptionDAO {
* @throws ApplicationManagementDAOException thrown if an error occurs while deleting data
*/
void deleteScheduledSubscriptionByTenant(int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the details of group subscriptions related to a appReleaseId.
*
* @param appReleaseId the appReleaseId of the application release.
* @param unsubscribe the Status of the subscription.
* @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 GroupSubscriptionDTO} which contains the details of group subscriptions.
* @throws ApplicationManagementDAOException if connection establishment fails.
*/
List<GroupSubscriptionDTO> getGroupsSubscriptionDetailsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException;
/**
* This method is used to get the details of user subscriptions related to a appReleaseId.
*
* @param appReleaseId the appReleaseId of the application release.
* @param unsubscribe the Status of the subscription.
* @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 SubscriptionsDTO} which contains the details of subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
List<SubscriptionsDTO> getUserSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId,
int offset, int limit) throws ApplicationManagementDAOException;
/**
* This method is used to get the details of role subscriptions related to a appReleaseId.
*
* @param appReleaseId the appReleaseId of the application release.
* @param unsubscribe the Status of the subscription.
* @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 SubscriptionsDTO} which contains the details of subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
List<SubscriptionsDTO> getRoleSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException;
/**
* This method is used to get the details of device subscriptions related to a appReleaseId.
*
* @param appReleaseId the appReleaseId of the application release.
* @param unsubscribe the Status of the subscription.
* @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 DeviceSubscriptionDTO} which contains the details of device subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
List<DeviceSubscriptionDTO> getDeviceSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException;
/**
* This method is used to get the details of device subscriptions related to a UUID.
*
* @param appReleaseId the appReleaseId of the application release.
* @param deviceId the deviceId of the device that need to get operation details.
* @param tenantId id of the current tenant.
* @return {@link DeviceOperationDTO} which contains the details of device subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
List<DeviceOperationDTO> getSubscriptionOperationsByAppReleaseIDAndDeviceID(int appReleaseId, int deviceId, int tenantId)
throws ApplicationManagementDAOException;
/**
* This method is used to get the details of device subscriptions related to a UUID.
*
* @param appReleaseId the appReleaseId of the application release.
* @param unsubscribe the Status of the subscription.
* @param tenantId id of the current tenant.
* @param deviceIds deviceIds deviceIds to retrieve data.
* @return {@link DeviceOperationDTO} which contains the details of device subscriptions.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
List<DeviceSubscriptionDTO> getSubscriptionDetailsByDeviceIds(int appReleaseId, boolean unsubscribe, int tenantId, List<Integer> deviceIds)
throws ApplicationManagementDAOException;
/**
* This method is used to get the details of device subscriptions related to a UUID.
*
* @param appReleaseId the appReleaseId of the application release.
* @param unsubscribe the Status of the subscription.
* @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.
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
List<DeviceSubscriptionDTO> getAllSubscriptionsDetails(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of all subscription types related to a UUID.
*
* @param appReleaseId the appReleaseId of the application release.
* @param tenantId id of the current tenant.
* @return {@link int} which contains the count of the subscription type
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
int getAllSubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of all unsubscription types related to a UUID.
*
* @param appReleaseId the UUID of the application release.
* @param tenantId id of the current tenant.
* @return {@link int} which contains the count of the subscription type
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
int getAllUnsubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of device subscriptions related to a UUID.
*
* @param appReleaseId the UUID of the application release.
* @param tenantId id of the current tenant.
* @return {@link int} which contains the count of the subscription type
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
int getDeviceSubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of device unsubscription related to a UUID.
*
* @param appReleaseId the UUID of the application release.
* @param tenantId id of the current tenant.
* @return {@link int} which contains the count of the subscription type
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
int getDeviceUnsubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of group subscriptions related to a UUID.
*
* @param appReleaseId the UUID of the application release.
* @param tenantId id of the current tenant.
* @return {@link int} which contains the count of the subscription type
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
int getGroupSubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of group unsubscription related to a UUID.
*
* @param appReleaseId the UUID of the application release.
* @param tenantId id of the current tenant.
* @return {@link int} which contains the count of the subscription type
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
int getGroupUnsubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of role subscriptions related to a UUID.
*
* @param appReleaseId the UUID of the application release.
* @param tenantId id of the current tenant.
* @return {@link int} which contains the count of the subscription type
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
int getRoleSubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of role unsubscription related to a UUID.
*
* @param appReleaseId the UUID of the application release.
* @param tenantId id of the current tenant.
* @return {@link int} which contains the count of the subscription type
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
int getRoleUnsubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of user subscriptions related to a UUID.
*
* @param appReleaseId the UUID of the application release.
* @param tenantId id of the current tenant.
* @return {@link int} which contains the count of the subscription type
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
int getUserSubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
/**
* This method is used to get the counts of user unsubscription related to a UUID.
*
* @param appReleaseId the UUID of the application release.
* @param tenantId id of the current tenant.
* @return {@link int} which contains the count of the subscription type
* @throws ApplicationManagementDAOException if connection establishment or SQL execution fails.
*/
int getUserUnsubscriptionCount(int appReleaseId, int tenantId) throws ApplicationManagementDAOException;
}

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

@ -17,6 +17,9 @@
*/
package io.entgra.device.mgt.core.application.mgt.core.dao.impl.subscription;
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.SubscriptionsDTO;
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.exception.UnexpectedServerErrorException;
@ -44,6 +47,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;
public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements SubscriptionDAO {
private static final Log log = LogFactory.getLog(GenericSubscriptionDAOImpl.class);
@ -1445,13 +1449,13 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
+ "AR.PACKAGE_NAME, "
+ "AR.VERSION, "
+ "DS.SUBSCRIBED_BY, "
+ "DS.STATUS, "
+ "DS.ACTION_TRIGGERED_FROM "
+ "FROM AP_APP_SUB_OP_MAPPING SOP "
+ "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 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();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
@ -1635,4 +1639,802 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public List<GroupSubscriptionDTO> getGroupsSubscriptionDetailsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get groups related to the given AppReleaseID.");
}
try {
Connection conn = this.getDBConnection();
List<GroupSubscriptionDTO> groupDetails = new ArrayList<>();
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 " +
"LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setBoolean(2, unsubscribe);
ps.setInt(3, tenantId);
ps.setInt(4, limit);
ps.setInt(5, offset);
try (ResultSet rs = ps.executeQuery()) {
GroupSubscriptionDTO groupDetail;
while (rs.next()) {
groupDetail = new GroupSubscriptionDTO();
groupDetail.setGroupName(rs.getString("GROUP_NAME"));
groupDetail.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
groupDetail.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
groupDetail.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
groupDetail.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
groupDetail.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
groupDetail.setAppReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
groupDetails.add(groupDetail);
}
}
return groupDetails;
}
} 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<SubscriptionsDTO> getUserSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId,
int offset, int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get user subscriptions related to the given UUID.");
}
try {
Connection conn = this.getDBConnection();
List<SubscriptionsDTO> userSubscriptions = new ArrayList<>();
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 " +
"LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setBoolean(2, unsubscribe);
ps.setInt(3, tenantId);
ps.setInt(4, limit);
ps.setInt(5, offset);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
SubscriptionsDTO userSubscription;
userSubscription = new SubscriptionsDTO();
userSubscription.setName(rs.getString("USER_NAME"));
userSubscription.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
userSubscription.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
userSubscription.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
userSubscription.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
userSubscription.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
userSubscription.setAppReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
userSubscriptions.add(userSubscription);
}
}
return userSubscriptions;
}
} 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<SubscriptionsDTO> getRoleSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset,
int limit) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get role subscriptions related to the given AppReleaseID.");
}
try {
Connection conn = this.getDBConnection();
List<SubscriptionsDTO> roleSubscriptions = new ArrayList<>();
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 " +
"LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setBoolean(2, unsubscribe);
ps.setInt(3, tenantId);
ps.setInt(4, limit);
ps.setInt(5, offset);
try (ResultSet rs = ps.executeQuery()) {
SubscriptionsDTO roleSubscription;
while (rs.next()) {
roleSubscription = new SubscriptionsDTO();
roleSubscription.setName(rs.getString("ROLE_NAME"));
roleSubscription.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
roleSubscription.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
roleSubscription.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
roleSubscription.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
roleSubscription.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
roleSubscription.setAppReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
roleSubscriptions.add(roleSubscription);
}
}
return roleSubscriptions;
}
} 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<DeviceSubscriptionDTO> getDeviceSubscriptionsByAppReleaseID(int appReleaseId, boolean unsubscribe, int tenantId, int offset, int limit)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get device subscriptions related to the given AppReleaseID.");
}
try {
Connection conn = this.getDBConnection();
List<DeviceSubscriptionDTO> deviceSubscriptions = new ArrayList<>();
String subscriptionStatusTime = unsubscribe ? "DS.UNSUBSCRIBED_TIMESTAMP" : "DS.SUBSCRIBED_TIMESTAMP";
String sql = "SELECT DS.DM_DEVICE_ID, " +
"DS.SUBSCRIBED_BY, " +
"DS.SUBSCRIBED_TIMESTAMP, " +
"DS.STATUS, " +
"DS.UNSUBSCRIBED, " +
"DS.UNSUBSCRIBED_BY, " +
"DS.UNSUBSCRIBED_TIMESTAMP, " +
"DS.AP_APP_RELEASE_ID " +
"FROM AP_DEVICE_SUBSCRIPTION DS " +
"WHERE DS.AP_APP_RELEASE_ID = ? " +
"AND DS.UNSUBSCRIBED = ? " +
"AND DS.TENANT_ID = ? " +
"AND DS.ACTION_TRIGGERED_FROM = 'DEVICE' " +
"ORDER BY " + subscriptionStatusTime + " DESC " +
"LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setBoolean(2, unsubscribe);
ps.setInt(3, tenantId);
ps.setInt(4, limit);
ps.setInt(5, offset);
try (ResultSet rs = ps.executeQuery()) {
DeviceSubscriptionDTO deviceSubscription;
while (rs.next()) {
deviceSubscription = new DeviceSubscriptionDTO();
deviceSubscription.setDeviceId(rs.getInt("DM_DEVICE_ID"));
deviceSubscription.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
deviceSubscription.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_TIMESTAMP"));
deviceSubscription.setStatus(rs.getString("STATUS"));
deviceSubscription.setUnsubscribed(rs.getBoolean("UNSUBSCRIBED"));
deviceSubscription.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
deviceSubscription.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_TIMESTAMP"));
deviceSubscription.setAppReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
deviceSubscriptions.add(deviceSubscription);
}
}
return deviceSubscriptions;
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get device subscriptions for the given UUID.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "SQL Error occurred while getting device subscriptions for the given UUID.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public List<DeviceOperationDTO> getSubscriptionOperationsByAppReleaseIDAndDeviceID(
int appReleaseId, int deviceId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get device subscriptions related to the given AppReleaseID and DeviceID.");
}
try {
Connection conn = this.getDBConnection();
List<DeviceOperationDTO> deviceSubscriptions = new ArrayList<>();
String sql = "SELECT " +
" ads.DM_DEVICE_ID, " +
" aasom.OPERATION_ID, " +
" ads.STATUS, " +
" ads.ACTION_TRIGGERED_FROM, " +
" ads.SUBSCRIBED_TIMESTAMP AS ACTION_TRIGGERED_AT, " +
" ads.AP_APP_RELEASE_ID " +
"FROM AP_APP_SUB_OP_MAPPING aasom " +
"JOIN AP_DEVICE_SUBSCRIPTION ads " +
"ON aasom.AP_DEVICE_SUBSCRIPTION_ID = ads.ID " +
"WHERE ads.AP_APP_RELEASE_ID = ? " +
"AND ads.DM_DEVICE_ID = ? " +
"AND ads.TENANT_ID = ? " +
"ORDER BY aasom.OPERATION_ID DESC " +
"LIMIT 1";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, deviceId);
ps.setInt(3, tenantId);
try (ResultSet rs = ps.executeQuery()) {
DeviceOperationDTO deviceSubscription;
while (rs.next()) {
deviceSubscription = new DeviceOperationDTO();
deviceSubscription.setDeviceId(rs.getInt("DM_DEVICE_ID"));
deviceSubscription.setStatus(rs.getString("STATUS"));
deviceSubscription.setOperationId(rs.getInt("OPERATION_ID"));
deviceSubscription.setActionTriggeredFrom(rs.getString("ACTION_TRIGGERED_FROM"));
deviceSubscription.setActionTriggeredAt(rs.getTimestamp("ACTION_TRIGGERED_AT"));
deviceSubscription.setAppReleaseId(rs.getInt("AP_APP_RELEASE_ID"));
deviceSubscriptions.add(deviceSubscription);
}
}
}
return deviceSubscriptions;
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to get device subscriptions for the given AppReleaseID and DeviceID.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "SQL Error occurred while getting device subscriptions for the given AppReleaseID and DeviceID.";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public List<DeviceSubscriptionDTO> getSubscriptionDetailsByDeviceIds(int appReleaseId, boolean unsubscribe, int tenantId, List<Integer> deviceIds)
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";
String sql = "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(",")) + ") "
+ "ORDER BY " + subscriptionStatusTime + " DESC";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setBoolean(2, unsubscribe);
ps.setInt(3, tenantId);
for (int i = 0; i < deviceIds.size(); i++) {
ps.setInt(4 + i, deviceIds.get(i));
}
try (ResultSet rs = ps.executeQuery()) {
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved device subscriptions for application release id "
+ appReleaseId + " and device ids " + deviceIds);
}
List<DeviceSubscriptionDTO> subscriptions = new ArrayList<>();
while (rs.next()) {
DeviceSubscriptionDTO subscription = new DeviceSubscriptionDTO();
subscription.setId(rs.getInt("ID"));
subscription.setSubscribedBy(rs.getString("SUBSCRIBED_BY"));
subscription.setSubscribedTimestamp(rs.getTimestamp("SUBSCRIBED_AT"));
subscription.setUnsubscribed(rs.getBoolean("IS_UNSUBSCRIBED"));
subscription.setUnsubscribedBy(rs.getString("UNSUBSCRIBED_BY"));
subscription.setUnsubscribedTimestamp(rs.getTimestamp("UNSUBSCRIBED_AT"));
subscription.setActionTriggeredFrom(rs.getString("ACTION_TRIGGERED_FROM"));
subscription.setStatus(rs.getString("STATUS"));
subscription.setDeviceId(rs.getInt("DEVICE_ID"));
subscriptions.add(subscription);
}
return subscriptions;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get device subscription data for application ID: " + appReleaseId
+ " and device ids: " + deviceIds + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting device subscriptions for "
+ "application Id: " + appReleaseId + " and device ids: " + deviceIds + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public List<DeviceSubscriptionDTO> getAllSubscriptionsDetails(int appReleaseId, boolean unsubscribe, int tenantId,
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 sql = "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=? "
+ "ORDER BY " + subscriptionStatusTime + " DESC "
+ "LIMIT ? OFFSET ?";
try {
Connection conn = this.getDBConnection();
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setBoolean(2, unsubscribe);
ps.setInt(3, tenantId);
ps.setInt(4, limit);
ps.setInt(5, offset);
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 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");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT COUNT(*) AS count " +
"FROM AP_DEVICE_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = FALSE";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("count");
}
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get all subscriptions count for application appReleaseId: "
+ appReleaseId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting all subscriptions count for appReleaseId: "
+ appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int getAllUnsubscriptionCount(int appReleaseId, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting all unsubscription count for the application appReleaseId " + appReleaseId
+ " from the database");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT COUNT(*) AS count " +
"FROM AP_DEVICE_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = TRUE";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("count");
}
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get all unsubscription count for application appReleaseId: "
+ appReleaseId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting all unsubscription count for appReleaseId: "
+ appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int getDeviceSubscriptionCount(int appReleaseId, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting device subscriptions count for the application appReleaseId " + appReleaseId
+ " from the database");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT COUNT(*) AS count " +
"FROM AP_DEVICE_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = FALSE " +
"AND ACTION_TRIGGERED_FROM = 'DEVICE'";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("count");
}
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get device subscriptions count for application appReleaseId: "
+ appReleaseId;
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 count for appReleaseId: "
+ appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int getDeviceUnsubscriptionCount(int appReleaseId, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting device unsubscriptions count for the application appReleaseId " + appReleaseId
+ " from the database");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT COUNT(*) AS count " +
"FROM AP_DEVICE_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = TRUE " +
"AND ACTION_TRIGGERED_FROM = 'DEVICE'";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("count");
}
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get device unsubscription count for application appReleaseId: "
+ appReleaseId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting device unsubscription count for appReleaseId: "
+ appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int getGroupSubscriptionCount(int appReleaseId, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting group subscriptions count for the application appReleaseId " + appReleaseId
+ " from the database");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT COUNT(*) AS count " +
"FROM AP_GROUP_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = FALSE";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("count");
}
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get group subscriptions count for application appReleaseId: "
+ appReleaseId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting group subscriptions count for appReleaseId: "
+ appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int getGroupUnsubscriptionCount(int appReleaseId, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting group unsubscriptions count for the application appReleaseId " + appReleaseId
+ " from the database");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT COUNT(*) AS count " +
"FROM AP_GROUP_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = TRUE";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("count");
}
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get group unsubscription count for application appReleaseId: "
+ appReleaseId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting group unsubscription count for appReleaseId: "
+ appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int getRoleSubscriptionCount(int appReleaseId, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting role subscriptions count for the application appReleaseId " + appReleaseId
+ " from the database");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT COUNT(*) AS count " +
"FROM AP_ROLE_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = FALSE";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("count");
}
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get role subscriptions count for application appReleaseId: "
+ appReleaseId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting role subscriptions count for appReleaseId: "
+ appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int getRoleUnsubscriptionCount(int appReleaseId, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting role unsubscription count for the application appReleaseId " + appReleaseId
+ " from the database");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT COUNT(*) AS count " +
"FROM AP_ROLE_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = TRUE";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("count");
}
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get role unsubscription count for application appReleaseId: "
+ appReleaseId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting role unsubscription count for appReleaseId: "
+ appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int getUserSubscriptionCount(int appReleaseId, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting user subscriptions count for the application appReleaseId " + appReleaseId
+ " from the database");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT COUNT(*) AS count " +
"FROM AP_USER_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = FALSE";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("count");
}
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get user subscriptions count for application appReleaseId: "
+ appReleaseId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting user subscriptions count for appReleaseId: "
+ appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
@Override
public int getUserUnsubscriptionCount(int appReleaseId, int tenantId)
throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting user unsubscription count for the application appReleaseId " + appReleaseId
+ " from the database");
}
try {
Connection conn = this.getDBConnection();
String sql = "SELECT COUNT(*) AS count " +
"FROM AP_USER_SUBSCRIPTION " +
"WHERE AP_APP_RELEASE_ID = ? " +
"AND TENANT_ID = ? " +
"AND UNSUBSCRIBED = TRUE";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, appReleaseId);
ps.setInt(2, tenantId);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return rs.getInt("count");
}
return 0;
}
} catch (SQLException e) {
String msg = "Error occurred while running SQL to get user unsubscription count for application appReleaseId: "
+ appReleaseId;
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection for getting user unsubscription count for appReleaseId: "
+ appReleaseId + ".";
log.error(msg, e);
throw new ApplicationManagementDAOException(msg, e);
}
}
}

@ -30,6 +30,7 @@ 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.exceptions.MetadataManagementException;
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.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
@ -96,17 +97,19 @@ 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.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.UserStoreException;
import javax.ws.rs.core.Response;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@ -723,24 +726,29 @@ public class ApplicationManagerImpl implements ApplicationManager {
* @throws ResourceManagementException if error occurred while uploading
*/
private ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact,
String deviceType)
String deviceType)
throws ResourceManagementException, ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
byte[] content = getByteContentOfApp(applicationArtifact);
String md5OfApp = generateMD5OfApp(applicationArtifact, content);
validateReleaseBinaryFileHash(md5OfApp);
releaseDTO.setUuid(UUID.randomUUID().toString());
releaseDTO.setAppHashValue(md5OfApp);
releaseDTO.setInstallerName(applicationArtifact.getInstallerName());
try {
String md5OfApp = applicationStorageManager.
getMD5(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())));
validateReleaseBinaryFileHash(md5OfApp);
releaseDTO.setUuid(UUID.randomUUID().toString());
releaseDTO.setAppHashValue(md5OfApp);
releaseDTO.setInstallerName(applicationArtifact.getInstallerName());
try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) {
applicationStorageManager.uploadReleaseArtifact(releaseDTO, deviceType,
binaryDuplicate, tenantId);
Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), tenantId);
} catch (IOException e) {
String msg = "Error occurred when uploading release artifact into the server";
log.error(msg);
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);
}
@ -769,6 +777,8 @@ public class ApplicationManagerImpl implements ApplicationManager {
return Constants.GOOGLE_PLAY_STORE_URL;
} else if (DeviceTypes.IOS.toString().equalsIgnoreCase(deviceType)) {
return Constants.APPLE_STORE_URL;
} else if (DeviceTypes.WINDOWS.toString().equalsIgnoreCase(deviceType)) {
return Constants.MICROSOFT_STORE_URL;
} else {
throw new IllegalArgumentException("No such device with the name " + deviceType);
}
@ -856,82 +866,77 @@ public class ApplicationManagerImpl implements ApplicationManager {
String uuid = UUID.randomUUID().toString();
applicationReleaseDTO.setUuid(uuid);
// The application executable artifacts such as apks are uploaded.
try {
byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
applicationReleaseDTO.setInstallerName(applicationArtifact.getInstallerName());
try (ByteArrayInputStream binary = new ByteArrayInputStream(content)) {
if (!DeviceTypes.WINDOWS.toString().equalsIgnoreCase(deviceType)) {
ApplicationInstaller applicationInstaller = applicationStorageManager
.getAppInstallerData(binary, deviceType);
applicationReleaseDTO.setVersion(applicationInstaller.getVersion());
applicationReleaseDTO.setPackageName(applicationInstaller.getPackageName());
} else {
String windowsInstallerName = applicationArtifact.getInstallerName();
String extension = windowsInstallerName.substring(windowsInstallerName.lastIndexOf(".") + 1);
if (!extension.equalsIgnoreCase(Constants.MSI) &&
!extension.equalsIgnoreCase(Constants.APPX)) {
String msg = "Application Type doesn't match with supporting application types of " +
deviceType + "platform which are APPX and MSI";
log.error(msg);
throw new BadRequestException(msg);
}
if (!DeviceTypes.WINDOWS.toString().equalsIgnoreCase(deviceType)) {
ApplicationInstaller applicationInstaller = applicationStorageManager
.getAppInstallerData(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), deviceType);
applicationReleaseDTO.setVersion(applicationInstaller.getVersion());
applicationReleaseDTO.setPackageName(applicationInstaller.getPackageName());
} else {
String windowsInstallerName = applicationArtifact.getInstallerName();
String extension = windowsInstallerName.substring(windowsInstallerName.lastIndexOf(".") + 1);
if (!extension.equalsIgnoreCase(Constants.MSI) &&
!extension.equalsIgnoreCase(Constants.APPX)) {
String msg = "Application Type doesn't match with supporting application types of " +
deviceType + "platform which are APPX and MSI";
log.error(msg);
throw new BadRequestException(msg);
}
}
String packageName = applicationReleaseDTO.getPackageName();
try {
ConnectionManagerUtil.openDBConnection();
if (!isNewRelease && applicationReleaseDAO
.isActiveReleaseExisitForPackageName(packageName, tenantId,
lifecycleStateManager.getEndState())) {
String msg = "Application release is already exist for the package name: " + packageName
+ ". 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 "
+ "application.";
log.error(msg);
throw new ApplicationManagementException(msg);
}
String md5OfApp = applicationStorageManager.getMD5(new ByteArrayInputStream(content));
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 packageName = applicationReleaseDTO.getPackageName();
try {
ConnectionManagerUtil.openDBConnection();
if (!isNewRelease && applicationReleaseDAO
.isActiveReleaseExisitForPackageName(packageName, tenantId,
lifecycleStateManager.getEndState())) {
String msg = "Application release is already exist for the package name: " + packageName
+ ". 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 "
+ "application.";
log.error(msg);
throw new ApplicationManagementException(msg);
}
String md5OfApp = applicationStorageManager.
getMD5(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())));
if (md5OfApp == null) {
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) {
log.error(msg);
throw new ApplicationStorageManagementException(msg);
}
if (this.applicationReleaseDAO.verifyReleaseExistenceByHash(md5OfApp, tenantId)) {
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();
"Application release exists for the uploaded binary file. Device Type: " + deviceType;
log.error(msg);
throw new BadRequestException(msg);
}
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) {
String msg = "Error occurred when getting byte array of binary file. Installer name: " + applicationArtifact
String msg = "Error occurred when getting file input stream. Installer name: " + applicationArtifact
.getInstallerName();
log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e);
@ -957,73 +962,64 @@ public class ApplicationManagerImpl implements ApplicationManager {
// The application executable artifacts such as apks are uploaded.
try {
byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) {
String md5OfApp = applicationStorageManager.getMD5(binaryClone);
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)) {
applicationReleaseDTO.setInstallerName(applicationArtifact.getInstallerName());
String md5OfApp = applicationStorageManager.getMD5(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())));
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);
}
try (ByteArrayInputStream binary = new ByteArrayInputStream(content)) {
ApplicationInstaller applicationInstaller = applicationStorageManager
.getAppInstallerData(binary, deviceType);
String packageName = applicationInstaller.getPackageName();
if (!applicationReleaseDTO.getAppHashValue().equals(md5OfApp)) {
applicationReleaseDTO.setInstallerName(applicationArtifact.getInstallerName());
ApplicationInstaller applicationInstaller = applicationStorageManager
.getAppInstallerData(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), deviceType);
String packageName = applicationInstaller.getPackageName();
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: " + deviceType + " and package name: " + packageName;
log.error(msg);
throw new BadRequestException(msg);
}
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());
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();
}
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: " + deviceType + " and package name: " + packageName;
log.error(msg);
throw new BadRequestException(msg);
}
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());
applicationReleaseDTO.setPackageName(packageName);
String deletingAppHashValue = applicationReleaseDTO.getAppHashValue();
applicationReleaseDTO.setAppHashValue(md5OfApp);
applicationStorageManager.uploadReleaseArtifact(applicationReleaseDTO, deviceType,
Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())),
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) {
@ -1032,7 +1028,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e);
} catch (IOException e) {
String msg = "Error occurred when getting byte array of binary file. Installer name: " + applicationArtifact
String msg = "Error occurred when getting file input stream. Installer name: " + applicationArtifact
.getInstallerName();
log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e);
@ -3607,52 +3603,49 @@ public class ApplicationManagerImpl implements ApplicationManager {
DeviceType deviceTypeObj = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId());
// The application executable artifacts such as deb are uploaded.
try {
byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) {
String md5OfApp = applicationStorageManager.getMD5(binaryClone);
if (md5OfApp == null) {
String msg = "Error occurred while retrieving md5sum value from the binary file for "
+ "application release UUID " + applicationReleaseDTO.get().getUuid();
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);
}
String md5OfApp = applicationStorageManager.getMD5(
Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())));
if (md5OfApp == null) {
String msg = "Error occurred while retrieving md5sum value from the binary file for "
+ "application release UUID " + applicationReleaseDTO.get().getUuid();
log.error(msg);
throw new ApplicationStorageManagementException(msg);
}
applicationReleaseDTO.get().setInstallerName(applicationArtifact.getInstallerName());
String deletingAppHashValue = applicationReleaseDTO.get().getAppHashValue();
applicationReleaseDTO.get().setAppHashValue(md5OfApp);
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) {
if (!applicationReleaseDTO.get().getAppHashValue().equals(md5OfApp)) {
try {
ConnectionManagerUtil.getDBConnection();
if (this.applicationReleaseDAO.verifyReleaseExistenceByHash(md5OfApp, tenantId)) {
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();
"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);
}
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) {
@ -4424,7 +4417,6 @@ public class ApplicationManagerImpl implements ApplicationManager {
spApplicationDAO.deleteSPApplicationMappingByTenant(tenantId);
spApplicationDAO.deleteIdentityServerByTenant(tenantId);
applicationDAO.deleteApplicationsByTenant(tenantId);
APIUtil.getApplicationStorageManager().deleteAppFolderOfTenant(tenantId);
ConnectionManagerUtil.commitDBTransaction();
} catch (DBConnectionException e) {
@ -4449,12 +4441,6 @@ public class ApplicationManagerImpl implements ApplicationManager {
+ " of tenant ID: " + tenantId ;
log.error(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 {
ConnectionManagerUtil.closeDBConnection();
}
@ -4463,19 +4449,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
@Override
public void deleteApplicationDataByTenantDomain(String tenantDomain) throws ApplicationManagementException {
int tenantId;
try{
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 {
tenantId = DataHolder.getInstance().getTenantManagerAdminService().getTenantId(tenantDomain);
ConnectionManagerUtil.beginDBTransaction();
vppApplicationDAO.deleteAssociationByTenant(tenantId);
@ -4499,40 +4475,54 @@ public class ApplicationManagerImpl implements ApplicationManager {
spApplicationDAO.deleteSPApplicationMappingByTenant(tenantId);
spApplicationDAO.deleteIdentityServerByTenant(tenantId);
applicationDAO.deleteApplicationsByTenant(tenantId);
APIUtil.getApplicationStorageManager().deleteAppFolderOfTenant(tenantId);
ConnectionManagerUtil.commitDBTransaction();
} catch (DBConnectionException e) {
String msg = "Error occurred while observing the database connection to delete applications for tenant with ID: "
+ tenantId;
String msg = "Error occurred while observing the database connection to delete applications for tenant with " +
"domain: " + tenantDomain;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Database access error is occurred when getting applications for tenant with ID: " + tenantId;
String msg = "Database access error is occurred when getting applications for tenant with domain: "
+ tenantDomain;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (LifeCycleManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred while deleting life-cycle state data of application releases of the tenant"
+ " of ID: " + tenantId ;
+ " of domain: " + tenantDomain ;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ReviewManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred while deleting reviews of application releases of the applications"
+ " of tenant ID: " + tenantId ;
+ " of tenant of domain: " + tenantDomain ;
log.error(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 ;
} catch (Exception e) {
String msg = "Error getting tenant ID from domain: "
+ tenantDomain;
log.error(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,6 +37,7 @@ 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 java.io.*;
import java.nio.file.Paths;
import java.util.List;
import static io.entgra.device.mgt.core.device.mgt.core.common.util.StorageManagementUtil.saveFile;
@ -155,13 +156,12 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
public void uploadReleaseArtifact(ApplicationReleaseDTO applicationReleaseDTO,
String deviceType, InputStream binaryFile, int tenantId) throws ResourceManagementException {
try {
byte [] content = IOUtils.toByteArray(binaryFile);
String artifactDirectoryPath =
storagePath + tenantId + File.separator + applicationReleaseDTO.getAppHashValue() + File.separator
+ Constants.APP_ARTIFACT;
StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
String artifactPath = artifactDirectoryPath + File.separator + applicationReleaseDTO.getInstallerName();
saveFile(new ByteArrayInputStream(content), artifactPath);
saveFile(binaryFile, artifactPath);
} catch (IOException e) {
String msg = "IO Exception while saving the release artifacts in the server for the application UUID "
+ applicationReleaseDTO.getUuid();
@ -324,4 +324,12 @@ 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,6 +31,7 @@ import io.entgra.device.mgt.core.device.mgt.common.exceptions.NotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.FileSystems;
@ -103,8 +104,13 @@ public class FileTransferServiceImpl implements FileTransferService {
@Override
public boolean isExistsOnLocal(URL downloadUrl) throws FileTransferServiceException {
try {
return FileTransferServiceHelperUtil.resolve(downloadUrl) != null;
} catch (FileTransferServiceHelperUtilException e) {
FileDescriptor fileDescriptor = FileTransferServiceHelperUtil.resolve(downloadUrl);
if (fileDescriptor != null && fileDescriptor.getFile() != null) {
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";
log.error(msg, e);
throw new FileTransferServiceException(msg, e);

@ -33,7 +33,9 @@ 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.task.ScheduledAppSubscriptionTaskManager;
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.tenant.mgt.common.spi.TenantManagerAdminService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
@ -71,6 +73,12 @@ import java.util.List;
* policy="dynamic"
* bind="setTaskService"
* 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")
public class ApplicationManagementServiceComponent {
@ -196,4 +204,20 @@ public class ApplicationManagementServiceComponent {
}
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,6 +27,8 @@ 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.core.lifecycle.LifecycleStateManager;
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.user.core.service.RealmService;
@ -57,6 +59,7 @@ public class DataHolder {
private TaskService taskService;
private FileTransferService fileTransferService;
private TenantManagerAdminService tenantManagerAdminService;
private static final DataHolder applicationMgtDataHolder = new DataHolder();
@ -163,4 +166,12 @@ public class DataHolder {
public void setFileTransferService(FileTransferService fileTransferService) {
this.fileTransferService = fileTransferService;
}
public TenantManagerAdminService getTenantManagerAdminService() {
return tenantManagerAdminService;
}
public void setTenantManagerAdminService(TenantManagerAdminService tenantManagerAdminService) {
this.tenantManagerAdminService = tenantManagerAdminService;
}
}

@ -181,6 +181,7 @@ public class ApplicationManagementUtil {
fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(artifactLinkUrl).download(artifactLinkUrl);
applicationArtifact.setInstallerName(fileDescriptor.getFullQualifiedName());
applicationArtifact.setInstallerStream(fileDescriptor.getFile());
applicationArtifact.setInstallerPath(fileDescriptor.getAbsolutePath());
}
if (iconLink != null) {
@ -188,6 +189,7 @@ public class ApplicationManagementUtil {
fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(iconLinkUrl).download(iconLinkUrl);
applicationArtifact.setIconName(fileDescriptor.getFullQualifiedName());
applicationArtifact.setIconStream(fileDescriptor.getFile());
applicationArtifact.setIconPath(fileDescriptor.getAbsolutePath());
}
if (bannerLink != null) {
@ -195,10 +197,12 @@ public class ApplicationManagementUtil {
fileDescriptor = FileDownloaderServiceProvider.getFileDownloaderService(bannerLinkUrl).download(bannerLinkUrl);
applicationArtifact.setBannerName(fileDescriptor.getFullQualifiedName());
applicationArtifact.setBannerStream(fileDescriptor.getFile());
applicationArtifact.setBannerPath(fileDescriptor.getAbsolutePath());
}
if (screenshotLinks != null) {
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
Map<String, Integer> screenshotNameCount = new HashMap<>();
URL screenshotLinkUrl;
@ -209,6 +213,7 @@ public class ApplicationManagementUtil {
screenshotNameCount.put(screenshotName, screenshotNameCount.getOrDefault(screenshotName, 0) + 1);
screenshotName = FileUtil.generateDuplicateFileName(screenshotName, screenshotNameCount.get(screenshotName));
screenshotData.put(screenshotName, fileDescriptor.getFile());
screenshotPaths.put(screenshotName, fileDescriptor.getAbsolutePath());
}
applicationArtifact.setScreenshots(screenshotData);
}

@ -74,6 +74,7 @@ public class Constants {
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 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";
// Subscription task related constants

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

@ -23,7 +23,9 @@ import com.google.gson.Gson;
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.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.internal.DataHolder;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.NotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -175,6 +177,12 @@ public class FileTransferServiceHelperUtil {
}
String []urlPathSegments = downloadUrl.getPath().split("/");
FileDescriptor fileDescriptorResolvedFromRelease = resolve(urlPathSegments);
if (fileDescriptorResolvedFromRelease != null) {
return fileDescriptorResolvedFromRelease;
}
if (urlPathSegments.length < 2) {
if (log.isDebugEnabled()) {
log.debug("URL patch segments contain less than 2 segments");
@ -234,4 +242,54 @@ public class FileTransferServiceHelperUtil {
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);
}
}
}

@ -37,6 +37,7 @@ import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManag
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory;
import io.entgra.device.mgt.core.device.mgt.core.internal.DeviceManagementDataHolder;
import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory;
import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.registry.core.config.RegistryContext;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.internal.RegistryDataHolder;
@ -96,6 +97,7 @@ public abstract class BaseTestCase {
ConnectionManagerUtil.init(dataSource);
DeviceManagementDAOFactory.init(dataSource);
MetadataManagementDAOFactory.init(dataSource);
OperationManagementDAOFactory.init(dataSource);
// PolicyManagementDAOFactory.init(dataSource);
// OperationManagementDAOFactory.init(dataSource);
// GroupManagementDAOFactory.init(dataSource);

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -125,6 +125,8 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT
(
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
DEVICE_TYPE VARCHAR(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL,
OWNER VARCHAR(255) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,

@ -149,6 +149,8 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION (
CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
DEVICE_TYPE VARCHAR(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL,
OWNER VARCHAR(50) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,

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

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

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

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.42-SNAPSHOT</version>
<version>5.1.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -111,6 +111,46 @@
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
</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>
<build>
@ -137,12 +177,27 @@
com.google.gson,
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
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.push.notification,
org.apache.commons.logging,
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>
<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>
</configuration>
</plugin>

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

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

@ -0,0 +1,108 @@
/*
* 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>
<artifactId>device-mgt-extensions</artifactId>
<groupId>io.entgra.device.mgt.core</groupId>
<version>5.0.42-SNAPSHOT</version>
<version>5.1.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

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

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

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

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

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

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

@ -165,6 +165,13 @@ import java.util.Map;
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devices/change-status"}
),
@Scope(
name = "Update status of a given operation",
description = "Updates the status of a given operation of a given device",
key = "dm:devices:ops:status:update",
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devices/operations/status-update"}
),
@Scope(
name = "Enroll Device",
description = "Register a device",
@ -303,6 +310,12 @@ public interface DeviceManagementService {
required = false)
@QueryParam("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(
name = "since",
value = "Checks if the requested variant was created since the specified date-time.\n" +
@ -2714,12 +2727,12 @@ public interface DeviceManagementService {
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Update status of a given opeation",
value = "Update status of a given operation",
notes = "Updates the status of a given operation of a given device in Entgra IoT Server.",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:ops:view")
@ExtensionProperty(name = Constants.SCOPE, value = "dm:devices:ops:status:update")
})
}
)

@ -298,8 +298,13 @@ public interface UserManagementAdminService {
name = "tenantDomain",
value = "The domain of the tenant to be deleted.",
required = true)
@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,7 +175,6 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
activity.setUsername(appActivity.getUsername());
activity.setPackageName(appActivity.getPackageName());
activity.setAppName(appActivity.getAppName());
activity.setStatus(appActivity.getStatus());
activity.setAppType(appActivity.getAppType());
activity.setVersion(appActivity.getVersion());
activity.setTriggeredBy(appActivity.getTriggeredBy());

@ -147,6 +147,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@QueryParam("customProperty") String customProperty,
@QueryParam("status") List<String> status,
@QueryParam("groupId") int groupId,
@QueryParam("excludeGroupId") int excludeGroupId,
@QueryParam("since") String since,
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@QueryParam("requireDeviceInfo") boolean requireDeviceInfo,
@ -209,7 +210,22 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
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();
if (groupId != 0) {
@ -541,22 +557,49 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@Path("/type/{deviceType}/id/{deviceId}/rename")
public Response renameDevice(Device device, @PathParam("deviceType") String deviceType,
@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();
try {
Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier
(deviceId, deviceType), true);
persistedDevice.setName(device.getName());
System.out.println("This is rename device");
boolean responseOfmodifyEnrollment = deviceManagementProviderService.modifyEnrollment(persistedDevice);
boolean responseOfDeviceNameChanged = deviceManagementProviderService.sendDeviceNameChangedNotification(
persistedDevice);
boolean response = responseOfmodifyEnrollment && responseOfDeviceNameChanged;
return Response.status(Response.Status.CREATED).entity(response).build();
} catch (DeviceManagementException e) {
String msg = "Error encountered while updating requested device of type : " + deviceType ;
Device updatedDevice = deviceManagementProviderService.updateDeviceName(device, deviceType, deviceId);
if (updatedDevice != null) {
boolean notificationResponse = deviceManagementProviderService.sendDeviceNameChangedNotification(updatedDevice);
if (notificationResponse) {
return Response.status(Response.Status.CREATED).entity(updatedDevice).build();
} else {
String msg = "Device updated successfully, but failed to send notification.";
log.warn(msg);
return Response.status(Response.Status.CREATED).entity(updatedDevice).header("Warning", msg).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) {
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);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
}
}

@ -273,7 +273,7 @@ public class GroupManagementServiceImpl implements GroupManagementService {
);
return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) {
String msg = "Error occurred while adding new group.";
String msg = "Error occurred while updating group. ";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (GroupNotExistException e) {

@ -19,6 +19,7 @@ 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.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.LogFactory;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
@ -29,9 +30,6 @@ 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 org.wso2.carbon.base.MultitenantConstants;
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.ws.rs.*;
@ -91,7 +89,7 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic
@DELETE
@Path("/domain/{tenantDomain}")
@Override
public Response deleteTenantByDomain(@PathParam("tenantDomain") String tenantDomain) {
public Response deleteTenantByDomain(@PathParam("tenantDomain") String tenantDomain, @QueryParam("deleteAppArtifacts") boolean deleteAppArtifacts) {
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
if (tenantId != MultitenantConstants.SUPER_TENANT_ID){
@ -99,15 +97,20 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic
log.error(msg);
return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build();
} else {
if (deleteAppArtifacts) {
DeviceMgtAPIUtils.getApplicationManager().deleteApplicationArtifactsByTenantDomain(tenantDomain);
}
DeviceMgtAPIUtils.getApplicationManager().deleteApplicationDataByTenantDomain(tenantDomain);
DeviceMgtAPIUtils.getDeviceManagementService().deleteDeviceDataByTenantDomain(tenantDomain);
TenantMgtAdminService tenantMgtAdminService = new TenantMgtAdminService();
tenantMgtAdminService.deleteTenant(tenantDomain);
DeviceMgtAPIUtils.getTenantManagerAdminService().deleteTenant(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();
}
} catch (StratosException | UserStoreException e) {
} catch (TenantMgtException e) {
String msg = "Error deleting tenant: " + tenantDomain;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();

@ -574,7 +574,11 @@ public class RequestValidationUtil {
}
if (operationCode != null && !operationCode.isEmpty()) {
validateOperationCodeFiltering(operationCode, type);
/*
Commenting this as dynamic device types doesn't have configuration based feature manager which
used to define fixed set of operation codes.
*/
// validateOperationCodeFiltering(operationCode, type);
operationLogFilters.setOperationCode(operationCode);
}
return operationLogFilters;

@ -24,6 +24,7 @@ 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.metadata.mgt.DeviceStatusManagementService;
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.client.Options;
import org.apache.axis2.java.security.SSLProtocolSocketFactory;
@ -163,6 +164,7 @@ public class DeviceMgtAPIUtils {
private static volatile ApplicationManager applicationManager;
private static volatile APIPublisherService apiPublisher;
private static volatile TenantManagerAdminService tenantManagerAdminService;
static {
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
@ -1243,4 +1245,21 @@ public class DeviceMgtAPIUtils {
}
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);
Response response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, null, null, false,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
}
@ -177,22 +177,22 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null,null, DEFAULT_STATUS_LIST, 1, null, null, false,
null,null, DEFAULT_STATUS_LIST, 1, 0, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, null, null, false,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, null, null, false,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, null, null, true,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, true,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
}
@ -307,7 +307,7 @@ public class DeviceManagementServiceImplTest {
Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true);
deviceManagementService.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null,
DEFAULT_ROLE, DEFAULT_OWNERSHIP, null,null, DEFAULT_STATUS_LIST, 1,
null, null, false, 10, 5);
0, null, null, false, 10, 5);
}
@Test(description = "Testing get devices when user is the device admin")
@ -326,11 +326,11 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP
, null, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
, null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP
, null, null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
, null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
}
@ -352,7 +352,7 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 0, null, null, false,
null, null, DEFAULT_STATUS_LIST, 0, 0, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode());
Mockito.reset(this.deviceAccessAuthorizationService);
@ -374,17 +374,17 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, false,
null, null, DEFAULT_STATUS_LIST, 0, 0, null, ifModifiedSince, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, true,
null, null, DEFAULT_STATUS_LIST, 0, 0, null, ifModifiedSince, true,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 0, null, "ErrorModifiedSince",
null, null, DEFAULT_STATUS_LIST, 0, 0, null, "ErrorModifiedSince",
false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
}
@ -405,17 +405,17 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null,DEFAULT_STATUS_LIST, 0, since, null, false,
null, null,DEFAULT_STATUS_LIST, 0, 0, since, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null,DEFAULT_STATUS_LIST, 0, since, null, true,
null, null,DEFAULT_STATUS_LIST, 0, 0, since, null, true,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null,DEFAULT_STATUS_LIST, 0, "ErrorSince", null, false,
null, null,DEFAULT_STATUS_LIST, 0, 0, "ErrorSince", null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
}
@ -438,7 +438,7 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, null, null, false,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Mockito.reset(this.deviceManagementProviderService);
@ -461,7 +461,7 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
null, null, DEFAULT_STATUS_LIST, 1, null, null, false,
null, null, DEFAULT_STATUS_LIST, 1, 0, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Mockito.reset(this.deviceAccessAuthorizationService);

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

@ -57,6 +57,9 @@ public class Device implements Serializable {
required = true)
private String deviceIdentifier;
@ApiModelProperty(name = "updatedTimeStamp", value = "Last updated timestamp of the device.")
private long lastUpdatedTimeStamp;
@ApiModelProperty(name = "enrolmentInfo", value = "This defines the device registration related information. " +
"It is mandatory to define this information.", required = true)
private EnrolmentInfo enrolmentInfo;
@ -221,6 +224,14 @@ public class Device implements Serializable {
this.historySnapshot = historySnapshot;
}
public long getLastUpdatedTimeStamp() {
return lastUpdatedTimeStamp;
}
public void setLastUpdatedTimeStamp(long lastUpdatedTimeStamp) {
this.lastUpdatedTimeStamp = lastUpdatedTimeStamp;
}
public static class Property {
private String name;

@ -69,9 +69,20 @@ public class DeviceIdentifier implements Serializable{
@Override
public String toString() {
return "deviceId {" +
"id='" + id + '\'' +
", type='" + type + '\'' +
'}';
return type + "|" + id;
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof DeviceIdentifier) {
return (this.hashCode() == obj.hashCode());
}
return false;
}
}

@ -58,6 +58,10 @@ public class MDMAppConstants {
}
public static final String INSTALL_ENTERPRISE_APPLICATION = "INSTALL_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
public static final String MSI = "MSI";
public static final String APPX = "APPX";

@ -0,0 +1,49 @@
/*
* 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.common.app.mgt.windows;
import com.google.gson.Gson;
import java.io.Serializable;
public class AppStoreApplication implements Serializable {
private String type;
private String packageIdentifier;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPackageIdentifier() {
return packageIdentifier;
}
public void setPackageIdentifier(String packageIdentifier) {
this.packageIdentifier = packageIdentifier;
}
public String toJSON() {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -0,0 +1,76 @@
/*
* 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.common.app.mgt.windows;
import com.google.gson.Gson;
import java.util.Properties;
public class WebClipApplication {
private String url;
private String name;
private String icon;
private String type;
private Properties properties;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public String toJSON() {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -0,0 +1,32 @@
/*
* 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.common.exceptions;
public class ConflictException extends Exception {
private static final long serialVersionUID = -4998775497944307646L;
public ConflictException(String message) {
super(message);
}
public ConflictException(String message, Throwable cause) {
super(message, cause);
}
}

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

@ -22,7 +22,7 @@
<parent>
<groupId>io.entgra.device.mgt.core</groupId>
<artifactId>device-mgt</artifactId>
<version>5.0.42-SNAPSHOT</version>
<version>5.1.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -137,10 +137,10 @@
</systemPropertyVariables>
<suiteXmlFiles>
<file>src/test/resources/testng.xml</file>
<file>src/test/resources/mysql-testng.xml</file>
<file>src/test/resources/mssql-testng.xml</file>
<file>src/test/resources/oracle-testng.xml</file>
<file>src/test/resources/postgre-testng.xml</file>
<!-- <file>src/test/resources/mysql-testng.xml</file>-->
<!-- <file>src/test/resources/mssql-testng.xml</file>-->
<!-- <file>src/test/resources/oracle-testng.xml</file>-->
<!-- <file>src/test/resources/postgre-testng.xml</file>-->
</suiteXmlFiles>
</configuration>
</plugin>

@ -28,7 +28,6 @@ public class DeviceCacheKey {
private String deviceId;
private String deviceType;
private int tenantId;
private volatile int hashCode;
public String getDeviceId() {
return deviceId;
@ -55,27 +54,21 @@ public class DeviceCacheKey {
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!DeviceCacheKey.class.isAssignableFrom(obj.getClass())) {
return false;
}
final DeviceCacheKey other = (DeviceCacheKey) obj;
String thisId = this.deviceId + "-" + this.deviceType + "_" + this.tenantId;
String otherId = other.deviceId + "-" + other.deviceType + "_" + other.tenantId;
if (!thisId.equals(otherId)) {
return false;
}
return true;
public int hashCode() {
return toString().hashCode();
}
@Override
public int hashCode() {
if (hashCode == 0) {
hashCode = Objects.hash(deviceId, deviceType, tenantId);
public String toString() {
return tenantId + "|" + deviceType + "|" + deviceId;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof DeviceCacheKey) {
return (this.hashCode() == obj.hashCode());
}
return hashCode;
return false;
}
}

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

Loading…
Cancel
Save