From e1519fa2a88f12e798627457d54cab257892b51f Mon Sep 17 00:00:00 2001 From: Pahansith Date: Sun, 24 Mar 2024 14:56:22 +0530 Subject: [PATCH 01/21] Add policy content store as Json --- .../pom.xml | 4 ++ .../impl/policy/AbstractPolicyDAOImpl.java | 41 ++++--------------- .../mgt/core/util/PolicyManagerUtil.java | 11 ++++- 3 files changed, 22 insertions(+), 34 deletions(-) diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml index 3c0fabec4b..8fd87c21b2 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/pom.xml @@ -180,6 +180,10 @@ io.entgra.device.mgt.core io.entgra.device.mgt.core.policy.mgt.common + + com.google.code.gson + gson + diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java index 85bd77d859..f69e672cf7 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.policy.mgt.core.dao.impl.policy; +import com.google.gson.Gson; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -54,6 +55,7 @@ import java.util.Properties; */ public abstract class AbstractPolicyDAOImpl implements PolicyDAO { + private static final Gson gson = new Gson(); private static final Log log = LogFactory.getLog(AbstractPolicyDAOImpl.class); @Override @@ -1187,13 +1189,13 @@ public abstract class AbstractPolicyDAOImpl implements PolicyDAO { stmt = conn.prepareStatement(query); stmt.setInt(1, deviceId); stmt.setInt(2, policy.getId()); - stmt.setBytes(3, PolicyManagerUtil.getBytes(policy)); + stmt.setString(3, PolicyManagerUtil.convertToJson(policy)); stmt.setTimestamp(4, currentTimestamp); stmt.setTimestamp(5, currentTimestamp); stmt.setInt(6, tenantId); stmt.setInt(7, enrolmentId); stmt.executeUpdate(); - } catch (SQLException | IOException e) { + } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while adding the evaluated feature list to device", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, null); @@ -1240,7 +1242,7 @@ public abstract class AbstractPolicyDAOImpl implements PolicyDAO { "APPLIED = ? WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setInt(1, policy.getId()); - stmt.setBytes(2, PolicyManagerUtil.getBytes(policy)); + stmt.setString(2, PolicyManagerUtil.convertToJson(policy)); stmt.setTimestamp(3, currentTimestamp); stmt.setBoolean(4, false); stmt.setInt(5, deviceId); @@ -1248,7 +1250,7 @@ public abstract class AbstractPolicyDAOImpl implements PolicyDAO { stmt.setInt(7, enrolmentId); stmt.executeUpdate(); - } catch (SQLException | IOException e) { + } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while updating the evaluated feature list " + "to device", e); } finally { @@ -1699,39 +1701,12 @@ public abstract class AbstractPolicyDAOImpl implements PolicyDAO { resultSet = stmt.executeQuery(); while (resultSet.next()) { - ByteArrayInputStream bais = null; - ObjectInputStream ois = null; - byte[] contentBytes; - - try { - contentBytes = resultSet.getBytes("POLICY_CONTENT"); - bais = new ByteArrayInputStream(contentBytes); - ois = new ObjectInputStream(bais); - policy = (Policy) ois.readObject(); - } finally { - if (bais != null) { - try { - bais.close(); - } catch (IOException e) { - log.warn("Error occurred while closing ByteArrayOutputStream", e); - } - } - if (ois != null) { - try { - ois.close(); - } catch (IOException e) { - log.warn("Error occurred while closing ObjectOutputStream", e); - } - } - } + String contentString = resultSet.getString("POLICY_CONTENT"); + policy = gson.fromJson(contentString, Policy.class); } } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while getting the applied policy", e); - } catch (IOException e) { - throw new PolicyManagerDAOException("Unable to read the byte stream for content", e); - } catch (ClassNotFoundException e) { - throw new PolicyManagerDAOException("Class not found while converting the object", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, resultSet); } diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/util/PolicyManagerUtil.java index 0bd3c36396..1aa7947e8e 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/util/PolicyManagerUtil.java @@ -62,7 +62,7 @@ import java.io.ObjectOutputStream; import java.util.*; public class PolicyManagerUtil { - + private static final Gson gson = new Gson(); public static final String GENERAL_CONFIG_RESOURCE_PATH = "general"; public static final String MONITORING_FREQUENCY = "notifierFrequency"; private static final Log log = LogFactory.getLog(PolicyManagerUtil.class); @@ -355,6 +355,15 @@ public class PolicyManagerUtil { return data; } + /** + * Using for converting policy objects into Json strings + * @param obj + * @return + */ + public static String convertToJson(Object obj) { + return gson.toJson(obj); + } + public static boolean convertIntToBoolean(int x) { return x == 1; From 5c73277c32d80d629ab69e94035f5860727e0441 Mon Sep 17 00:00:00 2001 From: Pahansith Date: Wed, 12 Jun 2024 12:37:25 +0530 Subject: [PATCH 02/21] Add FCM changes --- .../pom.xml | 8 ++- .../provider/fcm/FCMNotificationStrategy.java | 69 ++++++++++++++++--- pom.xml | 5 ++ 3 files changed, 73 insertions(+), 9 deletions(-) diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml index ffb529ef29..ea7aec37a0 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml @@ -111,6 +111,10 @@ org.wso2.carbon.analytics-common org.wso2.carbon.event.output.adapter.core + + com.google.auth + google-auth-library-oauth2-http + @@ -141,7 +145,9 @@ 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.extensions.logger.spi, + io.entgra.device.mgt.core.notification.logger.* diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java index c6100aa418..669edd314a 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java @@ -17,9 +17,14 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm; +import com.google.auth.oauth2.GoogleCredentials; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import com.hazelcast.aws.utility.Environment; +import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; +import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; +import io.entgra.device.mgt.core.notification.logger.impl.EntgraDeviceConnectivityLoggerImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; @@ -30,10 +35,14 @@ import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotific import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationExecutionFailedException; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.internal.FCMDataHolder; -import java.io.IOException; -import java.io.OutputStream; +import java.io.*; import java.net.HttpURLConnection; import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.Arrays; import java.util.List; public class FCMNotificationStrategy implements NotificationStrategy { @@ -42,7 +51,7 @@ public class FCMNotificationStrategy implements NotificationStrategy { 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_ENDPOINT = "https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages: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 HTTP_STATUS_CODE_OK = 200; @@ -59,12 +68,13 @@ public class FCMNotificationStrategy implements NotificationStrategy { @Override public void execute(NotificationContext ctx) throws PushNotificationExecutionFailedException { + String token = getFcmOauthToken(); try { if (NOTIFIER_TYPE_FCM.equals(config.getType())) { Device device = FCMDataHolder.getInstance().getDeviceManagementProviderService() .getDeviceWithTypeProperties(ctx.getDeviceId()); if(device.getProperties() != null && getFCMToken(device.getProperties()) != null) { - this.sendWakeUpCall(ctx.getOperation().getCode(), device); + this.sendWakeUpCall(ctx.getOperation().getCode(), device, token); } } else { if (log.isDebugEnabled()) { @@ -79,6 +89,25 @@ public class FCMNotificationStrategy implements NotificationStrategy { } } + private String getFcmOauthToken() { + GoogleCredentials googleCredentials = null; + try { + googleCredentials = GoogleCredentials + .fromStream(new FileInputStream("/etc/service-account.json")) + .createScoped(Arrays.asList("https://www.googleapis.com/auth/firebase.messaging")); + googleCredentials.refresh(); + if (null != googleCredentials) { + writeLog("========= Google Credentials created " + googleCredentials.getAccessToken()); + } else { + writeLog("========= Google Credentials is null"); + } + return googleCredentials.getAccessToken().getTokenValue(); + } catch (IOException e) { + log.error("Error occurred while getting the FCM OAuth token.", e); + throw new RuntimeException(e); + } + } + @Override public NotificationContext buildContext() { return null; @@ -89,9 +118,10 @@ public class FCMNotificationStrategy implements NotificationStrategy { } - private void sendWakeUpCall(String message, Device device) throws IOException, + private void sendWakeUpCall(String message, Device device, String token) throws IOException, PushNotificationExecutionFailedException { if (device.getProperties() != null) { + writeLog("===== Calling senWakeupCall " + device); OutputStream os = null; byte[] bytes = getFCMRequest(message, getFCMToken(device.getProperties())).getBytes(); @@ -99,7 +129,7 @@ public class FCMNotificationStrategy implements NotificationStrategy { try { conn = (HttpURLConnection) new URL(FCM_ENDPOINT).openConnection(); conn.setRequestProperty("Content-Type", "application/json"); - conn.setRequestProperty("Authorization", "key=" + config.getProperty(FCM_API_KEY)); + conn.setRequestProperty("Authorization", "Bearer " + token); conn.setRequestMethod("POST"); conn.setDoOutput(true); os = conn.getOutputStream(); @@ -125,7 +155,16 @@ public class FCMNotificationStrategy implements NotificationStrategy { private static String getFCMRequest(String message, String registrationId) { JsonObject fcmRequest = new JsonObject(); - fcmRequest.addProperty("delay_while_idle", false); + JsonObject messageObject = new JsonObject(); + messageObject.addProperty("token", registrationId); + JsonObject notification = new JsonObject(); + notification.addProperty("title", "FCM Message"); + notification.addProperty("body", message); + messageObject.add("notification", notification); + fcmRequest.add("message", messageObject); + + + /*fcmRequest.addProperty("delay_while_idle", false); fcmRequest.addProperty("time_to_live", TIME_TO_LIVE); fcmRequest.addProperty("priority", "high"); @@ -140,7 +179,9 @@ public class FCMNotificationStrategy implements NotificationStrategy { JsonArray regIds = new JsonArray(); regIds.add(new JsonPrimitive(registrationId)); - fcmRequest.add("registration_ids", regIds); + fcmRequest.add("registration_ids", regIds);*/ + + writeLog("========= FCM Request " + fcmRequest); return fcmRequest.toString(); } @@ -155,9 +196,21 @@ public class FCMNotificationStrategy implements NotificationStrategy { return fcmToken; } + private static void writeLog(String message) { + try (FileWriter fw = new FileWriter("/opt/entgra/migration/entgra-uem-ultimate-6.0.3.0/log.txt", true); + BufferedWriter bw = new BufferedWriter(fw)) { + bw.write(message); + bw.newLine(); + bw.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } + @Override public PushNotificationConfig getConfig() { return config; } + } diff --git a/pom.xml b/pom.xml index 680a4ced22..516bd8e982 100644 --- a/pom.xml +++ b/pom.xml @@ -1916,6 +1916,11 @@ mockito-inline ${mokito.version} + + com.google.auth + google-auth-library-oauth2-http + 1.20.0 + From aafa824f0838cd64c86c11cd5b54bd79a3966c01 Mon Sep 17 00:00:00 2001 From: Rajitha Kumara Date: Sun, 16 Jun 2024 15:51:56 +0530 Subject: [PATCH 03/21] Migrate from legacy FCM APIs to HTTP v1 --- .../pom.xml | 53 ++++- .../fcm/FCMBasedPushNotificationProvider.java | 4 +- .../provider/fcm/FCMNotificationStrategy.java | 189 ++++++++---------- .../push/notification/ContextMetadata.java | 30 +++ .../PushNotificationConfiguration.java | 11 + .../repository/conf/cdm-config.xml.j2 | 5 + pom.xml | 55 ++++- 7 files changed, 241 insertions(+), 106 deletions(-) create mode 100644 components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/ContextMetadata.java diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml index ea7aec37a0..4d4bf35cf9 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/pom.xml @@ -112,9 +112,45 @@ org.wso2.carbon.event.output.adapter.core - com.google.auth + org.wso2.orbit.com.google.http-client + google-http-client + + + org.wso2.orbit.com.google.auth-library-oauth2-http google-auth-library-oauth2-http + + org.wso2.orbit.io.opencensus + opencensus + + + io.opencensus + opencensus-api + + + io.opencensus + opencensus-contrib-http-util + + + org.wso2.orbit.io.grpc + grpc-context + + + com.google.http-client + google-http-client-gson + + + com.google.guava + failureaccess + + + com.google.guava + guava + + + org.wso2.carbon + org.wso2.carbon.utils + @@ -141,14 +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.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.* + io.entgra.device.mgt.core.notification.logger.*, + com.google.auth.oauth2.* + + 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 + + true diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMBasedPushNotificationProvider.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMBasedPushNotificationProvider.java index 1dbbacd720..2f849a4366 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMBasedPushNotificationProvider.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMBasedPushNotificationProvider.java @@ -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; } } diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java index 669edd314a..f003983360 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java @@ -18,13 +18,10 @@ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm; import com.google.auth.oauth2.GoogleCredentials; -import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.hazelcast.aws.utility.Environment; -import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.OperationManagerImpl; -import io.entgra.device.mgt.core.device.mgt.extensions.logger.spi.EntgraLogger; -import io.entgra.device.mgt.core.notification.logger.impl.EntgraDeviceConnectivityLoggerImpl; +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 org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; @@ -34,28 +31,34 @@ import io.entgra.device.mgt.core.device.mgt.common.push.notification.Notificatio import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationExecutionFailedException; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.internal.FCMDataHolder; +import org.wso2.carbon.utils.CarbonUtils; -import java.io.*; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.util.Arrays; import java.util.List; +import java.util.Properties; 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/v1/projects/myproject-b5ae1/messages: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_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 static final String FCM_ENDPOINT_KEY = "FCM_SERVER_ENDPOINT"; + private Properties contextMetadataProperties; + private volatile GoogleCredentials defaultApplication; public FCMNotificationStrategy(PushNotificationConfig config) { this.config = config; @@ -63,23 +66,25 @@ public class FCMNotificationStrategy implements NotificationStrategy { @Override public void init() { - + initContextConfigs(); + initDefaultOAuthApplication(); } @Override public void execute(NotificationContext ctx) throws PushNotificationExecutionFailedException { - String token = getFcmOauthToken(); try { if (NOTIFIER_TYPE_FCM.equals(config.getType())) { Device device = FCMDataHolder.getInstance().getDeviceManagementProviderService() .getDeviceWithTypeProperties(ctx.getDeviceId()); if(device.getProperties() != null && getFCMToken(device.getProperties()) != null) { - this.sendWakeUpCall(ctx.getOperation().getCode(), device, token); + defaultApplication.refresh(); + sendWakeUpCall(defaultApplication.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) { @@ -89,100 +94,93 @@ public class FCMNotificationStrategy implements NotificationStrategy { } } - private String getFcmOauthToken() { - GoogleCredentials googleCredentials = null; - try { - googleCredentials = GoogleCredentials - .fromStream(new FileInputStream("/etc/service-account.json")) - .createScoped(Arrays.asList("https://www.googleapis.com/auth/firebase.messaging")); - googleCredentials.refresh(); - if (null != googleCredentials) { - writeLog("========= Google Credentials created " + googleCredentials.getAccessToken()); - } else { - writeLog("========= Google Credentials is null"); + private void initDefaultOAuthApplication() { + if (defaultApplication == null) { + synchronized (FCMNotificationStrategy.class) { + if (defaultApplication == null) { + Path serviceAccountPath = Paths.get(FCM_SERVICE_ACCOUNT_PATH); + try { + this.defaultApplication = GoogleCredentials. + fromStream(Files.newInputStream(serviceAccountPath)). + createScoped(FCM_SCOPES); + } catch (IOException e) { + log.error("Fail to initialize default OAuth application for FCM communication"); + throw new IllegalStateException(e); + } + } } - return googleCredentials.getAccessToken().getTokenValue(); - } catch (IOException e) { - log.error("Error occurred while getting the FCM OAuth token.", e); - throw new RuntimeException(e); } } - @Override - public NotificationContext buildContext() { - return null; + private void initContextConfigs() { + PushNotificationConfiguration pushNotificationConfiguration = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig().getPushNotificationConfiguration(); + List contextMetadata = pushNotificationConfiguration.getContextMetadata(); + Properties properties = new Properties(); + if (contextMetadata != null) { + for (ContextMetadata metadata : contextMetadata) { + properties.setProperty(metadata.getKey(), metadata.getValue()); + } + } + contextMetadataProperties = properties; } - @Override - public void undeploy() { + private void sendWakeUpCall(String accessToken, String registrationId) throws IOException, + PushNotificationExecutionFailedException { + OutputStream os = null; + HttpURLConnection conn = null; - } + String fcmServerEndpoint = contextMetadataProperties.getProperty(FCM_ENDPOINT_KEY); + if(fcmServerEndpoint == null) { + String msg = "Encountered configuration issue. " + FCM_ENDPOINT_KEY + " is not defined"; + log.error(msg); + throw new PushNotificationExecutionFailedException(msg); + } + + try { + byte[] bytes = getFCMRequest(registrationId).getBytes(); + URL url = new URL(fcmServerEndpoint); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setRequestProperty("Authorization", "Bearer " + accessToken); + conn.setRequestMethod("POST"); + conn.setDoOutput(true); + + os = conn.getOutputStream(); + os.write(bytes); - private void sendWakeUpCall(String message, Device device, String token) throws IOException, - PushNotificationExecutionFailedException { - if (device.getProperties() != null) { - writeLog("===== Calling senWakeupCall " + device); - 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", "Bearer " + token); - conn.setRequestMethod("POST"); - conn.setDoOutput(true); - 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()); + } + } finally { + if (os != null) { + os.close(); } - if (status != HTTP_STATUS_CODE_OK) { - throw new PushNotificationExecutionFailedException("Push notification sending failed with the HTTP " + - "error code '" + status + "'"); + if (conn != null) { + conn.disconnect(); } } } - private static String getFCMRequest(String message, String registrationId) { - JsonObject fcmRequest = new JsonObject(); + private static String getFCMRequest(String registrationId) { JsonObject messageObject = new JsonObject(); messageObject.addProperty("token", registrationId); - JsonObject notification = new JsonObject(); - notification.addProperty("title", "FCM Message"); - notification.addProperty("body", message); - messageObject.add("notification", notification); - fcmRequest.add("message", messageObject); - - /*fcmRequest.addProperty("delay_while_idle", false); - fcmRequest.addProperty("time_to_live", TIME_TO_LIVE); - fcmRequest.addProperty("priority", "high"); + JsonObject fcmRequest = new JsonObject(); + fcmRequest.add("message", messageObject); - //Add message to FCM request - JsonObject data = new JsonObject(); - if (message != null && !message.isEmpty()) { - data.addProperty("data", message); - fcmRequest.add("data", data); - } + return fcmRequest.toString(); + } - //Set device reg-id - JsonArray regIds = new JsonArray(); - regIds.add(new JsonPrimitive(registrationId)); + @Override + public NotificationContext buildContext() { + return null; + } - fcmRequest.add("registration_ids", regIds);*/ + @Override + public void undeploy() { - writeLog("========= FCM Request " + fcmRequest); - return fcmRequest.toString(); } private static String getFCMToken(List properties) { @@ -196,21 +194,8 @@ public class FCMNotificationStrategy implements NotificationStrategy { return fcmToken; } - private static void writeLog(String message) { - try (FileWriter fw = new FileWriter("/opt/entgra/migration/entgra-uem-ultimate-6.0.3.0/log.txt", true); - BufferedWriter bw = new BufferedWriter(fw)) { - bw.write(message); - bw.newLine(); - bw.flush(); - } catch (IOException e) { - e.printStackTrace(); - } - } - @Override public PushNotificationConfig getConfig() { return config; } - - } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/ContextMetadata.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/ContextMetadata.java new file mode 100644 index 0000000000..9f89474766 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/ContextMetadata.java @@ -0,0 +1,30 @@ +package io.entgra.device.mgt.core.device.mgt.core.config.push.notification; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlValue; + +@XmlRootElement(name = "ContextMetadata") +public class ContextMetadata { + private String key; + private String value; + + @XmlAttribute(name = "key") + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/PushNotificationConfiguration.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/PushNotificationConfiguration.java index 90c6639cb1..0d64e45cdd 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/PushNotificationConfiguration.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/PushNotificationConfiguration.java @@ -33,6 +33,7 @@ public class PushNotificationConfiguration { private int schedulerTaskInitialDelay; private boolean schedulerTaskEnabled; private List pushNotificationProviders; + private List contextMetadata; @XmlElement(name = "SchedulerBatchSize", required = true) public int getSchedulerBatchSize() { @@ -79,4 +80,14 @@ public class PushNotificationConfiguration { public void setPushNotificationProviders(List pushNotificationProviders) { this.pushNotificationProviders = pushNotificationProviders; } + + @XmlElementWrapper(name = "ProviderContextMetadata") + @XmlElement(name = "ContextMetadata", required = true) + public List getContextMetadata() { + return contextMetadata; + } + + public void setContextMetadata(List contextMetadata) { + this.contextMetadata = contextMetadata; + } } diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 index 59e026f679..2d5f7639f8 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/cdm-config.xml.j2 @@ -48,6 +48,11 @@ {% endfor %} {% endif %} + {% if device_mgt_conf.push_notification_conf.fcm_server_endpoint is defined %} + + {{device_mgt_conf.push_notification_conf.fcm_server_endpoint}} + + {% endif %} {% if device_mgt_conf.pull_notification_conf is defined %} diff --git a/pom.xml b/pom.xml index 516bd8e982..2c7c6c6af3 100644 --- a/pom.xml +++ b/pom.xml @@ -405,7 +405,11 @@ ${io.entgra.device.mgt.core.version} - + + org.wso2.orbit.com.google.auth-library-oauth2-http + google-auth-library-oauth2-http + 1.20.0.wso2v1 + org.wso2.carbon @@ -1921,6 +1925,46 @@ google-auth-library-oauth2-http 1.20.0 + + org.wso2.orbit.com.google.http-client + google-http-client + ${com.google.http.client.version} + + + org.wso2.orbit.com.google.auth-library-oauth2-http + google-auth-library-oauth2-http + ${com.google.auth.library.auth2.http.version} + + + org.wso2.orbit.io.opencensus + opencensus + ${io.opencensus.version} + + + io.opencensus + opencensus-api + ${io.opencensus.api.version} + + + io.opencensus + opencensus-contrib-http-util + ${io.opencensus.contrib.http.util.version} + + + org.wso2.orbit.io.grpc + grpc-context + ${io.grpc.context.version} + + + com.google.http-client + google-http-client-gson + ${com.google.http.client.gson.version} + + + com.google.guava + failureaccess + ${com.google.failureaccess.version} + @@ -2311,6 +2355,15 @@ 4.3.1.wso2v1 1.4.199.wso2v1 1.1.3 + + 1.20.0.wso2v1 + 1.41.2.wso2v2 + 1.0.1 + 1.43.3 + 1.27.2.wso2v1 + 0.30.0.wso2v1 + 0.30.0 + 0.30.0 From b1d3503e8b3505907116d1fe4ead9f97f9bb99f1 Mon Sep 17 00:00:00 2001 From: Pahansith Date: Sun, 16 Jun 2024 18:11:19 +0530 Subject: [PATCH 04/21] Add improvements to Google API token generation in FCM --- .../provider/fcm/FCMNotificationStrategy.java | 44 ++-------- .../provider/fcm/util/FCMUtil.java | 80 +++++++++++++++++++ 2 files changed, 85 insertions(+), 39 deletions(-) create mode 100644 components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java index f003983360..033ef30293 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java @@ -22,6 +22,7 @@ import com.google.gson.JsonObject; 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.util.FCMUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Device; @@ -53,12 +54,7 @@ public class FCMNotificationStrategy implements NotificationStrategy { 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_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 static final String FCM_ENDPOINT_KEY = "FCM_SERVER_ENDPOINT"; - private Properties contextMetadataProperties; - private volatile GoogleCredentials defaultApplication; public FCMNotificationStrategy(PushNotificationConfig config) { this.config = config; @@ -66,8 +62,7 @@ public class FCMNotificationStrategy implements NotificationStrategy { @Override public void init() { - initContextConfigs(); - initDefaultOAuthApplication(); + } @Override @@ -77,8 +72,8 @@ public class FCMNotificationStrategy implements NotificationStrategy { Device device = FCMDataHolder.getInstance().getDeviceManagementProviderService() .getDeviceWithTypeProperties(ctx.getDeviceId()); if(device.getProperties() != null && getFCMToken(device.getProperties()) != null) { - defaultApplication.refresh(); - sendWakeUpCall(defaultApplication.getAccessToken().getTokenValue(), + FCMUtil.getInstance().getDefaultApplication().refresh(); + sendWakeUpCall(FCMUtil.getInstance().getDefaultApplication().getAccessToken().getTokenValue(), getFCMToken(device.getProperties())); } } else { @@ -94,43 +89,14 @@ public class FCMNotificationStrategy implements NotificationStrategy { } } - private void initDefaultOAuthApplication() { - if (defaultApplication == null) { - synchronized (FCMNotificationStrategy.class) { - if (defaultApplication == null) { - Path serviceAccountPath = Paths.get(FCM_SERVICE_ACCOUNT_PATH); - try { - this.defaultApplication = GoogleCredentials. - fromStream(Files.newInputStream(serviceAccountPath)). - createScoped(FCM_SCOPES); - } catch (IOException e) { - log.error("Fail to initialize default OAuth application for FCM communication"); - throw new IllegalStateException(e); - } - } - } - } - } - private void initContextConfigs() { - PushNotificationConfiguration pushNotificationConfiguration = DeviceConfigurationManager.getInstance(). - getDeviceManagementConfig().getPushNotificationConfiguration(); - List contextMetadata = pushNotificationConfiguration.getContextMetadata(); - Properties properties = new Properties(); - if (contextMetadata != null) { - for (ContextMetadata metadata : contextMetadata) { - properties.setProperty(metadata.getKey(), metadata.getValue()); - } - } - contextMetadataProperties = properties; - } private void sendWakeUpCall(String accessToken, String registrationId) throws IOException, PushNotificationExecutionFailedException { OutputStream os = null; HttpURLConnection conn = null; - String fcmServerEndpoint = contextMetadataProperties.getProperty(FCM_ENDPOINT_KEY); + 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); diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java new file mode 100644 index 0000000000..66212fc49b --- /dev/null +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java @@ -0,0 +1,80 @@ +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) { + log.error("Fail to initialize default OAuth application for FCM communication"); + throw new IllegalStateException(e); + } + } + } + + private void initContextConfigs() { + PushNotificationConfiguration pushNotificationConfiguration = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig().getPushNotificationConfiguration(); + List contextMetadata = pushNotificationConfiguration.getContextMetadata(); + Properties properties = new Properties(); + if (contextMetadata != null) { + for (ContextMetadata metadata : contextMetadata) { + properties.setProperty(metadata.getKey(), metadata.getValue()); + } + } + contextMetadataProperties = properties; + } + + 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; + } +} From c38aea743bb6b69e62fda0cf4fb2c63f508857c6 Mon Sep 17 00:00:00 2001 From: Pahansith Date: Tue, 25 Jun 2024 17:30:33 +0530 Subject: [PATCH 05/21] Add missing license headers --- .../notification/provider/fcm/util/FCMUtil.java | 17 +++++++++++++++++ .../push/notification/ContextMetadata.java | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java index 66212fc49b..11cef37c0f 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java @@ -1,3 +1,20 @@ +/* + * 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; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/ContextMetadata.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/ContextMetadata.java index 9f89474766..a5ead67f0a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/ContextMetadata.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/push/notification/ContextMetadata.java @@ -1,3 +1,20 @@ +/* + * Copyright (c) 2018 - 2023, 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.core.config.push.notification; import javax.xml.bind.annotation.XmlAttribute; From 23d31fd38c8f7cc24e7d3740ab109dbc3ebb1ab7 Mon Sep 17 00:00:00 2001 From: Pahansith Date: Fri, 5 Jul 2024 20:56:03 +0530 Subject: [PATCH 06/21] Fix code review suggestions --- .../provider/fcm/FCMNotificationStrategy.java | 35 +++++++++---------- .../provider/fcm/util/FCMUtil.java | 6 ++++ pom.xml | 12 +++---- 3 files changed, 27 insertions(+), 26 deletions(-) diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java index 033ef30293..39bd1ba7e5 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java @@ -17,11 +17,7 @@ */ package io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm; -import com.google.auth.oauth2.GoogleCredentials; import com.google.gson.JsonObject; -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.util.FCMUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -32,18 +28,12 @@ import io.entgra.device.mgt.core.device.mgt.common.push.notification.Notificatio import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationConfig; import io.entgra.device.mgt.core.device.mgt.common.push.notification.PushNotificationExecutionFailedException; import io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm.internal.FCMDataHolder; -import org.wso2.carbon.utils.CarbonUtils; -import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; -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 FCMNotificationStrategy implements NotificationStrategy { @@ -90,13 +80,19 @@ public class FCMNotificationStrategy implements NotificationStrategy { } - + /** + * 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 { - OutputStream os = null; HttpURLConnection conn = null; - String fcmServerEndpoint = FCMUtil.getInstance().getContextMetadataProperties().getProperty(FCM_ENDPOINT_KEY); + 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); @@ -112,23 +108,26 @@ public class FCMNotificationStrategy implements NotificationStrategy { conn.setRequestMethod("POST"); conn.setDoOutput(true); - os = conn.getOutputStream(); - os.write(bytes); + try (OutputStream os = conn.getOutputStream()) { + os.write(bytes); + } int status = conn.getResponseCode(); if (status != 200) { log.error("Response Status: " + status + ", Response Message: " + conn.getResponseMessage()); } } finally { - if (os != null) { - os.close(); - } if (conn != null) { conn.disconnect(); } } } + /** + * 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); diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java index 11cef37c0f..f7520801f6 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java @@ -76,6 +76,12 @@ public class FCMUtil { 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) { diff --git a/pom.xml b/pom.xml index 2c7c6c6af3..0120cb38cb 100644 --- a/pom.xml +++ b/pom.xml @@ -405,11 +405,6 @@ ${io.entgra.device.mgt.core.version} - - org.wso2.orbit.com.google.auth-library-oauth2-http - google-auth-library-oauth2-http - 1.20.0.wso2v1 - org.wso2.carbon @@ -1923,7 +1918,7 @@ com.google.auth google-auth-library-oauth2-http - 1.20.0 + ${com.google.auth.library.auth2.http.version} org.wso2.orbit.com.google.http-client @@ -1933,7 +1928,7 @@ org.wso2.orbit.com.google.auth-library-oauth2-http google-auth-library-oauth2-http - ${com.google.auth.library.auth2.http.version} + ${com.google.auth.library.wso2.auth2.http.version} org.wso2.orbit.io.opencensus @@ -2356,7 +2351,8 @@ 1.4.199.wso2v1 1.1.3 - 1.20.0.wso2v1 + 1.20.0.wso2v1 + 1.20.0 1.41.2.wso2v2 1.0.1 1.43.3 From 529d1aec01e8a0e904b67b3235f0523e91718b44 Mon Sep 17 00:00:00 2001 From: Pahansith Date: Fri, 5 Jul 2024 21:05:07 +0530 Subject: [PATCH 07/21] Add doc comments --- .../push/notification/provider/fcm/util/FCMUtil.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java index f7520801f6..0c6c433cc7 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.push.notification.provider.fcm/src/main/java/io/entgra/device/mgt/core/device/mgt/extensions/push/notification/provider/fcm/util/FCMUtil.java @@ -57,12 +57,17 @@ public class FCMUtil { fromStream(Files.newInputStream(serviceAccountPath)). createScoped(FCM_SCOPES); } catch (IOException e) { - log.error("Fail to initialize default OAuth application for FCM communication"); - throw new IllegalStateException(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(); From 9a99b5804f6302dffed32f30816d2cd3fa632d3c Mon Sep 17 00:00:00 2001 From: prathabanKavin Date: Wed, 10 Jul 2024 09:54:26 +0530 Subject: [PATCH 08/21] Fix user, role app installations failing --- .../core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 6ca1095faf..a04da1dd27 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -982,7 +982,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { + "e.TENANT_ID = ? AND " + "LOWER(e.OWNER) = LOWER(?) AND " + "e.STATUS IN (", - ")) e1 ORDER BY e1.DATE_OF_LAST_UPDATE DESC"); + ")) e1 WHERE d.ID = e1.DEVICE_ID ORDER BY e1.DATE_OF_LAST_UPDATE DESC"); deviceStatuses.stream().map(ignored -> "?").forEach(joiner::add); String query = joiner.toString(); From 8e33eebbf6ea7087a519353eb6bf46f1bdfb45a0 Mon Sep 17 00:00:00 2001 From: ashvini Date: Fri, 28 Jun 2024 12:38:35 +0530 Subject: [PATCH 09/21] Add tenant application artifact deletion configuration Fix code errors Remove spaces Refactor code --- .../common/services/ApplicationManager.java | 1 + .../mgt/core/impl/ApplicationManagerImpl.java | 35 ++++++++++++------- .../api/admin/UserManagementAdminService.java | 11 ++++-- .../admin/UserManagementAdminServiceImpl.java | 5 ++- 4 files changed, 35 insertions(+), 17 deletions(-) diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java index 4a1be2ea1e..bf3bdc5d40 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java @@ -547,4 +547,5 @@ public interface ApplicationManager { */ void deleteApplicationDataOfTenant(int tenantId) throws ApplicationManagementException; void deleteApplicationDataByTenantDomain(String tenantDomain) throws ApplicationManagementException; + void deleteApplicationArtifactsByTenantDomain(String tenantDomain) throws ApplicationManagementException; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java index efb55e60cb..f6d0fc228f 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java @@ -4424,7 +4424,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 +4448,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(); } @@ -4499,7 +4492,6 @@ public class ApplicationManagerImpl implements ApplicationManager { spApplicationDAO.deleteSPApplicationMappingByTenant(tenantId); spApplicationDAO.deleteIdentityServerByTenant(tenantId); applicationDAO.deleteApplicationsByTenant(tenantId); - APIUtil.getApplicationStorageManager().deleteAppFolderOfTenant(tenantId); ConnectionManagerUtil.commitDBTransaction(); } catch (DBConnectionException e) { @@ -4524,15 +4516,32 @@ public class ApplicationManagerImpl implements ApplicationManager { + " of tenant ID: " + tenantId ; log.error(msg, e); throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public void deleteApplicationArtifactsByTenantDomain(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 + "when trying to delete application artifacts of tenant"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + try { + APIUtil.getApplicationStorageManager().deleteAppFolderOfTenant(tenantId); } catch (ApplicationStorageManagementException e) { - ConnectionManagerUtil.rollbackDBTransaction(); - String msg = "Error occurred while deleting App folder of tenant" + String msg = "Error occurred while deleting Application folders of tenant" + " of tenant ID: " + tenantId ; log.error(msg, e); throw new ApplicationManagementException(msg, e); - } finally { - ConnectionManagerUtil.closeDBConnection(); } - } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java index 5d324aeb02..08b51ac9c4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/admin/UserManagementAdminService.java @@ -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); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java index d4f34d8e4a..d0e82d7fb3 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java @@ -91,7 +91,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,6 +99,9 @@ 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(); From 1576ef86d06f93984e7209748d30722d1e9fcbf2 Mon Sep 17 00:00:00 2001 From: Rajitha Kumara Date: Tue, 30 Apr 2024 08:14:23 +0530 Subject: [PATCH 10/21] App publishing improvements --- .../mgt/common/ApplicationArtifact.java | 36 ++ .../services/ApplicationStorageManager.java | 10 + .../mgt/core/impl/ApplicationManagerImpl.java | 356 +++++++++--------- .../impl/ApplicationStorageManagerImpl.java | 13 +- .../core/util/ApplicationManagementUtil.java | 5 + .../util/FileTransferServiceHelperUtil.java | 57 +++ .../common/util/StorageManagementUtil.java | 16 +- 7 files changed, 302 insertions(+), 191 deletions(-) diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationArtifact.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationArtifact.java index 371d022ec9..cbec13d3d3 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationArtifact.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/ApplicationArtifact.java @@ -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 screenshots; + private Map 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 getScreenshotPaths() { + return screenshotPaths; + } + + public void setScreenshotPaths(Map screenshotPaths) { + this.screenshotPaths = screenshotPaths; + } public String getInstallerName() { return installerName; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationStorageManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationStorageManager.java index 698c57f55a..bab015e97e 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationStorageManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationStorageManager.java @@ -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); } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java index efb55e60cb..60b61dab93 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java @@ -102,11 +102,15 @@ 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; @@ -727,20 +731,23 @@ public class ApplicationManagerImpl implements ApplicationManager { 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 (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) { - applicationStorageManager.uploadReleaseArtifact(releaseDTO, deviceType, - binaryDuplicate, tenantId); + 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()); + + applicationStorageManager.uploadReleaseArtifact(releaseDTO, deviceType, + 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); } return addImageArtifacts(releaseDTO, applicationArtifact, tenantId); } @@ -856,82 +863,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 +959,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()); - - try (ByteArrayInputStream binary = new ByteArrayInputStream(content)) { - ApplicationInstaller applicationInstaller = applicationStorageManager - .getAppInstallerData(binary, deviceType); - String packageName = applicationInstaller.getPackageName(); + 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 { - 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); - } + if (!applicationReleaseDTO.getAppHashValue().equals(md5OfApp)) { + applicationReleaseDTO.setInstallerName(applicationArtifact.getInstallerName()); + ApplicationInstaller applicationInstaller = applicationStorageManager + .getAppInstallerData(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), deviceType); + String packageName = applicationInstaller.getPackageName(); - 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 +1025,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 +3600,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) { diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java index 158361232c..167ebd84dc 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java @@ -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,13 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager public void uploadReleaseArtifact(ApplicationReleaseDTO applicationReleaseDTO, String deviceType, InputStream binaryFile, int tenantId) throws ResourceManagementException { try { - byte [] content = IOUtils.toByteArray(binaryFile); + //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 +325,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(); + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java index 846777c794..6374aadb13 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/ApplicationManagementUtil.java @@ -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 screenshotData = new TreeMap<>(); + Map screenshotPaths = new TreeMap<>(); // This is to handle cases in which multiple screenshots have the same name Map 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); } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/FileTransferServiceHelperUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/FileTransferServiceHelperUtil.java index 570998ebef..1a44848b87 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/FileTransferServiceHelperUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/FileTransferServiceHelperUtil.java @@ -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,53 @@ public class FileTransferServiceHelperUtil { throw new FileTransferServiceHelperUtilException("Error encountered while creating artifact file", e); } } + + private static FileDescriptor resolve(String []urlSegments) throws FileTransferServiceHelperUtilException { + if (urlSegments.length < 4) { + if (log.isDebugEnabled()) { + log.debug("URL path segments contain less than 2 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); + } + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/StorageManagementUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/StorageManagementUtil.java index 979a514db5..bf37d0bab6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/StorageManagementUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/common/util/StorageManagementUtil.java @@ -23,6 +23,8 @@ import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.Base64File; import io.entgra.device.mgt.core.device.mgt.core.common.exception.StorageManagementException; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -31,6 +33,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; +import java.nio.file.Paths; /** * This is a util class that handles Storage Management related tasks. @@ -87,13 +90,14 @@ public class StorageManagementUtil { * @param path Path the file need to be saved in. */ public static void saveFile(InputStream inputStream, String path) throws IOException { - try (OutputStream outStream = new FileOutputStream(new File(path))) { - byte[] buffer = new byte[inputStream.available()]; - if (inputStream.read(buffer) != -1) { - outStream.write(buffer); + try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(Files.newOutputStream(Paths.get(path))); + BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) { + byte []buffer = new byte[8192]; + int n; + while ((n = bufferedInputStream.read(buffer)) != -1) { + bufferedOutputStream.write(buffer, 0, n); } - } finally { - inputStream.close(); + bufferedOutputStream.flush(); } } From 2eb73213f3137aed5620f2de66b19da3ca67d2a1 Mon Sep 17 00:00:00 2001 From: Rajitha Kumara Date: Sat, 25 May 2024 07:00:05 +0530 Subject: [PATCH 11/21] Add requested changes --- .../mgt/core/impl/ApplicationManagerImpl.java | 50 ++++++++++--------- .../impl/ApplicationStorageManagerImpl.java | 1 - .../core/impl/FileTransferServiceImpl.java | 10 +++- .../util/FileTransferServiceHelperUtil.java | 3 +- 4 files changed, 36 insertions(+), 28 deletions(-) diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java index 60b61dab93..f560d8ce82 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java @@ -727,19 +727,20 @@ 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(); try { - String md5OfApp = applicationStorageManager.getMD5(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath()))); + String md5OfApp = applicationStorageManager. + getMD5(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath()))); validateReleaseBinaryFileHash(md5OfApp); releaseDTO.setUuid(UUID.randomUUID().toString()); releaseDTO.setAppHashValue(md5OfApp); releaseDTO.setInstallerName(applicationArtifact.getInstallerName()); - applicationStorageManager.uploadReleaseArtifact(releaseDTO, deviceType, - Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), tenantId); + applicationStorageManager.uploadReleaseArtifact(releaseDTO, deviceType, + Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), tenantId); } catch (IOException e) { String msg = "Error occurred when uploading release artifact into the server"; log.error(msg); @@ -748,6 +749,7 @@ public class ApplicationManagerImpl implements ApplicationManager { 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); } @@ -896,7 +898,8 @@ public class ApplicationManagerImpl implements ApplicationManager { log.error(msg); throw new ApplicationManagementException(msg); } - String md5OfApp = applicationStorageManager.getMD5(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath()))); + 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(); @@ -910,10 +913,9 @@ public class ApplicationManagerImpl implements ApplicationManager { throw new BadRequestException(msg); } applicationReleaseDTO.setAppHashValue(md5OfApp); - - applicationStorageManager - .uploadReleaseArtifact(applicationReleaseDTO, deviceType, - Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), tenantId); + 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(); @@ -969,9 +971,9 @@ public class ApplicationManagerImpl implements ApplicationManager { if (!applicationReleaseDTO.getAppHashValue().equals(md5OfApp)) { applicationReleaseDTO.setInstallerName(applicationArtifact.getInstallerName()); - ApplicationInstaller applicationInstaller = applicationStorageManager - .getAppInstallerData(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), deviceType); - String packageName = applicationInstaller.getPackageName(); + ApplicationInstaller applicationInstaller = applicationStorageManager + .getAppInstallerData(Files.newInputStream(Paths.get(applicationArtifact.getInstallerPath())), deviceType); + String packageName = applicationInstaller.getPackageName(); try { ConnectionManagerUtil.getDBConnection(); @@ -981,13 +983,13 @@ public class ApplicationManagerImpl implements ApplicationManager { log.error(msg); throw new BadRequestException(msg); } - if (applicationReleaseDTO.getPackageName() == null){ + 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)){ + 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 " @@ -1000,11 +1002,11 @@ public class ApplicationManagerImpl implements ApplicationManager { 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); + 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."; @@ -3625,11 +3627,11 @@ public class ApplicationManagerImpl implements ApplicationManager { 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); + 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."; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java index 167ebd84dc..ad1906ede1 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationStorageManagerImpl.java @@ -156,7 +156,6 @@ 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; diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/FileTransferServiceImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/FileTransferServiceImpl.java index 52789308fd..8af3324c67 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/FileTransferServiceImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/FileTransferServiceImpl.java @@ -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); diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/FileTransferServiceHelperUtil.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/FileTransferServiceHelperUtil.java index 1a44848b87..856faf4944 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/FileTransferServiceHelperUtil.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/FileTransferServiceHelperUtil.java @@ -244,9 +244,10 @@ public class FileTransferServiceHelperUtil { } 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 2 segments"); + log.debug("URL path segments contain less than 4 segments"); } return null; } From f9cea050aefb7b559ac78a7b899b8cf2a19fcebc Mon Sep 17 00:00:00 2001 From: prathabanKavin Date: Wed, 10 Jul 2024 11:22:17 +0530 Subject: [PATCH 12/21] Fix user,role removed devices --- .../core/device/mgt/core/dao/EnrollmentDAO.java | 3 ++- .../dao/impl/AbstractEnrollmentDAOImpl.java | 17 ++++++++++++++--- .../DeviceManagementProviderServiceImpl.java | 7 ++++++- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java index 93c456f929..df812fc62f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java @@ -101,11 +101,12 @@ public interface EnrollmentDAO { * Retrieves owners and the list of device IDs related to an owner. * * @param owner the owner whose device IDs need to be retrieved + * @param allowingDeviceStatuses statuses of devices need to be retrieved * @param tenantId the ID of the tenant * @return {@link OwnerWithDeviceDTO} which contains a list of devices related to a user * @throws DeviceManagementDAOException if an error occurs while fetching the data */ - OwnerWithDeviceDTO getOwnersWithDevices(String owner, int tenantId) throws DeviceManagementDAOException; + OwnerWithDeviceDTO getOwnersWithDevices(String owner, List allowingDeviceStatuses, int tenantId) throws DeviceManagementDAOException; /** * Retrieves a list of device IDs with owners and device status. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java index dad35f0795..7e02bd7ac0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java @@ -564,23 +564,34 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { } @Override - public OwnerWithDeviceDTO getOwnersWithDevices(String owner, int tenantId) + public OwnerWithDeviceDTO getOwnersWithDevices(String owner, List allowingDeviceStatuses, int tenantId) throws DeviceManagementDAOException { Connection conn = null; OwnerWithDeviceDTO ownerDetails = new OwnerWithDeviceDTO(); List deviceIds = new ArrayList<>(); int deviceCount = 0; + StringBuilder deviceFilters = new StringBuilder(); + for (int i = 0; i < allowingDeviceStatuses.size(); i++) { + deviceFilters.append("?"); + if (i < allowingDeviceStatuses.size() - 1) { + deviceFilters.append(","); + } + } + String sql = "SELECT e.DEVICE_ID, e.OWNER, e.STATUS AS DEVICE_STATUS, d.NAME AS DEVICE_NAME, e.DEVICE_TYPE AS DEVICE_TYPE, e.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION " + "FROM DM_ENROLMENT e " + "JOIN DM_DEVICE d ON e.DEVICE_ID = d.ID " + - "WHERE e.OWNER = ? AND e.TENANT_ID = ?"; + "WHERE e.OWNER = ? AND e.TENANT_ID = ? AND e.STATUS IN (" + deviceFilters.toString() + ")"; + try { conn = this.getConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, owner); stmt.setInt(2, tenantId); - + for (int i = 0; i < allowingDeviceStatuses.size(); i++) { + stmt.setString(3 + i, allowingDeviceStatuses.get(i)); + } try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { if (ownerDetails.getUserName() == null) { diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index a3039ba356..d2d73dc92a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -5358,9 +5358,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); OwnerWithDeviceDTO ownerWithDeviceDTO; + List allowingDeviceStatuses = new ArrayList<>(); + allowingDeviceStatuses.add(EnrolmentInfo.Status.ACTIVE.toString()); + allowingDeviceStatuses.add(EnrolmentInfo.Status.INACTIVE.toString()); + allowingDeviceStatuses.add(EnrolmentInfo.Status.UNREACHABLE.toString()); + try { DeviceManagementDAOFactory.openConnection(); - ownerWithDeviceDTO = this.enrollmentDAO.getOwnersWithDevices(owner, tenantId); + ownerWithDeviceDTO = this.enrollmentDAO.getOwnersWithDevices(owner, allowingDeviceStatuses, tenantId); if (ownerWithDeviceDTO == null) { String msg = "No data found for owner: " + owner; log.error(msg); From 68a4de92d654ea38244610d51358b0896c0258c3 Mon Sep 17 00:00:00 2001 From: prathabanKavin Date: Thu, 11 Jul 2024 00:49:59 +0530 Subject: [PATCH 13/21] Fix all,device,group removed devices --- .../device/mgt/core/dao/EnrollmentDAO.java | 2 +- .../core/device/mgt/core/dao/GroupDAO.java | 2 +- .../dao/impl/AbstractEnrollmentDAOImpl.java | 23 +++++++-- .../core/dao/impl/AbstractGroupDAOImpl.java | 49 ++++++++++++------- .../DeviceManagementProviderServiceImpl.java | 6 ++- .../GroupManagementProviderServiceImpl.java | 12 ++--- 6 files changed, 64 insertions(+), 30 deletions(-) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java index df812fc62f..4a4be1e0c3 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java @@ -126,5 +126,5 @@ public interface EnrollmentDAO { * @return {@link OwnerWithDeviceDTO} which contains a list of devices related to a user * @throws DeviceManagementDAOException if an error occurs while fetching the data */ - List getDevicesByTenantId(int tenantId) throws DeviceManagementDAOException; + List getDevicesByTenantId(int tenantId, List allowingDeviceStatuses) throws DeviceManagementDAOException; } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java index 5071f7a400..3e3fde8205 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java @@ -479,7 +479,7 @@ public interface GroupDAO { * @return {@link GroupDetailsDTO} which containing group details and a list of device IDs * @throws GroupManagementDAOException if an error occurs while retrieving the group details and devices */ - GroupDetailsDTO getGroupDetailsWithDevices(String groupName, int tenantId, int offset, int limit) + GroupDetailsDTO getGroupDetailsWithDevices(String groupName, List allowingDeviceStatuses, int tenantId, int offset, int limit) throws GroupManagementDAOException; } \ No newline at end of file diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java index 7e02bd7ac0..b8ad6f86df 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java @@ -654,18 +654,34 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { } @Override - public List getDevicesByTenantId(int tenantId) + public List getDevicesByTenantId(int tenantId, List allowingDeviceStatuses) throws DeviceManagementDAOException { List devices = new ArrayList<>(); + if (allowingDeviceStatuses.isEmpty()) { + return devices; + } + + StringBuilder deviceFilters = new StringBuilder(); + for (int i = 0; i < allowingDeviceStatuses.size(); i++) { + deviceFilters.append("?"); + if (i < allowingDeviceStatuses.size() - 1) { + deviceFilters.append(","); + } + } + String sql = "SELECT DEVICE_ID, OWNER, STATUS, DEVICE_TYPE, DEVICE_IDENTIFICATION " + "FROM DM_ENROLMENT " + - "WHERE TENANT_ID = ?"; + "WHERE TENANT_ID = ? AND STATUS IN (" + deviceFilters.toString() + ")"; Connection conn = null; try { conn = this.getConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setInt(1, tenantId); + int index = 1; + stmt.setInt(index++, tenantId); + for (String status : allowingDeviceStatuses) { + stmt.setString(index++, status); + } try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { @@ -687,4 +703,5 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { return devices; } + } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java index 780ba43cc6..1d9084eb7b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java @@ -1441,7 +1441,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { } @Override - public GroupDetailsDTO getGroupDetailsWithDevices(String groupName, int tenantId, int offset, int limit) + public GroupDetailsDTO getGroupDetailsWithDevices(String groupName, List allowedStatuses, int tenantId, int offset, int limit) throws GroupManagementDAOException { if (log.isDebugEnabled()) { log.debug("Request received in DAO Layer to get group details and device IDs for group: " + groupName); @@ -1454,6 +1454,14 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { Map deviceTypes = new HashMap<>(); Map deviceIdentifiers = new HashMap<>(); + StringBuilder deviceFilters = new StringBuilder(); + for (int i = 0; i < allowedStatuses.size(); i++) { + deviceFilters.append("?"); + if (i < allowedStatuses.size() - 1) { + deviceFilters.append(","); + } + } + String sql = "SELECT " + " g.ID AS GROUP_ID, " + @@ -1473,16 +1481,21 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { "WHERE " + " g.GROUP_NAME = ? " + " AND g.TENANT_ID = ? " + + " AND e.STATUS IN (" + deviceFilters.toString() + ") " + "LIMIT ? OFFSET ?"; Connection conn = null; try { conn = GroupManagementDAOFactory.getConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setString(1, groupName); - stmt.setInt(2, tenantId); - stmt.setInt(3, limit); - stmt.setInt(4, offset); + int index = 1; + stmt.setString(index++, groupName); + stmt.setInt(index++, tenantId); + for (String status : allowedStatuses) { + stmt.setString(index++, status); + } + stmt.setInt(index++, limit); + stmt.setInt(index++, offset); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { @@ -1500,19 +1513,19 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { deviceIdentifiers.put(deviceId, rs.getString("DEVICE_IDENTIFICATION")); } } - groupDetails.setDeviceIds(deviceIds); - groupDetails.setDeviceCount(deviceIds.size()); - groupDetails.setDeviceOwners(deviceOwners); - groupDetails.setDeviceStatuses(deviceStatuses); - groupDetails.setDeviceNames(deviceNames); - groupDetails.setDeviceTypes(deviceTypes); - groupDetails.setDeviceIdentifiers(deviceIdentifiers); - return groupDetails; + groupDetails.setDeviceIds(deviceIds); + groupDetails.setDeviceCount(deviceIds.size()); + groupDetails.setDeviceOwners(deviceOwners); + groupDetails.setDeviceStatuses(deviceStatuses); + groupDetails.setDeviceNames(deviceNames); + groupDetails.setDeviceTypes(deviceTypes); + groupDetails.setDeviceIdentifiers(deviceIdentifiers); + return groupDetails; + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving group details and device IDs for group: " + groupName; + log.error(msg, e); + throw new GroupManagementDAOException(msg, e); } - } catch (SQLException e) { - String msg = "Error occurred while retrieving group details and device IDs for group: " + groupName; - log.error(msg, e); - throw new GroupManagementDAOException(msg, e); - } } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index d2d73dc92a..5d33953a56 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -5418,9 +5418,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public List getDevicesByTenantId(int tenantId) throws DeviceManagementDAOException { List devices; + List allowingDeviceStatuses = new ArrayList<>(); + allowingDeviceStatuses.add(EnrolmentInfo.Status.ACTIVE.toString()); + allowingDeviceStatuses.add(EnrolmentInfo.Status.INACTIVE.toString()); + allowingDeviceStatuses.add(EnrolmentInfo.Status.UNREACHABLE.toString()); try { DeviceManagementDAOFactory.openConnection(); - devices = enrollmentDAO.getDevicesByTenantId(tenantId); + devices = enrollmentDAO.getDevicesByTenantId(tenantId, allowingDeviceStatuses); if (devices == null || devices.isEmpty()) { String msg = "No devices found for tenant ID: " + tenantId; log.error(msg); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java index c42feed9b8..bd10cac78a 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.core.service; +import io.entgra.device.mgt.core.device.mgt.common.*; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupConstants; import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper; @@ -39,13 +40,8 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import io.entgra.device.mgt.core.device.mgt.common.Device; -import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier; -import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceNotFoundException; -import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest; -import io.entgra.device.mgt.core.device.mgt.common.PaginationResult; import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException; import io.entgra.device.mgt.core.device.mgt.core.event.config.GroupAssignmentEventOperationExecutor; import io.entgra.device.mgt.core.device.mgt.core.geo.task.GeoFenceEventOperationManager; @@ -1695,10 +1691,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); GroupDetailsDTO groupDetailsWithDevices; + List allowingDeviceStatuses = new ArrayList<>(); + allowingDeviceStatuses.add(EnrolmentInfo.Status.ACTIVE.toString()); + allowingDeviceStatuses.add(EnrolmentInfo.Status.INACTIVE.toString()); + allowingDeviceStatuses.add(EnrolmentInfo.Status.UNREACHABLE.toString()); try { GroupManagementDAOFactory.openConnection(); - groupDetailsWithDevices = this.groupDAO.getGroupDetailsWithDevices(groupName, tenantId, offset, limit); + groupDetailsWithDevices = this.groupDAO.getGroupDetailsWithDevices(groupName, allowingDeviceStatuses, tenantId, offset, limit); } catch (GroupManagementDAOException | SQLException e) { String msg = "Error occurred while retrieving group details and device IDs for group: " + groupName; log.error(msg, e); From d566cf966a1c68ae353a5fabff7e995b04210ca3 Mon Sep 17 00:00:00 2001 From: navodzoysa Date: Sat, 6 Jul 2024 15:49:41 +0530 Subject: [PATCH 14/21] Add Microsoft Store integration for Windows devices --- .../mgt/core/impl/ApplicationManagerImpl.java | 2 + .../application/mgt/core/util/Constants.java | 1 + .../device/mgt/common/MDMAppConstants.java | 2 + .../app/mgt/windows/AppStoreApplication.java | 49 +++++ .../core/util/MDMWindowsOperationUtil.java | 184 ++++++++---------- .../src/main/resources/conf/mdm-ui-config.xml | 1 + 6 files changed, 139 insertions(+), 100 deletions(-) create mode 100644 components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/app/mgt/windows/AppStoreApplication.java diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java index efb55e60cb..721ab4decb 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java @@ -769,6 +769,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); } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java index b5b5fd5154..0b22db0668 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/util/Constants.java @@ -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 diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/MDMAppConstants.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/MDMAppConstants.java index 60d9503c97..da1714ede0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/MDMAppConstants.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/MDMAppConstants.java @@ -58,6 +58,8 @@ 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 diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/app/mgt/windows/AppStoreApplication.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/app/mgt/windows/AppStoreApplication.java new file mode 100644 index 0000000000..85a6cbd9a1 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/app/mgt/windows/AppStoreApplication.java @@ -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); + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMWindowsOperationUtil.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMWindowsOperationUtil.java index a1f0e0e31d..14050b6ea4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMWindowsOperationUtil.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/util/MDMWindowsOperationUtil.java @@ -27,6 +27,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.App; +import io.entgra.device.mgt.core.device.mgt.common.app.mgt.windows.AppStoreApplication; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.windows.EnterpriseApplication; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.windows.HostedAppxApplication; import io.entgra.device.mgt.core.device.mgt.common.app.mgt.windows.HostedMSIApplication; @@ -62,64 +63,26 @@ public class MDMWindowsOperationUtil { switch (application.getType()) { case ENTERPRISE: - operation.setCode(MDMAppConstants.WindowsConstants.INSTALL_ENTERPRISE_APPLICATION); EnterpriseApplication enterpriseApplication = new EnterpriseApplication(); - if (appType.equalsIgnoreCase(MDMAppConstants.WindowsConstants.APPX)) { - HostedAppxApplication hostedAppxApplication = new HostedAppxApplication(); - List dependencyPackageList = new ArrayList<>(); - for (int i = 0; i < metaJsonArray.size(); i++) { - JsonElement metaElement = metaJsonArray.get(i); - JsonObject metaObject = metaElement.getAsJsonObject(); - - if (MDMAppConstants.WindowsConstants.APPX_PACKAGE_URI.equals(metaObject.get("key").getAsString())) { - hostedAppxApplication.setPackageUri(metaObject.get("value").getAsString().trim()); - } - else if (MDMAppConstants.WindowsConstants.APPX_PACKAGE_FAMILY_NAME.equals(metaObject.get("key").getAsString())) { - hostedAppxApplication.setPackageFamilyName(metaObject.get("value").getAsString().trim()); - } - else if (MDMAppConstants.WindowsConstants.APPX_DEPENDENCY_PACKAGE_URL.equals(metaObject.get("key").getAsString()) - && metaObject.has("value")) { - dependencyPackageList.add(metaObject.get("value").getAsString().trim()); - hostedAppxApplication.setDependencyPackageUri(dependencyPackageList); - } - else if (MDMAppConstants.WindowsConstants.APPX_CERTIFICATE_HASH.equals(metaObject.get("key").getAsString()) - && metaObject.has("value")) { - hostedAppxApplication.setCertificateHash(metaObject.get("value").getAsString().trim()); - } - else if (MDMAppConstants.WindowsConstants.APPX_ENCODED_CERT_CONTENT.equals(metaObject.get("key").getAsString()) - && metaObject.has("value")) { - hostedAppxApplication.setEncodedCertificate(metaObject.get("value").getAsString().trim()); - } - } - enterpriseApplication.setHostedAppxApplication(hostedAppxApplication); - - } else if (appType.equalsIgnoreCase(MDMAppConstants.WindowsConstants.MSI)) { - HostedMSIApplication hostedMSIApplication = new HostedMSIApplication(); - for (int i = 0; i < metaJsonArray.size(); i++) { - JsonElement metaElement = metaJsonArray.get(i); - JsonObject metaObject = metaElement.getAsJsonObject(); - if (MDMAppConstants.WindowsConstants.MSI_PRODUCT_ID.equals(metaObject.get("key").getAsString())) { - hostedMSIApplication.setProductId(metaObject.get("value").getAsString().trim()); - } - else if (MDMAppConstants.WindowsConstants.MSI_CONTENT_URI.equals(metaObject.get("key").getAsString())) { - hostedMSIApplication.setContentUrl(metaObject.get("value").getAsString().trim()); - } - else if (MDMAppConstants.WindowsConstants.MSI_FILE_HASH.equals(metaObject.get("key").getAsString())) { - hostedMSIApplication.setFileHash(metaObject.get("value").getAsString().trim()); - } - } - enterpriseApplication.setHostedMSIApplication(hostedMSIApplication); - } + createEnterpriseAppPayload(appType, metaJsonArray, enterpriseApplication); + operation.setCode(MDMAppConstants.WindowsConstants.INSTALL_ENTERPRISE_APPLICATION); operation.setPayLoad(enterpriseApplication.toJSON()); break; + case PUBLIC: + AppStoreApplication appStoreApplication = new AppStoreApplication(); + appStoreApplication.setType(application.getType().toString()); + appStoreApplication.setPackageIdentifier(application.getIdentifier()); + operation.setCode(MDMAppConstants.WindowsConstants.INSTALL_STORE_APPLICATION); + operation.setPayLoad(appStoreApplication.toJSON()); + break; case WEB_CLIP: - operation.setCode(MDMAppConstants.WindowsConstants.INSTALL_WEB_CLIP_APPLICATION); WebClipApplication webClipApplication = new WebClipApplication(); webClipApplication.setUrl(application.getLocation()); webClipApplication.setName(application.getName()); webClipApplication.setIcon(application.getIconImage()); webClipApplication.setProperties(application.getProperties()); webClipApplication.setType(application.getType().toString()); + operation.setCode(MDMAppConstants.WindowsConstants.INSTALL_WEB_CLIP_APPLICATION); operation.setPayLoad(webClipApplication.toJSON()); break; default: @@ -148,64 +111,26 @@ public class MDMWindowsOperationUtil { switch (application.getType()) { case ENTERPRISE: - operation.setCode(MDMAppConstants.WindowsConstants.UNINSTALL_ENTERPRISE_APPLICATION); EnterpriseApplication enterpriseApplication = new EnterpriseApplication(); - if (appType.equalsIgnoreCase(MDMAppConstants.WindowsConstants.APPX)) { - HostedAppxApplication hostedAppxApplication = new HostedAppxApplication(); - List dependencyPackageList = new ArrayList<>(); - for (int i = 0; i < metaJsonArray.size(); i++) { - JsonElement metaElement = metaJsonArray.get(i); - JsonObject metaObject = metaElement.getAsJsonObject(); - - if (MDMAppConstants.WindowsConstants.APPX_PACKAGE_URI.equals(metaObject.get("key").getAsString())) { - hostedAppxApplication.setPackageUri(metaObject.get("value").getAsString().trim()); - } - else if (MDMAppConstants.WindowsConstants.APPX_PACKAGE_FAMILY_NAME.equals(metaObject.get("key").getAsString())) { - hostedAppxApplication.setPackageFamilyName(metaObject.get("value").getAsString().trim()); - } - else if (MDMAppConstants.WindowsConstants.APPX_DEPENDENCY_PACKAGE_URL.equals(metaObject.get("key").getAsString()) - && metaObject.has("value")) { - dependencyPackageList.add(metaObject.get("value").getAsString().trim()); - hostedAppxApplication.setDependencyPackageUri(dependencyPackageList); - } - else if (MDMAppConstants.WindowsConstants.APPX_CERTIFICATE_HASH.equals(metaObject.get("key").getAsString()) - && metaObject.has("value")) { - hostedAppxApplication.setCertificateHash(metaObject.get("value").getAsString().trim()); - } - else if (MDMAppConstants.WindowsConstants.APPX_ENCODED_CERT_CONTENT.equals(metaObject.get("key").getAsString()) - && metaObject.has("value")) { - hostedAppxApplication.setEncodedCertificate(metaObject.get("value").getAsString().trim()); - } - } - enterpriseApplication.setHostedAppxApplication(hostedAppxApplication); - - } else if (appType.equalsIgnoreCase(MDMAppConstants.WindowsConstants.MSI)) { - HostedMSIApplication hostedMSIApplication = new HostedMSIApplication(); - for (int i = 0; i < metaJsonArray.size(); i++) { - JsonElement metaElement = metaJsonArray.get(i); - JsonObject metaObject = metaElement.getAsJsonObject(); - if (MDMAppConstants.WindowsConstants.MSI_PRODUCT_ID.equals(metaObject.get("key").getAsString())) { - hostedMSIApplication.setProductId(metaObject.get("value").getAsString().trim()); - } - else if (MDMAppConstants.WindowsConstants.MSI_CONTENT_URI.equals(metaObject.get("key").getAsString())) { - hostedMSIApplication.setContentUrl(metaObject.get("value").getAsString().trim()); - } - else if (MDMAppConstants.WindowsConstants.MSI_FILE_HASH.equals(metaObject.get("key").getAsString())) { - hostedMSIApplication.setFileHash(metaObject.get("value").getAsString().trim()); - } - } - enterpriseApplication.setHostedMSIApplication(hostedMSIApplication); - } + createEnterpriseAppPayload(appType, metaJsonArray, enterpriseApplication); + operation.setCode(MDMAppConstants.WindowsConstants.UNINSTALL_ENTERPRISE_APPLICATION); operation.setPayLoad(enterpriseApplication.toJSON()); break; + case PUBLIC: + AppStoreApplication appStoreApplication = new AppStoreApplication(); + appStoreApplication.setType(application.getType().toString()); + appStoreApplication.setPackageIdentifier(application.getIdentifier()); + operation.setCode(MDMAppConstants.WindowsConstants.UNINSTALL_STORE_APPLICATION); + operation.setPayLoad(appStoreApplication.toJSON()); + break; case WEB_CLIP: - operation.setCode(MDMAppConstants.WindowsConstants.UNINSTALL_WEB_CLIP_APPLICATION); WebClipApplication webClipApplication = new WebClipApplication(); webClipApplication.setUrl(application.getLocation()); webClipApplication.setName(application.getName()); webClipApplication.setIcon(application.getIconImage()); webClipApplication.setProperties(application.getProperties()); webClipApplication.setType(application.getType().toString()); + operation.setCode(MDMAppConstants.WindowsConstants.UNINSTALL_WEB_CLIP_APPLICATION); operation.setPayLoad(webClipApplication.toJSON()); default: String msg = "Application type " + application.getType() + " is not supported"; @@ -216,6 +141,67 @@ public class MDMWindowsOperationUtil { return operation; } + /** + * Helper method to create enterprise APPX and MSI app payloads for both install and uninstall operations + * @param appType contains whether the app type is APPX or MSI + * @param metaJsonArray JSON array containing metadata of APPX and MSI apps + * @param enterpriseApplication {@link EnterpriseApplication} contains operation payload content that will be sent to the device + */ + private static void createEnterpriseAppPayload(String appType, JsonArray metaJsonArray, EnterpriseApplication enterpriseApplication) { + + JsonElement metaElement; + JsonObject metaObject; + if (MDMAppConstants.WindowsConstants.APPX.equalsIgnoreCase(appType)) { + HostedAppxApplication hostedAppxApplication = new HostedAppxApplication(); + List dependencyPackageList = new ArrayList<>(); + + for (int i = 0; i < metaJsonArray.size(); i++) { + metaElement = metaJsonArray.get(i); + metaObject = metaElement.getAsJsonObject(); + + if (MDMAppConstants.WindowsConstants.APPX_PACKAGE_URI.equals(metaObject.get("key").getAsString())) { + hostedAppxApplication.setPackageUri(metaObject.get("value").getAsString().trim()); + } + else if (MDMAppConstants.WindowsConstants.APPX_PACKAGE_FAMILY_NAME.equals(metaObject.get("key").getAsString())) { + hostedAppxApplication.setPackageFamilyName(metaObject.get("value").getAsString().trim()); + } + else if (MDMAppConstants.WindowsConstants.APPX_DEPENDENCY_PACKAGE_URL.equals(metaObject.get("key").getAsString()) + && metaObject.has("value")) { + dependencyPackageList.add(metaObject.get("value").getAsString().trim()); + hostedAppxApplication.setDependencyPackageUri(dependencyPackageList); + } + else if (MDMAppConstants.WindowsConstants.APPX_CERTIFICATE_HASH.equals(metaObject.get("key").getAsString()) + && metaObject.has("value")) { + hostedAppxApplication.setCertificateHash(metaObject.get("value").getAsString().trim()); + } + else if (MDMAppConstants.WindowsConstants.APPX_ENCODED_CERT_CONTENT.equals(metaObject.get("key").getAsString()) + && metaObject.has("value")) { + hostedAppxApplication.setEncodedCertificate(metaObject.get("value").getAsString().trim()); + } + } + enterpriseApplication.setHostedAppxApplication(hostedAppxApplication); + + } else if (MDMAppConstants.WindowsConstants.MSI.equalsIgnoreCase(appType)) { + HostedMSIApplication hostedMSIApplication = new HostedMSIApplication(); + + for (int i = 0; i < metaJsonArray.size(); i++) { + metaElement = metaJsonArray.get(i); + metaObject = metaElement.getAsJsonObject(); + + if (MDMAppConstants.WindowsConstants.MSI_PRODUCT_ID.equals(metaObject.get("key").getAsString())) { + hostedMSIApplication.setProductId(metaObject.get("value").getAsString().trim()); + } + else if (MDMAppConstants.WindowsConstants.MSI_CONTENT_URI.equals(metaObject.get("key").getAsString())) { + hostedMSIApplication.setContentUrl(metaObject.get("value").getAsString().trim()); + } + else if (MDMAppConstants.WindowsConstants.MSI_FILE_HASH.equals(metaObject.get("key").getAsString())) { + hostedMSIApplication.setFileHash(metaObject.get("value").getAsString().trim()); + } + } + enterpriseApplication.setHostedMSIApplication(hostedMSIApplication); + } + } + /** * Method to get the installer file extension type for windows type apps(either appx or msi) * @@ -223,8 +209,7 @@ public class MDMWindowsOperationUtil { * @return string extension of the windows app types(either appx or msi) */ public static String windowsAppType(String installerName) { - String extension = installerName.substring(installerName.lastIndexOf(".") + 1); - return extension; + return installerName.substring(installerName.lastIndexOf(".") + 1); } /** @@ -234,8 +219,7 @@ public class MDMWindowsOperationUtil { * @return the metaData Json String as Json Array */ public static JsonArray jsonStringToArray(String metaData) { - JsonArray metaJsonArray = new JsonParser().parse(metaData).getAsJsonArray(); - return metaJsonArray; + return new JsonParser().parse(metaData).getAsJsonArray(); } diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml index 32dc388789..65ffa660c8 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml @@ -387,6 +387,7 @@ win:ops:device-info win:ops:security-info win:ops:firewall-info + win:microsoft-store:search admin:tenant:view dm:admin:devices:usage:view and:ops:clear-app From 953f72afdccc06439f5e3e8ffe7abc794984afdf Mon Sep 17 00:00:00 2001 From: prathabanKavin Date: Thu, 11 Jul 2024 07:56:34 +0530 Subject: [PATCH 15/21] Filter devices according to their devicetype --- .../core/impl/SubscriptionManagerImpl.java | 23 ++++++++++++------- .../device/mgt/core/dao/EnrollmentDAO.java | 6 +++-- .../core/device/mgt/core/dao/GroupDAO.java | 4 +++- .../dao/impl/AbstractEnrollmentDAOImpl.java | 19 +++++++-------- .../core/dao/impl/AbstractGroupDAOImpl.java | 4 +++- .../DeviceManagementProviderService.java | 6 +++-- .../DeviceManagementProviderServiceImpl.java | 8 +++---- .../GroupManagementProviderService.java | 3 ++- .../GroupManagementProviderServiceImpl.java | 4 ++-- 9 files changed, 47 insertions(+), 30 deletions(-) diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java index 498abe0b02..6bb902d6b3 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -1720,8 +1720,9 @@ public class SubscriptionManagerImpl implements SubscriptionManager { log.error(msg); throw new NotFoundException(msg); } + ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(uuid, tenantId); int appReleaseId = applicationReleaseDTO.getId(); - + int deviceTypeId = applicationDTO.getDeviceTypeId(); List groupDetailsWithDevices = new ArrayList<>(); List groupDetails = @@ -1737,7 +1738,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { // Retrieve group details and device IDs for the group using the service layer GroupDetailsDTO groupDetailWithDevices = - groupManagementProviderService.getGroupDetailsWithDevices(groupName, offset, limit); + groupManagementProviderService.getGroupDetailsWithDevices(groupName, deviceTypeId, offset, limit); SubscriptionsDTO groupDetailDTO = new SubscriptionsDTO(); groupDetailDTO.setId(groupDetailWithDevices.getGroupId()); @@ -1910,8 +1911,9 @@ public class SubscriptionManagerImpl implements SubscriptionManager { log.error(msg); throw new NotFoundException(msg); } + ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(uuid, tenantId); int appReleaseId = applicationReleaseDTO.getId(); - + int deviceTypeId = applicationDTO.getDeviceTypeId(); List userSubscriptionsWithDevices = new ArrayList<>(); List userSubscriptions = @@ -1927,7 +1929,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { // Retrieve owner details and device IDs for the user using the service layer OwnerWithDeviceDTO ownerDetailsWithDevices = - deviceManagementProviderService.getOwnersWithDeviceIds(userName); + deviceManagementProviderService.getOwnersWithDeviceIds(userName, deviceTypeId); SubscriptionsDTO userSubscriptionDTO = new SubscriptionsDTO(); userSubscriptionDTO.setName(userSubscription.getName()); @@ -2097,8 +2099,9 @@ public class SubscriptionManagerImpl implements SubscriptionManager { log.error(msg); throw new NotFoundException(msg); } + ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(uuid, tenantId); int appReleaseId = applicationReleaseDTO.getId(); - + int deviceTypeId = applicationDTO.getDeviceTypeId(); List roleSubscriptionsWithDevices = new ArrayList<>(); List roleSubscriptions = @@ -2139,7 +2142,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { for (String user : users) { OwnerWithDeviceDTO ownerDetailsWithDevices; try { - ownerDetailsWithDevices = deviceManagementProviderService.getOwnersWithDeviceIds(user); + ownerDetailsWithDevices = deviceManagementProviderService.getOwnersWithDeviceIds(user, deviceTypeId); } catch (DeviceManagementDAOException e) { throw new ApplicationManagementException("Error retrieving owner details with devices for user: " + user, e); } @@ -2307,7 +2310,9 @@ public class SubscriptionManagerImpl implements SubscriptionManager { log.error(msg); throw new NotFoundException(msg); } + ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(uuid, tenantId); int appReleaseId = applicationReleaseDTO.getId(); + int deviceTypeId = applicationDTO.getDeviceTypeId(); DeviceManagementProviderService deviceManagementProviderService = HelperUtil.getDeviceManagementProviderService(); List deviceSubscriptions = @@ -2321,7 +2326,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } List allDevices = - deviceManagementProviderService.getDevicesByTenantId(tenantId); + deviceManagementProviderService.getDevicesByTenantId(tenantId, deviceTypeId); List deviceIds = allDevices.stream() .map(DeviceDetailsDTO::getDeviceId) @@ -2493,7 +2498,9 @@ public class SubscriptionManagerImpl implements SubscriptionManager { log.error(msg); throw new NotFoundException(msg); } + ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(uuid, tenantId); int appReleaseId = applicationReleaseDTO.getId(); + int deviceTypeId = applicationDTO.getDeviceTypeId(); List allSubscriptions = subscriptionDAO.getAllSubscriptionsDetails(appReleaseId, unsubscribe, tenantId, offset, limit); @@ -2522,7 +2529,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { statusCounts.put("NEW", 0); List allDevices = - deviceManagementProviderService.getDevicesByTenantId(tenantId); + deviceManagementProviderService.getDevicesByTenantId(tenantId, deviceTypeId); for (DeviceDetailsDTO device : allDevices) { Integer deviceId = device.getDeviceId(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java index 4a4be1e0c3..158b86e0a3 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java @@ -106,7 +106,7 @@ public interface EnrollmentDAO { * @return {@link OwnerWithDeviceDTO} which contains a list of devices related to a user * @throws DeviceManagementDAOException if an error occurs while fetching the data */ - OwnerWithDeviceDTO getOwnersWithDevices(String owner, List allowingDeviceStatuses, int tenantId) throws DeviceManagementDAOException; + OwnerWithDeviceDTO getOwnersWithDevices(String owner, List allowingDeviceStatuses, int tenantId, int deviceTypeId) throws DeviceManagementDAOException; /** * Retrieves a list of device IDs with owners and device status. @@ -123,8 +123,10 @@ public interface EnrollmentDAO { * Retrieves owners and the list of device IDs with device status. * * @param tenantId the ID of the tenant + * @param allowingDeviceStatuses the allowed device statuses of devices + * @param deviceTypeId the device type id * @return {@link OwnerWithDeviceDTO} which contains a list of devices related to a user * @throws DeviceManagementDAOException if an error occurs while fetching the data */ - List getDevicesByTenantId(int tenantId, List allowingDeviceStatuses) throws DeviceManagementDAOException; + List getDevicesByTenantId(int tenantId, List allowingDeviceStatuses, int deviceTypeId) throws DeviceManagementDAOException; } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java index 3e3fde8205..2bb6c48fb4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java @@ -473,13 +473,15 @@ public interface GroupDAO { * Get group details and list of device IDs related to the group. * * @param groupName Group name + * @param allowingDeviceStatuses the statuses of devices + * @param deviceTypeId the device type id * @param tenantId Tenant ID * @param offset the offset for the data set * @param limit the limit for the data set * @return {@link GroupDetailsDTO} which containing group details and a list of device IDs * @throws GroupManagementDAOException if an error occurs while retrieving the group details and devices */ - GroupDetailsDTO getGroupDetailsWithDevices(String groupName, List allowingDeviceStatuses, int tenantId, int offset, int limit) + GroupDetailsDTO getGroupDetailsWithDevices(String groupName, List allowingDeviceStatuses, int deviceTypeId, int tenantId, int offset, int limit) throws GroupManagementDAOException; } \ No newline at end of file diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java index b8ad6f86df..6f9d3e727f 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java @@ -564,7 +564,7 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { } @Override - public OwnerWithDeviceDTO getOwnersWithDevices(String owner, List allowingDeviceStatuses, int tenantId) + public OwnerWithDeviceDTO getOwnersWithDevices(String owner, List allowingDeviceStatuses, int tenantId, int deviceTypeId) throws DeviceManagementDAOException { Connection conn = null; OwnerWithDeviceDTO ownerDetails = new OwnerWithDeviceDTO(); @@ -582,15 +582,16 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { String sql = "SELECT e.DEVICE_ID, e.OWNER, e.STATUS AS DEVICE_STATUS, d.NAME AS DEVICE_NAME, e.DEVICE_TYPE AS DEVICE_TYPE, e.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION " + "FROM DM_ENROLMENT e " + "JOIN DM_DEVICE d ON e.DEVICE_ID = d.ID " + - "WHERE e.OWNER = ? AND e.TENANT_ID = ? AND e.STATUS IN (" + deviceFilters.toString() + ")"; + "WHERE e.OWNER = ? AND e.TENANT_ID = ? AND d.DEVICE_TYPE_ID = ? AND e.STATUS IN (" + deviceFilters.toString() + ")"; try { conn = this.getConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, owner); stmt.setInt(2, tenantId); + stmt.setInt(3, deviceTypeId); for (int i = 0; i < allowingDeviceStatuses.size(); i++) { - stmt.setString(3 + i, allowingDeviceStatuses.get(i)); + stmt.setString(4 + i, allowingDeviceStatuses.get(i)); } try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { @@ -654,7 +655,7 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { } @Override - public List getDevicesByTenantId(int tenantId, List allowingDeviceStatuses) + public List getDevicesByTenantId(int tenantId, List allowingDeviceStatuses, int deviceTypeId) throws DeviceManagementDAOException { List devices = new ArrayList<>(); if (allowingDeviceStatuses.isEmpty()) { @@ -669,9 +670,10 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { } } - String sql = "SELECT DEVICE_ID, OWNER, STATUS, DEVICE_TYPE, DEVICE_IDENTIFICATION " + - "FROM DM_ENROLMENT " + - "WHERE TENANT_ID = ? AND STATUS IN (" + deviceFilters.toString() + ")"; + String sql = "SELECT e.DEVICE_ID, e.OWNER, e.STATUS, e.DEVICE_TYPE, e.DEVICE_IDENTIFICATION " + + "FROM DM_ENROLMENT e " + + "JOIN DM_DEVICE d ON e.DEVICE_ID = d.ID " + + "WHERE e.TENANT_ID = ? AND e.STATUS IN (" + deviceFilters.toString() + ") AND d.DEVICE_TYPE_ID = ?"; Connection conn = null; try { @@ -682,6 +684,7 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { for (String status : allowingDeviceStatuses) { stmt.setString(index++, status); } + stmt.setInt(index++, deviceTypeId); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { @@ -702,6 +705,4 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { } return devices; } - - } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java index 1d9084eb7b..22e9fb18aa 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java @@ -1441,7 +1441,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { } @Override - public GroupDetailsDTO getGroupDetailsWithDevices(String groupName, List allowedStatuses, int tenantId, int offset, int limit) + public GroupDetailsDTO getGroupDetailsWithDevices(String groupName, List allowedStatuses, int deviceTypeId, int tenantId, int offset, int limit) throws GroupManagementDAOException { if (log.isDebugEnabled()) { log.debug("Request received in DAO Layer to get group details and device IDs for group: " + groupName); @@ -1481,6 +1481,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { "WHERE " + " g.GROUP_NAME = ? " + " AND g.TENANT_ID = ? " + + " AND d.DEVICE_TYPE_ID = ? " + " AND e.STATUS IN (" + deviceFilters.toString() + ") " + "LIMIT ? OFFSET ?"; @@ -1491,6 +1492,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { int index = 1; stmt.setString(index++, groupName); stmt.setInt(index++, tenantId); + stmt.setInt(index++, deviceTypeId); for (String status : allowedStatuses) { stmt.setString(index++, status); } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java index 9ab44929a1..8a892474ff 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderService.java @@ -1082,10 +1082,11 @@ public interface DeviceManagementProviderService { * Get owner details and device IDs for a given owner and tenant. * * @param owner the name of the owner. + * @param deviceTypeId the device type id * @return {@link OwnerWithDeviceDTO} which contains a list of devices related to a user. * @throws DeviceManagementException if an error occurs while fetching owner details. */ - OwnerWithDeviceDTO getOwnersWithDeviceIds(String owner) throws DeviceManagementDAOException; + OwnerWithDeviceDTO getOwnersWithDeviceIds(String owner, int deviceTypeId) throws DeviceManagementDAOException; /** * Get owner details and device IDs for a given owner and tenant. @@ -1099,10 +1100,11 @@ public interface DeviceManagementProviderService { /** * Get owner details and device IDs for a given owner and tenant. * @param tenantId the tenant id which devices need to be retried + * @param deviceTypeId the device type id * @return {@link DeviceDetailsDTO} which contains devices details. * @throws DeviceManagementException if an error occurs while fetching owner details. */ - List getDevicesByTenantId(int tenantId) throws DeviceManagementDAOException; + List getDevicesByTenantId(int tenantId, int deviceTypeId) throws DeviceManagementDAOException; /** * Get operation details by operation code. diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 5d33953a56..0f035a5bf9 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -5354,7 +5354,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public OwnerWithDeviceDTO getOwnersWithDeviceIds(String owner) throws DeviceManagementDAOException { + public OwnerWithDeviceDTO getOwnersWithDeviceIds(String owner, int deviceTypeId) throws DeviceManagementDAOException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); OwnerWithDeviceDTO ownerWithDeviceDTO; @@ -5365,7 +5365,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv try { DeviceManagementDAOFactory.openConnection(); - ownerWithDeviceDTO = this.enrollmentDAO.getOwnersWithDevices(owner, allowingDeviceStatuses, tenantId); + ownerWithDeviceDTO = this.enrollmentDAO.getOwnersWithDevices(owner, allowingDeviceStatuses, tenantId, deviceTypeId); if (ownerWithDeviceDTO == null) { String msg = "No data found for owner: " + owner; log.error(msg); @@ -5416,7 +5416,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public List getDevicesByTenantId(int tenantId) throws DeviceManagementDAOException { + public List getDevicesByTenantId(int tenantId, int deviceTypeId) throws DeviceManagementDAOException { List devices; List allowingDeviceStatuses = new ArrayList<>(); allowingDeviceStatuses.add(EnrolmentInfo.Status.ACTIVE.toString()); @@ -5424,7 +5424,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv allowingDeviceStatuses.add(EnrolmentInfo.Status.UNREACHABLE.toString()); try { DeviceManagementDAOFactory.openConnection(); - devices = enrollmentDAO.getDevicesByTenantId(tenantId, allowingDeviceStatuses); + devices = enrollmentDAO.getDevicesByTenantId(tenantId, allowingDeviceStatuses, deviceTypeId); if (devices == null || devices.isEmpty()) { String msg = "No devices found for tenant ID: " + tenantId; log.error(msg); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderService.java index fac06bfccf..b1200772a4 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderService.java @@ -377,11 +377,12 @@ public interface GroupManagementProviderService { * Get group details and device IDs for a given group name. * * @param groupName the name of the group. + * @param deviceTypeId the device type id * @param offset the offset for the data set * @param limit the limit for the data set * @return {@link GroupDetailsDTO} which containing group details and a list of device IDs * @throws GroupManagementException if an error occurs while fetching group details. */ - GroupDetailsDTO getGroupDetailsWithDevices(String groupName, int offset, int limit) throws GroupManagementException; + GroupDetailsDTO getGroupDetailsWithDevices(String groupName, int deviceTypeId, int offset, int limit) throws GroupManagementException; } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java index bd10cac78a..0d0e23cc48 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -1684,7 +1684,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } @Override - public GroupDetailsDTO getGroupDetailsWithDevices(String groupName, int offset, int limit) + public GroupDetailsDTO getGroupDetailsWithDevices(String groupName, int deviceTypeId, int offset, int limit) throws GroupManagementException { if (log.isDebugEnabled()) { log.debug("Retrieving group details and device IDs for group: " + groupName); @@ -1698,7 +1698,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid try { GroupManagementDAOFactory.openConnection(); - groupDetailsWithDevices = this.groupDAO.getGroupDetailsWithDevices(groupName, allowingDeviceStatuses, tenantId, offset, limit); + groupDetailsWithDevices = this.groupDAO.getGroupDetailsWithDevices(groupName, allowingDeviceStatuses, deviceTypeId, tenantId, offset, limit); } catch (GroupManagementDAOException | SQLException e) { String msg = "Error occurred while retrieving group details and device IDs for group: " + groupName; log.error(msg, e); From e1a47c68fbbf3822cf47669b6aef2197d2d16aad Mon Sep 17 00:00:00 2001 From: ashvini Date: Tue, 2 Jul 2024 14:20:57 +0530 Subject: [PATCH 16/21] Get TenantMgtAdminService as an osgi service Resolve comments Remove source reference Change error messages Make changes in code Add license Resolve comments Add java doc comments Resolve comments Resolve comment --- .../common/services/ApplicationManager.java | 14 +++++ .../pom.xml | 5 ++ .../mgt/core/impl/ApplicationManagerImpl.java | 57 +++++++------------ ...ApplicationManagementServiceComponent.java | 24 ++++++++ .../mgt/core/internal/DataHolder.java | 11 ++++ .../admin/UserManagementAdminServiceImpl.java | 14 ++--- .../mgt/api/jaxrs/util/DeviceMgtAPIUtils.java | 19 +++++++ .../common/spi/TenantManagerAdminService.java | 27 +++++++++ .../pom.xml | 1 + .../core/tenant/mgt/core/TenantManager.java | 1 + .../impl/TenantManagerAdminServiceImpl.java | 57 +++++++++++++++++++ .../internal/TenantMgtServiceComponent.java | 9 ++- .../listener/DeviceMgtTenantListener.java | 8 --- 13 files changed, 195 insertions(+), 52 deletions(-) create mode 100644 components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/src/main/java/io/entgra/device/mgt/core/tenant/mgt/common/spi/TenantManagerAdminService.java create mode 100644 components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerAdminServiceImpl.java diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java index bf3bdc5d40..7e13353980 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.common/src/main/java/io/entgra/device/mgt/core/application/mgt/common/services/ApplicationManager.java @@ -546,6 +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; } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml index 057345defc..b273d85a82 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/pom.xml @@ -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 @@ org.wso2.carbon.tenant.mgt compile + + io.entgra.device.mgt.core + io.entgra.device.mgt.core.tenant.mgt.common + diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java index f6d0fc228f..5131eeeed8 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/ApplicationManagerImpl.java @@ -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,8 +97,6 @@ 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; @@ -4456,19 +4455,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); @@ -4495,51 +4484,49 @@ public class ApplicationManagerImpl implements ApplicationManager { 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 (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{ - TenantMgtAdminService tenantMgtAdminService = new TenantMgtAdminService(); - TenantInfoBean tenantInfoBean = tenantMgtAdminService.getTenant(tenantDomain); - tenantId = tenantInfoBean.getTenantId(); - - } catch (Exception e) { - String msg = "Error getting tenant ID from domain: " - + tenantDomain + "when trying to delete application artifacts of tenant"; + 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); - } - try { - APIUtil.getApplicationStorageManager().deleteAppFolderOfTenant(tenantId); - } catch (ApplicationStorageManagementException e) { - String msg = "Error occurred while deleting Application folders of tenant" - + " of tenant ID: " + tenantId ; + } 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); } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java index 20cd9febbc..d1b8ff8288 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/ApplicationManagementServiceComponent.java @@ -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); + } } diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java index 80416dcd59..c67db70fb6 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/internal/DataHolder.java @@ -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; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java index d0e82d7fb3..91ed3f6d42 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java @@ -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.*; @@ -99,18 +97,20 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic log.error(msg); return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build(); } else { - if(deleteAppArtifacts){ + 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(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java index 885d521389..5451572519 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/util/DeviceMgtAPIUtils.java @@ -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; + } } diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/src/main/java/io/entgra/device/mgt/core/tenant/mgt/common/spi/TenantManagerAdminService.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/src/main/java/io/entgra/device/mgt/core/tenant/mgt/common/spi/TenantManagerAdminService.java new file mode 100644 index 0000000000..0b93e7ca5b --- /dev/null +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.common/src/main/java/io/entgra/device/mgt/core/tenant/mgt/common/spi/TenantManagerAdminService.java @@ -0,0 +1,27 @@ +/* + * 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.tenant.mgt.common.spi; + +import io.entgra.device.mgt.core.tenant.mgt.common.exception.TenantMgtException; + +public interface TenantManagerAdminService { + + void deleteTenant(String tenantDomain) throws TenantMgtException; + int getTenantId(String tenantDomain) throws TenantMgtException; +} diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml index 33d4c9969c..f89aa3cf39 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/pom.xml @@ -60,6 +60,7 @@ org.wso2.carbon.stratos.common.beans, org.wso2.carbon.stratos.common.exception, org.wso2.carbon.stratos.common.listeners, + org.wso2.carbon.tenant.mgt.services, io.entgra.device.mgt.core.device.mgt.common.metadata.mgt, io.entgra.device.mgt.core.device.mgt.common.exceptions, io.entgra.device.mgt.core.device.mgt.common.permission.mgt, diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/TenantManager.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/TenantManager.java index ac3ee406f9..ea26974300 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/TenantManager.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/TenantManager.java @@ -57,4 +57,5 @@ public interface TenantManager { * @throws TenantMgtException Throws when deleting Tenant related device data */ void deleteTenantDeviceData(int tenantId) throws TenantMgtException; + } diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerAdminServiceImpl.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerAdminServiceImpl.java new file mode 100644 index 0000000000..b96535da25 --- /dev/null +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/impl/TenantManagerAdminServiceImpl.java @@ -0,0 +1,57 @@ +/* + * 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.tenant.mgt.core.impl; + +import io.entgra.device.mgt.core.tenant.mgt.common.exception.TenantMgtException; +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.wso2.carbon.stratos.common.exception.StratosException; +import org.wso2.carbon.tenant.mgt.services.TenantMgtAdminService; +import org.wso2.carbon.user.api.UserStoreException; + + +public class TenantManagerAdminServiceImpl implements TenantManagerAdminService { + + private static final Log log = LogFactory.getLog(TenantManagerAdminServiceImpl.class); + + private static final TenantMgtAdminService tenantMgtAdminService = new TenantMgtAdminService(); + + @Override + public void deleteTenant(String tenantDomain) throws TenantMgtException { + try { + tenantMgtAdminService.deleteTenant(tenantDomain); + } catch (StratosException | UserStoreException e) { + String msg = "Error occurred while deleting tenant of domain: " + tenantDomain; + log.error(msg, e); + throw new TenantMgtException(msg, e); + } + } + + @Override + public int getTenantId(String tenantDomain) throws TenantMgtException { + try { + return tenantMgtAdminService.getTenant(tenantDomain).getTenantId(); + } catch (Exception e){ + String msg = "Error occurred while getting tenant ID of domain: " + tenantDomain; + log.error(msg, e); + throw new TenantMgtException(msg, e); + } + } +} diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/internal/TenantMgtServiceComponent.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/internal/TenantMgtServiceComponent.java index fa2f26c972..c6ad710cb8 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/internal/TenantMgtServiceComponent.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/internal/TenantMgtServiceComponent.java @@ -20,8 +20,10 @@ package io.entgra.device.mgt.core.tenant.mgt.core.internal; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.DeviceStatusManagementServiceImpl; +import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerAdminService; import io.entgra.device.mgt.core.tenant.mgt.common.spi.TenantManagerService; import io.entgra.device.mgt.core.tenant.mgt.core.TenantManager; +import io.entgra.device.mgt.core.tenant.mgt.core.impl.TenantManagerAdminServiceImpl; import io.entgra.device.mgt.core.tenant.mgt.core.impl.TenantManagerImpl; import io.entgra.device.mgt.core.tenant.mgt.core.impl.TenantManagerServiceImpl; import io.entgra.device.mgt.core.tenant.mgt.core.listener.DeviceMgtTenantListener; @@ -59,11 +61,14 @@ public class TenantMgtServiceComponent { try { TenantManagerService tenantManagerService = new TenantManagerServiceImpl(); componentContext.getBundleContext(). - registerService(TenantManagerServiceImpl.class.getName(), tenantManagerService, null); + registerService(TenantManagerService.class.getName(), tenantManagerService, null); + TenantManagerAdminService tenantManagerAdminService = new TenantManagerAdminServiceImpl(); + componentContext.getBundleContext(). + registerService(TenantManagerAdminService.class.getName(), tenantManagerAdminService, null); TenantManager tenantManager = new TenantManagerImpl(); TenantMgtDataHolder.getInstance().setTenantManager(tenantManager); WhiteLabelManagementService whiteLabelManagementService = new WhiteLabelManagementServiceImpl(); - componentContext.getBundleContext().registerService(WhiteLabelManagementServiceImpl.class.getName(), + componentContext.getBundleContext().registerService(WhiteLabelManagementService.class.getName(), whiteLabelManagementService, null); TenantMgtDataHolder.getInstance().setWhiteLabelManagementService(whiteLabelManagementService); DeviceStatusManagementService deviceStatusManagementService = new DeviceStatusManagementServiceImpl(); diff --git a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java index 257206f84f..978e69b0e4 100644 --- a/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java +++ b/components/tenant-mgt/io.entgra.device.mgt.core.tenant.mgt.core/src/main/java/io/entgra/device/mgt/core/tenant/mgt/core/listener/DeviceMgtTenantListener.java @@ -88,13 +88,5 @@ public class DeviceMgtTenantListener implements TenantMgtListener { @Override public void onPreDelete(int i) throws StratosException { // Any work to be performed before a tenant is deleted - TenantManager tenantManager = TenantMgtDataHolder.getInstance().getTenantManager(); - try{ - tenantManager.deleteTenantDeviceData(i); - tenantManager.deleteTenantApplicationData(i); - } catch (TenantMgtException e) { - String msg = "Error occurred while deleting tenant data"; - log.error(msg, e); - } } } From 1a1df9725333bcf8abbe9bfc4c87d6311284f14a Mon Sep 17 00:00:00 2001 From: prathabanKavin Date: Thu, 11 Jul 2024 12:32:39 +0530 Subject: [PATCH 17/21] Resolve comments --- .../mgt/core/impl/SubscriptionManagerImpl.java | 16 ++++++---------- .../core/device/mgt/core/dao/EnrollmentDAO.java | 6 ++++-- .../mgt/core/device/mgt/core/dao/GroupDAO.java | 3 ++- .../mgt/core/dao/impl/AbstractGroupDAOImpl.java | 3 ++- .../GroupManagementProviderServiceImpl.java | 3 ++- 5 files changed, 16 insertions(+), 15 deletions(-) diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java index 6bb902d6b3..203740c6da 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -1722,7 +1722,6 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(uuid, tenantId); int appReleaseId = applicationReleaseDTO.getId(); - int deviceTypeId = applicationDTO.getDeviceTypeId(); List groupDetailsWithDevices = new ArrayList<>(); List groupDetails = @@ -1738,7 +1737,8 @@ public class SubscriptionManagerImpl implements SubscriptionManager { // Retrieve group details and device IDs for the group using the service layer GroupDetailsDTO groupDetailWithDevices = - groupManagementProviderService.getGroupDetailsWithDevices(groupName, deviceTypeId, offset, limit); + groupManagementProviderService.getGroupDetailsWithDevices(groupName, applicationDTO.getDeviceTypeId(), + offset, limit); SubscriptionsDTO groupDetailDTO = new SubscriptionsDTO(); groupDetailDTO.setId(groupDetailWithDevices.getGroupId()); @@ -1913,7 +1913,6 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(uuid, tenantId); int appReleaseId = applicationReleaseDTO.getId(); - int deviceTypeId = applicationDTO.getDeviceTypeId(); List userSubscriptionsWithDevices = new ArrayList<>(); List userSubscriptions = @@ -1929,7 +1928,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { // Retrieve owner details and device IDs for the user using the service layer OwnerWithDeviceDTO ownerDetailsWithDevices = - deviceManagementProviderService.getOwnersWithDeviceIds(userName, deviceTypeId); + deviceManagementProviderService.getOwnersWithDeviceIds(userName, applicationDTO.getDeviceTypeId()); SubscriptionsDTO userSubscriptionDTO = new SubscriptionsDTO(); userSubscriptionDTO.setName(userSubscription.getName()); @@ -2101,7 +2100,6 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(uuid, tenantId); int appReleaseId = applicationReleaseDTO.getId(); - int deviceTypeId = applicationDTO.getDeviceTypeId(); List roleSubscriptionsWithDevices = new ArrayList<>(); List roleSubscriptions = @@ -2142,7 +2140,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { for (String user : users) { OwnerWithDeviceDTO ownerDetailsWithDevices; try { - ownerDetailsWithDevices = deviceManagementProviderService.getOwnersWithDeviceIds(user, deviceTypeId); + ownerDetailsWithDevices = deviceManagementProviderService.getOwnersWithDeviceIds(user, applicationDTO.getDeviceTypeId()); } catch (DeviceManagementDAOException e) { throw new ApplicationManagementException("Error retrieving owner details with devices for user: " + user, e); } @@ -2312,7 +2310,6 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(uuid, tenantId); int appReleaseId = applicationReleaseDTO.getId(); - int deviceTypeId = applicationDTO.getDeviceTypeId(); DeviceManagementProviderService deviceManagementProviderService = HelperUtil.getDeviceManagementProviderService(); List deviceSubscriptions = @@ -2326,7 +2323,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } List allDevices = - deviceManagementProviderService.getDevicesByTenantId(tenantId, deviceTypeId); + deviceManagementProviderService.getDevicesByTenantId(tenantId, applicationDTO.getDeviceTypeId()); List deviceIds = allDevices.stream() .map(DeviceDetailsDTO::getDeviceId) @@ -2500,7 +2497,6 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } ApplicationDTO applicationDTO = this.applicationDAO.getAppWithRelatedRelease(uuid, tenantId); int appReleaseId = applicationReleaseDTO.getId(); - int deviceTypeId = applicationDTO.getDeviceTypeId(); List allSubscriptions = subscriptionDAO.getAllSubscriptionsDetails(appReleaseId, unsubscribe, tenantId, offset, limit); @@ -2529,7 +2525,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { statusCounts.put("NEW", 0); List allDevices = - deviceManagementProviderService.getDevicesByTenantId(tenantId, deviceTypeId); + deviceManagementProviderService.getDevicesByTenantId(tenantId, applicationDTO.getDeviceTypeId()); for (DeviceDetailsDTO device : allDevices) { Integer deviceId = device.getDeviceId(); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java index 158b86e0a3..e7419aa013 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/EnrollmentDAO.java @@ -106,7 +106,8 @@ public interface EnrollmentDAO { * @return {@link OwnerWithDeviceDTO} which contains a list of devices related to a user * @throws DeviceManagementDAOException if an error occurs while fetching the data */ - OwnerWithDeviceDTO getOwnersWithDevices(String owner, List allowingDeviceStatuses, int tenantId, int deviceTypeId) throws DeviceManagementDAOException; + OwnerWithDeviceDTO getOwnersWithDevices(String owner, List allowingDeviceStatuses, int tenantId, int deviceTypeId) + throws DeviceManagementDAOException; /** * Retrieves a list of device IDs with owners and device status. @@ -128,5 +129,6 @@ public interface EnrollmentDAO { * @return {@link OwnerWithDeviceDTO} which contains a list of devices related to a user * @throws DeviceManagementDAOException if an error occurs while fetching the data */ - List getDevicesByTenantId(int tenantId, List allowingDeviceStatuses, int deviceTypeId) throws DeviceManagementDAOException; + List getDevicesByTenantId(int tenantId, List allowingDeviceStatuses, int deviceTypeId) + throws DeviceManagementDAOException; } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java index 2bb6c48fb4..abb12a6ea0 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/GroupDAO.java @@ -481,7 +481,8 @@ public interface GroupDAO { * @return {@link GroupDetailsDTO} which containing group details and a list of device IDs * @throws GroupManagementDAOException if an error occurs while retrieving the group details and devices */ - GroupDetailsDTO getGroupDetailsWithDevices(String groupName, List allowingDeviceStatuses, int deviceTypeId, int tenantId, int offset, int limit) + GroupDetailsDTO getGroupDetailsWithDevices(String groupName, List allowingDeviceStatuses, int deviceTypeId, + int tenantId, int offset, int limit) throws GroupManagementDAOException; } \ No newline at end of file diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java index 22e9fb18aa..7b9e918000 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java @@ -1441,7 +1441,8 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { } @Override - public GroupDetailsDTO getGroupDetailsWithDevices(String groupName, List allowedStatuses, int deviceTypeId, int tenantId, int offset, int limit) + public GroupDetailsDTO getGroupDetailsWithDevices(String groupName, List allowedStatuses, int deviceTypeId, + int tenantId, int offset, int limit) throws GroupManagementDAOException { if (log.isDebugEnabled()) { log.debug("Request received in DAO Layer to get group details and device IDs for group: " + groupName); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 0d0e23cc48..d6114b5c04 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -1698,7 +1698,8 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid try { GroupManagementDAOFactory.openConnection(); - groupDetailsWithDevices = this.groupDAO.getGroupDetailsWithDevices(groupName, allowingDeviceStatuses, deviceTypeId, tenantId, offset, limit); + groupDetailsWithDevices = this.groupDAO.getGroupDetailsWithDevices(groupName, allowingDeviceStatuses, + deviceTypeId, tenantId, offset, limit); } catch (GroupManagementDAOException | SQLException e) { String msg = "Error occurred while retrieving group details and device IDs for group: " + groupName; log.error(msg, e); From 2006d7e97db474ddd533a7ec49bbc5687e813901 Mon Sep 17 00:00:00 2001 From: Pahansith Date: Thu, 11 Jul 2024 23:33:16 +0530 Subject: [PATCH 18/21] Add policy type conversion from BLOB to Text DB scripts --- .../src/test/resources/carbon-home/dbscripts/dm-db-h2.sql | 2 +- .../src/test/resources/sql/h2.sql | 2 +- .../src/test/resources/sql/h2.sql | 2 +- .../src/test/resources/sql-files/h2.sql | 2 +- .../src/test/resources/carbon-home/dbscripts/dm-db-h2.sql | 2 +- .../src/test/resources/sql/CreateH2TestDB.sql | 2 +- .../src/test/resources/sql/CreateMySqlTestDB.sql | 2 +- .../src/test/resources/carbon-home/dbscripts/dm-db-h2.sql | 2 +- .../src/main/resources/dbscripts/cdm/h2.sql | 2 +- .../src/main/resources/dbscripts/cdm/mssql.sql | 2 +- .../src/main/resources/dbscripts/cdm/mysql.sql | 2 +- .../src/main/resources/dbscripts/cdm/oracle.sql | 2 +- .../src/main/resources/dbscripts/cdm/postgresql.sql | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql index 13ac69dfc6..29d1a225b2 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql @@ -329,7 +329,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED DEVICE_ID INT NOT NULL, ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL, - POLICY_CONTENT BLOB NULL, + POLICY_CONTENT TEXT NULL, TENANT_ID INT NOT NULL, APPLIED TINYINT(1) NULL, CREATED_TIME TIMESTAMP NULL, diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/sql/h2.sql b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/sql/h2.sql index a842fdf2ab..f998695f58 100644 --- a/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/sql/h2.sql +++ b/components/device-mgt-extensions/io.entgra.device.mgt.core.device.mgt.extensions.device.organization/src/test/resources/sql/h2.sql @@ -336,7 +336,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( DEVICE_ID INT NOT NULL , ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL , - POLICY_CONTENT BLOB NULL , + POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, APPLIED TINYINT(1) NULL , CREATED_TIME TIMESTAMP NULL , diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql index aea2602f2e..5f94591885 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/test/resources/sql/h2.sql @@ -336,7 +336,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( DEVICE_ID INT NOT NULL , ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL , - POLICY_CONTENT BLOB NULL , + POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, APPLIED TINYINT(1) NULL , CREATED_TIME TIMESTAMP NULL , diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql index d69d5e354b..ed810f8308 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.extensions/src/test/resources/sql-files/h2.sql @@ -242,7 +242,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( DEVICE_ID INT NOT NULL , ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL , - POLICY_CONTENT BLOB NULL , + POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, APPLIED TINYINT(1) NULL , CREATED_TIME TIMESTAMP NULL , diff --git a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql index 0c547b11a4..17f334c78f 100644 --- a/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql +++ b/components/operation-template-mgt/io.entgra.device.mgt.core.operation.template/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql @@ -288,7 +288,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( DEVICE_ID INT NOT NULL , ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL , - POLICY_CONTENT BLOB NULL , + POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, APPLIED TINYINT(1) NULL , CREATED_TIME TIMESTAMP NULL , diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index a9fa35a6fb..0086d545d2 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -322,7 +322,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( DEVICE_ID INT NOT NULL , ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL , - POLICY_CONTENT BLOB NULL , + POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, APPLIED TINYINT(1) NULL , CREATED_TIME TIMESTAMP NULL , diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateMySqlTestDB.sql b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateMySqlTestDB.sql index be7bf40b7d..feab172d0e 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateMySqlTestDB.sql +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/test/resources/sql/CreateMySqlTestDB.sql @@ -161,7 +161,7 @@ CREATE TABLE IF NOT EXISTS `WSO2CDM`.`DM_DEVICE_POLICY_APPLIED` ( `ID` INT(11) NOT NULL AUTO_INCREMENT, `DEVICE_ID` INT(11) NOT NULL, `POLICY_ID` INT(11) NOT NULL, - `POLICY_CONTENT` BLOB NULL DEFAULT NULL, + `POLICY_CONTENT` TEXT NULL DEFAULT NULL, `APPLIED` TINYINT(1) NULL DEFAULT NULL, `CREATED_TIME` TIMESTAMP NULL DEFAULT NULL, `UPDATED_TIME` TIMESTAMP NULL DEFAULT NULL, diff --git a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql index 046cfbec1d..8ed0e91922 100644 --- a/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql +++ b/components/subtype-mgt/io.entgra.device.mgt.core.subtype.mgt/src/test/resources/carbon-home/dbscripts/dm-db-h2.sql @@ -289,7 +289,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( DEVICE_ID INT NOT NULL , ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL , - POLICY_CONTENT BLOB NULL , + POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, APPLIED TINYINT(1) NULL , CREATED_TIME TIMESTAMP NULL , diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql index f34d6183e2..342c330376 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -304,7 +304,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( DEVICE_ID INT NOT NULL , ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL , - POLICY_CONTENT BLOB NULL , + POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, APPLIED TINYINT(1) NULL , CREATED_TIME TIMESTAMP NULL , diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql index dc05a39464..f6f3232e13 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -369,7 +369,7 @@ IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[D DEVICE_ID INTEGER NOT NULL , ENROLMENT_ID INTEGER NOT NULL, POLICY_ID INTEGER NOT NULL , - POLICY_CONTENT VARBINARY(MAX) NULL , + POLICY_CONTENT TEXT NULL , TENANT_ID INTEGER NOT NULL, APPLIED BIT NULL , CREATED_TIME DATETIME2 NULL , diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql index cd28fb74f1..4390f6a40d 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -355,7 +355,7 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( DEVICE_ID INT NOT NULL , ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL , - POLICY_CONTENT BLOB NULL , + POLICY_CONTENT TEXT NULL , TENANT_ID INT NOT NULL, APPLIED TINYINT(1) NULL , CREATED_TIME TIMESTAMP NULL , diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql index e500c55046..d5a442c69e 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -509,7 +509,7 @@ CREATE TABLE DM_DEVICE_POLICY_APPLIED ( DEVICE_ID NUMBER(10) NOT NULL , ENROLMENT_ID NUMBER(10) NOT NULL, POLICY_ID NUMBER(10) NOT NULL , - POLICY_CONTENT BLOB NULL , + POLICY_CONTENT TEXT NULL , TENANT_ID NUMBER(10) NOT NULL, APPLIED NUMBER(1) DEFAULT 0, CREATED_TIME TIMESTAMP(0) NULL , diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql index c0368f5826..354925efe5 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -365,7 +365,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( DEVICE_ID INTEGER NOT NULL , ENROLMENT_ID INTEGER NOT NULL, POLICY_ID INTEGER NOT NULL , - POLICY_CONTENT BYTEA NULL , + POLICY_CONTENT TEXT NULL , TENANT_ID INTEGER NOT NULL, APPLIED SMALLINT NULL , CREATED_TIME TIMESTAMP(0) NULL , From de1d79f27c2f2ef2d9f8802d2efcc88b35b25839 Mon Sep 17 00:00:00 2001 From: prathabanKavin Date: Thu, 11 Jul 2024 23:53:34 +0530 Subject: [PATCH 19/21] Fix same device data loading for subscriptions --- .../core/impl/SubscriptionManagerImpl.java | 76 +++++++++++-------- .../dao/impl/AbstractEnrollmentDAOImpl.java | 12 +-- 2 files changed, 51 insertions(+), 37 deletions(-) diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java index 203740c6da..174e317ee6 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -1929,6 +1929,9 @@ public class SubscriptionManagerImpl implements SubscriptionManager { // Retrieve owner details and device IDs for the user using the service layer OwnerWithDeviceDTO ownerDetailsWithDevices = deviceManagementProviderService.getOwnersWithDeviceIds(userName, applicationDTO.getDeviceTypeId()); + log.info("line no 1932 device ids : " + ownerDetailsWithDevices.getDeviceIds()); + log.info("line no 1933 device identifiers : " + ownerDetailsWithDevices.getDeviceIdentifiers()); + log.info("line no 1934 device names : " + ownerDetailsWithDevices.getDeviceNames()); SubscriptionsDTO userSubscriptionDTO = new SubscriptionsDTO(); userSubscriptionDTO.setName(userSubscription.getName()); @@ -1965,15 +1968,20 @@ public class SubscriptionManagerImpl implements SubscriptionManager { for (Integer deviceId : deviceIds) { List deviceSubscriptions = subscriptionDAO.getSubscriptionDetailsByDeviceIds( userSubscription.getAppReleaseId(), unsubscribe, tenantId, deviceIds); + OwnerWithDeviceDTO ownerWithDeviceByDeviceId = + deviceManagementProviderService.getOwnerWithDeviceByDeviceId(deviceId); + if (ownerWithDeviceByDeviceId == null) { + continue; + } boolean isNewDevice = true; for (DeviceSubscriptionDTO subscription : deviceSubscriptions) { if (subscription.getDeviceId() == deviceId) { DeviceSubscriptionData deviceDetail = new DeviceSubscriptionData(); deviceDetail.setDeviceId(subscription.getDeviceId()); deviceDetail.setSubId(subscription.getId()); - deviceDetail.setDeviceOwner(ownerDetailsWithDevices.getUserName()); - deviceDetail.setDeviceStatus(ownerDetailsWithDevices.getDeviceStatus()); - deviceDetail.setDeviceName(ownerDetailsWithDevices.getDeviceNames()); + deviceDetail.setDeviceOwner(ownerWithDeviceByDeviceId.getUserName()); + deviceDetail.setDeviceStatus(ownerWithDeviceByDeviceId.getDeviceStatus()); + deviceDetail.setDeviceName(ownerWithDeviceByDeviceId.getDeviceNames()); deviceDetail.setActionType(subscription.getActionTriggeredFrom()); deviceDetail.setStatus(subscription.getStatus()); deviceDetail.setActionType(subscription.getActionTriggeredFrom()); @@ -1982,8 +1990,8 @@ public class SubscriptionManagerImpl implements SubscriptionManager { deviceDetail.setUnsubscribed(subscription.isUnsubscribed()); deviceDetail.setUnsubscribedBy(subscription.getUnsubscribedBy()); deviceDetail.setUnsubscribedTimestamp(subscription.getUnsubscribedTimestamp()); - deviceDetail.setType(ownerDetailsWithDevices.getDeviceTypes()); - deviceDetail.setDeviceIdentifier(ownerDetailsWithDevices.getDeviceIdentifiers()); + deviceDetail.setType(ownerWithDeviceByDeviceId.getDeviceTypes()); + deviceDetail.setDeviceIdentifier(ownerWithDeviceByDeviceId.getDeviceIdentifiers()); status = subscription.getStatus(); switch (status) { @@ -2013,16 +2021,16 @@ public class SubscriptionManagerImpl implements SubscriptionManager { if (subscribedDevice.getDeviceId() == deviceId) { DeviceSubscriptionData subscribedDeviceDetail = new DeviceSubscriptionData(); subscribedDeviceDetail.setDeviceId(subscribedDevice.getDeviceId()); - subscribedDeviceDetail.setDeviceName(ownerDetailsWithDevices.getDeviceNames()); - subscribedDeviceDetail.setDeviceOwner(ownerDetailsWithDevices.getUserName()); - subscribedDeviceDetail.setDeviceStatus(ownerDetailsWithDevices.getDeviceStatus()); + subscribedDeviceDetail.setDeviceName(ownerWithDeviceByDeviceId.getDeviceNames()); + subscribedDeviceDetail.setDeviceOwner(ownerWithDeviceByDeviceId.getUserName()); + subscribedDeviceDetail.setDeviceStatus(ownerWithDeviceByDeviceId.getDeviceStatus()); subscribedDeviceDetail.setSubId(subscribedDevice.getId()); subscribedDeviceDetail.setActionTriggeredBy(subscribedDevice.getSubscribedBy()); subscribedDeviceDetail.setActionTriggeredTimestamp(subscribedDevice.getSubscribedTimestamp()); subscribedDeviceDetail.setActionType(subscribedDevice.getActionTriggeredFrom()); subscribedDeviceDetail.setStatus(subscribedDevice.getStatus()); - subscribedDeviceDetail.setType(ownerDetailsWithDevices.getDeviceTypes()); - subscribedDeviceDetail.setDeviceIdentifier(ownerDetailsWithDevices.getDeviceIdentifiers()); + subscribedDeviceDetail.setType(ownerWithDeviceByDeviceId.getDeviceTypes()); + subscribedDeviceDetail.setDeviceIdentifier(ownerWithDeviceByDeviceId.getDeviceIdentifiers()); subscribedDevices.add(subscribedDeviceDetail); statusCounts.put("SUBSCRIBED", statusCounts.get("SUBSCRIBED") + 1); isSubscribedDevice = true; @@ -2032,11 +2040,11 @@ public class SubscriptionManagerImpl implements SubscriptionManager { if (!isSubscribedDevice) { DeviceSubscriptionData newDeviceDetail = new DeviceSubscriptionData(); newDeviceDetail.setDeviceId(deviceId); - newDeviceDetail.setDeviceOwner(ownerDetailsWithDevices.getUserName()); - newDeviceDetail.setDeviceStatus(ownerDetailsWithDevices.getDeviceStatus()); - newDeviceDetail.setDeviceName(ownerDetailsWithDevices.getDeviceNames()); - newDeviceDetail.setType(ownerDetailsWithDevices.getDeviceTypes()); - newDeviceDetail.setDeviceIdentifier(ownerDetailsWithDevices.getDeviceIdentifiers()); + newDeviceDetail.setDeviceOwner(ownerWithDeviceByDeviceId.getUserName()); + newDeviceDetail.setDeviceStatus(ownerWithDeviceByDeviceId.getDeviceStatus()); + newDeviceDetail.setDeviceName(ownerWithDeviceByDeviceId.getDeviceNames()); + newDeviceDetail.setType(ownerWithDeviceByDeviceId.getDeviceTypes()); + newDeviceDetail.setDeviceIdentifier(ownerWithDeviceByDeviceId.getDeviceIdentifiers()); newDevices.add(newDeviceDetail); statusCounts.put("NEW", statusCounts.get("NEW") + 1); } @@ -2153,7 +2161,11 @@ public class SubscriptionManagerImpl implements SubscriptionManager { subscribedDeviceSubscriptions = subscriptionDAO.getSubscriptionDetailsByDeviceIds( appReleaseId, !unsubscribe, tenantId, deviceIds); } - + OwnerWithDeviceDTO ownerWithDeviceByDeviceId = + deviceManagementProviderService.getOwnerWithDeviceByDeviceId(deviceId); + if (ownerWithDeviceByDeviceId == null) { + continue; + } List deviceSubscriptions; try { deviceSubscriptions = subscriptionDAO.getSubscriptionDetailsByDeviceIds( @@ -2167,9 +2179,9 @@ public class SubscriptionManagerImpl implements SubscriptionManager { if (deviceSubscription.getDeviceId() == deviceId) { DeviceSubscriptionData deviceDetail = new DeviceSubscriptionData(); deviceDetail.setDeviceId(deviceSubscription.getDeviceId()); - deviceDetail.setDeviceName(ownerDetailsWithDevices.getDeviceNames()); - deviceDetail.setDeviceOwner(ownerDetailsWithDevices.getUserName()); - deviceDetail.setDeviceStatus(ownerDetailsWithDevices.getDeviceStatus()); + deviceDetail.setDeviceName(ownerWithDeviceByDeviceId.getDeviceNames()); + deviceDetail.setDeviceOwner(ownerWithDeviceByDeviceId.getUserName()); + deviceDetail.setDeviceStatus(ownerWithDeviceByDeviceId.getDeviceStatus()); deviceDetail.setActionType(deviceSubscription.getActionTriggeredFrom()); deviceDetail.setStatus(deviceSubscription.getStatus()); deviceDetail.setActionType(deviceSubscription.getActionTriggeredFrom()); @@ -2179,8 +2191,8 @@ public class SubscriptionManagerImpl implements SubscriptionManager { deviceDetail.setUnsubscribed(deviceSubscription.isUnsubscribed()); deviceDetail.setUnsubscribedBy(deviceSubscription.getUnsubscribedBy()); deviceDetail.setUnsubscribedTimestamp(deviceSubscription.getUnsubscribedTimestamp()); - deviceDetail.setType(ownerDetailsWithDevices.getDeviceTypes()); - deviceDetail.setDeviceIdentifier(ownerDetailsWithDevices.getDeviceIdentifiers()); + deviceDetail.setType(ownerWithDeviceByDeviceId.getDeviceTypes()); + deviceDetail.setDeviceIdentifier(ownerWithDeviceByDeviceId.getDeviceIdentifiers()); status = deviceSubscription.getStatus(); switch (status) { @@ -2210,16 +2222,16 @@ public class SubscriptionManagerImpl implements SubscriptionManager { if (subscribedDevice.getDeviceId() == deviceId) { DeviceSubscriptionData subscribedDeviceDetail = new DeviceSubscriptionData(); subscribedDeviceDetail.setDeviceId(subscribedDevice.getDeviceId()); - subscribedDeviceDetail.setDeviceName(ownerDetailsWithDevices.getDeviceNames()); - subscribedDeviceDetail.setDeviceOwner(ownerDetailsWithDevices.getUserName()); - subscribedDeviceDetail.setDeviceStatus(ownerDetailsWithDevices.getDeviceStatus()); + subscribedDeviceDetail.setDeviceName(ownerWithDeviceByDeviceId.getDeviceNames()); + subscribedDeviceDetail.setDeviceOwner(ownerWithDeviceByDeviceId.getUserName()); + subscribedDeviceDetail.setDeviceStatus(ownerWithDeviceByDeviceId.getDeviceStatus()); subscribedDeviceDetail.setSubId(subscribedDevice.getId()); subscribedDeviceDetail.setActionTriggeredBy(subscribedDevice.getSubscribedBy()); subscribedDeviceDetail.setActionTriggeredTimestamp(subscribedDevice.getSubscribedTimestamp()); subscribedDeviceDetail.setActionType(subscribedDevice.getActionTriggeredFrom()); subscribedDeviceDetail.setStatus(subscribedDevice.getStatus()); - subscribedDeviceDetail.setType(ownerDetailsWithDevices.getDeviceTypes()); - subscribedDeviceDetail.setDeviceIdentifier(ownerDetailsWithDevices.getDeviceIdentifiers()); + subscribedDeviceDetail.setType(ownerWithDeviceByDeviceId.getDeviceTypes()); + subscribedDeviceDetail.setDeviceIdentifier(ownerWithDeviceByDeviceId.getDeviceIdentifiers()); subscribedDevices.add(subscribedDeviceDetail); statusCounts.put("SUBSCRIBED", statusCounts.get("SUBSCRIBED") + 1); isSubscribedDevice = true; @@ -2229,11 +2241,11 @@ public class SubscriptionManagerImpl implements SubscriptionManager { if (!isSubscribedDevice) { DeviceSubscriptionData newDeviceDetail = new DeviceSubscriptionData(); newDeviceDetail.setDeviceId(deviceId); - newDeviceDetail.setDeviceName(ownerDetailsWithDevices.getDeviceNames()); - newDeviceDetail.setDeviceOwner(ownerDetailsWithDevices.getUserName()); - newDeviceDetail.setDeviceStatus(ownerDetailsWithDevices.getDeviceStatus()); - newDeviceDetail.setType(ownerDetailsWithDevices.getDeviceTypes()); - newDeviceDetail.setDeviceIdentifier(ownerDetailsWithDevices.getDeviceIdentifiers()); + newDeviceDetail.setDeviceName(ownerWithDeviceByDeviceId.getDeviceNames()); + newDeviceDetail.setDeviceOwner(ownerWithDeviceByDeviceId.getUserName()); + newDeviceDetail.setDeviceStatus(ownerWithDeviceByDeviceId.getDeviceStatus()); + newDeviceDetail.setType(ownerWithDeviceByDeviceId.getDeviceTypes()); + newDeviceDetail.setDeviceIdentifier(ownerWithDeviceByDeviceId.getDeviceIdentifiers()); newDevices.add(newDeviceDetail); statusCounts.put("NEW", statusCounts.get("NEW") + 1); } @@ -2266,7 +2278,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { } return roleSubscriptionsWithDevices; - } catch (ApplicationManagementDAOException e) { + } catch (ApplicationManagementDAOException | DeviceManagementDAOException e) { String msg = "Error occurred in retrieving role subscriptions with devices"; log.error(msg, e); throw new ApplicationManagementException(msg, e); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java index 6f9d3e727f..9a25164a5b 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java @@ -597,9 +597,11 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { while (rs.next()) { if (ownerDetails.getUserName() == null) { ownerDetails.setUserName(rs.getString("OWNER")); - ownerDetails.setDeviceStatus(rs.getString("DEVICE_STATUS")); - ownerDetails.setDeviceNames(rs.getString("DEVICE_NAME")); } + ownerDetails.setDeviceStatus(rs.getString("DEVICE_STATUS")); + ownerDetails.setDeviceNames(rs.getString("DEVICE_NAME")); + ownerDetails.setDeviceTypes("DEVICE_TYPE"); + ownerDetails.setDeviceIdentifiers("DEVICE_IDENTIFICATION"); deviceIds.add(rs.getInt("DEVICE_ID")); deviceCount++; } @@ -610,11 +612,11 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } - ownerDetails.setDeviceIds(deviceIds); - ownerDetails.setDeviceTypes("DEVICE_TYPE"); - ownerDetails.setDeviceIdentifiers("DEVICE_IDENTIFICATION"); ownerDetails.setDeviceCount(deviceCount); + log.info("line no 617 device ids : " + ownerDetails.getDeviceIds()); + log.info("line no 618 device identifiers : " + ownerDetails.getDeviceIdentifiers()); + log.info("line no 619 device names : " + ownerDetails.getDeviceNames()); return ownerDetails; } From 11bca0f4ae99a17363b257a6a270c6900011af12 Mon Sep 17 00:00:00 2001 From: prathabanKavin Date: Thu, 11 Jul 2024 23:57:14 +0530 Subject: [PATCH 20/21] Remove unnecessary logs --- .../application/mgt/core/impl/SubscriptionManagerImpl.java | 3 --- .../device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java | 3 --- 2 files changed, 6 deletions(-) diff --git a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java index 174e317ee6..6d90d22272 100644 --- a/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/io.entgra.device.mgt.core.application.mgt.core/src/main/java/io/entgra/device/mgt/core/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -1929,9 +1929,6 @@ public class SubscriptionManagerImpl implements SubscriptionManager { // Retrieve owner details and device IDs for the user using the service layer OwnerWithDeviceDTO ownerDetailsWithDevices = deviceManagementProviderService.getOwnersWithDeviceIds(userName, applicationDTO.getDeviceTypeId()); - log.info("line no 1932 device ids : " + ownerDetailsWithDevices.getDeviceIds()); - log.info("line no 1933 device identifiers : " + ownerDetailsWithDevices.getDeviceIdentifiers()); - log.info("line no 1934 device names : " + ownerDetailsWithDevices.getDeviceNames()); SubscriptionsDTO userSubscriptionDTO = new SubscriptionsDTO(); userSubscriptionDTO.setName(userSubscription.getName()); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java index 9a25164a5b..98ef10ebe6 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/dao/impl/AbstractEnrollmentDAOImpl.java @@ -614,9 +614,6 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO { } ownerDetails.setDeviceIds(deviceIds); ownerDetails.setDeviceCount(deviceCount); - log.info("line no 617 device ids : " + ownerDetails.getDeviceIds()); - log.info("line no 618 device identifiers : " + ownerDetails.getDeviceIdentifiers()); - log.info("line no 619 device names : " + ownerDetails.getDeviceNames()); return ownerDetails; } From 8a82d1666c5add4bb056e4d41813aa4fe0a0e462 Mon Sep 17 00:00:00 2001 From: ashvini Date: Tue, 13 Feb 2024 12:49:53 +0530 Subject: [PATCH 21/21] Add capability to search policies by device type Resolve comments Resolve comments Remove unnecessary changes --- .../service/api/PolicyManagementService.java | 6 ++ .../impl/PolicyManagementServiceImpl.java | 4 ++ .../mgt/common/PolicyPaginationRequest.java | 9 +++ .../impl/policy/AbstractPolicyDAOImpl.java | 63 +++++++++++++++++++ .../dao/impl/policy/GenericPolicyDAOImpl.java | 25 +++++--- .../dao/impl/policy/OraclePolicyDAOImpl.java | 25 +++++--- .../impl/policy/PostgreSQLPolicyDAOImpl.java | 25 +++++--- .../impl/policy/SQLServerPolicyDAOImpl.java | 25 +++++--- .../mgt/core/mgt/impl/PolicyManagerImpl.java | 6 ++ 9 files changed, 160 insertions(+), 28 deletions(-) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java index 8cce7e92b3..4abcf68617 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/api/PolicyManagementService.java @@ -934,6 +934,12 @@ public interface PolicyManagementService { required = false) @QueryParam("status") String status, + @ApiParam( + name = "deviceType", + value = "The device type of the policy that needs filtering.", + required = false) + @QueryParam("deviceType") + String deviceType, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time. \n" + diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/PolicyManagementServiceImpl.java index 311b4292a7..d882018073 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.api/src/main/java/io/entgra/device/mgt/core/device/mgt/api/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -488,6 +488,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { @QueryParam("name") String name, @QueryParam("type") String type, @QueryParam("status") String status, + @QueryParam("deviceType") String deviceType, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { @@ -505,6 +506,9 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { if (status != null){ request.setStatus(status); } + if (deviceType != null) { + request.setDeviceType(deviceType); + } try { PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); policies = policyAdministratorPoint.getPolicyList(request); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PolicyPaginationRequest.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PolicyPaginationRequest.java index 8a0a2f3bd4..ddbc3a51a7 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PolicyPaginationRequest.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.common/src/main/java/io/entgra/device/mgt/core/device/mgt/common/PolicyPaginationRequest.java @@ -24,6 +24,7 @@ public class PolicyPaginationRequest { private String name; private String type; private String status; + private String deviceType; public PolicyPaginationRequest(int start, int rowCount) { this.startIndex = start; @@ -70,6 +71,14 @@ public class PolicyPaginationRequest { this.status = status; } + public String getDeviceType() { + return deviceType; + } + + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + @Override public String toString() { return "Group Name '" + this.name + "' num of rows: " + this.rowCount + " start index: " + this.startIndex; diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java index 85bd77d859..524e127a14 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java @@ -26,6 +26,7 @@ import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.CorrectiveAction; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.DeviceGroupWrapper; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Policy; import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.PolicyCriterion; +import io.entgra.device.mgt.core.device.mgt.common.policy.mgt.Profile; import io.entgra.device.mgt.core.policy.mgt.common.Criterion; import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyDAO; import io.entgra.device.mgt.core.policy.mgt.core.dao.PolicyManagementDAOFactory; @@ -1844,4 +1845,66 @@ public abstract class AbstractPolicyDAOImpl implements PolicyDAO { } return policies; } + + /** + * Extracts a list of Policy objects with associated Profile objects from the given ResultSet + * + * @param resultSet The ResultSet containing the policy and profile data + * @param tenantId The tenant ID + * @return A list of Policy objects populated with data from the ResultSet + * @throws SQLException If an SQL error occurs while processing the ResultSet + */ + protected List extractPolicyListWithProfileFromDbResult(ResultSet resultSet, int tenantId) throws SQLException { + List policies = new ArrayList<>(); + while (resultSet.next()) { + Policy policy = createPolicyFromResultSet(resultSet, tenantId); + Profile profile = createProfileFromResultSet(resultSet, tenantId); + policy.setProfile(profile); + policies.add(policy); + } + return policies; + } + + /** + * Creates a Policy object from the current row in the given ResultSet + * + * @param resultSet The ResultSet containing the policy data + * @param tenantId The tenant ID + * @return A Policy object populated with data from the ResultSet + * @throws SQLException If an SQL error occurs while processing the ResultSet + */ + private Policy createPolicyFromResultSet(ResultSet resultSet, int tenantId) throws SQLException { + Policy policy = new Policy(); + policy.setId(resultSet.getInt("ID")); + policy.setProfileId(resultSet.getInt("PROFILE_ID")); + policy.setPolicyName(resultSet.getString("NAME")); + policy.setTenantId(tenantId); + policy.setPriorityId(resultSet.getInt("PRIORITY")); + policy.setCompliance(resultSet.getString("COMPLIANCE")); + policy.setOwnershipType(resultSet.getString("OWNERSHIP_TYPE")); + policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED"))); + policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE"))); + policy.setDescription(resultSet.getString("DESCRIPTION")); + policy.setPolicyType(resultSet.getString("POLICY_TYPE")); + policy.setPolicyPayloadVersion(resultSet.getString("PAYLOAD_VERSION")); + return policy; + } + + /** + * Creates a Profile object from the current row in the given ResultSet + * + * @param resultSet The ResultSet containing the profile data + * @param tenantId The tenant ID + * @return A Profile object populated with data from the ResultSet + * @throws SQLException If an SQL error occurs while processing the ResultSet + */ + private Profile createProfileFromResultSet(ResultSet resultSet, int tenantId) throws SQLException { + Profile profile = new Profile(); + profile.setProfileId(resultSet.getInt("PROFILE_ID")); + profile.setProfileName(resultSet.getString("PROFILE_NAME")); + profile.setTenantId(tenantId); + profile.setDeviceType(resultSet.getString("DEVICE_TYPE")); + return profile; + } + } diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/GenericPolicyDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/GenericPolicyDAOImpl.java index 2e7b3aa87f..772bdbd31d 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/GenericPolicyDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/GenericPolicyDAOImpl.java @@ -48,24 +48,27 @@ public class GenericPolicyDAOImpl extends AbstractPolicyDAOImpl { String name = request.getName(); String type = request.getType(); String status = request.getStatus(); + String deviceType = request.getDeviceType(); int statusValue = 0; boolean isPolicyNameProvided = false; boolean isPolicyTypeProvided = false; boolean isPolicyStatusProvided = false; + boolean isDeviceTypeProvided = false; try { conn = this.getConnection(); String query = "SELECT * " + - "FROM DM_POLICY " + - "WHERE TENANT_ID = ? "; + "FROM DM_POLICY P " + + "LEFT JOIN DM_PROFILE PR ON P.PROFILE_ID = PR.ID " + + "WHERE P.TENANT_ID = ? "; if (name != null && !name.isEmpty()) { - query += "AND NAME LIKE ? " ; + query += "AND P.NAME LIKE ? " ; isPolicyNameProvided = true; } if (type != null && !type.isEmpty()) { - query += "AND POLICY_TYPE = ? " ; + query += "AND P.POLICY_TYPE = ? " ; isPolicyTypeProvided = true; } @@ -73,11 +76,16 @@ public class GenericPolicyDAOImpl extends AbstractPolicyDAOImpl { if (status.equals("ACTIVE")) { statusValue = 1; } - query += "AND ACTIVE = ? " ; + query += "AND P.ACTIVE = ? " ; isPolicyStatusProvided = true; } - query += "ORDER BY ID LIMIT ?,?"; + if (deviceType != null && !deviceType.isEmpty()) { + query += "AND PR.DEVICE_TYPE = ? "; + isDeviceTypeProvided = true; + } + + query += "ORDER BY P.ID LIMIT ?,?"; try (PreparedStatement stmt = conn.prepareStatement(query)) { int paramIdx = 1; @@ -91,10 +99,13 @@ public class GenericPolicyDAOImpl extends AbstractPolicyDAOImpl { if (isPolicyStatusProvided) { stmt.setInt(paramIdx++, statusValue); } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getRowCount()); try (ResultSet resultSet = stmt.executeQuery()) { - return this.extractPolicyListFromDbResult(resultSet, tenantId); + return this.extractPolicyListWithProfileFromDbResult(resultSet, tenantId); } } } catch (SQLException e) { diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/OraclePolicyDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/OraclePolicyDAOImpl.java index 19642f162e..bbc6d1a57a 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/OraclePolicyDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/OraclePolicyDAOImpl.java @@ -47,24 +47,27 @@ public class OraclePolicyDAOImpl extends AbstractPolicyDAOImpl { String name = request.getName(); String type = request.getType(); String status = request.getStatus(); + String deviceType = request.getDeviceType(); int statusValue = 0; boolean isPolicyNameProvided = false; boolean isPolicyTypeProvided = false; boolean isPolicyStatusProvided = false; + boolean isDeviceTypeProvided = false; try { conn = this.getConnection(); String query = "SELECT * " + - "FROM DM_POLICY " + - "WHERE TENANT_ID = ? "; + "FROM DM_POLICY P " + + "LEFT JOIN DM_PROFILE PR ON P.PROFILE_ID = PR.ID " + + "WHERE P.TENANT_ID = ? "; if (name != null && !name.isEmpty()) { - query += "AND NAME LIKE ? " ; + query += "AND P.NAME LIKE ? " ; isPolicyNameProvided = true; } if (type != null && !type.isEmpty()) { - query += "AND POLICY_TYPE = ? " ; + query += "AND P.POLICY_TYPE = ? " ; isPolicyTypeProvided = true; } @@ -72,11 +75,16 @@ public class OraclePolicyDAOImpl extends AbstractPolicyDAOImpl { if (status.equals("ACTIVE")) { statusValue = 1; } - query += "AND ACTIVE = ? " ; + query += "AND P.ACTIVE = ? " ; isPolicyStatusProvided = true; } - query += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + if (deviceType != null && !deviceType.isEmpty()) { + query += "AND PR.DEVICE_TYPE = ? "; + isDeviceTypeProvided = true; + } + + query += "ORDER BY P.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement stmt = conn.prepareStatement(query)) { int paramIdx = 1; @@ -90,10 +98,13 @@ public class OraclePolicyDAOImpl extends AbstractPolicyDAOImpl { if (isPolicyStatusProvided) { stmt.setInt(paramIdx++, statusValue); } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getRowCount()); try (ResultSet resultSet = stmt.executeQuery()) { - return this.extractPolicyListFromDbResult(resultSet, tenantId); + return this.extractPolicyListWithProfileFromDbResult(resultSet, tenantId); } } } catch (SQLException e) { diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/PostgreSQLPolicyDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/PostgreSQLPolicyDAOImpl.java index 26b211e6e2..01baefd69a 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/PostgreSQLPolicyDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/PostgreSQLPolicyDAOImpl.java @@ -47,24 +47,27 @@ public class PostgreSQLPolicyDAOImpl extends AbstractPolicyDAOImpl { String name = request.getName(); String type = request.getType(); String status = request.getStatus(); + String deviceType = request.getDeviceType(); int statusValue = 0; boolean isPolicyNameProvided = false; boolean isPolicyTypeProvided = false; boolean isPolicyStatusProvided = false; + boolean isDeviceTypeProvided = false; try { conn = this.getConnection(); String query = "SELECT * " + - "FROM DM_POLICY " + - "WHERE TENANT_ID = ? "; + "FROM DM_POLICY P " + + "LEFT JOIN DM_PROFILE PR ON P.PROFILE_ID = PR.ID " + + "WHERE P.TENANT_ID = ? "; if (name != null && !name.isEmpty()) { - query += "AND NAME LIKE ? " ; + query += "AND P.NAME LIKE ? " ; isPolicyNameProvided = true; } if (type != null && !type.isEmpty()) { - query += "AND POLICY_TYPE = ? " ; + query += "AND P.POLICY_TYPE = ? " ; isPolicyTypeProvided = true; } @@ -72,11 +75,16 @@ public class PostgreSQLPolicyDAOImpl extends AbstractPolicyDAOImpl { if (status.equals("ACTIVE")) { statusValue = 1; } - query += "AND ACTIVE = ? " ; + query += "AND P.ACTIVE = ? " ; isPolicyStatusProvided = true; } - query += "ORDER BY ID LIMIT ? OFFSET ?"; + if (deviceType != null && !deviceType.isEmpty()) { + query += "AND PR.DEVICE_TYPE = ?"; + isDeviceTypeProvided = true; + } + + query += "ORDER BY P.ID LIMIT ? OFFSET ?"; try (PreparedStatement stmt = conn.prepareStatement(query)) { int paramIdx = 1; @@ -90,10 +98,13 @@ public class PostgreSQLPolicyDAOImpl extends AbstractPolicyDAOImpl { if (isPolicyStatusProvided) { stmt.setInt(paramIdx++, statusValue); } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getRowCount()); try (ResultSet resultSet = stmt.executeQuery()) { - return this.extractPolicyListFromDbResult(resultSet, tenantId); + return this.extractPolicyListWithProfileFromDbResult(resultSet, tenantId); } } } catch (SQLException e) { diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/SQLServerPolicyDAOImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/SQLServerPolicyDAOImpl.java index 6e4df5cb15..5f59491ca5 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/SQLServerPolicyDAOImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/dao/impl/policy/SQLServerPolicyDAOImpl.java @@ -47,24 +47,27 @@ public class SQLServerPolicyDAOImpl extends AbstractPolicyDAOImpl { String name = request.getName(); String type = request.getType(); String status = request.getStatus(); + String deviceType = request.getDeviceType(); int statusValue = 0; boolean isPolicyNameProvided = false; boolean isPolicyTypeProvided = false; boolean isPolicyStatusProvided = false; + boolean isDeviceTypeProvided = false; try { conn = this.getConnection(); String query = "SELECT * " + - "FROM DM_POLICY " + - "WHERE TENANT_ID = ? "; + "FROM DM_POLICY P " + + "LEFT JOIN DM_PROFILE PR ON P.PROFILE_ID = PR.ID " + + "WHERE P.TENANT_ID = ? "; if (name != null && !name.isEmpty()) { - query += "AND NAME LIKE ? " ; + query += "AND P.NAME LIKE ? " ; isPolicyNameProvided = true; } if (type != null && !type.isEmpty()) { - query += "AND POLICY_TYPE = ? " ; + query += "AND P.POLICY_TYPE = ? " ; isPolicyTypeProvided = true; } @@ -72,11 +75,16 @@ public class SQLServerPolicyDAOImpl extends AbstractPolicyDAOImpl { if (status.equals("ACTIVE")) { statusValue = 1; } - query += "AND ACTIVE = ? " ; + query += "AND P.ACTIVE = ? " ; isPolicyStatusProvided = true; } - query += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + if (deviceType != null && !deviceType.isEmpty()) { + query += "AND PR.DEVICE_TYPE = ?"; + isDeviceTypeProvided = true; + } + + query += "ORDER BY P.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement stmt = conn.prepareStatement(query)) { int paramIdx = 1; @@ -90,10 +98,13 @@ public class SQLServerPolicyDAOImpl extends AbstractPolicyDAOImpl { if (isPolicyStatusProvided) { stmt.setInt(paramIdx++, statusValue); } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getRowCount()); try (ResultSet resultSet = stmt.executeQuery()) { - return this.extractPolicyListFromDbResult(resultSet, tenantId); + return this.extractPolicyListWithProfileFromDbResult(resultSet, tenantId); } } } catch (SQLException e) { diff --git a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index 9d362bcc9e..cf6e0da5a8 100644 --- a/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/io.entgra.device.mgt.core.policy.mgt.core/src/main/java/io/entgra/device/mgt/core/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -1532,6 +1532,8 @@ public class PolicyManagerImpl implements PolicyManager { for (Policy policy : policyList) { policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId())); policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId())); + policy.setProfile(profileDAO.getProfile(policy.getId())); + List deviceGroupWrappers = policyDAO.getDeviceGroupsOfPolicy(policy.getId()); if (!deviceGroupWrappers.isEmpty()) { deviceGroupWrappers = this.getDeviceGroupNames(deviceGroupWrappers); @@ -1551,6 +1553,10 @@ public class PolicyManagerImpl implements PolicyManager { String msg = "Error occurred while getting device groups."; log.error(msg, e); throw new PolicyManagementException(msg, e); + } catch (ProfileManagerDAOException e) { + String msg = "Error occurred while getting profiles."; + log.error(msg, e); + throw new PolicyManagementException(msg, e); } finally { PolicyManagementDAOFactory.closeConnection(); }