From 48e2cb69a08870ab8c95baaa052e6a06edbf534f Mon Sep 17 00:00:00 2001 From: charitha Date: Thu, 18 Jun 2020 11:02:57 +0530 Subject: [PATCH 1/5] Add IoT-Node-IP response header --- .../framework/WebappAuthenticationValve.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java index 1370482cd2..b987c14311 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java @@ -36,6 +36,11 @@ import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthen import org.wso2.carbon.webapp.authenticator.framework.authorizer.WebappTenantAuthorizer; import javax.servlet.http.HttpServletResponse; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.Enumeration; +import java.util.HashMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.regex.Pattern; @@ -49,6 +54,31 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { @Override public void invoke(Request request, Response response, CompositeValve compositeValve) { + if (response != null) { + if (inetAddress == null) { + try { + Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); + while (ifaces.hasMoreElements()) { + NetworkInterface iface = ifaces.nextElement(); + if (!iface.isLoopback() && iface.isUp()) { + Enumeration addresses = iface.getInetAddresses(); + while (addresses.hasMoreElements()) { + inetAddress = addresses.nextElement(); + break; + } + } + break; + } + } catch (SocketException e) { + if (log.isDebugEnabled()) { + log.debug("Unable to get IP address of the node.", e); + } + } + } + if (inetAddress != null) { + response.setHeader("IoT-Node-IP", inetAddress.getHostAddress()); + } + } if ((this.isContextSkipped(request) || this.skipAuthentication(request)) && (StringUtils.isEmpty(request.getHeader(AUTHORIZE_PERMISSION)))) { From 485179e16feaca061c879f318b76b12929ef95ad Mon Sep 17 00:00:00 2001 From: charitha Date: Thu, 18 Jun 2020 11:06:59 +0530 Subject: [PATCH 2/5] Add IoT-Node-IP response header --- .../authenticator/framework/WebappAuthenticationValve.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java index b987c14311..897bba0812 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java @@ -40,7 +40,6 @@ import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; -import java.util.HashMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.regex.Pattern; @@ -48,10 +47,12 @@ import java.util.regex.Pattern; public class WebappAuthenticationValve extends CarbonTomcatValve { private static final Log log = LogFactory.getLog(WebappAuthenticationValve.class); - private static TreeMap nonSecuredEndpoints = new TreeMap<>(); + private static final TreeMap nonSecuredEndpoints = new TreeMap<>(); private static final String PERMISSION_PREFIX = "/permission/admin"; public static final String AUTHORIZE_PERMISSION = "Authorize-Permission"; + private static InetAddress inetAddress = null; + @Override public void invoke(Request request, Response response, CompositeValve compositeValve) { if (response != null) { From eeacb455d5034ecd93b06745046ee654f8aed0cc Mon Sep 17 00:00:00 2001 From: charitha Date: Wed, 24 Jun 2020 21:38:35 +0530 Subject: [PATCH 3/5] Fix incorrect instantiations of Provider Services --- .../provider/fcm/FCMNotificationStrategy.java | 5 +- .../DeviceManagementPluginRepository.java | 3 +- .../impl/DeviceInformationManagerImpl.java | 2 +- .../internal/DeviceManagementDataHolder.java | 20 ++- .../DeviceManagementServiceComponent.java | 13 +- .../DeviceManagementProviderServiceImpl.java | 14 +- .../GroupManagementProviderServiceImpl.java | 47 +++--- .../DeviceManagementProviderServiceTest.java | 2 + .../mgt/core/PolicyManagerServiceImpl.java | 6 +- .../PolicyEnforcementDelegatorImpl.java | 20 +-- .../core/impl/PolicyInformationPointImpl.java | 29 ++-- .../internal/PolicyManagementDataHolder.java | 45 ++++-- .../PolicyManagementServiceComponent.java | 6 +- .../mgt/core/mgt/impl/PolicyManagerImpl.java | 152 ++++++++++-------- .../policy/mgt/core/task/MonitoringTask.java | 9 +- .../mgt/core/BasePolicyManagementDAOTest.java | 7 + .../policy/mgt/core/MonitoringTestCase.java | 7 + .../policy/mgt/core/PolicyDAOTestCase.java | 2 + .../mgt/core/PolicyEvaluationTestCase.java | 2 + .../core/PolicyManagerServiceImplTest.java | 1 + 20 files changed, 222 insertions(+), 170 deletions(-) diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java index 432ea0360f..989f4b093c 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/fcm/FCMNotificationStrategy.java @@ -95,7 +95,7 @@ public class FCMNotificationStrategy implements NotificationStrategy { OutputStream os = null; byte[] bytes = getFCMRequest(message, getFCMToken(device.getProperties())).getBytes(); - HttpURLConnection conn; + HttpURLConnection conn = null; try { conn = (HttpURLConnection) new URL(FCM_ENDPOINT).openConnection(); conn.setRequestProperty("Content-Type", "application/json"); @@ -108,6 +108,9 @@ public class FCMNotificationStrategy implements NotificationStrategy { if (os != null) { os.close(); } + if (conn != null) { + conn.disconnect(); + } } int status = conn.getResponseCode(); if (log.isDebugEnabled()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java index 462575a90a..0175493525 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java @@ -270,8 +270,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis return tenantProviders; } - private void registerPushNotificationStrategy(DeviceManagementService deviceManagementService) - throws DeviceManagementException { + private void registerPushNotificationStrategy(DeviceManagementService deviceManagementService) { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( deviceManagementService.getProvisioningConfig().getProviderTenantDomain(), true); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 2b4756d0f5..2e791f733d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -66,7 +66,7 @@ import java.util.Map; public class DeviceInformationManagerImpl implements DeviceInformationManager { private final DeviceDetailsDAO deviceDetailsDAO; - private DeviceDAO deviceDAO; + private final DeviceDAO deviceDAO; private static final Log log = LogFactory.getLog(DeviceInformationManagerImpl.class); private static final String LOCATION_EVENT_STREAM_DEFINITION = "org.wso2.iot.LocationStream"; private static final String DEVICE_INFO_EVENT_STREAM_DEFINITION = "org.wso2.iot.DeviceInfoStream"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java index 4f8cd365ab..e65ebe2fa4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -27,6 +27,7 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig; import org.wso2.carbon.device.mgt.core.config.license.LicenseConfig; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier; import org.wso2.carbon.device.mgt.core.privacy.PrivacyComplianceProvider; @@ -48,10 +49,11 @@ import java.util.Map; public class DeviceManagementDataHolder { - private static DeviceManagementDataHolder thisInstance = new DeviceManagementDataHolder(); + private static final DeviceManagementDataHolder thisInstance = new DeviceManagementDataHolder(); private RealmService realmService; private TenantManager tenantManager; private DeviceManagementProviderService deviceManagerProvider; + private DeviceInformationManager deviceInformationManager; private LicenseManager licenseManager; private RegistryService registryService; private LicenseConfig licenseConfig; @@ -59,7 +61,7 @@ public class DeviceManagementDataHolder { private AppManagementConfig appManagerConfig; private OperationManager operationManager; private ConfigurationContextService configurationContextService; - private HashMap requireDeviceAuthorization = new HashMap<>(); + private final HashMap requireDeviceAuthorization = new HashMap<>(); private DeviceAccessAuthorizationService deviceAccessAuthorizationService; private GroupManagementProviderService groupManagementProviderService; private TaskService taskService; @@ -69,10 +71,10 @@ public class DeviceManagementDataHolder { private DeviceStatusTaskManagerService deviceStatusTaskManagerService; private DeviceTypeGeneratorService deviceTypeGeneratorService; private PrivacyComplianceProvider privacyComplianceProvider; - private Map deviceStatusTaskPluginConfigs = Collections.synchronizedMap( - new HashMap()); + private final Map deviceStatusTaskPluginConfigs = Collections.synchronizedMap( + new HashMap<>()); - private Map map = new HashMap<>(); + private final Map map = new HashMap<>(); public Map getMap(){ return this.map; @@ -276,4 +278,12 @@ public class DeviceManagementDataHolder { public void setPrivacyComplianceProvider(PrivacyComplianceProvider privacyComplianceProvider) { this.privacyComplianceProvider = privacyComplianceProvider; } + + public DeviceInformationManager getDeviceInformationManager() { + return deviceInformationManager; + } + + public void setDeviceInformationManager(DeviceInformationManager deviceInformationManager) { + this.deviceInformationManager = deviceInformationManager; + } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index b8df6a0071..edc388f202 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -133,10 +133,10 @@ import java.util.concurrent.TimeUnit; public class DeviceManagementServiceComponent { private static final Object LOCK = new Object(); - private static Log log = LogFactory.getLog(DeviceManagementServiceComponent.class); - private static List listeners = new ArrayList<>(); - private static List deviceManagers = new ArrayList<>(); - private static List startupListeners = new ArrayList<>(); + private static final Log log = LogFactory.getLog(DeviceManagementServiceComponent.class); + private static final List listeners = new ArrayList<>(); + private static final List deviceManagers = new ArrayList<>(); + private static final List startupListeners = new ArrayList<>(); public static void registerPluginInitializationListener(PluginInitializationListener listener) { synchronized (LOCK) { @@ -340,7 +340,10 @@ public class DeviceManagementServiceComponent { PermissionManagerService permissionManagerService = PermissionManagerServiceImpl.getInstance(); bundleContext.registerService(PermissionManagerService.class.getName(), permissionManagerService, null); - bundleContext.registerService(DeviceInformationManager.class, new DeviceInformationManagerImpl(), null); + DeviceInformationManager deviceInformationManager = new DeviceInformationManagerImpl(); + bundleContext.registerService(DeviceInformationManager.class, deviceInformationManager, null); + DeviceManagementDataHolder.getInstance().setDeviceInformationManager(deviceInformationManager); + bundleContext.registerService(SearchManagerService.class, new SearchManagerServiceImpl(), null); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index f89dbce3ad..1ad270361b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -63,7 +63,6 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySna import org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotificationConfiguration; import org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotifier; import org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotifierException; -import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException; @@ -103,7 +102,6 @@ import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; -import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion; @@ -149,7 +147,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv private static final String OPERATION_RESPONSE_EVENT_STREAM_DEFINITION = "org.wso2.iot.OperationResponseStream"; private final DeviceManagementPluginRepository pluginRepository; - private final DeviceInformationManager deviceInformationManager; private final DeviceDAO deviceDAO; private final DeviceTypeDAO deviceTypeDAO; private final EnrollmentDAO enrollmentDAO; @@ -157,8 +154,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv public DeviceManagementProviderServiceImpl() { this.pluginRepository = new DeviceManagementPluginRepository(); - this.deviceInformationManager = new DeviceInformationManagerImpl(); - this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); this.applicationDAO = DeviceManagementDAOFactory.getApplicationDAO(); this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); @@ -399,6 +394,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv extractDeviceLocationToUpdate(device); try { if (device.getDeviceInfo() != null) { + DeviceInformationManager deviceInformationManager = DeviceManagementDataHolder + .getInstance().getDeviceInformationManager(); deviceInformationManager.addDeviceInfo(device, device.getDeviceInfo()); } } catch (DeviceDetailsMgtException e) { @@ -2838,7 +2835,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (log.isDebugEnabled()) { log.debug("Add device:" + deviceIdentifier.getId() + " to default group"); } - GroupManagementProviderService groupManagementProviderService = new GroupManagementProviderServiceImpl(); + GroupManagementProviderService groupManagementProviderService = DeviceManagementDataHolder + .getInstance().getGroupManagementProviderService(); try { DeviceGroup defaultGroup = createDefaultGroup(groupManagementProviderService, ownership.toString()); if (defaultGroup != null) { @@ -3103,6 +3101,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } DeviceInfo info; try { + DeviceInformationManager deviceInformationManager = DeviceManagementDataHolder + .getInstance().getDeviceInformationManager(); info = deviceInformationManager.getDeviceInfo(device); } catch (DeviceDetailsMgtException e) { String msg = "Error occurred while retrieving advance info of '" + device.getType() + @@ -3402,6 +3402,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv * @param device Device object */ private void extractDeviceLocationToUpdate(Device device) { + DeviceInformationManager deviceInformationManager = DeviceManagementDataHolder + .getInstance().getDeviceInformationManager(); List properties = device.getProperties(); if (properties != null) { String latitude = null; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 0fc3e978c9..740f6afd61 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -55,10 +55,10 @@ import java.util.Map; public class GroupManagementProviderServiceImpl implements GroupManagementProviderService { - private static Log log = LogFactory.getLog(GroupManagementProviderServiceImpl.class); + private static final Log log = LogFactory.getLog(GroupManagementProviderServiceImpl.class); - private GroupDAO groupDAO; - private DeviceDAO deviceDAO; + private final GroupDAO groupDAO; + private final DeviceDAO deviceDAO; /** * Set groupDAO from GroupManagementDAOFactory when class instantiate. @@ -912,9 +912,21 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid log.debug("Get groups of device " + deviceIdentifier.getId()); } int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - DeviceManagementProviderService managementProviderService = new DeviceManagementProviderServiceImpl(); + DeviceManagementProviderService managementProviderService = DeviceManagementDataHolder + .getInstance().getDeviceManagementProvider(); + Device device; + try { + device = managementProviderService.getDevice(deviceIdentifier, false); + } catch (DeviceManagementException e) { + String msg = "Error occurred while retrieving device groups."; + log.error(msg, e); + throw new GroupManagementException(msg, e); + } + return getDeviceGroups(requireGroupProps, tenantId, device); + } + + private List getDeviceGroups(boolean requireGroupProps, int tenantId, Device device) throws GroupManagementException { try { - Device device = managementProviderService.getDevice(deviceIdentifier, false); GroupManagementDAOFactory.openConnection(); List deviceGroups = groupDAO.getGroups(device.getId(), tenantId); if (requireGroupProps) { @@ -925,7 +937,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } } return deviceGroups; - } catch (DeviceManagementException | GroupManagementDAOException | SQLException e) { + } catch (GroupManagementDAOException | SQLException e) { String msg = "Error occurred while retrieving device groups."; log.error(msg, e); throw new GroupManagementException(msg, e); @@ -950,28 +962,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid log.debug("Get groups of device " + device.getDeviceIdentifier()); } int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - try { - GroupManagementDAOFactory.openConnection(); - List deviceGroups = groupDAO.getGroups(device.getId(), tenantId); - if (requireGroupProps) { - if (deviceGroups != null && !deviceGroups.isEmpty()) { - for (DeviceGroup group : deviceGroups) { - populateGroupProperties(group, tenantId); - } - } - } - return deviceGroups; - } catch (GroupManagementDAOException | SQLException e) { - String msg = "Error occurred while retrieving device groups."; - log.error(msg, e); - throw new GroupManagementException(msg, e); - } catch (Exception e) { - String msg = "Error occurred in getGroups"; - log.error(msg, e); - throw new GroupManagementException(msg, e); - } finally { - GroupManagementDAOFactory.closeConnection(); - } + return getDeviceGroups(requireGroupProps, tenantId, device); } /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java index 619ded45e9..80183bbcff 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java @@ -77,6 +77,7 @@ import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException; +import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; @@ -124,6 +125,7 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService()); DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(new DeviceAccessAuthorizationServiceImpl()); DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new GroupManagementProviderServiceImpl()); + DeviceManagementDataHolder.getInstance().setDeviceInformationManager(new DeviceInformationManagerImpl()); DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null); deviceMgtService.registerDeviceType(new TestDeviceManagementService(DEVICE_TYPE, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java index f7ca96c02e..813e7015c4 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java @@ -69,9 +69,9 @@ public class PolicyManagerServiceImpl implements PolicyManagerService { private static final Log log = LogFactory.getLog(PolicyManagerServiceImpl.class); - PolicyAdministratorPoint policyAdministratorPoint; - MonitoringManager monitoringManager; - private PolicyManager policyManager; + private final PolicyAdministratorPoint policyAdministratorPoint; + private final MonitoringManager monitoringManager; + private final PolicyManager policyManager; public PolicyManagerServiceImpl() { policyAdministratorPoint = new PolicyAdministratorPointImpl(); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java index 9bf9c6023a..12ce24e824 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java @@ -41,15 +41,14 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants; -import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyTransformException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; -import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; @@ -60,8 +59,8 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato private static final Log log = LogFactory.getLog(PolicyEnforcementDelegatorImpl.class); - private List devices; - private List updatedPolicyIds; + private final List devices; + private final List updatedPolicyIds; public PolicyEnforcementDelegatorImpl(List devices, List updatedPolicyIds) { @@ -75,7 +74,6 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato } this.devices = devices; this.updatedPolicyIds = updatedPolicyIds; - } @Override @@ -111,7 +109,8 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato @Override public Policy getEffectivePolicy(DeviceIdentifier identifier) throws PolicyDelegationException { try { - PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); + PolicyManagerService policyManagerService = PolicyManagementDataHolder.getInstance() + .getPolicyManagerService(); PolicyAdministratorPoint policyAdministratorPoint; Policy policy = policyManagerService.getPEP().getEffectivePolicy(identifier); @@ -124,11 +123,7 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato } return policy; //return PolicyManagementDataHolder.getInstance().getPolicyEvaluationPoint().getEffectivePolicy(identifier); - } catch (PolicyEvaluationException e) { - String msg = "Error occurred while retrieving the effective policy for devices."; - log.error(msg, e); - throw new PolicyDelegationException(msg, e); - } catch (PolicyManagementException e) { + } catch (PolicyEvaluationException | PolicyManagementException e) { String msg = "Error occurred while retrieving the effective policy for devices."; log.error(msg, e); throw new PolicyDelegationException(msg, e); @@ -199,7 +194,8 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato */ public Policy getAppliedPolicyToDevice(Device device) throws PolicyDelegationException { try { - PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); + PolicyManagerService policyManagerService = PolicyManagementDataHolder.getInstance() + .getPolicyManagerService(); return policyManagerService.getAppliedPolicyToDevice(device); } catch (PolicyManagementException e) { String msg = "Error occurred while retrieving the applied policy for devices."; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java index 498ccc82f4..1c08b1d5a8 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java @@ -40,17 +40,19 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.common.Feature; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; -import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl; -import org.wso2.carbon.policy.mgt.common.*; +import org.wso2.carbon.policy.mgt.common.FeatureManagementException; +import org.wso2.carbon.policy.mgt.common.PIPDevice; +import org.wso2.carbon.policy.mgt.common.PolicyFilter; +import org.wso2.carbon.policy.mgt.common.PolicyInformationPoint; +import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; @@ -68,9 +70,9 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { private static final Log log = LogFactory.getLog(PolicyInformationPointImpl.class); - PolicyManager policyManager; - FeatureManager featureManager; - DeviceManagementProviderService deviceManagementService; + private final PolicyManager policyManager; + private final FeatureManager featureManager; + private final DeviceManagementProviderService deviceManagementService; public PolicyInformationPointImpl() { deviceManagementService = @@ -85,8 +87,8 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { Device device; DeviceType deviceType = new DeviceType(); deviceType.setName(deviceIdentifier.getType()); - DeviceManagementProviderService deviceManagementService = new DeviceManagementProviderServiceImpl(); - GroupManagementProviderService groupManagementProviderService = new GroupManagementProviderServiceImpl(); + GroupManagementProviderService groupManagementProviderService = PolicyManagementDataHolder + .getInstance().getGroupManagementService(); try { device = deviceManagementService.getDevice(deviceIdentifier, false); @@ -184,11 +186,10 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { } } - private List removeDuplicatePolicies(List> policies) { - Map map = new HashMap(); - List finalPolicies = new ArrayList(); + Map map = new HashMap<>(); + List finalPolicies = new ArrayList<>(); for (List policyList : policies) { for (Policy policy : policyList) { if (!map.containsKey(policy.getId())) { @@ -200,8 +201,4 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { return finalPolicies; } - private DeviceManagementProviderService getDeviceManagementService() { - return new DeviceManagementProviderServiceImpl(); - } - } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementDataHolder.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementDataHolder.java index 15b394442d..4842565861 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementDataHolder.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementDataHolder.java @@ -18,16 +18,18 @@ package org.wso2.carbon.policy.mgt.core.internal; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint; import org.wso2.carbon.policy.mgt.common.PolicyInformationPoint; +import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.user.core.service.RealmService; -import org.wso2.carbon.user.core.tenant.TenantManager; import java.util.HashMap; import java.util.Map; @@ -35,16 +37,16 @@ import java.util.Map; public class PolicyManagementDataHolder { private RealmService realmService; - private TenantManager tenantManager; - private PolicyEvaluationPoint policyEvaluationPoint; - private Map policyEvaluationPoints = new HashMap<>(); + private final Map policyEvaluationPoints = new HashMap<>(); private PolicyInformationPoint policyInformationPoint; private DeviceManagementProviderService deviceManagementService; + private GroupManagementProviderService groupManagementService; + private PolicyManagerService policyManagerService; private MonitoringManager monitoringManager; private PolicyManager policyManager; private TaskService taskService; - private static PolicyManagementDataHolder thisInstance = new PolicyManagementDataHolder(); + private static final PolicyManagementDataHolder thisInstance = new PolicyManagementDataHolder(); private PolicyManagementDataHolder() {} @@ -74,18 +76,6 @@ public class PolicyManagementDataHolder { public void setRealmService(RealmService realmService) { this.realmService = realmService; - this.setTenantManager(realmService); - } - - private void setTenantManager(RealmService realmService) { - if (realmService == null) { - throw new IllegalStateException("Realm service is not initialized properly"); - } - this.tenantManager = realmService.getTenantManager(); - } - - public TenantManager getTenantManager() { - return tenantManager; } public PolicyEvaluationPoint getPolicyEvaluationPoint() { @@ -127,4 +117,25 @@ public class PolicyManagementDataHolder { public void setTaskService(TaskService taskService) { this.taskService = taskService; } + + public synchronized GroupManagementProviderService getGroupManagementService() { + if (groupManagementService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + groupManagementService = (GroupManagementProviderService) + ctx.getOSGiService(GroupManagementProviderService.class, null); + if (groupManagementService == null) { + String msg = "GroupImpl Management service has not initialized."; + throw new IllegalStateException(msg); + } + } + return groupManagementService; + } + + public PolicyManagerService getPolicyManagerService() { + return policyManagerService; + } + + public void setPolicyManagerService(PolicyManagerService policyManagerService) { + this.policyManagerService = policyManagerService; + } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java index 7d14db6972..8c5819a2f1 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java @@ -67,7 +67,7 @@ import org.wso2.carbon.user.core.service.RealmService; @SuppressWarnings("unused") public class PolicyManagementServiceComponent { - private static Log log = LogFactory.getLog(PolicyManagementServiceComponent.class); + private static final Log log = LogFactory.getLog(PolicyManagementServiceComponent.class); protected void activate(ComponentContext componentContext) { @@ -77,8 +77,10 @@ public class PolicyManagementServiceComponent { DataSourceConfig dsConfig = config.getPolicyManagementRepository().getDataSourceConfig(); PolicyManagementDAOFactory.init(dsConfig); + PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); componentContext.getBundleContext().registerService( - PolicyManagerService.class.getName(), new PolicyManagerServiceImpl(), null); + PolicyManagerService.class.getName(), policyManagerService, null); + PolicyManagementDataHolder.getInstance().setPolicyManagerService(policyManagerService); PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getPolicyConfiguration(); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index afa35e106d..c8737f1468 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -56,9 +56,7 @@ import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; -import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl; import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl; import org.wso2.carbon.policy.mgt.core.dao.*; @@ -74,12 +72,12 @@ import java.util.*; public class PolicyManagerImpl implements PolicyManager { - private PolicyDAO policyDAO; - private ProfileDAO profileDAO; - private FeatureDAO featureDAO; - private ProfileManager profileManager; - private PolicyConfiguration policyConfiguration; - private static Log log = LogFactory.getLog(PolicyManagerImpl.class); + private final PolicyDAO policyDAO; + private final ProfileDAO profileDAO; + private final FeatureDAO featureDAO; + private final ProfileManager profileManager; + private final PolicyConfiguration policyConfiguration; + private static final Log log = LogFactory.getLog(PolicyManagerImpl.class); public PolicyManagerImpl() { this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO(); @@ -495,10 +493,11 @@ public class PolicyManagerImpl implements PolicyManager { Policy policy) throws PolicyManagementException { List deviceList = new ArrayList<>(); - DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); + DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder + .getInstance().getDeviceManagementService(); for (DeviceIdentifier deviceIdentifier : deviceIdentifierList) { try { - Device device = service.getDevice(deviceIdentifier, false); + Device device = deviceManagementService.getDevice(deviceIdentifier, false); deviceList.add(device); } catch (DeviceManagementException e) { throw new PolicyManagementException("Error occurred while retrieving device information", e); @@ -732,19 +731,23 @@ public class PolicyManagerImpl implements PolicyManager { List policyIdList; List policies = new ArrayList<>(); - try { - DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); - Device device = service.getDevice(deviceIdentifier, false); + DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder + .getInstance().getDeviceManagementService(); + Device device; + try { + device = deviceManagementService.getDevice(deviceIdentifier, false); + } catch (DeviceManagementException e) { + throw new PolicyManagementException("Error occurred while getting device related to device identifier (" + + deviceIdentifier.getId() + " - " + deviceIdentifier.getType() + ")", e); + } + try { PolicyManagementDAOFactory.openConnection(); policyIdList = policyDAO.getPolicyIdsOfDevice(device); } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the policies for device identifier (" + deviceIdentifier.getId() + " - " + deviceIdentifier.getType() + ")", e); - } catch (DeviceManagementException e) { - throw new PolicyManagementException("Error occurred while getting device related to device identifier (" + - deviceIdentifier.getId() + " - " + deviceIdentifier.getType() + ")", e); } catch (SQLException e) { throw new PolicyManagementException("Error occurred while open a data source connection", e); } finally { @@ -814,7 +817,6 @@ public class PolicyManagerImpl implements PolicyManager { try { PolicyManagementDAOFactory.openConnection(); policyIdList = policyDAO.getPolicyOfRole(roleName); - } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the policies.", e); } catch (SQLException e) { @@ -882,9 +884,16 @@ public class PolicyManagerImpl implements PolicyManager { List deviceList = new ArrayList<>(); List deviceIds; + DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder + .getInstance().getDeviceManagementService(); + List allDevices; + try { + allDevices = deviceManagementService.getAllDevices(); + } catch (DeviceManagementException e) { + throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" + + policyId + ")", e); + } try { - DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance().getDeviceManagementService(); - List allDevices = service.getAllDevices(); PolicyManagementDAOFactory.openConnection(); deviceIds = policyDAO.getPolicyAppliedDevicesIds(policyId); HashMap allDeviceMap = new HashMap<>(); @@ -906,9 +915,6 @@ public class PolicyManagerImpl implements PolicyManager { policyId + ")", e); } catch (SQLException e) { throw new PolicyManagementException("Error occurred while opening a connection to the data source", e); - } catch (DeviceManagementException e) { - throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" + - policyId + ")", e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -918,12 +924,17 @@ public class PolicyManagerImpl implements PolicyManager { @Override public void addAppliedPolicyFeaturesToDevice(DeviceIdentifier deviceIdentifier, Policy policy) throws PolicyManagementException { - int deviceId = -1; + DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder + .getInstance().getDeviceManagementService(); + Device device; + try { + device = deviceManagementService.getDevice(deviceIdentifier, false); + } catch (DeviceManagementException e) { + throw new PolicyManagementException("Error occurred while getting the device details (" + + deviceIdentifier.getId() + ")", e); + } + int deviceId = device.getId(); try { - DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); - Device device = service.getDevice(deviceIdentifier, false); - deviceId = device.getId(); - PolicyManagementDAOFactory.beginTransaction(); boolean exist = policyDAO.checkPolicyAvailable(deviceId, device.getEnrolmentInfo().getId()); if (exist) { @@ -936,9 +947,6 @@ public class PolicyManagerImpl implements PolicyManager { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyManagementException("Error occurred while adding the evaluated policy to device (" + deviceId + " - " + policy.getId() + ")", e); - } catch (DeviceManagementException e) { - throw new PolicyManagementException("Error occurred while getting the device details (" + - deviceIdentifier.getId() + ")", e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -997,12 +1005,18 @@ public class PolicyManagerImpl implements PolicyManager { @Override public void addAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier, Policy policy) throws PolicyManagementException { - - int deviceId = -1; + DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder + .getInstance().getDeviceManagementService(); + Device device; + try { + device = deviceManagementService.getDevice(deviceIdentifier, false); + } catch (DeviceManagementException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while getting the device details (" + + deviceIdentifier.getId() + ")", e); + } + int deviceId = device.getId(); try { - DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); - Device device = service.getDevice(deviceIdentifier, false); - deviceId = device.getId(); PolicyManagementDAOFactory.beginTransaction(); Policy policySaved = policyDAO.getAppliedPolicy(deviceId, device.getEnrolmentInfo().getId()); @@ -1016,10 +1030,6 @@ public class PolicyManagerImpl implements PolicyManager { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyManagementException("Error occurred while adding the evaluated policy to device (" + deviceId + " - " + policy.getId() + ")", e); - } catch (DeviceManagementException e) { - PolicyManagementDAOFactory.rollbackTransaction(); - throw new PolicyManagementException("Error occurred while getting the device details (" + - deviceIdentifier.getId() + ")", e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -1027,12 +1037,18 @@ public class PolicyManagerImpl implements PolicyManager { @Override public void removeAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { - - int deviceId = -1; + DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder + .getInstance().getDeviceManagementService(); + Device device; + try { + device = deviceManagementService.getDevice(deviceIdentifier, false); + } catch (DeviceManagementException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while getting the device details (" + + deviceIdentifier.getId() + ")", e); + } + int deviceId = device.getId(); try { - DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); - Device device = service.getDevice(deviceIdentifier, false); - deviceId = device.getId(); PolicyManagementDAOFactory.beginTransaction(); Policy policySaved = policyDAO.getAppliedPolicy(deviceId, device.getEnrolmentInfo().getId()); @@ -1044,10 +1060,6 @@ public class PolicyManagerImpl implements PolicyManager { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyManagementException("Error occurred while removing the applied policy to device (" + deviceId + ")", e); - } catch (DeviceManagementException e) { - PolicyManagementDAOFactory.rollbackTransaction(); - throw new PolicyManagementException("Error occurred while getting the device details (" + - deviceIdentifier.getId() + ")", e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -1057,17 +1069,21 @@ public class PolicyManagerImpl implements PolicyManager { public boolean checkPolicyAvailable(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { boolean exist; + DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder + .getInstance().getDeviceManagementService(); + Device device; + try { + device = deviceManagementService.getDevice(deviceIdentifier, false); + } catch (DeviceManagementException e) { + throw new PolicyManagementException("Error occurred while getting the device details (" + + deviceIdentifier.getId() + ")", e); + } try { - DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); - Device device = service.getDevice(deviceIdentifier, false); PolicyManagementDAOFactory.openConnection(); exist = policyDAO.checkPolicyAvailable(device.getId(), device.getEnrolmentInfo().getId()); } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while checking whether device has a policy " + "to apply.", e); - } catch (DeviceManagementException e) { - throw new PolicyManagementException("Error occurred while getting the device details (" + - deviceIdentifier.getId() + ")", e); } catch (SQLException e) { throw new PolicyManagementException("Error occurred while opening a connection to the data source", e); } finally { @@ -1078,19 +1094,24 @@ public class PolicyManagerImpl implements PolicyManager { @Override public boolean setPolicyApplied(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { + + DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder + .getInstance().getDeviceManagementService(); + Device device; try { - DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); - Device device = service.getDevice(deviceIdentifier, false); + device = deviceManagementService.getDevice(deviceIdentifier, false); + } catch (DeviceManagementException e) { + throw new PolicyManagementException("Error occurred while getting the device details (" + + deviceIdentifier.getId() + ")", e); + } + try { PolicyManagementDAOFactory.openConnection(); policyDAO.setPolicyApplied(device.getId(), device.getEnrolmentInfo().getId()); return true; } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while setting the policy has applied to device (" + deviceIdentifier.getId() + ")", e); - } catch (DeviceManagementException e) { - throw new PolicyManagementException("Error occurred while getting the device details (" + - deviceIdentifier.getId() + ")", e); } catch (SQLException e) { throw new PolicyManagementException("Error occurred while opening a connection to the data source", e); } finally { @@ -1115,10 +1136,11 @@ public class PolicyManagerImpl implements PolicyManager { @Override @Deprecated public Policy getAppliedPolicyToDevice(DeviceIdentifier deviceId) throws PolicyManagementException { - DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); + DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder + .getInstance().getDeviceManagementService(); Device device; try { - device = service.getDevice(deviceId, false); + device = deviceManagementService.getDevice(deviceId, false); if (device == null) { if (log.isDebugEnabled()) { log.debug("No device is found upon the device identifier '" + deviceId.getId() + @@ -1163,17 +1185,18 @@ public class PolicyManagerImpl implements PolicyManager { } } - private List getDeviceGroupNames(List groupWrappers) throws GroupManagementException { - GroupManagementProviderService groupManagementProviderService = new GroupManagementProviderServiceImpl(); + private List getDeviceGroupNames(List groupWrappers) + throws GroupManagementException { + GroupManagementProviderService groupManagementService = PolicyManagementDataHolder + .getInstance().getGroupManagementService(); for (DeviceGroupWrapper wrapper : groupWrappers) { - DeviceGroup deviceGroup = groupManagementProviderService.getGroup(wrapper.getId(), false); + DeviceGroup deviceGroup = groupManagementService.getGroup(wrapper.getId(), false); wrapper.setName(deviceGroup.getName()); wrapper.setOwner(deviceGroup.getOwner()); } return groupWrappers; } - private List convertDevices(List devices) { List deviceIdentifiers = new ArrayList<>(); for (Device device : devices) { @@ -1185,7 +1208,6 @@ public class PolicyManagerImpl implements PolicyManager { return deviceIdentifiers; } - private void addPolicyRevokeOperation(List deviceIdentifiers) throws PolicyManagementException { try { String type = null; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java index f75995179b..0acbac6a60 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java @@ -16,7 +16,6 @@ * under the License. */ - package org.wso2.carbon.policy.mgt.core.task; import org.apache.commons.logging.Log; @@ -29,11 +28,9 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.ntask.core.Task; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; -import org.wso2.carbon.user.api.UserStoreException; import java.util.ArrayList; import java.util.List; @@ -43,11 +40,8 @@ public class MonitoringTask implements Task { private static final Log log = LogFactory.getLog(MonitoringTask.class); - Map properties; - @Override public void setProperties(Map map) { - this.properties = map; } @Override @@ -84,7 +78,8 @@ public class MonitoringTask implements Task { log.debug("Monitoring task started to run for all tenants."); } try { - DeviceManagementProviderService deviceManagementService = new DeviceManagementProviderServiceImpl(); + DeviceManagementProviderService deviceManagementService = PolicyManagementDataHolder + .getInstance().getDeviceManagementService(); List tenants = deviceManagementService.getDeviceEnrolledTenants(); for (Integer tenant : tenants) { if (MultitenantConstants.SUPER_TENANT_ID == tenant) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java index d487d35a25..450313aac0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java @@ -39,6 +39,7 @@ import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationSe import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; @@ -112,11 +113,17 @@ public abstract class BasePolicyManagementDAOTest { DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService( new DeviceAccessAuthorizationServiceImpl()); DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(groupMgtService); + DeviceManagementDataHolder.getInstance().setDeviceInformationManager(new DeviceInformationManagerImpl()); DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null); PolicyEvaluationPoint policyEvaluationPoint = new SimplePolicyEvaluationTest(); PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint("Simple", policyEvaluationPoint); PolicyManagementDataHolder.getInstance().setDeviceManagementService(deviceMgtService); + PolicyManagementDataHolder.getInstance().setPolicyManagerService(new PolicyManagerServiceImpl()); + + Field groupManagementService = PolicyManagementDataHolder.class.getDeclaredField("groupManagementService"); + groupManagementService.setAccessible(true); + groupManagementService.set(PolicyManagementDataHolder.getInstance(), groupMgtService); profileManager = new ProfileManagerImpl(); } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java index 58fadeef8d..6bb6a1fe6b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java @@ -22,16 +22,19 @@ package org.wso2.carbon.policy.mgt.core; import junit.framework.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; +import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; @@ -55,7 +58,11 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { public void testMonitorDao() { DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); + DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(service); + DeviceManagementDataHolder.getInstance().setDeviceInformationManager(new DeviceInformationManagerImpl()); + DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(new GroupManagementProviderServiceImpl()); PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); + PolicyManagementDataHolder.getInstance().setPolicyManagerService(policyManagerService); List policies = null; List devices = null; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java index 9142aa45b4..98b5940e4c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java @@ -55,6 +55,8 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { @BeforeClass public void init() throws Exception { + log.info("Initializing policy tests"); + super.initializeServices(); initDatSource(); // System.setProperty("GetTenantIDForTest", "Super"); initiatePrivilegedCaronContext(); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java index ac7fa971f4..bf7a5bb760 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java @@ -46,6 +46,8 @@ public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest { @BeforeClass public void init() throws Exception { + log.info("Initializing policy tests"); + super.initializeServices(); PolicyEvaluationPoint evaluationPoint = new SimplePolicyEvaluationTest(); PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint(evaluationPoint.getName(), evaluationPoint); } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java index 2ffacebbac..d372eb63d8 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImplTest.java @@ -89,6 +89,7 @@ public class PolicyManagerServiceImplTest extends BasePolicyManagementDAOTest { public void addPolicy() throws DeviceManagementException, GroupManagementException, PolicyManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); policyManagerService = new PolicyManagerServiceImpl(); + PolicyManagementDataHolder.getInstance().setPolicyManagerService(policyManagerService); DeviceManagementService deviceManagementService = new TypeXDeviceManagementService(DEVICE_TYPE_A); deviceMgtService.registerDeviceType(deviceManagementService); operationManager = new OperationManagerImpl(DEVICE_TYPE_A, deviceManagementService); From c6fef5d0d15cfc3aec229c9ae6ae6df02f076b4d Mon Sep 17 00:00:00 2001 From: charitha Date: Wed, 30 Sep 2020 10:13:10 +0530 Subject: [PATCH 4/5] Add task operation with list of device ids --- .../operation/mgt/OperationManager.java | 2 + .../carbon/device/mgt/core/dao/DeviceDAO.java | 14 +- .../core/dao/impl/AbstractDeviceDAOImpl.java | 59 ++++++ .../operation/mgt/OperationManagerImpl.java | 191 +++++++++--------- .../mgt/dao/impl/GenericOperationDAOImpl.java | 2 + .../DeviceManagementProviderService.java | 45 +++-- .../DeviceManagementProviderServiceImpl.java | 28 +++ 7 files changed, 231 insertions(+), 110 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java index 8bf77e1875..9faa732090 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java @@ -45,6 +45,8 @@ public interface OperationManager { Activity addOperation(Operation operation, List devices) throws OperationManagementException, InvalidDeviceException; + void addTaskOperation(List devices, Operation operation) throws OperationManagementException; + void addTaskOperation(String deviceType, Operation operation) throws OperationManagementException; /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index aa920737cc..537539864c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -527,7 +527,7 @@ public interface DeviceDAO { List findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, int geohashLength,int tenantId) throws DeviceManagementDAOException; - /*** + /** * This method is used to identify whether given device ids are exist or not. * * @param deviceIdentifiers List of device identifiers. @@ -539,6 +539,18 @@ public interface DeviceDAO { List getDevicesByIdentifiers(List deviceIdentifiers, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve devices with specified device identifiers filtered with statuses. + * + * @param deviceIdentifiers List of device identifiers. + * @param tenantId tenant id. + * @return returns list of device ids that matches with device identifiers. + * @throws DeviceManagementDAOException throws {@link DeviceManagementDAOException} if connections establishment + * fails. + */ + List getDevicesByIdentifiersAndStatuses(List deviceIdentifiers, List statuses, int tenantId) + throws DeviceManagementDAOException; + /*** * This method is used to permanently delete devices and their related details * @param deviceIdentifiers List of device identifiers. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 825b684e0c..4eff108ba5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -1829,6 +1829,65 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } + @Override + public List getDevicesByIdentifiersAndStatuses(List deviceIdentifiers, + List statuses, int tenantId) + throws DeviceManagementDAOException { + try { + Connection conn = this.getConnection(); + int index = 1; + int counter = 0; + List devices = new ArrayList<>(); + + StringJoiner statusJoiner = new StringJoiner(",", "e.STATUS IN (", ") "); + while (counter < statuses.size()) { + statusJoiner.add("?"); + counter++; + } + + StringJoiner joiner = new StringJoiner(",", + "SELECT " + + "d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, " + + "e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + + "FROM " + + "DM_ENROLMENT e, " + + "(SELECT d.ID, d.DESCRIPTION, d.NAME, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION " + + "FROM DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE " + + "t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION IN (", + ") AND d.TENANT_ID = ?) d1 " + + "WHERE d1.ID = e.DEVICE_ID AND " + statusJoiner.toString() + + "AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC, e.STATUS ASC"); + + counter = 0; + while (counter < deviceIdentifiers.size()) { + joiner.add("?"); + counter++; + } + String query = joiner.toString(); + try (PreparedStatement ps = conn.prepareStatement(query)) { + for (String identifier : deviceIdentifiers) { + ps.setString(index++, identifier); + } + ps.setInt(index++, tenantId); + for (EnrolmentInfo.Status status : statuses) { + ps.setString(index++, status.toString()); + } + ps.setInt(index, tenantId); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + devices.add(DeviceManagementDAOUtil.loadDevice(rs)); + } + } + } + return devices; + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while obtaining the DB connection to get devices for" + + " given device identifiers and statuses.", e); + } + } + @Override public List getDeviceLocationInfo(DeviceIdentifier deviceIdentifier, long from, long to) throws DeviceManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index 9377015bf4..b2e7b769ae 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -24,15 +24,15 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.MonitoringOperation; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; +import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus; @@ -227,67 +227,21 @@ public class OperationManagerImpl implements OperationManager { + operationCode); } Activity activity = new Activity(); - //Send the operation statuses only for admin triggered operations - String deviceType = validDeviceIds.get(0).getType(); activity.setActivityStatus(this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult)); return activity; } } - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - int operationId = this.lookupOperationDAO(operation).addOperation(operationDto); - operationDto.setId(operationId); - - boolean isScheduled = false; - NotificationStrategy notificationStrategy = getNotificationStrategy(); - - // check whether device list is greater than batch size notification strategy has enable to send push - // notification using scheduler task - if (DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getPushNotificationConfiguration().getSchedulerBatchSize() <= authorizedDeviceIds.size() && - notificationStrategy != null) { - isScheduled = notificationStrategy.getConfig().isScheduled(); - } - int failAttempts = 0; - while (true) { - try { - operationMappingDAO.addOperationMapping(operationDto, - new ArrayList<>(enrolments.values()), isScheduled, tenantId); - OperationManagementDAOFactory.commitTransaction(); - break; - } catch (OperationManagementDAOException e) { - OperationManagementDAOFactory.rollbackTransaction(); - if (++failAttempts > 3) { - String msg = "Error occurred while updating operation mapping. Operation ID: " + - operationId; - log.error(msg, e); - throw new OperationManagementException(msg, e); - } - log.warn("Unable to update operation status. Operation ID: " + operationId + - ", Attempt: " + failAttempts + ", Error: " + e.getMessage()); - try { - Thread.sleep(2000); - } catch (InterruptedException ignore) { - break; - } - } - } - if (!isScheduled && notificationStrategy != null) { - for (Device d : enrolments.values()) { - this.sendNotification(operation, d); - } - } + persistsOperation(operation, operationDto, enrolments); Activity activity = new Activity(); - activity.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + operationId); + activity.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + operation.getId()); activity.setCode(operationCode); activity.setCreatedTimeStamp(new Date().toString()); activity.setType(Activity.Type.valueOf(operationDto.getType().toString())); //For now set the operation statuses only for admin triggered operations if (!isScheduledOperation) { - //Get the device-type from 1st valid DeviceIdentifier. We know the 1st element is definitely there. - String deviceType = validDeviceIds.get(0).getType(); activity.setActivityStatus(this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult)); } @@ -305,6 +259,46 @@ public class OperationManagerImpl implements OperationManager { } } + @Override + public void addTaskOperation(List devices, Operation operation) throws OperationManagementException { + try { + OperationManagementDAOFactory.beginTransaction(); + operation.setInitiatedBy(SYSTEM); + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto = + OperationDAOUtil.convertOperation(operation); + String operationCode = operationDto.getCode(); + Map enrolments = new HashMap<>(); + for (Device device : devices) { + enrolments.put(device.getEnrolmentInfo().getId(), device); + } + if (operationDto.getControl() == + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT) { + Map pendingOperationIDs = operationDAO + .getExistingOperationIDs(enrolments.keySet().toArray(new Integer[0]), operationCode); + Device device; + for (Integer enrolmentId : pendingOperationIDs.keySet()) { + operation.setId(pendingOperationIDs.get(enrolmentId)); + device = enrolments.get(enrolmentId); + this.sendNotification(operation, device); + //No need to keep this enrollment as it has a pending operation + enrolments.remove(enrolmentId); + } + if (enrolments.size() == 0) { + //No operations to be add. All are repeated. + return; + } + } + persistsOperation(operation, operationDto, enrolments); + } catch (OperationManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + throw new OperationManagementException("Error occurred while adding task operation", e); + } catch (TransactionManagementException e) { + throw new OperationManagementException("Error occurred while initiating the transaction", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + } + @Override public void addTaskOperation(String deviceType, Operation operation) throws OperationManagementException { List validStatuses = Arrays.asList(EnrolmentInfo.Status.ACTIVE.toString(), @@ -356,49 +350,7 @@ public class OperationManagerImpl implements OperationManager { break; } } - - int operationId = this.lookupOperationDAO(operation).addOperation(operationDto); - operationDto.setId(operationId); - - boolean isScheduled = false; - NotificationStrategy notificationStrategy = getNotificationStrategy(); - - // check whether device list is greater than batch size notification strategy has enable to send push - // notification using scheduler task - if (DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). - getPushNotificationConfiguration().getSchedulerBatchSize() <= enrolments.size() && - notificationStrategy != null) { - isScheduled = notificationStrategy.getConfig().isScheduled(); - } - int failAttempts = 0; - while (true) { - try { - operationMappingDAO.addOperationMapping(operationDto, - new ArrayList<>(enrolments.values()), isScheduled, tenantId); - OperationManagementDAOFactory.commitTransaction(); - break; - } catch (OperationManagementDAOException e) { - OperationManagementDAOFactory.rollbackTransaction(); - if (++failAttempts > 3) { - String msg = "Error occurred while updating operation mapping. Operation ID: " + - operationId; - log.error(msg, e); - throw new OperationManagementException(msg, e); - } - log.warn("Unable to update operation status. Operation ID: " + operationId + - ", Attempt: " + failAttempts + ", Error: " + e.getMessage()); - try { - Thread.sleep(2000); - } catch (InterruptedException ignore) { - break; - } - } - } - if (!isScheduled && notificationStrategy != null) { - for (Device device : enrolments.values()) { - this.sendNotification(operation, device); - } - } + persistsOperation(operation, operationDto, enrolments); try { Thread.sleep(2000); } catch (InterruptedException ignore) { @@ -418,6 +370,57 @@ public class OperationManagerImpl implements OperationManager { } } + private void persistsOperation(Operation operation, + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto, + Map enrolments) + throws OperationManagementDAOException, OperationManagementException { + + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + int operationId = this.lookupOperationDAO(operation).addOperation(operationDto); + operationDto.setId(operationId); + operation.setId(operationId); + + boolean isScheduled = false; + NotificationStrategy notificationStrategy = getNotificationStrategy(); + + // check whether device list is greater than batch size notification strategy has enable to send push + // notification using scheduler task + if (DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). + getPushNotificationConfiguration().getSchedulerBatchSize() <= enrolments.size() && + notificationStrategy != null) { + isScheduled = notificationStrategy.getConfig().isScheduled(); + } + int failAttempts = 0; + while (true) { + try { + operationMappingDAO.addOperationMapping(operationDto, + new ArrayList<>(enrolments.values()), isScheduled, tenantId); + OperationManagementDAOFactory.commitTransaction(); + break; + } catch (OperationManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + if (++failAttempts > 3) { + String msg = "Error occurred while updating operation mapping. Operation ID: " + + operationId; + log.error(msg, e); + throw new OperationManagementException(msg, e); + } + log.warn("Unable to update operation status. Operation ID: " + operationId + + ", Attempt: " + failAttempts + ", Error: " + e.getMessage()); + try { + Thread.sleep(2000); + } catch (InterruptedException ignore) { + break; + } + } + } + if (!isScheduled && notificationStrategy != null) { + for (Device device : enrolments.values()) { + this.sendNotification(operation, device); + } + } + } + private void sendNotification(Operation operation, Device device) { NotificationStrategy notificationStrategy = getNotificationStrategy(); /* diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index e20628da85..fe26b7677b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -25,6 +25,7 @@ import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationResponse; +import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.OperationResponseMeta; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping; @@ -429,6 +430,7 @@ public class GenericOperationDAOImpl implements OperationDAO { while (rs.next()) { if (enrolmentId == 0) { activity = new Activity(); + activity.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + operationId); activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); activity.setCode(rs.getString("OPERATION_CODE")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 3a79a9cd42..b63b109533 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -14,23 +14,23 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. + */ +/* + * Copyright (c) 2020, Entgra (pvt) Ltd. (http://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 * - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://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 + * 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. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.wso2.carbon.device.mgt.core.service; @@ -73,6 +73,7 @@ import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion; import org.wso2.carbon.device.mgt.core.geo.GeoCluster; import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; +import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import java.sql.SQLException; import java.util.Date; @@ -655,6 +656,9 @@ public interface DeviceManagementProviderService { void addTaskOperation(String deviceType, Operation operation) throws OperationManagementException; + void addTaskOperation(String type, List devices, Operation operation) + throws OperationManagementException; + List getOperations(DeviceIdentifier deviceId) throws OperationManagementException; PaginationResult getOperations(DeviceIdentifier deviceId, @@ -906,7 +910,6 @@ public interface DeviceManagementProviderService { * @param deviceIdentifiers A list of device identifiers * @return A list of devices * @throws {@link DeviceManagementException} - * @throws {@link InvalidDeviceException} */ List getDeviceByIdList(List deviceIdentifiers) throws DeviceManagementException; @@ -918,4 +921,16 @@ public interface DeviceManagementProviderService { * @return enrollment steps of each enrollment types which are provided in the device type xml file */ DeviceEnrollmentInvitationDetails getDeviceEnrollmentInvitationDetails(String deviceType); + + /** + * This method is used to retrieve devices with specified device identifiers filtered with statuses. + * + * @param deviceIdentifiers A list of device identifiers + * @param statuses A list of device statuses + * @return A list of devices + * @throws {@link DeviceManagementException} + */ + List getDevicesByIdentifiersAndStatuses(List deviceIdentifiers, List statuses) + throws DeviceManagementException; + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 5e28129390..7413d3f6e4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -1838,6 +1838,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv pluginRepository.getOperationManager(type, this.getTenantId()).addTaskOperation(type, operation); } + @Override + public void addTaskOperation(String type, List devices, Operation operation) + throws OperationManagementException { + pluginRepository.getOperationManager(type, this.getTenantId()).addTaskOperation(devices, operation); + } + @Override public List getOperations(DeviceIdentifier deviceId) throws OperationManagementException { return pluginRepository.getOperationManager(deviceId.getType(), this.getTenantId()).getOperations(deviceId); @@ -4212,4 +4218,26 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementService dms = pluginRepository.getDeviceManagementService(deviceType, tenantId); return dms.getDeviceEnrollmentInvitationDetails(); } + + @Override + public List getDevicesByIdentifiersAndStatuses(List deviceIdentifiers, + List statuses) + throws DeviceManagementException { + int tenantId = this.getTenantId(); + try { + DeviceManagementDAOFactory.openConnection(); + return deviceDAO.getDevicesByIdentifiersAndStatuses(deviceIdentifiers, statuses, tenantId); + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while retrieving device list."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the data source"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + } From 9998ec3669aa2d904e0158dfe5eab2bd0ae117c4 Mon Sep 17 00:00:00 2001 From: Saad Sahibjan Date: Wed, 30 Sep 2020 18:14:57 +0530 Subject: [PATCH 5/5] Allow other statuses to update the device status --- .../DeviceManagementProviderServiceImpl.java | 26 +++++++------------ 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 7413d3f6e4..b5333d9677 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -2744,24 +2744,16 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return false; //New status is similar to current } int tenantId = this.getTenantId(); - switch (newStatus) { - case ACTIVE: + if (EnrolmentInfo.Status.REMOVED == newStatus) { + isDeviceUpdated = disenrollDevice(deviceIdentifier); + } else { + enrolmentInfo = device.getEnrolmentInfo(); + if (enrolmentInfo.getStatus() != newStatus) { + enrolmentInfo.setStatus(newStatus); isDeviceUpdated = updateEnrollment(deviceId, enrolmentInfo, tenantId); - break; - case INACTIVE: - enrolmentInfo = device.getEnrolmentInfo(); - if (enrolmentInfo.getStatus() != newStatus) { - enrolmentInfo.setStatus(newStatus); - isDeviceUpdated = updateEnrollment(deviceId, enrolmentInfo, tenantId); - } else { - isDeviceUpdated = false; - } - break; - case REMOVED: - isDeviceUpdated = disenrollDevice(deviceIdentifier); - break; - default: - throw new DeviceManagementException("Invalid status retrieved. Status : " + newStatus); + } else { + isDeviceUpdated = false; + } } return isDeviceUpdated; }