From be705ce81b4b8139e2ca1c633081c0a623acaf24 Mon Sep 17 00:00:00 2001 From: Charitha Goonetilleke Date: Wed, 6 May 2020 06:19:45 +0000 Subject: [PATCH] Performance improvements --- .../apimgt/integration/client/util/Utils.java | 2 +- .../lifecycle/util/AnnotationProcessor.java | 6 +- components/apimgt-extensions/pom.xml | 4 +- .../DeviceManagementAdminServiceImpl.java | 2 +- .../impl/util/DeviceMgtAPITestHelper.java | 1 - .../device/mgt/common/DeviceManager.java | 2 - .../device/mgt/common/EnrolmentInfo.java | 10 + .../mgt/common/MonitoringOperation.java | 17 + .../device/mgt/common/PaginationRequest.java | 5 +- .../operation/mgt/OperationManager.java | 15 +- .../type/mgt/DeviceTypeMetaDefinition.java | 8 - .../DeviceManagementPluginRepository.java | 6 +- .../core/archival/ArchivalServiceImpl.java | 363 +++--- .../beans/ArchiveCommandOperation.java | 44 - .../beans/ArchiveEnrolmentOperationMap.java | 80 -- .../archival/beans/ArchiveNotification.java | 80 -- .../core/archival/beans/ArchiveOperation.java | 100 -- .../beans/ArchiveOperationResponse.java | 83 -- .../beans/ArchiveProfileOperation.java | 53 - .../mgt/core/archival/dao/ArchivalDAO.java | 34 +- .../core/archival/dao/ArchivalDAOUtil.java | 10 - .../dao/ArchivalDestinationDAOFactory.java | 40 +- .../dao/ArchivalSourceDAOFactory.java | 1 - .../core/archival/dao/DataDeletionDAO.java | 6 +- .../archival/dao/impl/ArchivalDAOImpl.java | 898 ++++++------- .../dao/impl/DataDeletionDAOImpl.java | 50 +- .../DeviceAccessAuthorizationServiceImpl.java | 12 - .../archival/ArchivalTaskConfiguration.java | 20 + .../mgt/core/config/archival/DBConfig.java | 51 + .../carbon/device/mgt/core/dao/DeviceDAO.java | 33 +- .../device/mgt/core/dao/EnrollmentDAO.java | 10 +- .../core/dao/impl/AbstractDeviceDAOImpl.java | 282 ++--- .../core/dao/impl/AbstractGroupDAOImpl.java | 75 +- .../mgt/core/dao/impl/EnrollmentDAOImpl.java | 112 +- .../dao/impl/device/GenericDeviceDAOImpl.java | 364 +++--- .../dao/impl/device/OracleDeviceDAOImpl.java | 331 ++--- .../impl/device/PostgreSQLDeviceDAOImpl.java | 347 ++--- .../impl/device/SQLServerDeviceDAOImpl.java | 357 +++--- .../dao/impl/group/GenericGroupDAOImpl.java | 2 +- .../dao/impl/group/OracleGroupDAOImpl.java | 2 +- .../impl/group/PostgreSQLGroupDAOImpl.java | 2 +- .../dao/impl/group/SQLServerGroupDAOImpl.java | 2 +- .../dao/util/DeviceManagementDAOUtil.java | 3 +- .../details/mgt/DeviceInformationManager.java | 2 + .../mgt/dao/impl/DeviceDetailsDAOImpl.java | 3 +- .../impl/DeviceInformationManagerImpl.java | 45 +- .../operation/mgt/OperationResponseMeta.java | 69 + .../operation/mgt/OperationManagerImpl.java | 664 +++++++--- .../core/operation/mgt/dao/OperationDAO.java | 15 +- .../mgt/dao/OperationManagementDAOUtil.java | 9 +- .../mgt/dao/OperationMappingDAO.java | 7 +- .../mgt/dao/impl/GenericOperationDAOImpl.java | 538 +++++--- .../mgt/dao/impl/OperationMappingDAOImpl.java | 55 +- .../mgt/dao/impl/PolicyOperationDAOImpl.java | 2 +- .../impl/operation/MySQLOperationDAOImpl.java | 309 ++--- .../operation/OracleOperationDAOImpl.java | 29 +- .../operation/PostgreSQLOperationDAOImpl.java | 62 + .../operation/SQLServerOperationDAOImpl.java | 29 +- .../mgt/dao/util/OperationDAOUtil.java | 16 +- .../DeviceManagementProviderService.java | 13 +- .../DeviceManagementProviderServiceImpl.java | 634 +++++----- .../task/impl/DeviceStatusMonitoringTask.java | 47 +- .../device/mgt/core/task/TaskOperation.java | 59 - .../carbon/device/mgt/core/task/Utils.java | 2 - .../mgt/core/task/impl/ArchivalTask.java | 16 +- .../task/impl/ArchivalTaskManagerImpl.java | 1 - .../core/task/impl/DeviceTaskManagerImpl.java | 91 +- .../mgt/core/util/DeviceManagerUtil.java | 119 +- .../device/mgt/core/TestDeviceManager.java | 5 - .../mgt/core/common/TestDataHolder.java | 6 +- .../core/dao/EnrolmentPersistenceTests.java | 2 +- .../operation/OperationManagementTests.java | 12 +- .../DeviceManagementProviderServiceTest.java | 10 +- .../src/test/resources/sql/h2.sql | 32 +- .../type/template/DeviceTypeManager.java | 39 +- .../template/DeviceTypeManagerService.java | 11 +- .../HTTPDeviceTypeManagerService.java | 4 - .../type/template/config/Claimable.java | 104 -- .../config/DeviceTypeConfiguration.java | 23 - .../template/config/TaskConfiguration.java | 9 + .../util/DeviceTypePluginConstants.java | 1 - ...rviceAndDeviceTypeGeneratorServceTest.java | 1 - .../handlers/ScopeValidationHandler.java | 58 +- .../impl/ComplianceDecisionPointImpl.java | 22 +- .../policy/mgt/core/task/MonitoringTask.java | 11 +- .../mgt/core/mock/TypeXDeviceManager.java | 5 - .../src/test/resources/sql/CreateH2TestDB.sql | 60 +- .../src/test/resources/testng.xml | 1 - .../src/main/resources/conf/cdm-config.xml | 11 +- .../dbscripts/cdm/archival/mysql.sql | 28 +- .../dbscripts/cdm/archival/postgresql.sql | 57 + .../src/main/resources/dbscripts/cdm/h2.sql | 26 +- .../main/resources/dbscripts/cdm/mssql.sql | 64 +- .../main/resources/dbscripts/cdm/mysql.sql | 67 +- .../main/resources/dbscripts/cdm/oracle.sql | 39 +- .../resources/dbscripts/cdm/postgresql.sql | 1121 +++++++++-------- 96 files changed, 4322 insertions(+), 4268 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveCommandOperation.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveEnrolmentOperationMap.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveNotification.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveOperation.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveOperationResponse.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveProfileOperation.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/archival/DBConfig.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/OperationResponseMeta.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/TaskOperation.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Claimable.java create mode 100644 features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/postgresql.sql diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java index 85004efd69..29845990d7 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/util/Utils.java @@ -102,7 +102,7 @@ public class Utils { final ProxySelector proxySelector = new ProxySelector() { @Override - public java.util.List select(URI uri) { + public List select(URI uri) { List proxyList = new ArrayList<>(); String host = uri.getHost(); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java index a1b6f16d8f..9cac3ca45a 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java @@ -94,7 +94,7 @@ public class AnnotationProcessor { private Class tagClass; private Class extensionClass; private Class extensionPropertyClass; - private Class apiOperation; + private Class apiOperation; private Class scopeClass; private Class scopesClass; private Map apiScopes; @@ -119,8 +119,8 @@ public class AnnotationProcessor { .loadClass(org.wso2.carbon.apimgt.annotations.api.Scope.class.getName()); scopesClass = (Class) classLoader .loadClass(org.wso2.carbon.apimgt.annotations.api.Scopes.class.getName()); - apiOperation = (Class)classLoader - .loadClass((io.swagger.annotations.ApiOperation.class.getName())); + apiOperation = (Class)classLoader + .loadClass((ApiOperation.class.getName())); } catch (ClassNotFoundException e) { log.error("An error has occurred while loading classes ", e); } diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index c85818189e..750ebe73dd 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -34,8 +34,8 @@ http://wso2.org - org.wso2.carbon.apimgt.integration.generated.client - org.wso2.carbon.apimgt.integration.client + org.wso2.carbon.apimgt.integration.generated.client + org.wso2.carbon.apimgt.integration.client org.wso2.carbon.apimgt.webapp.publisher org.wso2.carbon.apimgt.application.extension org.wso2.carbon.apimgt.application.extension.api diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index e4030b6d50..cd3fdb95e3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -140,7 +140,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe @QueryParam("owner") String owner, List deviceIdentifiers){ try { - if (DeviceMgtAPIUtils.getDeviceManagementService().updateEnrollment(owner, deviceIdentifiers)) { + if (DeviceMgtAPIUtils.getDeviceManagementService().updateEnrollment(owner, true, deviceIdentifiers)) { String msg = "Device owner is updated successfully."; return Response.status(Response.Status.OK).entity(msg).build(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/DeviceMgtAPITestHelper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/DeviceMgtAPITestHelper.java index f1f0d1628d..6f869bd952 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/DeviceMgtAPITestHelper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/DeviceMgtAPITestHelper.java @@ -52,7 +52,6 @@ public class DeviceMgtAPITestHelper { deviceType.setName(name != null ? name : DEVICE_TYPE); DeviceTypeMetaDefinition deviceTypeMetaDefinition = new DeviceTypeMetaDefinition(); - deviceTypeMetaDefinition.setClaimable(true); deviceTypeMetaDefinition.setDescription(DEVICE_TYPE_DESCRIPTION); PushNotificationConfig pushNotificationConfig = diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java index 2c7336144f..334ab858bc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java @@ -184,8 +184,6 @@ public interface DeviceManager { */ boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) throws DeviceManagementException; - boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException; - boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrolmentInfo.Status status) throws DeviceManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java index af44df25c2..796110b63e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java @@ -40,6 +40,8 @@ public class EnrolmentInfo implements Serializable { @ApiModelProperty(name = "id", value = "ID of the device in the WSO2 EMM device information database.", required = true) private int id; + + private boolean isTransferred; @ApiModelProperty(name = "dateOfEnrolment", value = "Date of the device enrollment. This value is not necessary.", required = false ) private Long dateOfEnrolment; @ApiModelProperty(name = "dateOfLastUpdate", value = "Date of the device's last update. This value is not necessary.", required = false ) @@ -72,6 +74,14 @@ public class EnrolmentInfo implements Serializable { this.id = id; } + public boolean isTransferred() { + return isTransferred; + } + + public void setTransferred(boolean transferred) { + isTransferred = transferred; + } + public Long getDateOfEnrolment() { return dateOfEnrolment; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/MonitoringOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/MonitoringOperation.java index 8d5a8cc434..ba2fc0637a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/MonitoringOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/MonitoringOperation.java @@ -25,6 +25,7 @@ public class MonitoringOperation { private String taskName; private int recurrentTimes; + private boolean responsePersistence = true; public String getTaskName() { return taskName; @@ -42,5 +43,21 @@ public class MonitoringOperation { this.recurrentTimes = recurrentTimes; } + public boolean hasResponsePersistence() { + return responsePersistence; + } + + public void setResponsePersistence(boolean responsePersistence) { + this.responsePersistence = responsePersistence; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof MonitoringOperation) { + MonitoringOperation op = (MonitoringOperation) obj; + return taskName != null && taskName.equals(op.getTaskName()); + } + return false; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java index aed55ea50c..56cecfe008 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.common; +import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -33,14 +34,14 @@ public class PaginationRequest { private int groupId; private String owner; private String ownerPattern; - private List statusList; private String deviceType; private String deviceName; private String ownership; private String ownerRole; - private Map property = new HashMap<>(); private Date since; private String filter; + private Map property = new HashMap<>(); + private List statusList = new ArrayList<>(); public PaginationRequest(int start, int rowCount) { this.startIndex = start; 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 3edfb20161..8bf77e1875 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(String deviceType, Operation operation) throws OperationManagementException; + /** * Method to retrieve the list of all operations to a device. * @@ -66,6 +68,17 @@ public interface OperationManager { */ PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException; + /** + * Method to retrieve the list of operations placed for device with specified status. + * + * @param deviceId - Device Identifier of the device + * @param status - Status of the operation + * @return A List of operations applied to the given device-id. + * @throws OperationManagementException If some unusual behaviour is observed while fetching the + * operation list. + */ + List getOperations(DeviceIdentifier deviceId, Operation.Status status) + throws OperationManagementException; /** * Method to retrieve the list of available operations to a device. @@ -86,7 +99,7 @@ public interface OperationManager { void updateOperation(DeviceIdentifier deviceId, Operation operation) throws OperationManagementException; - void updateOperation(int enrolmentId, Operation operation) throws OperationManagementException; + void updateOperation(int enrolmentId, Operation operation, DeviceIdentifier deviceId) throws OperationManagementException; Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId) throws OperationManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java index c49d030e7e..dcc7ff47cd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java @@ -43,14 +43,6 @@ public class DeviceTypeMetaDefinition { this.features = features; } - public boolean isClaimable() { - return claimable; - } - - public void setClaimable(boolean isClaimable) { - this.claimable = isClaimable; - } - public PushNotificationConfig getPushNotificationConfig() { return pushNotificationConfig; } 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 d16ad2c288..462575a90a 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 @@ -56,15 +56,15 @@ import java.util.Map; public class DeviceManagementPluginRepository implements DeviceManagerStartupListener { - private Map providers; + private final Map providers; private boolean isInitiated; private static final Log log = LogFactory.getLog(DeviceManagementPluginRepository.class); - private OperationManagerRepository operationManagerRepository; + private final OperationManagerRepository operationManagerRepository; private static final long DEFAULT_UPDATE_TIMESTAMP = 900000L; public DeviceManagementPluginRepository() { this.operationManagerRepository = new OperationManagerRepository(); - providers = Collections.synchronizedMap(new HashMap()); + providers = Collections.synchronizedMap(new HashMap<>()); DeviceManagementServiceComponent.registerStartupListener(this); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/ArchivalServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/ArchivalServiceImpl.java index e41152d47d..558af2be83 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/ArchivalServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/ArchivalServiceImpl.java @@ -18,34 +18,34 @@ package org.wso2.carbon.device.mgt.core.archival; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; -import org.wso2.carbon.device.mgt.core.archival.beans.*; -import org.wso2.carbon.device.mgt.core.archival.dao.*; +import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDAO; +import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDAOException; +import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDestinationDAOFactory; +import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalSourceDAOFactory; +import org.wso2.carbon.device.mgt.core.archival.dao.DataDeletionDAO; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.Date; import java.util.List; public class ArchivalServiceImpl implements ArchivalService { - private static Log log = LogFactory.getLog(ArchivalServiceImpl.class); + private static final Log log = LogFactory.getLog(ArchivalServiceImpl.class); - private ArchivalDAO archivalDAO; - private DataDeletionDAO dataDeletionDAO; + private final ArchivalDAO archivalDAO; + private final DataDeletionDAO dataDeletionDAO; private static final int EXECUTION_BATCH_SIZE = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getArchivalConfiguration() .getArchivalTaskConfiguration().getBatchSize(); - private static final boolean ARCHIVE_PENDING_OPERATIONS = + private static final int ARCHIVAL_LOCK_INTERVAL = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getArchivalConfiguration() - .getArchivalTaskConfiguration().isArchivePendingOperations(); - - private String[] NOT_IN_PROGRESS_OPS = new String[]{"COMPLETED", "ERROR", "REPEATED"}; - private String[] NOT_PENDING_OPS = new String[]{"COMPLETED", "ERROR", "REPEATED", "IN_PROGRESS"}; - private String[] NOT_PENDING_IN_PROGRESS_OPS = new String[]{"COMPLETED", "ERROR", "REPEATED"}; + .getArchivalTaskConfiguration().getArchivalLockInterval(); public ArchivalServiceImpl() { this.archivalDAO = ArchivalSourceDAOFactory.getDataPurgingDAO(); @@ -54,187 +54,160 @@ public class ArchivalServiceImpl implements ArchivalService { @Override public void archiveTransactionalRecords() throws ArchivalException { - List allOperations; - try { - ArchivalSourceDAOFactory.openConnection(); - ArchivalDestinationDAOFactory.openConnection(); + beginTransactions(); + Timestamp currentTime = new Timestamp(new Date().getTime()); + //Purge the largest table, DM_DEVICE_OPERATION_RESPONSE if (log.isDebugEnabled()) { - log.debug("Fetching All Operations"); + log.debug("## Archiving operation responses"); } - allOperations = archivalDAO.getAllOperations(); - if (log.isDebugEnabled()) { - log.debug("Fetching All Pending Operations"); - } - - - } catch (ArchivalDAOException e) { -// rollbackTransactions(); - String msg = "Rollback the get all operations and get all pending operations"; - log.error(msg, e); - throw new ArchivalException(msg, e); - } catch (SQLException e) { - String msg = "An error occurred while connecting to the archival database"; - log.error(msg, e); - throw new ArchivalException(msg, e); - } finally { - ArchivalSourceDAOFactory.closeConnection(); - ArchivalDestinationDAOFactory.closeConnection(); - } + int failAttempts; - List candidates = allOperations; - log.info(allOperations.size() + " All Operations."); + List nonRemovableMappings = archivalDAO.getNonRemovableOperationMappingIDs(currentTime); + int totalLargeOpResCount = archivalDAO.getLargeOperationResponseCount(currentTime, nonRemovableMappings); - if (!ARCHIVE_PENDING_OPERATIONS) { - try { - ArchivalSourceDAOFactory.openConnection(); - ArchivalDestinationDAOFactory.openConnection(); - List pendingAndIPOperations = archivalDAO.getPendingAndInProgressOperations(); - log.info(pendingAndIPOperations.size() +" P&IP Operations"); -// Get the diff of operations - candidates.removeAll(pendingAndIPOperations); - } catch (ArchivalDAOException e) { - String msg = "Error occurred while retrieving the pending operations"; - log.error(msg, e); - throw new ArchivalException(msg, e); - } catch (SQLException e) { - String msg = "An error occurred while connecting to the archival database"; - log.error(msg, e); - throw new ArchivalException(msg, e); - } finally { - ArchivalSourceDAOFactory.closeConnection(); - ArchivalDestinationDAOFactory.closeConnection(); + if (totalLargeOpResCount > 0) { + int iterationCount = totalLargeOpResCount / EXECUTION_BATCH_SIZE; + int residualRecSize = 0; + if ((totalLargeOpResCount % EXECUTION_BATCH_SIZE) != 0) { + residualRecSize = totalLargeOpResCount % EXECUTION_BATCH_SIZE; + iterationCount++; + } + failAttempts = 0; + for (int iter = 0; iter < iterationCount; iter++) { + try { + if (iter == (iterationCount - 1)) { + archivalDAO.transferLargeOperationResponses(residualRecSize, currentTime, nonRemovableMappings); + archivalDAO.removeLargeOperationResponses(residualRecSize, currentTime, nonRemovableMappings); + } else { + archivalDAO.transferLargeOperationResponses(EXECUTION_BATCH_SIZE, currentTime, nonRemovableMappings); + archivalDAO.removeLargeOperationResponses(EXECUTION_BATCH_SIZE, currentTime, nonRemovableMappings); + } + commitTransactions(); + failAttempts = 0; + } catch (ArchivalDAOException e) { + rollbackTransactions(); + if (++failAttempts > 3) { + String msg = "Error occurred while trying to archive Large Operation Responses. Abort archiving."; + log.error(msg, e); + throw new ArchivalException(msg, e); + } + String msg = "Error occurred while trying to archive Large Operation Responses. " + + "Failed attempts: " + failAttempts + " Error: " + e.getMessage(); + log.warn(msg); + iter--; + } + Thread.sleep(ARCHIVAL_LOCK_INTERVAL); + } } - } - int total = candidates.size(); - int batches = calculateNumberOfBatches(total); - log.info(total + " Operations ready for archiving. " + batches + " iterations to be done."); - int batchSize = EXECUTION_BATCH_SIZE; - if (log.isDebugEnabled()) { - log.debug(total + " Operations ready for archiving. " + batches + " iterations to be done."); - log.debug(batchSize + " is the batch size"); - } - - for (int i = 1; i <= batches; i++) { - int startIdx = batchSize * (i - 1); - int endIdx = batchSize * i; - if (i == batches) { - endIdx = startIdx + (total % batchSize); - } - if (log.isDebugEnabled()) { - log.debug("\n\n############ Iterating over batch " + i + "[" + - startIdx + "," + endIdx + "] #######"); - } - List subList = candidates.subList(startIdx, endIdx); + int totalOpResCount = archivalDAO.getOperationResponseCount(currentTime, nonRemovableMappings); - if (log.isDebugEnabled()) { - log.debug("SubList size is: " + subList.size()); - if (subList.size() > 0) { - log.debug("First Element is: " + subList.get(0)); - log.debug("Last Element is: " + subList.get(subList.size() - 1)); + if (totalOpResCount > 0) { + int iterationCount = totalOpResCount / EXECUTION_BATCH_SIZE; + int residualRecSize = 0; + if ((totalOpResCount % EXECUTION_BATCH_SIZE) != 0) { + residualRecSize = totalOpResCount % EXECUTION_BATCH_SIZE; + iterationCount++; } - } - - if (log.isDebugEnabled()) { - for (Integer val : subList) { - if (log.isDebugEnabled()) { - log.debug("Sub List Element: " + val); + failAttempts = 0; + for (int iter = 0; iter < iterationCount; iter++) { + try { + if (iter == (iterationCount - 1)) { + archivalDAO.transferOperationResponses(residualRecSize, currentTime, nonRemovableMappings); + archivalDAO.removeOperationResponses(residualRecSize, currentTime, nonRemovableMappings); + } else { + archivalDAO.transferOperationResponses(EXECUTION_BATCH_SIZE, currentTime, nonRemovableMappings); + archivalDAO.removeOperationResponses(EXECUTION_BATCH_SIZE, currentTime, nonRemovableMappings); + } + commitTransactions(); + failAttempts = 0; + } catch (ArchivalDAOException e) { + rollbackTransactions(); + if (++failAttempts > 3) { + String msg = "Error occurred while trying to archive Operation Responses. Abort archiving."; + log.error(msg, e); + throw new ArchivalException(msg, e); + } + String msg = "Error occurred while trying to archive Operation Responses. " + + "Failed attempts: " + failAttempts + " Error: " + e.getMessage(); + log.warn(msg); + iter--; } + Thread.sleep(ARCHIVAL_LOCK_INTERVAL); } } - try { - beginTransactions(); - prepareTempTable(subList); - commitTransactions(); - } catch (Exception e) { - rollbackTransactions(); - String msg = "Error occurred while preparing the operations."; - log.error(msg, e); - throw new ArchivalException(msg, e); - } finally { - ArchivalSourceDAOFactory.closeConnection(); - ArchivalDestinationDAOFactory.closeConnection(); + //Purge the notifications table, DM_NOTIFICATION + if (log.isDebugEnabled()) { + log.debug("## Archiving notifications"); } - - List operationResponses = null; - List notification = null; - List commandOperations = null; - List profileOperations = null; - List enrollmentMapping = null; - List operations = null; - - try { - openConnection(); - operationResponses = archivalDAO.selectOperationResponses(); - notification = archivalDAO.selectNotifications(); - enrollmentMapping = archivalDAO.selectEnrolmentMappings(); - operations = archivalDAO.selectOperations(); - - } catch (Exception e) { - String msg = "Error occurred while retrieving data."; - log.error(msg, e); - throw new ArchivalException(msg, e); - } finally { - closeConnection(); + archivalDAO.moveNotifications(currentTime); + commitTransactions(); + //Purge the enrolment mappings table, DM_ENROLMENT_OP_MAPPING + if (log.isDebugEnabled()) { + log.debug("## Archiving enrolment mappings"); } - - try { - beginTransactions(); - - //Purge the largest table, DM_DEVICE_OPERATION_RESPONSE - if (log.isDebugEnabled()) { - log.debug("## Archiving operation responses"); - } - archivalDAO.moveOperationResponses(operationResponses); - - //Purge the notifications table, DM_NOTIFICATION - if (log.isDebugEnabled()) { - log.debug("## Archiving notifications"); - } - archivalDAO.moveNotifications(notification); - - //Purge the enrolment mappings table, DM_ENROLMENT_OP_MAPPING - if (log.isDebugEnabled()) { - log.debug("## Archiving enrolment mappings"); - } - archivalDAO.moveEnrolmentMappings(enrollmentMapping); - - //Finally, purge the operations table, DM_OPERATION - if (log.isDebugEnabled()) { - log.debug("## Archiving operations"); + int opMappingCount = archivalDAO.getOpMappingsCount(currentTime); + if (opMappingCount > 0) { + int iterationCount = opMappingCount / EXECUTION_BATCH_SIZE; + int residualRecSize = 0; + if ((opMappingCount % EXECUTION_BATCH_SIZE) != 0) { + residualRecSize = opMappingCount % EXECUTION_BATCH_SIZE; + iterationCount++; } - archivalDAO.moveOperations(operations); - commitTransactions(); - if (log.isDebugEnabled()) { - log.debug("End of Iteration : " + i); + failAttempts = 0; + for (int iter = 0; iter < iterationCount; iter++) { + try { + if (iter == (iterationCount - 1)) { + archivalDAO.transferEnrollmentOpMappings(residualRecSize, currentTime); + archivalDAO.removeEnrollmentOPMappings(residualRecSize, currentTime); + } else { + archivalDAO.transferEnrollmentOpMappings(EXECUTION_BATCH_SIZE, currentTime); + archivalDAO.removeEnrollmentOPMappings(EXECUTION_BATCH_SIZE, currentTime); + } + commitTransactions(); + failAttempts = 0; + } catch (ArchivalDAOException e) { + rollbackTransactions(); + if (++failAttempts > 3) { + String msg = "Error occurred while trying to archive Operation Enrollment Mappings. Abort archiving."; + log.error(msg, e); + throw new ArchivalException(msg, e); + } + String msg = "Error occurred while trying to archive Operation Enrollment Mappings. " + + "Failed attempts: " + failAttempts + " Error: " + e.getMessage(); + log.warn(msg); + iter--; + } + Thread.sleep(ARCHIVAL_LOCK_INTERVAL); } - } catch (ArchivalDAOException e) { - rollbackTransactions(); - String msg = "Error occurred while trying to archive data to the six tables"; - log.error(msg, e); - throw new ArchivalException(msg, e); - } finally { - ArchivalSourceDAOFactory.closeConnection(); - ArchivalDestinationDAOFactory.closeConnection(); } - } - } + //Finally, purge the operations table, DM_OPERATION + if (log.isDebugEnabled()) { + log.debug("## Archiving operations"); + } - private void prepareTempTable(List subList) throws ArchivalDAOException { - //Clean up the DM_ARCHIVED_OPERATIONS table - if (log.isDebugEnabled()) { - log.debug("## Truncating the temporary table"); - } - archivalDAO.truncateOperationIDsForArchival(); - if (log.isDebugEnabled()) { - log.debug("## Inserting into the temporary table"); + archivalDAO.transferOperations(); + archivalDAO.removeOperations(); + commitTransactions(); + } catch (ArchivalDAOException e) { + rollbackTransactions(); + String msg = "Error occurred while trying to archive data to the six tables"; + log.error(msg, e); + throw new ArchivalException(msg, e); + } catch (InterruptedException e) { + rollbackTransactions(); + String msg = "Error while halting archival thread to free up table locks."; + log.error(msg, e); + throw new ArchivalException(msg, e); + } finally { + ArchivalSourceDAOFactory.closeConnection(); + ArchivalDestinationDAOFactory.closeConnection(); } - archivalDAO.copyOperationIDsForArchival(subList); } private void beginTransactions() throws ArchivalException { @@ -247,28 +220,6 @@ public class ArchivalServiceImpl implements ArchivalService { } } - private void openConnection() throws ArchivalException { - try { - ArchivalSourceDAOFactory.openConnection(); - } catch (SQLException e) { - String msg = "An error occurred during opening connection"; - log.error(msg, e); - throw new ArchivalException(msg, e); - } - - } - - private void closeConnection() throws ArchivalException { - try { - ArchivalSourceDAOFactory.closeConnection(); - } catch (Exception e) { - String msg = "An error occurred during opening connection"; - log.error(msg, e); - throw new ArchivalException(msg, e); - } - - } - private void commitTransactions() { ArchivalSourceDAOFactory.commitTransaction(); ArchivalDestinationDAOFactory.commitTransaction(); @@ -279,22 +230,16 @@ public class ArchivalServiceImpl implements ArchivalService { ArchivalDestinationDAOFactory.rollbackTransaction(); } - private int calculateNumberOfBatches(int total) { - int batches = 0; - int batchSize = EXECUTION_BATCH_SIZE; - if ((total % batchSize) > 0) { - batches = (total / batchSize) + 1; - } else { - batches = total / batchSize; - } - return batches; - } - @Override public void deleteArchivedRecords() throws ArchivalException { try { ArchivalDestinationDAOFactory.openConnection(); + if (log.isDebugEnabled()) { + log.debug("## Deleting Large operation responses"); + } + dataDeletionDAO.deleteLargeOperationResponses(); + if (log.isDebugEnabled()) { log.debug("## Deleting operation responses"); } @@ -305,16 +250,6 @@ public class ArchivalServiceImpl implements ArchivalService { } dataDeletionDAO.deleteNotifications(); - if (log.isDebugEnabled()) { - log.debug("## Deleting command operations"); - } - dataDeletionDAO.deleteCommandOperations(); - - if (log.isDebugEnabled()) { - log.debug("## Deleting profile operations "); - } - dataDeletionDAO.deleteProfileOperations(); - if (log.isDebugEnabled()) { log.debug("## Deleting enrolment mappings "); } @@ -332,4 +267,4 @@ public class ArchivalServiceImpl implements ArchivalService { ArchivalDestinationDAOFactory.closeConnection(); } } -} +} \ 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/archival/beans/ArchiveCommandOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveCommandOperation.java deleted file mode 100644 index f044a21fa4..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveCommandOperation.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package org.wso2.carbon.device.mgt.core.archival.beans; - -public class ArchiveCommandOperation { - - - private int operationId; - private int enabled; - - public int getOperationId() { - return operationId; - } - - public void setOperationId(int operationId) { - this.operationId = operationId; - } - - public int getEnabled() { - return enabled; - } - - public void setEnabled(int enabled) { - this.enabled = enabled; - } -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveEnrolmentOperationMap.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveEnrolmentOperationMap.java deleted file mode 100644 index c85b893f78..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveEnrolmentOperationMap.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package org.wso2.carbon.device.mgt.core.archival.beans; - -public class ArchiveEnrolmentOperationMap { - - - private int id; - private int enrolmentId; - private int operationId; - private String status; - private int createdTimestamp; - private int updatedTimestamp; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getEnrolmentId() { - return enrolmentId; - } - - public void setEnrolmentId(int enrolmentId) { - this.enrolmentId = enrolmentId; - } - - public int getOperationId() { - return operationId; - } - - public void setOperationId(int operationId) { - this.operationId = operationId; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public int getCreatedTimestamp() { - return createdTimestamp; - } - - public void setCreatedTimestamp(int createdTimestamp) { - this.createdTimestamp = createdTimestamp; - } - - public int getUpdatedTimestamp() { - return updatedTimestamp; - } - - public void setUpdatedTimestamp(int updatedTimestamp) { - this.updatedTimestamp = updatedTimestamp; - } -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveNotification.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveNotification.java deleted file mode 100644 index 7c0ea9b044..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveNotification.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package org.wso2.carbon.device.mgt.core.archival.beans; - -public class ArchiveNotification { - - - private int notificationId; - private int deviceId; - private int operationId; - private int tenantId; - private String status; - private String description; - - public int getNotificationId() { - return notificationId; - } - - public void setNotificationId(int notificationId) { - this.notificationId = notificationId; - } - - public int getDeviceId() { - return deviceId; - } - - public void setDeviceId(int deviceId) { - this.deviceId = deviceId; - } - - public int getOperationId() { - return operationId; - } - - public void setOperationId(int operationId) { - this.operationId = operationId; - } - - public int getTenantId() { - return tenantId; - } - - public void setTenantId(int tenantId) { - this.tenantId = tenantId; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveOperation.java deleted file mode 100644 index 1826d7089d..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveOperation.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package org.wso2.carbon.device.mgt.core.archival.beans; - -import java.sql.Timestamp; - -public class ArchiveOperation { - - private int id; - private String type; - private Timestamp createdTimeStamp; - private Timestamp recievedTimeStamp; - private String operationCode; - - private Object operationDetails; - private String initiatedBy; - private boolean enabled; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public Timestamp getCreatedTimeStamp() { - return createdTimeStamp; - } - - public void setCreatedTimeStamp(Timestamp createdTimeStamp) { - this.createdTimeStamp = createdTimeStamp; - } - - public Timestamp getRecievedTimeStamp() { - return recievedTimeStamp; - } - - public void setRecievedTimeStamp(Timestamp recievedTimeStamp) { - this.recievedTimeStamp = recievedTimeStamp; - } - - public String getOperationCode() { - return operationCode; - } - - public void setOperationCode(String operationCode) { - this.operationCode = operationCode; - } - - public Object getOperationDetails() { - return operationDetails; - } - - public void setOperationDetails(Object operationDetails) { - this.operationDetails = operationDetails; - } - - public String getInitiatedBy() { - return initiatedBy; - } - - public void setInitiatedBy(String initiatedBy) { - this.initiatedBy = initiatedBy; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveOperationResponse.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveOperationResponse.java deleted file mode 100644 index ce4712382c..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveOperationResponse.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package org.wso2.carbon.device.mgt.core.archival.beans; - -import java.sql.Timestamp; - -public class ArchiveOperationResponse { - - - private int id; - private int enrolmentId; - private int operationId; - private int enOpMapId; - private Object operationResponse; - private Timestamp receivedTimeStamp; - - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getEnrolmentId() { - return enrolmentId; - } - - public void setEnrolmentId(int enrolmentId) { - this.enrolmentId = enrolmentId; - } - - public int getOperationId() { - return operationId; - } - - public void setOperationId(int operationId) { - this.operationId = operationId; - } - - public int getEnOpMapId() { - return enOpMapId; - } - - public void setEnOpMapId(int enOpMapId) { - this.enOpMapId = enOpMapId; - } - - public Object getOperationResponse() { - return operationResponse; - } - - public void setOperationResponse(Object operationResponse) { - this.operationResponse = operationResponse; - } - - public Timestamp getReceivedTimeStamp() { - return receivedTimeStamp; - } - - public void setReceivedTimeStamp(Timestamp receivedTimeStamp) { - this.receivedTimeStamp = receivedTimeStamp; - } -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveProfileOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveProfileOperation.java deleted file mode 100644 index add85dc262..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/beans/ArchiveProfileOperation.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package org.wso2.carbon.device.mgt.core.archival.beans; - -public class ArchiveProfileOperation { - - - private int operationId; - private int enabled; - private Object operationDetails; - - public int getOperationId() { - return operationId; - } - - public void setOperationId(int operationId) { - this.operationId = operationId; - } - - public int getEnabled() { - return enabled; - } - - public void setEnabled(int enabled) { - this.enabled = enabled; - } - - public Object getOperationDetails() { - return operationDetails; - } - - public void setOperationDetails(Object operationDetails) { - this.operationDetails = operationDetails; - } -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDAO.java index 8fc598d169..73033d4826 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDAO.java @@ -18,9 +18,7 @@ package org.wso2.carbon.device.mgt.core.archival.dao; -import org.wso2.carbon.device.mgt.core.archival.beans.*; - -import java.sql.ResultSet; +import java.sql.Timestamp; import java.util.List; /** @@ -28,34 +26,30 @@ import java.util.List; */ public interface ArchivalDAO { - int DEFAULT_BATCH_SIZE = 1000; - - List getAllOperations() throws ArchivalDAOException; - - List getPendingAndInProgressOperations() throws ArchivalDAOException; + List getNonRemovableOperationMappingIDs(Timestamp time) throws ArchivalDAOException; - void copyOperationIDsForArchival(List operationIds) throws ArchivalDAOException; + int getLargeOperationResponseCount(Timestamp time, List nonRemovableMappings) throws ArchivalDAOException; - List selectOperationResponses() throws ArchivalDAOException; + int getOpMappingsCount(Timestamp time) throws ArchivalDAOException; - void moveOperationResponses(List rs) throws ArchivalDAOException; + int getOperationResponseCount(Timestamp time, List nonRemovableMappings) throws ArchivalDAOException; - List selectNotifications() throws ArchivalDAOException; + void transferOperationResponses(int batchSize, Timestamp time, List nonRemovableMappings) throws ArchivalDAOException; - void moveNotifications(List rs) throws ArchivalDAOException; + void transferLargeOperationResponses(int batchSize, Timestamp time, List nonRemovableMappings) throws ArchivalDAOException; - List selectCommandOperations() throws ArchivalDAOException; + void removeLargeOperationResponses(int batchSize, Timestamp time, List nonRemovableMappings) throws ArchivalDAOException; - List selectProfileOperations() throws ArchivalDAOException; + void removeOperationResponses(int batchSize, Timestamp time, List nonRemovableMappings) throws ArchivalDAOException; - List selectEnrolmentMappings() throws ArchivalDAOException; + void moveNotifications(Timestamp time) throws ArchivalDAOException; - void moveEnrolmentMappings(List rs) throws ArchivalDAOException; + void transferEnrollmentOpMappings(int batchSize, Timestamp time) throws ArchivalDAOException; - List selectOperations() throws ArchivalDAOException; + void removeEnrollmentOPMappings(int batchSize, Timestamp time) throws ArchivalDAOException; - void moveOperations(List rs) throws ArchivalDAOException; + void transferOperations() throws ArchivalDAOException; - void truncateOperationIDsForArchival() throws ArchivalDAOException; + void removeOperations() throws ArchivalDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDAOUtil.java index a630ab8b54..084b815c3d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDAOUtil.java @@ -57,14 +57,4 @@ public class ArchivalDAOUtil { } } - - public static void cleanupResultSet(ResultSet rs) { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing the result set", e); - } - } - } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDestinationDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDestinationDAOFactory.java index 8b68e7a3c3..c6c54fbbb9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDestinationDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalDestinationDAOFactory.java @@ -39,8 +39,7 @@ public class ArchivalDestinationDAOFactory { private static final Log log = LogFactory.getLog(OperationManagementDAOFactory.class); private static DataSource dataSource; private static String databaseEngine; - private static int retentionPeriod; - private static ThreadLocal currentConnection = new ThreadLocal(); + private static ThreadLocal currentConnection = new ThreadLocal<>(); public static DataDeletionDAO getDataDeletionDAO() { return new DataDeletionDAOImpl(DeviceConfigurationManager.getInstance().getDeviceManagementConfig() @@ -77,6 +76,16 @@ public class ArchivalDestinationDAOFactory { } } + public static void beginTransaction(Connection conn) throws TransactionManagementException { + try { + conn.setAutoCommit(false); +// currentConnection.set(conn); + } catch (SQLException e) { + throw new TransactionManagementException( + "Error occurred while retrieving config.datasource connection", e); + } + } + public static void openConnection() throws SQLException { currentConnection.set(dataSource.getConnection()); } @@ -102,6 +111,16 @@ public class ArchivalDestinationDAOFactory { } } + public static void closeConnection(Connection conn) { + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + log.error("Error occurred while close the connection"); + } + } + } + public static void commitTransaction() { try { Connection conn = currentConnection.get(); @@ -118,6 +137,21 @@ public class ArchivalDestinationDAOFactory { } } + public static void commitTransaction(Connection conn) { + try { + if (conn != null) { + conn.commit(); + } else { + if (log.isDebugEnabled()) { + log.debug("Datasource connection associated with the current thread is null, hence commit " + + "has not been attempted"); + } + } + } catch (SQLException e) { + log.error("Error occurred while committing the transaction", e); + } + } + public static void rollbackTransaction() { try { Connection conn = currentConnection.get(); @@ -153,7 +187,7 @@ public class ArchivalDestinationDAOFactory { } List jndiPropertyList = jndiConfig.getJndiProperties(); if (jndiPropertyList != null) { - Hashtable jndiProperties = new Hashtable(); + Hashtable jndiProperties = new Hashtable<>(); for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { jndiProperties.put(prop.getName(), prop.getValue()); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalSourceDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalSourceDAOFactory.java index 0f669a50ef..9d69613f75 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalSourceDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/ArchivalSourceDAOFactory.java @@ -18,7 +18,6 @@ package org.wso2.carbon.device.mgt.core.archival.dao; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.exceptions.IllegalTransactionStateException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/DataDeletionDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/DataDeletionDAO.java index fae688d66e..7b33ad9db0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/DataDeletionDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/DataDeletionDAO.java @@ -23,16 +23,12 @@ package org.wso2.carbon.device.mgt.core.archival.dao; */ public interface DataDeletionDAO { - int DEFAULT_RETENTION_PERIOD = 364; + void deleteLargeOperationResponses() throws ArchivalDAOException; void deleteOperationResponses() throws ArchivalDAOException; void deleteNotifications() throws ArchivalDAOException; - void deleteCommandOperations() throws ArchivalDAOException; - - void deleteProfileOperations() throws ArchivalDAOException; - void deleteEnrolmentMappings() throws ArchivalDAOException; void deleteOperations() throws ArchivalDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/impl/ArchivalDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/impl/ArchivalDAOImpl.java index ed89a0a30e..8c34f3dee5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/impl/ArchivalDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/impl/ArchivalDAOImpl.java @@ -20,712 +20,580 @@ package org.wso2.carbon.device.mgt.core.archival.dao.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.core.archival.beans.*; -import org.wso2.carbon.device.mgt.core.archival.dao.*; - -import java.sql.*; -import java.util.*; +import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDAO; +import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDAOException; +import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDAOUtil; +import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDestinationDAOFactory; +import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalSourceDAOFactory; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; public class ArchivalDAOImpl implements ArchivalDAO { private static final Log log = LogFactory.getLog(ArchivalDAOImpl.class); - private int retentionPeriod; - private int batchSize = ArchivalDAO.DEFAULT_BATCH_SIZE; - private Timestamp currentTimestamp; + private final int retentionPeriod; + private static final String SOURCE_DB = + DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getArchivalConfiguration() + .getArchivalTaskConfiguration().getDbConfig().getSourceDB(); - public ArchivalDAOImpl(int retentionPeriod) { - this.retentionPeriod = retentionPeriod; - } + private static final String DESTINATION_DB = + DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getArchivalConfiguration() + .getArchivalTaskConfiguration().getDbConfig().getDestinationDB(); public ArchivalDAOImpl(int retentionPeriod, int batchSize) { this.retentionPeriod = retentionPeriod; - this.batchSize = batchSize; - this.currentTimestamp = new Timestamp(new java.util.Date().getTime()); if (log.isDebugEnabled()) { - log.debug("Using batch size of " + this.batchSize + " with retention period " + this.retentionPeriod); + log.debug("Using batch size of " + batchSize + " with retention period " + this.retentionPeriod); } } - @Override - public List getAllOperations() throws ArchivalDAOException { - List operationIds = new ArrayList<>(); - Statement stmt = null; + public List getNonRemovableOperationMappingIDs(Timestamp time) throws ArchivalDAOException { + PreparedStatement stmt = null; ResultSet rs = null; + List removableOperationMappingIds = new ArrayList<>(); try { Connection conn = ArchivalSourceDAOFactory.getConnection(); - String sql = "SELECT ID FROM DM_OPERATION WHERE CREATED_TIMESTAMP < (DATE_SUB(NOW(), INTERVAL " - + this.retentionPeriod + " DAY))"; - stmt = this.createMemoryEfficientStatement(conn); - rs = stmt.executeQuery(sql); - if (log.isDebugEnabled()) { - log.debug("Selected Operation Ids from Enrolment OP Mapping"); - } + String sql = "SELECT ID FROM DM_ENROLMENT_OP_MAPPING " + + "WHERE UPDATED_TIMESTAMP < UNIX_TIMESTAMP(DATE_SUB(?, INTERVAL ? DAY)) " + + "AND (STATUS != 'COMPLETED' AND STATUS != 'ERROR')"; + + stmt = conn.prepareStatement(sql); + stmt.setTimestamp(1, time); + stmt.setInt(2, this.retentionPeriod); + + long startTime = System.currentTimeMillis(); + rs = stmt.executeQuery(); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; while (rs.next()) { - operationIds.add(rs.getInt("ID")); + removableOperationMappingIds.add(rs.getInt("ID")); } + + if (log.isDebugEnabled()) { + log.debug("Time Elapsed for getting Non Removable Operation Mapping IDs: " + difference); + log.debug("Total Non Removable Operation Mapping IDs: " + removableOperationMappingIds.size()); + } + } catch (SQLException e) { - String msg = "An error occurred while getting a list operation Ids to archive"; - log.error(msg, e); + String msg = "Error occurred while getting Non Removable Operation Mapping IDs. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { ArchivalDAOUtil.cleanupResources(stmt, rs); } - if (log.isDebugEnabled()) { - log.debug(operationIds.size() + " operations found for the archival"); - log.debug(operationIds.size() + "[" + operationIds.get(0) + "," + operationIds.get(batchSize - 1) + "]"); - } - return operationIds; + return removableOperationMappingIds; } - @Override - public List getPendingAndInProgressOperations() throws ArchivalDAOException { - List operationIds = new ArrayList<>(); - Statement stmt = null; + public int getLargeOperationResponseCount(Timestamp time, List nonRemovableMappings) + throws ArchivalDAOException { + PreparedStatement stmt = null; ResultSet rs = null; + int count = 0; + try { Connection conn = ArchivalSourceDAOFactory.getConnection(); - String sql = "(SELECT DISTINCT\n" + - " OPERATION_ID\n" + - " FROM\n" + - " DM_ENROLMENT_OP_MAPPING\n" + - " WHERE\n" + - " STATUS = 'PENDING'\n" + - " AND CREATED_TIMESTAMP < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL " - + this.retentionPeriod + " DAY))) \n" + - " UNION ALL \n" + - "\t(SELECT DISTINCT\n" + - " OPERATION_ID\n" + - " FROM\n" + - " DM_ENROLMENT_OP_MAPPING\n" + - " WHERE\n" + - " STATUS = 'IN_PROGRESS'\n" + - " AND CREATED_TIMESTAMP < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL " + - "" + this.retentionPeriod + " DAY)))"; - stmt = this.createMemoryEfficientStatement(conn); - rs = stmt.executeQuery(sql); - if (log.isDebugEnabled()) { - log.debug("Selected Pending or In Progress Operation IDs"); + StringBuilder sql = new StringBuilder("SELECT COUNT(*) AS COUNT FROM DM_DEVICE_OPERATION_RESPONSE_LARGE " + + "WHERE RECEIVED_TIMESTAMP < (DATE_SUB( ? , INTERVAL ? DAY))"); + if (nonRemovableMappings.size() > 0) { + sql.append(" AND EN_OP_MAP_ID NOT IN ("); + for (int i = 0; i < nonRemovableMappings.size(); i++) { + sql.append(nonRemovableMappings.get(i)); + if (i != nonRemovableMappings.size() - 1) { + sql.append(","); + } + } + sql.append(")"); } + + stmt = conn.prepareStatement(sql.toString()); + stmt.setTimestamp(1, time); + stmt.setInt(2, this.retentionPeriod); + + long startTime = System.currentTimeMillis(); + rs = stmt.executeQuery(); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; + while (rs.next()) { - operationIds.add(rs.getInt("OPERATION_ID")); + count = rs.getInt("COUNT"); } + + if (log.isDebugEnabled()) { + log.debug("Time Elapsed for getting Large Operation Response Count : " + difference); + log.debug("Total Large Operation Responses for Archival : " + count); + } + } catch (SQLException e) { - String msg = "An error occurred while getting a list pending or in progress operation Ids to archive"; - log.error(msg, e); + String msg = "Error occurred while archiving the large operation responses. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { ArchivalDAOUtil.cleanupResources(stmt, rs); } - if (log.isDebugEnabled()) { - log.debug(operationIds.size() + " operations found for the archival"); - log.debug(operationIds.size() + "[" + operationIds.get(0) + "," + operationIds.get(batchSize - 1) + "]"); - } - return operationIds; + return count; } - @Override - public void copyOperationIDsForArchival(List operationIds) throws ArchivalDAOException { + public int getOpMappingsCount(Timestamp time) throws ArchivalDAOException { PreparedStatement stmt = null; + ResultSet rs = null; + int count = 0; + try { Connection conn = ArchivalSourceDAOFactory.getConnection(); - String sql = "INSERT INTO DM_ARCHIVED_OPERATIONS(ID,CREATED_TIMESTAMP) VALUES (?,NOW())"; + String sql = "SELECT COUNT(ID) AS COUNT FROM DM_ENROLMENT_OP_MAPPING " + + "WHERE UPDATED_TIMESTAMP < UNIX_TIMESTAMP(DATE_SUB( ? , INTERVAL ? DAY))" + + "AND (STATUS = 'COMPLETED' OR STATUS = 'ERROR')"; + stmt = conn.prepareStatement(sql); + stmt.setTimestamp(1, time); + stmt.setInt(2, this.retentionPeriod); - int count = 0; - for (int i = 0; i < operationIds.size(); i++) { - stmt.setInt(1, operationIds.get(i)); - stmt.addBatch(); + long startTime = System.currentTimeMillis(); + rs = stmt.executeQuery(); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; - if (++count % this.batchSize == 0) { - stmt.executeBatch(); - } + while (rs.next()) { + count = rs.getInt("COUNT"); } - stmt.executeBatch(); + if (log.isDebugEnabled()) { - log.debug(count + " Records copied to the temporary table."); + log.debug("Time Elapsed for getting Op Mappings Count : " + difference); + log.debug("Total Enrollment Operation Mappings for Archival : " + count); } + } catch (SQLException e) { - String msg = "Error while copying operation Ids for archival"; - log.error(msg, e); + String msg = "Error occurred while getting Op Mappings Count. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { - ArchivalDAOUtil.cleanupResources(stmt); + ArchivalDAOUtil.cleanupResources(stmt, rs); } + return count; } @Override - public List selectOperationResponses() throws ArchivalDAOException { - Statement stmt = null; + public int getOperationResponseCount(Timestamp time, List nonRemovableMappings) + throws ArchivalDAOException { + PreparedStatement stmt = null; ResultSet rs = null; + int count = 0; - List operationResponses = new ArrayList<>(); try { Connection conn = ArchivalSourceDAOFactory.getConnection(); - String sql = "SELECT \n" + - " o.ID,\n" + - " o.ENROLMENT_ID,\n" + - " o.OPERATION_ID,\n" + - " o.EN_OP_MAP_ID,\n" + - " o.OPERATION_RESPONSE,\n" + - " o.RECEIVED_TIMESTAMP\n" + - "FROM\n" + - " DM_DEVICE_OPERATION_RESPONSE o\n" + - " INNER JOIN\n" + - " DM_ARCHIVED_OPERATIONS da ON o.OPERATION_ID = da.ID;"; - stmt = this.createMemoryEfficientStatement(conn); - rs = stmt.executeQuery(sql); + + StringBuilder sql = new StringBuilder("SELECT COUNT(*) AS COUNT FROM DM_DEVICE_OPERATION_RESPONSE " + + "WHERE RECEIVED_TIMESTAMP < (DATE_SUB( ? , INTERVAL ? DAY))"); + if (nonRemovableMappings.size() > 0) { + sql.append(" AND EN_OP_MAP_ID NOT IN ("); + for (int i = 0; i < nonRemovableMappings.size(); i++) { + sql.append(nonRemovableMappings.get(i)); + if (i != nonRemovableMappings.size() - 1) { + sql.append(","); + } + } + sql.append(")"); + } + + stmt = conn.prepareStatement(sql.toString()); + stmt.setTimestamp(1, time); + stmt.setInt(2, this.retentionPeriod); + + long startTime = System.currentTimeMillis(); + rs = stmt.executeQuery(); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; while (rs.next()) { - ArchiveOperationResponse rep = new ArchiveOperationResponse(); - rep.setId(rs.getInt("ID")); - rep.setEnrolmentId(rs.getInt("ENROLMENT_ID")); - rep.setOperationId(rs.getInt("OPERATION_ID")); - rep.setOperationResponse(rs.getBytes("OPERATION_RESPONSE")); - rep.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP")); - operationResponses.add(rep); + count = rs.getInt("COUNT"); } if (log.isDebugEnabled()) { - log.debug("Selecting done for the Operation Response"); + log.debug("Time Elapsed for getting Operation Response Count : " + difference); + log.debug("Total Operation Responses for Archival : " + count); } } catch (SQLException e) { - String msg = "Error occurred while archiving the operation responses"; - log.error(msg, e); + String msg = "Error occurred while archiving the operation response count. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { ArchivalDAOUtil.cleanupResources(stmt, rs); } - - return operationResponses; - + return count; } @Override - public void moveOperationResponses(List archiveOperationResponse) throws ArchivalDAOException { - PreparedStatement stmt2 = null; - Statement stmt3 = null; - try { - Connection conn = ArchivalSourceDAOFactory.getConnection(); + public void transferOperationResponses(int batchSize, Timestamp time, List nonRemovableMappings) + throws ArchivalDAOException { + PreparedStatement ps = null; - - Connection conn2 = ArchivalDestinationDAOFactory.getConnection(); - String sql = "INSERT INTO DM_DEVICE_OPERATION_RESPONSE_ARCH VALUES(?, ?, ?, ?, ?,?)"; - stmt2 = conn2.prepareStatement(sql); - - int count = 0; - for (ArchiveOperationResponse rs : archiveOperationResponse) { - stmt2.setInt(1, rs.getId()); - stmt2.setInt(2, rs.getEnrolmentId()); - stmt2.setInt(3, rs.getOperationId()); - stmt2.setBytes(4, (byte[]) rs.getOperationResponse()); - stmt2.setTimestamp(5, rs.getReceivedTimeStamp()); - stmt2.setTimestamp(6, this.currentTimestamp); - stmt2.addBatch(); - - if (++count % batchSize == 0) { - stmt2.executeBatch(); - if (log.isDebugEnabled()) { - log.debug("Executing Operation Responses batch " + count); + try { + Connection conn = ArchivalDestinationDAOFactory.getConnection(); + + StringBuilder sql = new StringBuilder("INSERT INTO " + DESTINATION_DB + ".DM_DEVICE_OPERATION_RESPONSE_ARCH " + + "SELECT OPR.ID, OPR.ENROLMENT_ID, OPR.OPERATION_ID, OPR.OPERATION_RESPONSE, OPR.RECEIVED_TIMESTAMP, NOW(), OPR.IS_LARGE_RESPONSE " + + "FROM " + SOURCE_DB + ".DM_DEVICE_OPERATION_RESPONSE OPR " + + "WHERE OPR.RECEIVED_TIMESTAMP < ( DATE_SUB( ? , INTERVAL ? DAY))"); + if (nonRemovableMappings.size() > 0) { + sql.append(" AND EN_OP_MAP_ID NOT IN ("); + for (int i = 0; i < nonRemovableMappings.size(); i++) { + sql.append(nonRemovableMappings.get(i)); + if (i != nonRemovableMappings.size() - 1) { + sql.append(","); } } + sql.append(")"); } - stmt2.executeBatch(); - if (log.isDebugEnabled()) { - log.debug(count + " [OPERATION_RESPONSES] Records copied to the archival table. Starting deletion"); - } - //try the deletion now - sql = "DELETE o.* FROM DM_DEVICE_OPERATION_RESPONSE o\n" + - " INNER JOIN\n" + - " DM_ARCHIVED_OPERATIONS da ON o.OPERATION_ID = da.ID \n" + - "WHERE\n" + - " o.OPERATION_ID = da.ID;"; - stmt3 = conn.createStatement(); - int affected = stmt3.executeUpdate(sql); + sql.append(" ORDER BY OPR.RECEIVED_TIMESTAMP LIMIT ?"); + + long startTime = System.currentTimeMillis(); + + ps = conn.prepareStatement(sql.toString()); + ps.setTimestamp(1, time); + ps.setInt(2, this.retentionPeriod); + ps.setInt(3, batchSize); + + int affected = ps.executeUpdate(); + + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; + if (log.isDebugEnabled()) { - log.debug(affected + " Rows deleted"); + log.debug("Time Elapsed for Transferring Operation Responses : " + difference); + log.debug("Transfer of " + affected + " Operation Responses Completed"); } } catch (SQLException e) { - String msg = "Error occurred while archiving the operation responses"; - log.error(msg, e); + String msg = "Error occurred while archiving the operation responses. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { - ArchivalDAOUtil.cleanupResources(stmt2); - ArchivalDAOUtil.cleanupResources(stmt3); + ArchivalDAOUtil.cleanupResources(ps); } } @Override - public List selectNotifications() throws ArchivalDAOException { + public void transferLargeOperationResponses(int batchSize, Timestamp time, List nonRemovableMappings) + throws ArchivalDAOException { + + PreparedStatement ps = null; - Statement stmt = null; - ResultSet rs = null; - List notifications = new ArrayList<>(); try { - Connection conn = ArchivalSourceDAOFactory.getConnection(); - String sql = "SELECT \n" + - " o.NOTIFICATION_ID,\n" + - " o.DEVICE_ID,\n" + - " o.OPERATION_ID,\n" + - " o.TENANT_ID,\n" + - " o.STATUS,\n" + - " o.DESCRIPTION\n" + - "FROM\n" + - " DM_NOTIFICATION o\n" + - " INNER JOIN\n" + - " DM_ARCHIVED_OPERATIONS da ON o.OPERATION_ID = da.ID;"; - stmt = this.createMemoryEfficientStatement(conn); - rs = stmt.executeQuery(sql); + Connection conn = ArchivalDestinationDAOFactory.getConnection(); + + StringBuilder sql = new StringBuilder("INSERT INTO " + DESTINATION_DB + ".DM_DEVICE_OPERATION_RESPONSE_LARGE_ARCH " + + "SELECT OPR.ID, OPR.OPERATION_RESPONSE, NOW() " + + "FROM " + SOURCE_DB + ".DM_DEVICE_OPERATION_RESPONSE_LARGE OPR " + + "WHERE OPR.RECEIVED_TIMESTAMP < ( DATE_SUB( ? , INTERVAL ? DAY))"); + if (nonRemovableMappings.size() > 0) { + sql.append(" AND EN_OP_MAP_ID NOT IN ("); + for (int i = 0; i < nonRemovableMappings.size(); i++) { + sql.append(nonRemovableMappings.get(i)); + if (i != nonRemovableMappings.size() - 1) { + sql.append(","); + } + } + sql.append(")"); + } + sql.append(" ORDER BY OPR.RECEIVED_TIMESTAMP LIMIT ?"); + long startTime = System.currentTimeMillis(); - while (rs.next()) { + ps = conn.prepareStatement(sql.toString()); + ps.setTimestamp(1, time); + ps.setInt(2, this.retentionPeriod); + ps.setInt(3, batchSize); - ArchiveNotification note = new ArchiveNotification(); - note.setNotificationId(rs.getInt("NOTIFICATION_ID")); - note.setDeviceId(rs.getInt("DEVICE_ID")); - note.setOperationId(rs.getInt("OPERATION_ID")); - note.setTenantId(rs.getInt("TENANT_ID")); - note.setStatus(rs.getString("STATUS")); - note.setDescription(rs.getString("DESCRIPTION")); - notifications.add(note); - } + int affected = ps.executeUpdate(); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; if (log.isDebugEnabled()) { - log.debug("Selecting done for the Notification"); + log.debug("Time Elapsed for Transferring Large Operation Responses : " + difference); + log.debug("Transfer of " + affected + " Large Operation Responses Completed"); } } catch (SQLException e) { - String msg = "Error occurred while archiving the notifications"; - log.error(msg, e); + String msg = "Error occurred while archiving large operation responses. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { - ArchivalDAOUtil.cleanupResources(stmt, rs); + ArchivalDAOUtil.cleanupResources(ps); } - return notifications; } - @Override - public void moveNotifications(List archiveNotifications) throws ArchivalDAOException { - Statement stmt = null; - PreparedStatement stmt2 = null; - Statement stmt3 = null; - try { - Connection conn = ArchivalSourceDAOFactory.getConnection(); - Connection conn2 = ArchivalDestinationDAOFactory.getConnection(); + public void removeLargeOperationResponses(int batchSize, Timestamp time, List nonRemovableMappings) + throws ArchivalDAOException { + PreparedStatement ps = null; - String sql = "INSERT INTO DM_NOTIFICATION_ARCH VALUES(?, ?, ?, ?, ?, ?, ?)"; - stmt2 = conn2.prepareStatement(sql); - - int count = 0; -// while (rs.next()) { - for (ArchiveNotification rs : archiveNotifications) { - stmt2.setInt(1, rs.getNotificationId()); - stmt2.setInt(2, rs.getDeviceId()); - stmt2.setInt(3, rs.getOperationId()); - stmt2.setInt(4, rs.getTenantId()); - stmt2.setString(5, rs.getStatus()); - stmt2.setString(6, rs.getDescription()); - stmt2.setTimestamp(7, this.currentTimestamp); - stmt2.addBatch(); - - if (++count % batchSize == 0) { - stmt2.executeBatch(); - if (log.isDebugEnabled()) { - log.debug("Executing Notifications batch " + count); + Connection conn; + try { + conn = ArchivalSourceDAOFactory.getConnection(); + + StringBuilder sql = new StringBuilder("DELETE FROM DM_DEVICE_OPERATION_RESPONSE_LARGE " + + "WHERE RECEIVED_TIMESTAMP < ( DATE_SUB( ? , INTERVAL ? DAY))"); + if (nonRemovableMappings.size() > 0) { + sql.append(" AND EN_OP_MAP_ID NOT IN ("); + for (int i = 0; i < nonRemovableMappings.size(); i++) { + sql.append(nonRemovableMappings.get(i)); + if (i != nonRemovableMappings.size() - 1) { + sql.append(","); } } + sql.append(")"); } - stmt2.executeBatch(); - if (log.isDebugEnabled()) { - log.debug(count + " [NOTIFICATIONS] Records copied to the archival table. Starting deletion"); - } - sql = "DELETE o.* FROM DM_NOTIFICATION o\n" + - " INNER JOIN\n" + - " DM_ARCHIVED_OPERATIONS da ON o.OPERATION_ID = da.ID \n" + - "WHERE\n" + - " o.OPERATION_ID = da.ID;"; - stmt3 = conn.createStatement(); - int affected = stmt3.executeUpdate(sql); + sql.append(" ORDER BY RECEIVED_TIMESTAMP LIMIT ?"); + long startTime = System.currentTimeMillis(); + + ps = conn.prepareStatement(sql.toString()); + ps.setTimestamp(1, time); + ps.setInt(2, this.retentionPeriod); + ps.setInt(3, batchSize); + + int affected = ps.executeUpdate(); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; + if (log.isDebugEnabled()) { - log.debug(affected + " Rows deleted"); + log.debug("Time Elapsed for Removing Large Operation Responses : " + difference); + log.debug(affected + " Rows deleted from DM_DEVICE_OPERATION_RESPONSE_LARGE"); } } catch (SQLException e) { - String msg = "Error occurred while archiving the notifications"; - log.error(msg, e); + String msg = "Error occurred while removing the operation responses. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { - ArchivalDAOUtil.cleanupResources(stmt2); - ArchivalDAOUtil.cleanupResources(stmt3); + ArchivalDAOUtil.cleanupResources(ps); } } @Override - public List selectCommandOperations() throws ArchivalDAOException { - Statement stmt = null; - ResultSet rs = null; + public void removeOperationResponses(int batchSize, Timestamp time, List nonRemovableMappings) + throws ArchivalDAOException { + PreparedStatement ps = null; - List commandOperations = new ArrayList<>(); + Connection conn; try { - Connection conn = ArchivalSourceDAOFactory.getConnection(); - String sql = "SELECT \n" + - " *\n" + - "FROM\n" + - " DM_COMMAND_OPERATION o\n" + - " INNER JOIN\n" + - " DM_ARCHIVED_OPERATIONS da ON o.OPERATION_ID = da.ID;"; - stmt = this.createMemoryEfficientStatement(conn); - rs = stmt.executeQuery(sql); + conn = ArchivalSourceDAOFactory.getConnection(); + + StringBuilder sql = new StringBuilder("DELETE FROM DM_DEVICE_OPERATION_RESPONSE " + + "WHERE RECEIVED_TIMESTAMP < ( DATE_SUB( ? , INTERVAL ? DAY))"); + if (nonRemovableMappings.size() > 0) { + sql.append(" AND EN_OP_MAP_ID NOT IN ("); + for (int i = 0; i < nonRemovableMappings.size(); i++) { + sql.append(nonRemovableMappings.get(i)); + if (i != nonRemovableMappings.size() - 1) { + sql.append(","); + } + } + sql.append(")"); + } + sql.append(" ORDER BY RECEIVED_TIMESTAMP LIMIT ?"); + long startTime = System.currentTimeMillis(); - while (rs.next()) { - ArchiveCommandOperation op = new ArchiveCommandOperation(); - op.setOperationId(rs.getInt("OPERATION_ID")); - op.setEnabled(rs.getInt("ENABLED")); + ps = conn.prepareStatement(sql.toString()); + ps.setTimestamp(1, time); + ps.setInt(2, this.retentionPeriod); + ps.setInt(3, batchSize); - commandOperations.add(op); - } + int affected = ps.executeUpdate(); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; if (log.isDebugEnabled()) { - log.debug("Selecting done for the Command Operation"); + log.debug("Time Elapsed for Removing Operation Responses : " + difference); + log.debug(affected + " Rows deleted from DM_DEVICE_OPERATION_RESPONSE"); } } catch (SQLException e) { - String msg = "Error occurred while archiving the command operation"; - log.error(msg, e); + String msg = "Error occurred while removing operation responses. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { - ArchivalDAOUtil.cleanupResources(stmt, rs); + ArchivalDAOUtil.cleanupResources(ps); } - return commandOperations; } @Override - public List selectProfileOperations() throws ArchivalDAOException { - Statement stmt = null; - ResultSet rs = null; - List profileOperations = new ArrayList<>(); + public void moveNotifications(Timestamp time) throws ArchivalDAOException { + PreparedStatement ps1 = null; + PreparedStatement ps2 = null; + try { Connection conn = ArchivalSourceDAOFactory.getConnection(); - String sql = "SELECT \n" + - " *\n" + - "FROM\n" + - " DM_PROFILE_OPERATION o\n" + - " INNER JOIN\n" + - " DM_ARCHIVED_OPERATIONS da ON o.OPERATION_ID = da.ID;"; - stmt = this.createMemoryEfficientStatement(conn); - rs = stmt.executeQuery(sql); + Connection conn2 = ArchivalDestinationDAOFactory.getConnection(); - while (rs.next()) { - ArchiveProfileOperation op = new ArchiveProfileOperation(); + String sql = "INSERT INTO " + DESTINATION_DB + ".DM_NOTIFICATION_ARCH " + + "SELECT NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, TENANT_ID, STATUS, DESCRIPTION, NOW() " + + "FROM " + SOURCE_DB + ".DM_NOTIFICATION " + + "WHERE LAST_UPDATED_TIMESTAMP < ( DATE_SUB( ? , INTERVAL ? DAY) )"; - op.setOperationId(rs.getInt("OPERATION_ID")); - op.setEnabled(rs.getInt("ENABLED")); - op.setOperationDetails(rs.getBytes("OPERATION_DETAILS")); - profileOperations.add(op); + ps1 = conn2.prepareStatement(sql); + ps1.setTimestamp(1, time); + ps1.setInt(2, this.retentionPeriod); - } + long startTime = System.currentTimeMillis(); + int affected = ps1.executeUpdate(); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; if (log.isDebugEnabled()) { - log.debug("Selecting done for the Profile Operation"); + log.debug("Time Elapsed for Transfer of operations : " + difference); + log.debug(affected + " [NOTIFICATIONS] Records copied to the archival table. Starting deletion"); } - } catch (SQLException e) { - String msg = "Error occurred while archiving the profile operation"; - log.error(msg, e); - throw new ArchivalDAOException(msg, e); - } finally { - ArchivalDAOUtil.cleanupResources(stmt, rs); - } - return profileOperations; - } - - @Override - public List selectEnrolmentMappings() throws ArchivalDAOException { - Statement stmt = null; - ResultSet rs = null; - List operationMaps = new ArrayList<>(); - try { - Connection conn = ArchivalSourceDAOFactory.getConnection(); - String sql = "SELECT \n" + - " o.ID,\n" + - " o.ENROLMENT_ID,\n" + - " o.OPERATION_ID,\n" + - " o.STATUS,\n" + - " o.CREATED_TIMESTAMP,\n" + - " o.UPDATED_TIMESTAMP\n" + - "FROM\n" + - " DM_ENROLMENT_OP_MAPPING o\n" + - " INNER JOIN\n" + - " DM_ARCHIVED_OPERATIONS da ON o.OPERATION_ID = da.ID;"; - stmt = this.createMemoryEfficientStatement(conn); - rs = stmt.executeQuery(sql); + sql = "DELETE FROM DM_NOTIFICATION WHERE LAST_UPDATED_TIMESTAMP < ( DATE_SUB( ? , INTERVAL ? DAY) )"; - while (rs.next()) { + ps2 = conn.prepareStatement(sql); + ps2.setTimestamp(1, time); + ps2.setInt(2, this.retentionPeriod); - ArchiveEnrolmentOperationMap eom = new ArchiveEnrolmentOperationMap(); - eom.setId(rs.getInt("ID")); - eom.setEnrolmentId(rs.getInt("ENROLMENT_ID")); - eom.setOperationId(rs.getInt("OPERATION_ID")); - eom.setStatus(rs.getString("STATUS")); - eom.setCreatedTimestamp(rs.getInt("CREATED_TIMESTAMP")); - eom.setUpdatedTimestamp(rs.getInt("UPDATED_TIMESTAMP")); - operationMaps.add(eom); - } + startTime = System.currentTimeMillis(); + affected = ps2.executeUpdate(); + endTime = System.currentTimeMillis(); + difference = endTime - startTime; if (log.isDebugEnabled()) { - log.debug("Selecting done for the Enrolment OP Mapping"); + log.debug("Time Elapsed for deleting operations : " + difference); + log.debug(affected + " Rows deleted"); } } catch (SQLException e) { - String msg = "Error occurred while archiving the enrolment op mappings"; - log.error(msg, e); + String msg = "Error occurred while deleting operations. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { - ArchivalDAOUtil.cleanupResources(stmt, rs); + ArchivalDAOUtil.cleanupResources(ps1); + ArchivalDAOUtil.cleanupResources(ps2); } - - return operationMaps; } @Override - public void moveEnrolmentMappings(List operationMaps) throws ArchivalDAOException { - Statement stmt = null; - PreparedStatement stmt2 = null; - Statement stmt3 = null; + public void transferEnrollmentOpMappings(int batchSize, Timestamp time) throws ArchivalDAOException { + + PreparedStatement ps = null; + try { - Connection conn = ArchivalSourceDAOFactory.getConnection(); - Connection conn2 = ArchivalDestinationDAOFactory.getConnection(); + Connection conn = ArchivalDestinationDAOFactory.getConnection(); + + String sql = "INSERT INTO " + DESTINATION_DB + ".DM_ENROLMENT_OP_MAPPING_ARCH " + + "SELECT OPR.ID, OPR.ENROLMENT_ID, OPR.OPERATION_ID, OPR.STATUS, OPR.CREATED_TIMESTAMP, OPR.UPDATED_TIMESTAMP, NOW() " + + "FROM " + SOURCE_DB + ".DM_ENROLMENT_OP_MAPPING OPR " + + "WHERE OPR.UPDATED_TIMESTAMP < UNIX_TIMESTAMP( DATE_SUB( ? , INTERVAL ? DAY)) " + + "AND (STATUS = 'COMPLETED' OR STATUS = 'ERROR') " + + "ORDER BY OPR.UPDATED_TIMESTAMP LIMIT ?"; + + ps = conn.prepareStatement(sql); + ps.setTimestamp(1, time); + ps.setInt(2, this.retentionPeriod); + ps.setInt(3, batchSize); + + long startTime = System.currentTimeMillis(); + int affected = ps.executeUpdate(); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; - String sql = "INSERT INTO DM_ENROLMENT_OP_MAPPING_ARCH VALUES(?, ?, ?, ?, ?, ?, ?)"; - stmt2 = conn2.prepareStatement(sql); - - int count = 0; - for (ArchiveEnrolmentOperationMap rs : operationMaps) { - stmt2.setInt(1, rs.getId()); - stmt2.setInt(2, rs.getEnrolmentId()); - stmt2.setInt(3, rs.getOperationId()); - stmt2.setString(4, rs.getStatus()); - stmt2.setInt(5, rs.getCreatedTimestamp()); - stmt2.setInt(6, rs.getUpdatedTimestamp()); - stmt2.setTimestamp(7, this.currentTimestamp); - stmt2.addBatch(); - - if (++count % batchSize == 0) { - stmt2.executeBatch(); - if (log.isDebugEnabled()) { - log.debug("Executing Enrolment Mappings batch " + count); - } - } - } - stmt2.executeBatch(); - if (log.isDebugEnabled()) { - log.debug(count + " [ENROLMENT_OP_MAPPING] Records copied to the archival table. Starting deletion"); - } - sql = "DELETE o.* FROM DM_ENROLMENT_OP_MAPPING o\n" + - " INNER JOIN\n" + - " DM_ARCHIVED_OPERATIONS da ON o.OPERATION_ID = da.ID \n" + - "WHERE\n" + - " o.OPERATION_ID = da.ID;"; - stmt3 = conn.createStatement(); - int affected = stmt3.executeUpdate(sql); if (log.isDebugEnabled()) { - log.debug(affected + " Rows deleted"); + log.debug("Time Elapsed for Transferring Enrollment Operation Mappings : " + difference); + log.debug("Transfer of " + affected + " Enrollment Operation Mappings Completed"); } } catch (SQLException e) { - String msg = "Error occurred while archiving the enrolment op mappings"; - log.error(msg, e); + String msg = "Error occurred while archiving Enrollment Operation Mappings. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { - ArchivalDAOUtil.cleanupResources(stmt2); - ArchivalDAOUtil.cleanupResources(stmt3); + ArchivalDAOUtil.cleanupResources(ps); } } @Override - public List selectOperations() throws ArchivalDAOException { - Statement stmt = null; - ResultSet rs = null; - List operations = new ArrayList<>(); - try { - Connection conn = ArchivalSourceDAOFactory.getConnection(); - String sql = "SELECT \n" + - " o.ID,\n" + - " o.TYPE,\n" + - " o.CREATED_TIMESTAMP,\n" + - " o.RECEIVED_TIMESTAMP,\n" + - " o.OPERATION_CODE,\n" + - " o.INITIATED_BY,\n" + - " o.OPERATION_DETAILS,\n" + - " o.ENABLED \n" + - "FROM\n" + - " DM_OPERATION o\n" + - " INNER JOIN\n" + - " DM_ARCHIVED_OPERATIONS da ON o.ID = da.ID;"; - stmt = this.createMemoryEfficientStatement(conn); - rs = stmt.executeQuery(sql); + public void removeEnrollmentOPMappings(int batchSize, Timestamp time) throws ArchivalDAOException { + PreparedStatement ps = null; + Connection conn; - while (rs.next()) { + try { + conn = ArchivalSourceDAOFactory.getConnection(); - ArchiveOperation op = new ArchiveOperation(); - op.setId(rs.getInt("ID")); - op.setType(rs.getString("TYPE")); - op.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP")); - op.setRecievedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP")); - op.setOperationCode(rs.getString("OPERATION_CODE")); - op.setInitiatedBy(rs.getString("INITIATED_BY")); - op.setOperationDetails(rs.getObject("OPERATION_DETAILS")); - op.setEnabled(rs.getBoolean("ENABLED")); + String sql = "DELETE FROM DM_ENROLMENT_OP_MAPPING " + + "WHERE UPDATED_TIMESTAMP < UNIX_TIMESTAMP( DATE_SUB( ? , INTERVAL ? DAY)) " + + "AND (STATUS = 'COMPLETED' OR STATUS = 'ERROR') " + + "ORDER BY UPDATED_TIMESTAMP LIMIT ?"; - operations.add(op); + ps = conn.prepareStatement(sql); + ps.setTimestamp(1, time); + ps.setInt(2, this.retentionPeriod); + ps.setInt(3, batchSize); - } + long startTime = System.currentTimeMillis(); + int affected = ps.executeUpdate(); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; if (log.isDebugEnabled()) { - log.debug("Selecting done for the Operation"); + log.debug("Time Elapsed for Removing Enrollment Operation Mappings : " + difference); + log.debug(affected + " Rows deleted from DM_ENROLMENT_OP_MAPPING"); } } catch (SQLException e) { - String msg = "Error occurred while archiving the operations"; - log.error(msg, e); + String msg = "Error occurred while removing Enrollment Operation Mappings. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { - ArchivalDAOUtil.cleanupResources(stmt, rs); + ArchivalDAOUtil.cleanupResources(ps); } - return operations; } @Override - public void moveOperations(List operations) throws ArchivalDAOException { + public void transferOperations() throws ArchivalDAOException { Statement stmt = null; - PreparedStatement stmt2 = null; - Statement stmt3 = null; try { - Connection conn = ArchivalSourceDAOFactory.getConnection(); - Connection conn2 = ArchivalDestinationDAOFactory.getConnection(); - String sql = "INSERT INTO DM_OPERATION_ARCH VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)"; - stmt2 = conn2.prepareStatement(sql); - - int count = 0; - for (ArchiveOperation rs : operations) { - stmt2.setInt(1, rs.getId()); - stmt2.setString(2, rs.getType()); - stmt2.setTimestamp(3, rs.getCreatedTimeStamp()); - stmt2.setTimestamp(4, rs.getRecievedTimeStamp()); - stmt2.setString(5, rs.getOperationCode()); - stmt2.setString(6, rs.getInitiatedBy()); - stmt2.setBytes(7, (byte[]) rs.getOperationDetails()); - stmt2.setBoolean(8, rs.isEnabled()); - - stmt2.setTimestamp(9, this.currentTimestamp); - stmt2.addBatch(); - - if (++count % batchSize == 0) { - stmt2.executeBatch(); - if (log.isDebugEnabled()) { - log.debug("Final Execution of Operations batch " + count); - } - } - } - stmt2.executeBatch(); - if (log.isDebugEnabled()) { - log.debug(count + " [OPERATIONS] Records copied to the archival table. Starting deletion"); - } - sql = "DELETE o.* FROM DM_OPERATION o\n" + - " INNER JOIN\n" + - " DM_ARCHIVED_OPERATIONS da ON o.ID = da.ID \n" + - "WHERE\n" + - " o.ID = da.ID;"; - stmt3 = conn.createStatement(); - int affected = stmt3.executeUpdate(sql); + Connection conn = ArchivalDestinationDAOFactory.getConnection(); + stmt = conn.createStatement(); + + String sql = "INSERT INTO " + DESTINATION_DB + ".DM_OPERATION_ARCH " + + "SELECT OPR.ID, OPR.TYPE, OPR.CREATED_TIMESTAMP, OPR.RECEIVED_TIMESTAMP, " + + "OPR.OPERATION_CODE, OPR.INITIATED_BY, OPR.OPERATION_DETAILS, OPR.ENABLED, NOW() " + + "FROM " + SOURCE_DB + ".DM_OPERATION OPR " + + "WHERE OPR.ID NOT IN (SELECT DISTINCT OPERATION_ID FROM " + SOURCE_DB + ".DM_ENROLMENT_OP_MAPPING)"; + + long startTime = System.currentTimeMillis(); + int affected = stmt.executeUpdate(sql); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; + if (log.isDebugEnabled()) { - log.debug(affected + " Rows deleted"); + log.debug("Time Elapsed for Transferring Operations : " + difference); + log.debug("Transfer of " + affected + " Operations Completed"); } } catch (SQLException e) { - String msg = "Error occurred while archiving the operations"; - log.error(msg, e); + String msg = "Error occurred while archiving Operations. " + e.getMessage(); throw new ArchivalDAOException(msg, e); } finally { - ArchivalDAOUtil.cleanupResources(stmt2); - ArchivalDAOUtil.cleanupResources(stmt3); + ArchivalDAOUtil.cleanupResources(stmt); } } @Override - public void truncateOperationIDsForArchival() throws ArchivalDAOException { - PreparedStatement stmt = null; - try { - Connection conn = ArchivalSourceDAOFactory.getConnection(); - conn.setAutoCommit(false); - String sql = "TRUNCATE DM_ARCHIVED_OPERATIONS"; - stmt = conn.prepareStatement(sql); - stmt.executeUpdate(); + public void removeOperations() throws ArchivalDAOException { + Statement stmt = null; + Connection conn; - conn.commit(); - } catch (SQLException e) { - String msg = "Error occurred while truncating operation Ids"; - log.error(msg, e); - throw new ArchivalDAOException(msg, e); - } finally { - ArchivalDAOUtil.cleanupResources(stmt); - } - } + try { + conn = ArchivalSourceDAOFactory.getConnection(); + stmt = conn.createStatement(); - private Statement createMemoryEfficientStatement(Connection conn) throws ArchivalDAOException, SQLException { - Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); - stmt.setFetchSize(Integer.MIN_VALUE); - return stmt; - } + String sql = "DELETE FROM DM_OPERATION " + + "WHERE ID NOT IN (SELECT DISTINCT OPERATION_ID FROM DM_ENROLMENT_OP_MAPPING)"; - private String buildWhereClause(String[] statuses) { - StringBuilder whereClause = new StringBuilder("WHERE "); - for (int i = 0; i < statuses.length; i++) { - whereClause.append("STATUS ='"); - whereClause.append(statuses[i]); - whereClause.append("' "); - if (i != (statuses.length - 1)) - whereClause.append(" OR "); - } - return whereClause.toString(); - } + long startTime = System.currentTimeMillis(); + int affected = stmt.executeUpdate(sql); + long endTime = System.currentTimeMillis(); + long difference = endTime - startTime; - private void copyOperationIDsForArchival() throws ArchivalDAOException { - PreparedStatement stmt = null; - Statement createStmt = null; - try { - Connection conn = ArchivalSourceDAOFactory.getConnection(); -// conn.setAutoCommit(false); -// String sql = "INSERT INTO DM_ARCHIVED_OPERATIONS(ID,CREATED_TIMESTAMP)" + -// " SELECT DISTINCT op.ID as OPERATION_ID, NOW()" + -// " FROM DM_ENROLMENT_OP_MAPPING AS opm" + -// " LEFT JOIN DM_OPERATION AS op ON opm.OPERATION_ID = op.ID" + -// " WHERE opm.STATUS='ERROR' OR opm.STATUS='COMPLETED'" + -// " AND op.RECEIVED_TIMESTAMP < DATE_SUB(NOW(), INTERVAL ? DAY);"; -// stmt = conn.prepareStatement(sql); -// stmt.setInt(1, this.retentionPeriod); -// stmt.addBatch(); -// stmt.executeBatch(); -// conn.commit(); - - //Create the temporary table first -// String sql = "CREATE TEMPORARY TABLE DM_ARCHIVED_OPERATIONS (ID INTEGER NOT NULL," + -// " CREATED_TIMESTAMP TIMESTAMP NOT NULL, PRIMARY KEY (ID))" ; -// createStmt = conn.createStatement(); -// createStmt.execute(sql); -// if(log.isDebugEnabled()) { -// log.debug("Temporary table DM_ARCHIVED_OPERATIONS has been created "); -// } - //Copy eligible operations into DM_ARCHIVED_OPERATIONS - String sql = "INSERT INTO DM_ARCHIVED_OPERATIONS(ID,CREATED_TIMESTAMP)" + - " SELECT DISTINCT OPERATION_ID, NOW()" + - " FROM DM_ENROLMENT_OP_MAPPING" + - " WHERE STATUS='ERROR' OR STATUS='COMPLETED' OR STATUS='REPEATED'" + - " AND CREATED_TIMESTAMP < DATE_SUB(NOW(), INTERVAL ? DAY)"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, this.retentionPeriod); - int affected = stmt.executeUpdate(); - log.info(affected + " Eligible operations found for archival"); + if (log.isDebugEnabled()) { + log.debug("Time Elapsed for Removing Operations : " + difference); + log.debug(affected + " Rows deleted from DM_OPERATION"); + } } catch (SQLException e) { - throw new ArchivalDAOException("Error occurred while copying operation Ids for archival", e); + String msg = "Error occurred while removing Operations. " + e.getMessage(); + throw new ArchivalDAOException(msg, e); } finally { ArchivalDAOUtil.cleanupResources(stmt); - ArchivalDAOUtil.cleanupResources(createStmt); } } -} \ 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/archival/dao/impl/DataDeletionDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/impl/DataDeletionDAOImpl.java index 35f339f1bf..f6211b7d85 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/impl/DataDeletionDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/archival/dao/impl/DataDeletionDAOImpl.java @@ -18,14 +18,13 @@ package org.wso2.carbon.device.mgt.core.archival.dao.impl; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.core.archival.dao.DataDeletionDAO; import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDAOException; import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDAOUtil; import org.wso2.carbon.device.mgt.core.archival.dao.ArchivalDestinationDAOFactory; -import org.wso2.carbon.device.mgt.core.task.impl.ArchivedDataDeletionTask; +import org.wso2.carbon.device.mgt.core.archival.dao.DataDeletionDAO; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import java.sql.Connection; import java.sql.PreparedStatement; @@ -34,7 +33,11 @@ import java.sql.SQLException; public class DataDeletionDAOImpl implements DataDeletionDAO { private static Log log = LogFactory.getLog(DataDeletionDAOImpl.class); - private int retentionPeriod = DataDeletionDAO.DEFAULT_RETENTION_PERIOD; + private int retentionPeriod; + + private static final String DESTINATION_DB = + DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getArchivalConfiguration() + .getArchivalTaskConfiguration().getDbConfig().getDestinationDB(); public DataDeletionDAOImpl(int retentionPeriod) { this.retentionPeriod = retentionPeriod; @@ -49,7 +52,7 @@ public class DataDeletionDAOImpl implements DataDeletionDAO { try { Connection conn = ArchivalDestinationDAOFactory.getConnection(); conn.setAutoCommit(false); - String sql = "DELETE FROM DM_DEVICE_OPERATION_RESPONSE_ARCH " + + String sql = "DELETE FROM "+ DESTINATION_DB +".DM_DEVICE_OPERATION_RESPONSE_ARCH " + "WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)"; stmt = conn.prepareStatement(sql); stmt.setInt(1, this.retentionPeriod); @@ -63,57 +66,38 @@ public class DataDeletionDAOImpl implements DataDeletionDAO { } @Override - public void deleteNotifications() throws ArchivalDAOException { - PreparedStatement stmt = null; - try { - Connection conn = ArchivalDestinationDAOFactory.getConnection(); - conn.setAutoCommit(false); - String sql = "DELETE FROM DM_NOTIFICATION_ARCH" + - " WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, this.retentionPeriod); - stmt.executeUpdate(); - conn.commit(); - } catch (SQLException e) { - throw new ArchivalDAOException("Error occurred while deleting notifications", e); - } finally { - ArchivalDAOUtil.cleanupResources(stmt); - } - } - - @Override - public void deleteCommandOperations() throws ArchivalDAOException { + public void deleteLargeOperationResponses() throws ArchivalDAOException { PreparedStatement stmt = null; try { Connection conn = ArchivalDestinationDAOFactory.getConnection(); conn.setAutoCommit(false); - String sql = "DELETE FROM DM_COMMAND_OPERATION_ARCH" + - " WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)"; + String sql = "DELETE FROM "+ DESTINATION_DB +".DM_DEVICE_OPERATION_RESPONSE_LARGE_ARCH " + + "WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)"; stmt = conn.prepareStatement(sql); stmt.setInt(1, this.retentionPeriod); stmt.executeUpdate(); conn.commit(); } catch (SQLException e) { - throw new ArchivalDAOException("Error occurred while deleting command operations", e); + throw new ArchivalDAOException("Error occurred while deleting operation responses", e); } finally { ArchivalDAOUtil.cleanupResources(stmt); } } @Override - public void deleteProfileOperations() throws ArchivalDAOException { + public void deleteNotifications() throws ArchivalDAOException { PreparedStatement stmt = null; try { Connection conn = ArchivalDestinationDAOFactory.getConnection(); conn.setAutoCommit(false); - String sql = "DELETE FROM DM_PROFILE_OPERATION_ARCH" + + String sql = "DELETE FROM "+ DESTINATION_DB +".DM_NOTIFICATION_ARCH" + " WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)"; stmt = conn.prepareStatement(sql); stmt.setInt(1, this.retentionPeriod); stmt.executeUpdate(); conn.commit(); } catch (SQLException e) { - throw new ArchivalDAOException("Error occurred while deleting profile operations", e); + throw new ArchivalDAOException("Error occurred while deleting notifications", e); } finally { ArchivalDAOUtil.cleanupResources(stmt); } @@ -125,7 +109,7 @@ public class DataDeletionDAOImpl implements DataDeletionDAO { try { Connection conn = ArchivalDestinationDAOFactory.getConnection(); conn.setAutoCommit(false); - String sql = "DELETE FROM DM_ENROLMENT_OP_MAPPING_ARCH WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)"; + String sql = "DELETE FROM "+ DESTINATION_DB + ".DM_ENROLMENT_OP_MAPPING_ARCH WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)"; stmt = conn.prepareStatement(sql); stmt.setInt(1, this.retentionPeriod); stmt.executeUpdate(); @@ -143,7 +127,7 @@ public class DataDeletionDAOImpl implements DataDeletionDAO { try { Connection conn = ArchivalDestinationDAOFactory.getConnection(); conn.setAutoCommit(false); - String sql = "DELETE FROM DM_OPERATION_ARCH WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)"; + String sql = "DELETE FROM "+ DESTINATION_DB +".DM_OPERATION_ARCH WHERE ARCHIVED_AT < DATE_SUB(NOW(), INTERVAL ? DAY)"; stmt = conn.prepareStatement(sql); stmt.setInt(1, this.retentionPeriod); stmt.executeUpdate(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java index 9cddd7effc..6b84513c98 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java @@ -269,16 +269,4 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori permission.setPath(PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION)); return PermissionUtils.putPermission(permission); } - - public static final class PermissionMethod { - public static final String READ = "read"; - public static final String WRITE = "write"; - public static final String DELETE = "delete"; - public static final String ACTION = "action"; - public static final String UI_EXECUTE = "ui.execute"; - - private PermissionMethod() { - throw new AssertionError(); - } - } } \ 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/config/archival/ArchivalTaskConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/archival/ArchivalTaskConfiguration.java index 382dc1d486..618e5866a5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/archival/ArchivalTaskConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/archival/ArchivalTaskConfiguration.java @@ -28,8 +28,28 @@ public class ArchivalTaskConfiguration { private String taskClazz; private int retentionPeriod; private int batchSize; + private int archivalLockInterval; private PurgingTaskConfiguration purgingTaskConfiguration; private boolean archivePendingOperations; + private DBConfig dbConfig; + + @XmlElement(name = "ArchivalLockInterval", required = true) + public int getArchivalLockInterval() { + return archivalLockInterval; + } + + public void setArchivalLockInterval(int archivalLockInterval) { + this.archivalLockInterval = archivalLockInterval; + } + + @XmlElement(name = "DBConfig", required = true) + public DBConfig getDbConfig() { + return dbConfig; + } + + public void setDbConfig(DBConfig dbConfig) { + this.dbConfig = dbConfig; + } @XmlElement(name = "Enabled", required = true) public boolean isEnabled() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/archival/DBConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/archival/DBConfig.java new file mode 100644 index 0000000000..4b896ef353 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/archival/DBConfig.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.config.archival; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * This class represents the information related to data archival configurations. + */ +@XmlRootElement(name = "DBConfig") +public class DBConfig { + + private String destinationDB; + private String sourceDB; + + @XmlElement(name = "DestinationDB", required = true) + public String getDestinationDB() { + return destinationDB; + } + + public void setDestinationDB(String destinationDB) { + this.destinationDB = destinationDB; + } + + @XmlElement(name = "SourceDB", required = true) + public String getSourceDB() { + return sourceDB; + } + + public void setSourceDB(String sourceDB) { + this.sourceDB = sourceDB; + } + +} 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 316762012b..aa920737cc 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 @@ -15,23 +15,6 @@ * specific language governing permissions and limitations * under the License. */ -/* - * 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 - * - * 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. - */ /* * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * @@ -409,13 +392,13 @@ public interface DeviceDAO { */ int getDeviceCount(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; - /** - * This method is used to retrieve the available device types of a given tenant. - * - * @return returns list of device types. - * @throws DeviceManagementDAOException - */ - List getDeviceTypes() throws DeviceManagementDAOException; + /** + * This method is used to retrieve the available device types of a given tenant. + * + * @return returns list of device types. + * @throws DeviceManagementDAOException + */ + List getDeviceTypes() throws DeviceManagementDAOException; /** * This method is used to retrieve devices of a given device name. @@ -426,7 +409,7 @@ public interface DeviceDAO { * @throws DeviceManagementDAOException */ List getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit) - throws DeviceManagementDAOException; + throws DeviceManagementDAOException; /** * This method is used to retrieve devices of a given device name as a paginated result. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java index b8230d6cf2..6613b3044a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java @@ -28,18 +28,12 @@ public interface EnrollmentDAO { EnrolmentInfo addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException; - int updateEnrollment(int deviceId, EnrolmentInfo enrolmentInfo, - int tenantId) throws DeviceManagementDAOException; - - int updateEnrollment(EnrolmentInfo enrolmentInfo) throws DeviceManagementDAOException; + int updateEnrollment(EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException; boolean updateEnrollmentStatus(List enrolmentInfos) throws DeviceManagementDAOException; int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException; - boolean setStatus(int enrolmentId, String currentOwner, Status status, - int tenantId) throws DeviceManagementDAOException; - boolean setStatus(String currentOwner, Status status, int tenantId) throws DeviceManagementDAOException; boolean setStatus(int enrolmentId, Status status, int tenantId) throws DeviceManagementDAOException; @@ -48,6 +42,8 @@ public interface EnrollmentDAO { EnrolmentInfo getEnrollment(int deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException; + EnrolmentInfo getEnrollment(int deviceId, int tenantId) throws DeviceManagementDAOException; + List getEnrollmentsOfUser(int deviceId, String user, int tenantId) throws DeviceManagementDAOException; 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 7abfd7babf..d9b7d49542 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 @@ -16,23 +16,6 @@ * under the License. * */ -/* - * 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 - * - * 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. - */ /* * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * @@ -170,6 +153,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { + "e.OWNER, " + "e.OWNERSHIP, " + "e.STATUS, " + + "e.IS_TRANSFERRED, " + "e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, " + "e.ID AS ENROLMENT_ID " @@ -247,7 +231,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + @@ -286,20 +270,20 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "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.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 = ? AND d.TENANT_ID = ?) d1 " + - "WHERE " + - "d1.ID = e.DEVICE_ID " + - "AND TENANT_ID = ? " + - "ORDER BY e.DATE_OF_LAST_UPDATE DESC, e.STATUS ASC"; + "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 = ? AND d.TENANT_ID = ?) d1 " + + "WHERE " + + "d1.ID = e.DEVICE_ID " + + "AND TENANT_ID = ? " + + "ORDER BY e.DATE_OF_LAST_UPDATE DESC, e.STATUS ASC"; // Status adeed as an orderby clause to fix a bug : when an existing device is // re-enrolled, earlier enrollment is marked as removed and a new enrollment is added. // However, both enrollments share the same time stamp. When retrieving the device @@ -334,7 +318,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + @@ -368,7 +352,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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, DM_DEVICE_DETAIL dt " + "WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " + @@ -394,7 +378,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } @Override - public List getDeviceBasedOnDeviceProperties(Map deviceProps, int tenantId) + public List getDeviceBasedOnDeviceProperties(Map deviceProps, int tenantId) throws DeviceManagementDAOException { Connection conn = null; PreparedStatement stmt = null; @@ -407,8 +391,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { for (Map.Entry entry : deviceProps.entrySet()) { stmt = conn.prepareStatement("SELECT DEVICE_IDENTIFICATION FROM DM_DEVICE_PROPERTIES " + - "WHERE (PROPERTY_NAME , PROPERTY_VALUE) IN " + - "((? , ?)) AND TENANT_ID = ?"); + "WHERE (PROPERTY_NAME , PROPERTY_VALUE) IN " + + "((? , ?)) AND TENANT_ID = ?"); stmt.setString(1, entry.getKey()); stmt.setString(2, entry.getValue()); stmt.setInt(3, tenantId); @@ -421,7 +405,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { outputLists.add(deviceList); } List deviceIds = findIntersection(outputLists); - for(String deviceId : deviceIds){ + for (String deviceId : deviceIds) { devices.add(getDeviceProps(deviceId, tenantId)); } } catch (SQLException e) { @@ -445,15 +429,15 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { conn = this.getConnection(); List> outputLists = new ArrayList<>(); String sql = "SELECT " + - "p.DEVICE_IDENTIFICATION, " + - "p.DEVICE_TYPE_NAME, " + - "p.TENANT_ID FROM " + - "DM_DEVICE_PROPERTIES p "; + "p.DEVICE_IDENTIFICATION, " + + "p.DEVICE_TYPE_NAME, " + + "p.TENANT_ID FROM " + + "DM_DEVICE_PROPERTIES p "; String groupByClause = "GROUP BY " + - "p.DEVICE_IDENTIFICATION, " + - "p.DEVICE_TYPE_NAME, " + - "p.TENANT_ID"; + "p.DEVICE_IDENTIFICATION, " + + "p.DEVICE_TYPE_NAME, " + + "p.TENANT_ID"; int iterationCount = 0; StringBuilder propertyQuery = new StringBuilder(" "); @@ -558,22 +542,22 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "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.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," + - " DM_DEVICE_DETAIL dt " + - "WHERE " + - "t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND" + - " dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?) d1 " + - "WHERE" + - " d1.ID = e.DEVICE_ID AND TENANT_ID = ? " + - "ORDER BY " + - "e.DATE_OF_LAST_UPDATE DESC"; + "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," + + " DM_DEVICE_DETAIL dt " + + "WHERE " + + "t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND" + + " dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?) d1 " + + "WHERE" + + " d1.ID = e.DEVICE_ID AND TENANT_ID = ? " + + "ORDER BY " + + "e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); int paramIdx = 1; stmt.setString(paramIdx++, deviceIdentifier); @@ -603,7 +587,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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, DM_DEVICE_DETAIL dt " + "WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " + @@ -638,7 +622,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + @@ -668,30 +652,31 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { Connection conn = this.getConnection(); String sql = "SELECT d1.ID AS DEVICE_ID, " + - "d1.DESCRIPTION, " + - "d1.NAME AS DEVICE_NAME, " + - "d1.DEVICE_TYPE, " + - "e.TENANT_ID, " + - "d1.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "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.NAME = ? " + - "AND t.ID = d.DEVICE_TYPE_ID " + - "AND d.DEVICE_IDENTIFICATION = ?) d1 " + - "WHERE d1.ID = e.DEVICE_ID " + - "ORDER BY e.DATE_OF_LAST_UPDATE DESC"; + "d1.DESCRIPTION, " + + "d1.NAME AS DEVICE_NAME, " + + "d1.DEVICE_TYPE, " + + "e.TENANT_ID, " + + "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.NAME = ? " + + "AND t.ID = d.DEVICE_TYPE_ID " + + "AND d.DEVICE_IDENTIFICATION = ?) d1 " + + "WHERE d1.ID = e.DEVICE_ID " + + "ORDER BY e.DATE_OF_LAST_UPDATE DESC"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, deviceIdentifier.getType()); @@ -711,7 +696,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } catch (SQLException e) { String msg = "Error occurred while listing devices (with tenant id) for type " + - deviceIdentifier.getType(); + deviceIdentifier.getType(); log.error(msg); throw new DeviceManagementDAOException(msg, e); } @@ -726,7 +711,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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 " + "d.ID = ? AND t.ID = d.DEVICE_TYPE_ID AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + @@ -753,11 +738,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; - List devices = null; + List devices; try { conn = this.getConnection(); String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "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 AS DEVICE_ID, " + "d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " + @@ -789,7 +774,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + @@ -823,10 +808,10 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," + + String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE," + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + - "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + + "e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + "e.TENANT_ID = ? AND LOWER(e.OWNER) = LOWER(?)) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + "AND t.ID = d.DEVICE_TYPE_ID ORDER BY e1.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); @@ -856,10 +841,10 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," + + String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE," + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + - "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + + "e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + "e.TENANT_ID = ? AND LOWER(e.OWNER) = LOWER(?) ORDER BY e.DATE_OF_LAST_UPDATE DESC) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + "AND t.ID = d.DEVICE_TYPE_ID AND t.NAME= ?"; stmt = conn.prepareStatement(sql); @@ -1189,15 +1174,15 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { Connection conn = getConnection(); String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT " + - "FROM DM_ENROLMENT e, " + - "(SELECT " + - "d.ID, " + - "d.NAME, " + - "d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM " + - "DM_DEVICE d, " + - "DM_DEVICE_TYPE t"; + "FROM DM_ENROLMENT e, " + + "(SELECT " + + "d.ID, " + + "d.NAME, " + + "d.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM " + + "DM_DEVICE d, " + + "DM_DEVICE_TYPE t"; //Add query for last updated timestamp if (since != null) { sql = sql + " , DM_DEVICE_DETAIL dt"; @@ -1270,7 +1255,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + - "registered devices", e); + "registered devices", e); } } @@ -1449,16 +1434,17 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { int enrolmentId = -1; try { conn = this.getConnection(); - String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS,DATE_OF_ENROLMENT, " + - "DATE_OF_LAST_UPDATE, TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?)"; + String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS, IS_TRANSFERRED, " + + "DATE_OF_ENROLMENT, DATE_OF_LAST_UPDATE, TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(sql, new String[]{"id"}); stmt.setInt(1, device.getId()); stmt.setString(2, device.getEnrolmentInfo().getOwner()); stmt.setString(3, device.getEnrolmentInfo().getOwnership().toString()); stmt.setString(4, device.getEnrolmentInfo().getStatus().toString()); - stmt.setTimestamp(5, new Timestamp(new Date().getTime())); + stmt.setBoolean(5, device.getEnrolmentInfo().isTransferred()); stmt.setTimestamp(6, new Timestamp(new Date().getTime())); - stmt.setInt(7, tenantId); + stmt.setTimestamp(7, new Timestamp(new Date().getTime())); + stmt.setInt(8, tenantId); stmt.execute(); rs = stmt.getGeneratedKeys(); @@ -1542,6 +1528,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { + "OWNER, " + "OWNERSHIP, " + "STATUS, " + + "IS_TRANSFERRED, " + "DATE_OF_ENROLMENT, " + "DATE_OF_LAST_UPDATE, " + "TENANT_ID " @@ -1589,7 +1576,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { EnrolmentInfo enrolmentInfo = null; try { conn = this.getConnection(); - String sql = "SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " + + String sql = "SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, IS_TRANSFERRED, DATE_OF_ENROLMENT, " + "DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID " + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " + "AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + @@ -1622,9 +1609,9 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e" + - ".OWNERSHIP, e.STATUS, e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS " + + ".OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS " + "ENROLMENT_ID FROM DM_ENROLMENT e WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); @@ -1687,7 +1674,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "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 AS DEVICE_ID, " + "d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE, d.LAST_UPDATED_TIMESTAMP FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? AND d.LAST_UPDATED_TIMESTAMP < CURRENT_TIMESTAMP) d1 " + @@ -1805,8 +1792,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { 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.DATE_OF_LAST_UPDATE, " - + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + + "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 " @@ -1854,11 +1841,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { String sql = "SELECT DEVICE_ID, TENANT_ID, DEVICE_ID_NAME, DEVICE_TYPE_NAME, LATITUDE, LONGITUDE, SPEED, " + "HEADING, TIMESTAMP, GEO_HASH, DEVICE_OWNER, DEVICE_ALTITUDE, DISTANCE " + - "FROM DM_DEVICE_HISTORY_LAST_SEVEN_DAYS " + - "WHERE DEVICE_ID_NAME = ? " + - "AND DEVICE_TYPE_NAME = ? " + - "AND TIMESTAMP >= ? " + - "AND TIMESTAMP <= ?"; + "FROM DM_DEVICE_HISTORY_LAST_SEVEN_DAYS " + + "WHERE DEVICE_ID_NAME = ? " + + "AND DEVICE_TYPE_NAME = ? " + + "AND TIMESTAMP >= ? " + + "AND TIMESTAMP <= ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceIdentifier.getId()); @@ -1962,24 +1949,25 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { boolean isVersionProvided = false; String sql = "SELECT " + - "d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, " + - "d.NAME AS DEVICE_NAME, " + - "t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_DEVICE AS d " + - "INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " + - "INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " + - "WHERE " + - "t.NAME = ? AND e.TENANT_ID = ? AND d.ID " + - "NOT IN " + - "(SELECT a.DEVICE_ID FROM DM_APPLICATION AS a WHERE a.APP_IDENTIFIER = ?"; + "d.ID AS DEVICE_ID, " + + "d.DESCRIPTION, " + + "d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.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_DEVICE AS d " + + "INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " + + "INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " + + "WHERE " + + "t.NAME = ? AND e.TENANT_ID = ? AND d.ID " + + "NOT IN " + + "(SELECT a.DEVICE_ID FROM DM_APPLICATION AS a WHERE a.APP_IDENTIFIER = ?"; if (!StringUtils.isBlank(version)) { sql = sql + " AND a.VERSION = ? "; @@ -2026,14 +2014,14 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { boolean isVersionProvided = false; String sql = "SELECT " + - "COUNT(d.ID) AS DEVICE_COUNT " + - "FROM DM_DEVICE AS d " + - "INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " + - "INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " + - "WHERE " + - "t.NAME = ? AND e.TENANT_ID = ? AND d.ID " + - "NOT IN " + - "(SELECT a.DEVICE_ID FROM DM_APPLICATION AS a WHERE a.APP_IDENTIFIER = ?"; + "COUNT(d.ID) AS DEVICE_COUNT " + + "FROM DM_DEVICE AS d " + + "INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " + + "INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " + + "WHERE " + + "t.NAME = ? AND e.TENANT_ID = ? AND d.ID " + + "NOT IN " + + "(SELECT a.DEVICE_ID FROM DM_APPLICATION AS a WHERE a.APP_IDENTIFIER = ?"; if (!StringUtils.isBlank(version)) { sql = sql + " AND a.VERSION = ? "; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java index efb485065c..80fe1c8ad7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractGroupDAOImpl.java @@ -57,7 +57,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql; - if(deviceGroup.getStatus() == null || deviceGroup.getStatus().isEmpty()){ + if (deviceGroup.getStatus() == null || deviceGroup.getStatus().isEmpty()) { sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, OWNER, TENANT_ID) VALUES (?, ?, ?, ?)"; } else { sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, OWNER, TENANT_ID, STATUS) VALUES (?, ?, ?, ?, ?)"; @@ -68,7 +68,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { stmt.setString(2, deviceGroup.getName()); stmt.setString(3, deviceGroup.getOwner()); stmt.setInt(4, tenantId); - if(hasStatus) { + if (hasStatus) { stmt.setString(5, deviceGroup.getStatus()); } @@ -94,7 +94,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { Connection conn = GroupManagementDAOFactory.getConnection(); stmt = conn.prepareStatement( "INSERT INTO GROUP_PROPERTIES(GROUP_ID, PROPERTY_NAME, " + - "PROPERTY_VALUE, TENANT_ID) VALUES (?, ?, ?, ?)"); + "PROPERTY_VALUE, TENANT_ID) VALUES (?, ?, ?, ?)"); for (Map.Entry entry : deviceGroup.getGroupProperties().entrySet()) { stmt.setInt(1, groupId); stmt.setString(2, entry.getKey()); @@ -106,7 +106,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { status = true; } catch (SQLException e) { String msg = "Error occurred while adding properties for group '" + - deviceGroup.getName() + "' values : " + deviceGroup.getGroupProperties(); + deviceGroup.getName() + "' values : " + deviceGroup.getGroupProperties(); throw new GroupManagementDAOException(msg, e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, null); @@ -122,7 +122,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { Connection conn = GroupManagementDAOFactory.getConnection(); stmt = conn.prepareStatement( "UPDATE GROUP_PROPERTIES SET PROPERTY_VALUE = ? WHERE GROUP_ID = ? AND " + - "TENANT_ID = ? AND PROPERTY_NAME = ?"); + "TENANT_ID = ? AND PROPERTY_NAME = ?"); for (Map.Entry entry : deviceGroup.getGroupProperties().entrySet()) { stmt.setString(1, entry.getValue()); stmt.setInt(2, groupId); @@ -134,7 +134,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { status = true; } catch (SQLException e) { String msg = "Error occurred while adding properties for group '" + - deviceGroup.getName() + "' values : " + deviceGroup.getGroupProperties(); + deviceGroup.getName() + "' values : " + deviceGroup.getGroupProperties(); throw new GroupManagementDAOException(msg, e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, null); @@ -152,7 +152,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { String sql = "UPDATE DM_GROUP SET DESCRIPTION = ?, GROUP_NAME = ?, OWNER = ? WHERE ID = ? AND TENANT_ID = ?"; - if(deviceGroup.getStatus() != null && !deviceGroup.getStatus().isEmpty()){ + if (deviceGroup.getStatus() != null && !deviceGroup.getStatus().isEmpty()) { sql = "UPDATE DM_GROUP SET DESCRIPTION = ?, GROUP_NAME = ?, OWNER = ?, STATUS = ? WHERE ID = ? AND TENANT_ID = ?"; hasStatus = true; } @@ -161,7 +161,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { stmt.setString(paramIndex++, deviceGroup.getDescription()); stmt.setString(paramIndex++, deviceGroup.getName()); stmt.setString(paramIndex++, deviceGroup.getOwner()); - if(hasStatus) { + if (hasStatus) { stmt.setString(paramIndex++, deviceGroup.getStatus()); } stmt.setInt(paramIndex++, groupId); @@ -234,11 +234,11 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { } } - public Map getAllGroupProperties(int groupId, int tenantId) + public Map getAllGroupProperties(int groupId, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; - Map properties = new HashMap(); + Map properties = new HashMap(); try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT PROPERTY_NAME, PROPERTY_VALUE FROM GROUP_PROPERTIES WHERE GROUP_ID = ? AND TENANT_ID = ?"; @@ -248,7 +248,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { resultSet = stmt.executeQuery(); while (resultSet.next()) { properties.put(resultSet.getString("PROPERTY_NAME"), - resultSet.getString("PROPERTY_VALUE")); + resultSet.getString("PROPERTY_VALUE")); } } catch (SQLException e) { String msg = "Error occurred while deleting group ID : " + groupId; @@ -339,13 +339,13 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT COUNT(ID) AS GROUP_COUNT FROM DM_GROUP WHERE TENANT_ID = ?"; - if(!StringUtils.isEmpty(status)){ + if (!StringUtils.isEmpty(status)) { sql += " AND STATUS = ?"; statusAvailable = true; } stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - if(statusAvailable){ + if (statusAvailable) { stmt.setString(2, status); } resultSet = stmt.executeQuery(); @@ -384,7 +384,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { sql += " AND OWNER LIKE ?"; hasOwner = true; } - if(!StringUtils.isEmpty(request.getStatus())){ + if (!StringUtils.isEmpty(request.getStatus())) { sql += " AND STATUS = ?"; hasStatus = true; } @@ -781,6 +781,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { + "e.OWNER, " + "e.OWNERSHIP, " + "e.STATUS, " + + "e.IS_TRANSFERRED, " + "e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, " + "e.ID AS ENROLMENT_ID " @@ -797,11 +798,11 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { + "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 " + "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; - try (PreparedStatement stmt = conn.prepareStatement(sql)){ + try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, groupName); stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); - try (ResultSet rs = stmt.executeQuery() ){ + try (ResultSet rs = stmt.executeQuery()) { devices = new ArrayList<>(); while (rs.next()) { Device device = DeviceManagementDAOUtil.loadDevice(rs); @@ -824,26 +825,26 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { try { Connection connection = GroupManagementDAOFactory.getConnection(); StringJoiner sql = new StringJoiner(",", - "SELECT DEVICE.ID AS DEVICE_ID, " + - "DEVICE.NAME AS DEVICE_NAME, " + - "DEVICE_TYPE.NAME AS DEVICE_TYPE, " + - "DEVICE.DESCRIPTION, " + - "DEVICE.DEVICE_IDENTIFICATION, " + - "ENROLMENT.ID AS ENROLMENT_ID, " + - "ENROLMENT.OWNER, " + - "ENROLMENT.OWNERSHIP, " + - "ENROLMENT.DATE_OF_ENROLMENT, " + - "ENROLMENT.DATE_OF_LAST_UPDATE, " + - "ENROLMENT.STATUS " + - "FROM DM_DEVICE AS DEVICE, DM_DEVICE_TYPE AS DEVICE_TYPE, DM_ENROLMENT " + - "AS ENROLMENT " + - "WHERE DEVICE_TYPE.NAME = ? AND DEVICE" + - ".ID " + - "NOT IN " + - "(SELECT DEVICE_ID " + - "FROM DM_DEVICE_GROUP_MAP " + - "WHERE GROUP_ID IN (SELECT ID FROM DM_GROUP WHERE GROUP_NAME NOT IN (", - ")) GROUP BY DEVICE_ID)"); + "SELECT DEVICE.ID AS DEVICE_ID, " + + "DEVICE.NAME AS DEVICE_NAME, " + + "DEVICE_TYPE.NAME AS DEVICE_TYPE, " + + "DEVICE.DESCRIPTION, " + + "DEVICE.DEVICE_IDENTIFICATION, " + + "ENROLMENT.ID AS ENROLMENT_ID, " + + "ENROLMENT.OWNER, " + + "ENROLMENT.OWNERSHIP, " + + "ENROLMENT.DATE_OF_ENROLMENT, " + + "ENROLMENT.DATE_OF_LAST_UPDATE, " + + "ENROLMENT.STATUS, " + + "ENROLMENT.IS_TRANSFERRED " + + "FROM DM_DEVICE AS DEVICE, DM_DEVICE_TYPE AS DEVICE_TYPE, DM_ENROLMENT " + + "AS ENROLMENT " + + "WHERE DEVICE_TYPE.NAME = ? AND DEVICE.ID " + + "NOT IN " + + "(SELECT DEVICE_ID " + + "FROM DM_DEVICE_GROUP_MAP " + + "WHERE GROUP_ID IN (SELECT ID FROM DM_GROUP WHERE GROUP_NAME NOT IN (", + ")) GROUP BY DEVICE_ID)"); groupNames.stream().map(e -> "?").forEach(sql::add); try (PreparedStatement stmt = connection.prepareStatement(String.valueOf(sql))) { @@ -862,7 +863,7 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO { } catch (SQLException e) { String msg = "Error occurred while retrieving information of group unassigned devices"; log.error(msg, e); - throw new GroupManagementDAOException(msg,e); + throw new GroupManagementDAOException(msg, e); } return groupUnassignedDeviceList; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java index 77aab5bae9..186b3b4dd6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java @@ -75,47 +75,21 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { } @Override - public int updateEnrollment(int deviceId, EnrolmentInfo enrolmentInfo, - int tenantId) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - try { - conn = this.getConnection(); - String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE DEVICE_ID = ?" + - " AND OWNER = ? AND TENANT_ID = ? AND ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, enrolmentInfo.getOwnership().toString()); - stmt.setString(2, enrolmentInfo.getStatus().toString()); - stmt.setTimestamp(3, new Timestamp(new Date().getTime())); - stmt.setInt(4, deviceId); - stmt.setString(5, enrolmentInfo.getOwner()); - stmt.setInt(6, tenantId); - stmt.setInt(7, enrolmentInfo.getId()); - int status = stmt.executeUpdate(); - return status; - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - } - - @Override - public int updateEnrollment(EnrolmentInfo enrolmentInfo) throws DeviceManagementDAOException { + public int updateEnrollment(EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; try { conn = this.getConnection(); - String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE ID = ?"; + String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, DATE_OF_LAST_UPDATE = ? " + + "WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, enrolmentInfo.getOwnership().toString()); stmt.setString(2, enrolmentInfo.getStatus().toString()); stmt.setTimestamp(3, new Timestamp(new Date().getTime())); stmt.setInt(4, enrolmentInfo.getId()); - int status = stmt.executeUpdate(); - return status; + stmt.setInt(5, tenantId); + return stmt.executeUpdate(); } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e); } finally { @@ -188,28 +162,6 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { } } - @Override - public boolean setStatus(int enrolmentID, String currentOwner, EnrolmentInfo.Status status, - int tenantId) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - try { - conn = this.getConnection(); - String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE ID = ? AND OWNER = ? AND TENANT_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, status.toString()); - stmt.setInt(2, enrolmentID); - stmt.setString(3, currentOwner); - stmt.setInt(4, tenantId); - stmt.executeUpdate(); - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, null); - } - return true; - } - private int getCountOfDevicesOfOwner(String owner, int tenantID) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; @@ -314,7 +266,7 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { EnrolmentInfo enrolmentInfo = null; try { conn = this.getConnection(); - String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " + + String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, IS_TRANSFERRED, DATE_OF_ENROLMENT, " + "DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, deviceId); @@ -333,6 +285,33 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { } } + @Override + public EnrolmentInfo getEnrollment(int deviceId, int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + EnrolmentInfo enrolmentInfo = null; + try { + conn = this.getConnection(); + String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, IS_TRANSFERRED, DATE_OF_ENROLMENT, " + + "DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND TENANT_ID = ? " + + "ORDER BY DATE_OF_LAST_UPDATE DESC"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + stmt.setInt(2, tenantId); + rs = stmt.executeQuery(); + if (rs.next()) { + enrolmentInfo = this.loadEnrolment(rs); + } + return enrolmentInfo; + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " + + "information of device '" + deviceId + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + @Override public List getEnrollmentsOfUser(int deviceId, String user, int tenantId) throws DeviceManagementDAOException { @@ -343,7 +322,7 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { EnrolmentInfo enrolmentInfo = null; try { conn = this.getConnection(); - String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " + + String sql = "SELECT ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, IS_TRANSFERRED, DATE_OF_ENROLMENT, " + "DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, deviceId); @@ -369,20 +348,21 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { try { Connection conn = this.getConnection(); boolean updateStatus = true; - String sql = "UPDATE " - + "DM_ENROLMENT " - + "SET OWNER = ? " - + "WHERE ID = ? AND " - + "TENANT_ID = ?"; + String sql = "UPDATE DM_ENROLMENT " + + "SET OWNER = ?, IS_TRANSFERRED = ?, DATE_OF_LAST_UPDATE = ? " + + "WHERE ID = ? AND TENANT_ID = ?"; try (PreparedStatement ps = conn.prepareStatement(sql)) { if (conn.getMetaData().supportsBatchUpdates()) { for (Device device : devices) { ps.setString(1, owner); - ps.setInt(2, device.getId()); - ps.setInt(3, tenantId); + ps.setBoolean(2, device.getEnrolmentInfo().isTransferred()); + ps.setTimestamp(3, new Timestamp(new Date().getTime())); + ps.setInt(4, device.getEnrolmentInfo().getId()); + ps.setInt(5, tenantId); ps.addBatch(); } - for (int i : ps.executeBatch()) { + int[] batchResult = ps.executeBatch(); + for (int i : batchResult) { if (i == 0 || i == Statement.SUCCESS_NO_INFO || i == Statement.EXECUTE_FAILED) { updateStatus = false; break; @@ -391,8 +371,9 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { } else { for (Device device : devices) { ps.setString(1, owner); - ps.setInt(2, device.getId()); - ps.setInt(3, tenantId); + ps.setBoolean(2, device.getEnrolmentInfo().isTransferred()); + ps.setInt(3, device.getId()); + ps.setInt(4, tenantId); if (ps.executeUpdate() == 0) { updateStatus = false; break; @@ -415,6 +396,7 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); enrolmentInfo.setOwner(rs.getString("OWNER")); enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP"))); + enrolmentInfo.setTransferred(rs.getBoolean("IS_TRANSFERRED")); enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime()); enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime()); enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS"))); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 7d3c6afd90..63df06538d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -70,24 +70,24 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { try { Connection conn = getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, " + - "(SELECT d.ID, " + - "d.DESCRIPTION, " + - "d.NAME, " + - "d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t "; + "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, " + + "d.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE d, DM_DEVICE_TYPE t "; //Add the query to filter active devices on timestamp if (since != null) { sql = sql + ", DM_DEVICE_DETAIL dt"; @@ -168,7 +168,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + - "registered devices"; + "registered devices"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -197,34 +197,35 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { try { Connection conn = getConnection(); String sql = "SELECT d1.DEVICE_ID, " + - "d1.DESCRIPTION, " + - "d1.NAME AS DEVICE_NAME, " + - "d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, " + - "(SELECT gd.DEVICE_ID, " + - "gd.DESCRIPTION, " + - "gd.NAME, " + - "gd.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM " + - "(SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, " + - "d.NAME, " + - "d.DEVICE_IDENTIFICATION, " + - "d.DEVICE_TYPE_ID " + - "FROM DM_DEVICE d, " + - "(SELECT dgm.DEVICE_ID " + - "FROM DM_DEVICE_GROUP_MAP dgm " + - "WHERE dgm.GROUP_ID = ?) dgm1 " + - "WHERE d.ID = dgm1.DEVICE_ID " + - "AND d.TENANT_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 gd.DEVICE_ID, " + + "gd.DESCRIPTION, " + + "gd.NAME, " + + "gd.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM " + + "(SELECT d.ID AS DEVICE_ID, " + + "d.DESCRIPTION, " + + "d.NAME, " + + "d.DEVICE_IDENTIFICATION, " + + "d.DEVICE_TYPE_ID " + + "FROM DM_DEVICE d, " + + "(SELECT dgm.DEVICE_ID " + + "FROM DM_DEVICE_GROUP_MAP dgm " + + "WHERE dgm.GROUP_ID = ?) dgm1 " + + "WHERE d.ID = dgm1.DEVICE_ID " + + "AND d.TENANT_ID = ?"; //Add the query for device-name if (deviceName != null && !deviceName.isEmpty()) { sql = sql + " AND d.NAME LIKE ?"; @@ -306,7 +307,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of" + - " devices belonging to group : " + groupId; + " devices belonging to group : " + groupId; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -320,12 +321,12 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," + - " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + - "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + - "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + - "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + - "AND t.ID = d.DEVICE_TYPE_ID LIMIT ?,?"; + String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE," + + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + + "e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + + "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "AND t.ID = d.DEVICE_TYPE_ID LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, request.getOwner()); @@ -339,7 +340,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + - request.getOwner() + "'", e); + request.getOwner() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -355,11 +356,11 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + - "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + - "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,?"; + "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.NAME, " + + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setString(1, request.getDeviceName() + "%"); stmt.setInt(2, tenantId); @@ -374,7 +375,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + - "'" + request.getDeviceName() + "'", e); + "'" + request.getDeviceName() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -390,11 +391,11 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + - "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ?,?"; + "d.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 (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, request.getOwnership()); @@ -409,7 +410,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + - "'" + request.getOwnership() + "'", e); + "'" + request.getOwnership() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -425,41 +426,43 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { try { Connection conn = getConnection(); String sql = "SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, " + - "d.NAME AS DEVICE_NAME, " + - "t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM " + - "(SELECT e.ID, " + - "e.DEVICE_ID, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_ENROLMENT, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ?"; + "d.DESCRIPTION, " + + "d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.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 " + + "(SELECT e.ID, " + + "e.DEVICE_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_ENROLMENT, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ?"; if (statusList == null || statusList.isEmpty()) { String msg = "Error occurred while fetching the list of devices. Status List can't " + - "be null or empty"; + "be null or empty"; log.error(msg); throw new DeviceManagementDAOException(msg); } sql += buildStatusQuery(statusList); sql += ") e, " + - "DM_DEVICE d, " + - "DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID " + - "AND d.DEVICE_TYPE_ID = t.ID " + - "AND d.TENANT_ID = ? " + - "LIMIT ?,?"; + "DM_DEVICE d, " + + "DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID " + + "AND d.DEVICE_TYPE_ID = t.ID " + + "AND d.TENANT_ID = ? " + + "LIMIT ?,?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIdx = 1; @@ -481,7 +484,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices that matches to status " + - request.getStatusList().toString(); + request.getStatusList().toString(); log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -497,21 +500,22 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isStatusProvided = false; String sql = "SELECT " + - "d.ID AS DEVICE_ID, " + - "d.DESCRIPTION,d.NAME AS DEVICE_NAME, " + - "t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE," + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " + - "WHERE d.ID = e.DEVICE_ID AND " + - "d.DEVICE_TYPE_ID = t.ID AND " + - "e.TENANT_ID = ? AND " + - "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; + "d.ID AS DEVICE_ID, " + + "d.DESCRIPTION,d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.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_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " + + "WHERE d.ID = e.DEVICE_ID AND " + + "d.DEVICE_TYPE_ID = t.ID AND " + + "e.TENANT_ID = ? AND " + + "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; if (statusList != null && !statusList.isEmpty()) { sql += buildStatusQuery(statusList); isStatusProvided = true; @@ -548,7 +552,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + - "registered devices under tenant id " + tenantId; + "registered devices under tenant id " + tenantId; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -562,14 +566,14 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isStatusProvided = false; String sql = "SELECT " + - "COUNT(d.ID) AS DEVICE_COUNT " + - "FROM DM_DEVICE AS d , " + - "DM_ENROLMENT AS e , " + - "DM_DEVICE_TYPE AS t " + - "WHERE d.ID = e.DEVICE_ID " + - "AND d.DEVICE_TYPE_ID = t.ID " + - "AND e.TENANT_ID = ? " + - "AND e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; + "COUNT(d.ID) AS DEVICE_COUNT " + + "FROM DM_DEVICE AS d , " + + "DM_ENROLMENT AS e , " + + "DM_DEVICE_TYPE AS t " + + "WHERE d.ID = e.DEVICE_ID " + + "AND d.DEVICE_TYPE_ID = t.ID " + + "AND e.TENANT_ID = ? " + + "AND e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; if (statusList != null && !statusList.isEmpty()) { sql += buildStatusQuery(statusList); isStatusProvided = true; @@ -601,7 +605,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + - "registered devices under tenant id " + tenantId; + "registered devices under tenant id " + tenantId; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -609,7 +613,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override public List getCountOfDevicesByDuration(PaginationRequest request, List statusList, int tenantId, - String fromDate, String toDate) + String fromDate, String toDate) throws DeviceManagementDAOException { List countList = new ArrayList<>(); String ownership = request.getOwnership(); @@ -617,14 +621,14 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { String sql = "SELECT " + - "SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) AS ENROLMENT_DATE, " + - "COUNT(SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10)) AS ENROLMENT_COUNT " + - "FROM DM_DEVICE AS d " + - "INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " + - "INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " + - "AND e.TENANT_ID = ? " + - "AND e.DATE_OF_ENROLMENT " + - "BETWEEN ? AND ? "; + "SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) AS ENROLMENT_DATE, " + + "COUNT(SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10)) AS ENROLMENT_COUNT " + + "FROM DM_DEVICE AS d " + + "INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " + + "INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " + + "AND e.TENANT_ID = ? " + + "AND e.DATE_OF_ENROLMENT " + + "BETWEEN ? AND ? "; //Add the query for status if (statusList != null && !statusList.isEmpty()) { @@ -703,7 +707,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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.NAME, " + "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + @@ -733,7 +737,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices corresponding" + - "to the mentioned filtering criteria"; + "to the mentioned filtering criteria"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } finally { @@ -766,6 +770,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { + "DM_ENROLMENT.DATE_OF_ENROLMENT, " + "DM_ENROLMENT.DATE_OF_LAST_UPDATE, " + "DM_ENROLMENT.STATUS, " + + "DM_ENROLMENT.IS_TRANSFERRED, " + "device_types.NAME AS DEVICE_TYPE " + "FROM DM_DEVICE " + "INNER JOIN DM_ENROLMENT ON " @@ -809,7 +814,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all registered devices " + - "according to device ids and the limit area."; + "according to device ids and the limit area."; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -823,8 +828,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { int index = 1; StringJoiner joiner = new StringJoiner(",", "SELECT " + - "COUNT(e.DEVICE_ID) AS DEVICE_ID "+ - "FROM DM_ENROLMENT AS e, DM_DEVICE AS f "+ + "COUNT(e.DEVICE_ID) AS DEVICE_ID " + + "FROM DM_ENROLMENT AS e, DM_DEVICE AS f " + "WHERE " + "e.DEVICE_ID=f.ID AND " + "e.DEVICE_ID IN (", ") AND e.TENANT_ID = ?"); @@ -870,37 +875,38 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { /* following variable is used to identify the datasource type.This is due to a convert function performed in the query which will depend on the datasource */ String dataSourceType = conn.getMetaData().getDatabaseProductName(); - String sql="SELECT " + - "d1.DEVICE_TYPE, " + - "d1.DEVICE_ID, " + - "d1.DEVICE_NAME, " + - "d1.DESCRIPTION, " + - "d1.DEVICE_IDENTIFICATION, " + - "ddd.OS_VERSION, " + - "e.ID AS ENROLMENT_ID, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT " + - "FROM DM_DEVICE_INFO ddi," + - "DM_DEVICE_DETAIL ddd, " + - "DM_ENROLMENT e, " + - "(SELECT dt.NAME AS DEVICE_TYPE, " + - "d.ID AS DEVICE_ID, " + - "d.NAME AS DEVICE_NAME, " + - "DESCRIPTION, " + - "DEVICE_IDENTIFICATION " + - "FROM DM_DEVICE_TYPE dt, " + - "DM_DEVICE d " + - "WHERE dt.NAME = ? " + - "AND PROVIDER_TENANT_ID = ? " + - "AND dt.ID = d.DEVICE_TYPE_ID " + - ") d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID " + - "AND d1.DEVICE_ID = ddi.DEVICE_ID " + - "AND d1.DEVICE_ID = ddd.DEVICE_ID " + - "AND ddi.KEY_FIELD = ? "; + String sql = "SELECT " + + "d1.DEVICE_TYPE, " + + "d1.DEVICE_ID, " + + "d1.DEVICE_NAME, " + + "d1.DESCRIPTION, " + + "d1.DEVICE_IDENTIFICATION, " + + "ddd.OS_VERSION, " + + "e.ID AS ENROLMENT_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT " + + "FROM DM_DEVICE_INFO ddi," + + "DM_DEVICE_DETAIL ddd, " + + "DM_ENROLMENT e, " + + "(SELECT dt.NAME AS DEVICE_TYPE, " + + "d.ID AS DEVICE_ID, " + + "d.NAME AS DEVICE_NAME, " + + "DESCRIPTION, " + + "DEVICE_IDENTIFICATION " + + "FROM DM_DEVICE_TYPE dt, " + + "DM_DEVICE d " + + "WHERE dt.NAME = ? " + + "AND PROVIDER_TENANT_ID = ? " + + "AND dt.ID = d.DEVICE_TYPE_ID " + + ") d1 " + + "WHERE d1.DEVICE_ID = e.DEVICE_ID " + + "AND d1.DEVICE_ID = ddi.DEVICE_ID " + + "AND d1.DEVICE_ID = ddd.DEVICE_ID " + + "AND ddi.KEY_FIELD = ? "; if (dataSourceType.contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2)) { sql += "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? "; } else if (dataSourceType.contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL)) { @@ -930,7 +936,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while building or executing queries to retrieve information " + - "of devices with an older OS build date"; + "of devices with an older OS build date"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -945,17 +951,17 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { convert function performed in the query which will depend on the datasource */ String dataSourceType = conn.getMetaData().getDatabaseProductName(); String sql = "SELECT " + - "COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " + - "FROM DM_DEVICE_INFO ddi, " + - "(SELECT d.ID AS DEVICE_ID " + - "FROM DM_DEVICE_TYPE dt, " + - "DM_DEVICE d " + - "WHERE dt.NAME = ? " + - "AND PROVIDER_TENANT_ID = ? " + - "AND dt.ID = d.DEVICE_TYPE_ID " + - ") d1 " + - "WHERE d1.DEVICE_ID = ddi.DEVICE_ID " + - "AND ddi.KEY_FIELD = ? "; + "COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " + + "FROM DM_DEVICE_INFO ddi, " + + "(SELECT d.ID AS DEVICE_ID " + + "FROM DM_DEVICE_TYPE dt, " + + "DM_DEVICE d " + + "WHERE dt.NAME = ? " + + "AND PROVIDER_TENANT_ID = ? " + + "AND dt.ID = d.DEVICE_TYPE_ID " + + ") d1 " + + "WHERE d1.DEVICE_ID = ddi.DEVICE_ID " + + "AND ddi.KEY_FIELD = ? "; if (dataSourceType.contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2)) { sql += "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? "; } else if (dataSourceType.contains(DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL)) { @@ -977,7 +983,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while building or executing queries to retrieve the count " + - "of devices with an older OS build date"; + "of devices with an older OS build date"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index db30811c58..07bd3089ed 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -71,24 +71,25 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, " + - "(SELECT d.ID, " + - "d.DESCRIPTION, " + - "d.NAME, " + - "d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t "; + "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, " + + "d.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t "; //Add the query to filter active devices on timestamp if (since != null) { sql = sql + ", DM_DEVICE_DETAIL dt"; @@ -169,7 +170,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + - "registered devices"; + "registered devices"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -199,35 +200,36 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = getConnection(); String sql = "SELECT d1.DEVICE_ID, " + - "d1.DESCRIPTION, " + - "d1.NAME AS DEVICE_NAME, " + - "d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, " + - "(SELECT gd.DEVICE_ID, " + - "gd.DESCRIPTION, " + - "gd.NAME, " + - "gd.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM " + - "(SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, " + - "d.NAME, " + - "d.DEVICE_IDENTIFICATION, " + - "d.DEVICE_TYPE_ID " + - "FROM DM_DEVICE d, " + - "(SELECT dgm.DEVICE_ID " + - "FROM DM_DEVICE_GROUP_MAP dgm " + - "WHERE dgm.GROUP_ID = ?) dgm1 " + - "WHERE " + - "d.ID = dgm1.DEVICE_ID " + - "AND d.TENANT_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 gd.DEVICE_ID, " + + "gd.DESCRIPTION, " + + "gd.NAME, " + + "gd.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM " + + "(SELECT d.ID AS DEVICE_ID, " + + "d.DESCRIPTION, " + + "d.NAME, " + + "d.DEVICE_IDENTIFICATION, " + + "d.DEVICE_TYPE_ID " + + "FROM DM_DEVICE d, " + + "(SELECT dgm.DEVICE_ID " + + "FROM DM_DEVICE_GROUP_MAP dgm " + + "WHERE dgm.GROUP_ID = ?) dgm1 " + + "WHERE " + + "d.ID = dgm1.DEVICE_ID " + + "AND d.TENANT_ID = ?"; //Add the query for device-name if (deviceName != null && !deviceName.isEmpty()) { sql = sql + " AND d.NAME LIKE ?"; @@ -309,7 +311,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of" + - " devices belonging to group : " + groupId; + " devices belonging to group : " + groupId; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -323,12 +325,12 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," - + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " - + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " - + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " - + "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " - + "AND t.ID = d.DEVICE_TYPE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE," + + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + + "e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + + "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "AND t.ID = d.DEVICE_TYPE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, request.getOwner()); @@ -342,7 +344,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + - request.getOwner() + "'", e); + request.getOwner() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -358,7 +360,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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.NAME, " + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " @@ -378,7 +380,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + - "'" + request.getDeviceName() + "'", e); + "'" + request.getDeviceName() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -394,8 +396,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " - + "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " - + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + + "d.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 (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, " + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " @@ -414,7 +416,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + - "'" + request.getOwnership() + "'", e); + "'" + request.getOwnership() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -431,41 +433,43 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = getConnection(); String sql = "SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, " + - "d.NAME AS DEVICE_NAME, " + - "t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM (SELECT e.ID, " + - "e.DEVICE_ID, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_ENROLMENT, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ?"; + "d.DESCRIPTION, " + + "d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.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 (SELECT e.ID, " + + "e.DEVICE_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_ENROLMENT, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ?"; if (statusList == null || statusList.isEmpty()) { String msg = "Error occurred while fetching the list of devices. Status List can't " + - "be null or empty"; + "be null or empty"; log.error(msg); throw new DeviceManagementDAOException(msg); } sql += buildStatusQuery(statusList); sql += ") e," + - "DM_DEVICE d," + - "DM_DEVICE_TYPE t" + - "WHERE DEVICE_ID = e.DEVICE_ID" + - "AND d.DEVICE_TYPE_ID = t.ID" + - "AND d.TENANT_ID = ?" + - "LIMIT ?,?"; + "DM_DEVICE d," + + "DM_DEVICE_TYPE t" + + "WHERE DEVICE_ID = e.DEVICE_ID" + + "AND d.DEVICE_TYPE_ID = t.ID" + + "AND d.TENANT_ID = ?" + + "LIMIT ?,?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIdx = 1; @@ -486,7 +490,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices that matches to status " + - request.getStatusList().toString(); + request.getStatusList().toString(); log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -502,21 +506,22 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { String ownership = request.getOwnership(); String sql = "SELECT " + - "d.ID AS DEVICE_ID, " + - "d.DESCRIPTION,d.NAME AS DEVICE_NAME, " + - "t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE," + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " + - "WHERE d.ID = e.DEVICE_ID AND " + - "d.DEVICE_TYPE_ID = t.ID AND " + - "e.TENANT_ID = ? AND " + - "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; + "d.ID AS DEVICE_ID, " + + "d.DESCRIPTION,d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.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_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " + + "WHERE d.ID = e.DEVICE_ID AND " + + "d.DEVICE_TYPE_ID = t.ID AND " + + "e.TENANT_ID = ? AND " + + "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; if (statusList != null && !statusList.isEmpty()) { sql += buildStatusQuery(statusList); isStatusProvided = true; @@ -553,7 +558,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + - "registered devices under tenant id " + tenantId; + "registered devices under tenant id " + tenantId; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -566,7 +571,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override public List getCountOfDevicesByDuration(PaginationRequest request, List statusList, int tenantId, - String fromDate, String toDate) + String fromDate, String toDate) throws DeviceManagementDAOException { List countList = new ArrayList<>(); String ownership = request.getOwnership(); @@ -576,7 +581,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { "SELECT " + "SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) AS ENROLMENT_DATE, " + "COUNT(SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10)) AS ENROLMENT_COUNT " + - "FROM DM_DEVICE AS d " + + "FROM DM_DEVICE AS d " + "INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " + "INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " + "AND e.TENANT_ID = ? " + @@ -640,7 +645,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } sqlBuilder.append(")"); return true; - }else { + } else { return false; } } @@ -673,7 +678,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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.NAME, " + "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + @@ -702,7 +707,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices corresponding" + - "to the mentioned filtering criteria"; + "to the mentioned filtering criteria"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } finally { @@ -735,6 +740,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { + "DM_ENROLMENT.DATE_OF_ENROLMENT, " + "DM_ENROLMENT.DATE_OF_LAST_UPDATE, " + "DM_ENROLMENT.STATUS, " + + "DM_ENROLMENT.IS_TRANSFERRED, " + "device_types.NAME AS DEVICE_TYPE " + "FROM DM_DEVICE " + "INNER JOIN DM_ENROLMENT ON " @@ -778,7 +784,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all registered devices " + - "according to device ids and the limit area."; + "according to device ids and the limit area."; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -792,8 +798,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { int index = 1; StringJoiner joiner = new StringJoiner(",", "SELECT " + - "COUNT(e.DEVICE_ID) AS DEVICE_ID "+ - "FROM DM_ENROLMENT AS e, DM_DEVICE AS f "+ + "COUNT(e.DEVICE_ID) AS DEVICE_ID " + + "FROM DM_ENROLMENT AS e, DM_DEVICE AS f " + "WHERE " + "e.DEVICE_ID=f.ID AND " + "e.DEVICE_ID IN (", ") AND e.TENANT_ID = ?"); @@ -836,41 +842,42 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { try { Long osValue = (Long) request.getProperty(Constants.OS_VALUE); Connection conn = getConnection(); - String sql="SELECT " + - "d1.DEVICE_TYPE, " + - "d1.DEVICE_ID, " + - "d1.DEVICE_NAME, " + - "d1.DESCRIPTION, " + - "d1.DEVICE_IDENTIFICATION, " + - "ddd.OS_VERSION, " + - "e.ID AS ENROLMENT_ID, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT " + - "FROM DM_DEVICE_INFO ddi, " + - "DM_DEVICE_DETAIL ddd, " + - "DM_ENROLMENT e, " + - "(SELECT dt.NAME AS DEVICE_TYPE, " + - "d.ID AS DEVICE_ID, " + - "d.NAME AS DEVICE_NAME, " + - "DESCRIPTION, " + - "DEVICE_IDENTIFICATION " + - " FROM DM_DEVICE_TYPE dt, " + - "DM_DEVICE d " + - "WHERE dt.NAME = ? " + - "AND PROVIDER_TENANT_ID = ? " + - "AND dt.ID = d.DEVICE_TYPE_ID " + - ") d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID " + - "AND d1.DEVICE_ID = ddi.DEVICE_ID " + - "AND d1.DEVICE_ID = ddd.DEVICE_ID " + - "AND ddi.KEY_FIELD = ? " + - "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " + - "ORDER BY ENROLMENT_ID " + - "OFFSET ? ROWS " + - "FETCH NEXT ? ROWS ONLY"; + String sql = "SELECT " + + "d1.DEVICE_TYPE, " + + "d1.DEVICE_ID, " + + "d1.DEVICE_NAME, " + + "d1.DESCRIPTION, " + + "d1.DEVICE_IDENTIFICATION, " + + "ddd.OS_VERSION, " + + "e.ID AS ENROLMENT_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT " + + "FROM DM_DEVICE_INFO ddi, " + + "DM_DEVICE_DETAIL ddd, " + + "DM_ENROLMENT e, " + + "(SELECT dt.NAME AS DEVICE_TYPE, " + + "d.ID AS DEVICE_ID, " + + "d.NAME AS DEVICE_NAME, " + + "DESCRIPTION, " + + "DEVICE_IDENTIFICATION " + + " FROM DM_DEVICE_TYPE dt, " + + "DM_DEVICE d " + + "WHERE dt.NAME = ? " + + "AND PROVIDER_TENANT_ID = ? " + + "AND dt.ID = d.DEVICE_TYPE_ID " + + ") d1 " + + "WHERE d1.DEVICE_ID = e.DEVICE_ID " + + "AND d1.DEVICE_ID = ddi.DEVICE_ID " + + "AND d1.DEVICE_ID = ddd.DEVICE_ID " + + "AND ddi.KEY_FIELD = ? " + + "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " + + "ORDER BY ENROLMENT_ID " + + "OFFSET ? ROWS " + + "FETCH NEXT ? ROWS ONLY"; try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, request.getDeviceType()); @@ -894,7 +901,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while building or executing queries to retrieve information " + - "of devices with an older OS build date"; + "of devices with an older OS build date"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -906,18 +913,18 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { try { Connection conn = getConnection(); String sql = "SELECT " + - "COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " + - "FROM DM_DEVICE_INFO ddi, " + - "(SELECT d.ID AS DEVICE_ID " + - "FROM DM_DEVICE_TYPE dt, " + - "DM_DEVICE d " + - "WHERE dt.NAME = ? " + - "AND PROVIDER_TENANT_ID = ? " + - "AND dt.ID = d.DEVICE_TYPE_ID " + - ") d1 " + - "WHERE d1.DEVICE_ID = ddi.DEVICE_ID " + - "AND ddi.KEY_FIELD = ? " + - "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?"; + "COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " + + "FROM DM_DEVICE_INFO ddi, " + + "(SELECT d.ID AS DEVICE_ID " + + "FROM DM_DEVICE_TYPE dt, " + + "DM_DEVICE d " + + "WHERE dt.NAME = ? " + + "AND PROVIDER_TENANT_ID = ? " + + "AND dt.ID = d.DEVICE_TYPE_ID " + + ") d1 " + + "WHERE d1.DEVICE_ID = ddi.DEVICE_ID " + + "AND ddi.KEY_FIELD = ? " + + "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?"; try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, deviceType); @@ -934,7 +941,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while building or executing queries to retrieve the count " + - "of devices with an older OS build date"; + "of devices with an older OS build date"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index d4a6ba853e..da1c8a2630 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -70,26 +70,27 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, " + - "(SELECT d.ID, " + - "d.DESCRIPTION, " + - "d.NAME, " + - "d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t " + - "WHERE DEVICE_TYPE_ID = t.ID " + - "AND d.TENANT_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, " + + "d.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t " + + "WHERE DEVICE_TYPE_ID = t.ID " + + "AND d.TENANT_ID = ?"; //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -157,7 +158,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + - "registered devices"; + "registered devices"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -187,34 +188,35 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = getConnection(); String sql = "SELECT d1.DEVICE_ID, " + - "d1.DESCRIPTION, " + - "d1.NAME AS DEVICE_NAME, " + - "d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, " + - "(SELECT gd.DEVICE_ID, " + - "gd.DESCRIPTION, " + - "gd.NAME, " + - "gd.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM " + - "(SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, " + - "d.NAME, " + - "d.DEVICE_IDENTIFICATION, " + - "d.DEVICE_TYPE_ID " + - "FROM DM_DEVICE d, " + - "(SELECT dgm.DEVICE_ID " + - "FROM DM_DEVICE_GROUP_MAP dgm " + - "WHERE dgm.GROUP_ID = ?) dgm1 " + - "WHERE d.ID = dgm1.DEVICE_ID " + - "AND d.TENANT_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 gd.DEVICE_ID, " + + "gd.DESCRIPTION, " + + "gd.NAME, " + + "gd.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM " + + "(SELECT d.ID AS DEVICE_ID, " + + "d.DESCRIPTION, " + + "d.NAME, " + + "d.DEVICE_IDENTIFICATION, " + + "d.DEVICE_TYPE_ID " + + "FROM DM_DEVICE d, " + + "(SELECT dgm.DEVICE_ID " + + "FROM DM_DEVICE_GROUP_MAP dgm " + + "WHERE dgm.GROUP_ID = ?) dgm1 " + + "WHERE d.ID = dgm1.DEVICE_ID " + + "AND d.TENANT_ID = ?"; //Add the query for device-name if (deviceName != null && !deviceName.isEmpty()) { sql = sql + " AND d.NAME LIKE ?"; @@ -296,7 +298,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of" + - " devices belonging to group : " + groupId; + " devices belonging to group : " + groupId; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -310,12 +312,12 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," + - " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + - "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + - "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + - "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + - "AND t.ID = d.DEVICE_TYPE_ID LIMIT ? OFFSET ?"; + String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE," + + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + + "e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + + "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "AND t.ID = d.DEVICE_TYPE_ID LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, request.getOwner()); @@ -329,7 +331,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + - request.getOwner() + "'", e); + request.getOwner() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -345,11 +347,11 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + - "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + - "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?"; + "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.NAME, " + + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, request.getDeviceName() + "%"); stmt.setInt(2, tenantId); @@ -364,7 +366,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + - "'" + request.getDeviceName() + "'", e); + "'" + request.getDeviceName() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -380,11 +382,11 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + - "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ? OFFSET ?"; + "d.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 (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, request.getOwnership()); @@ -399,7 +401,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + - "'" + request.getOwnership() + "'", e); + "'" + request.getOwnership() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -416,39 +418,41 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = getConnection(); String sql = "SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, " + - "d.NAME AS DEVICE_NAME, " + - "t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM " + - "(SELECT e.ID, " + - "e.DEVICE_ID, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_ENROLMENT, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ?"; + "d.DESCRIPTION, " + + "d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.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 " + + "(SELECT e.ID, " + + "e.DEVICE_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_ENROLMENT, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ?"; if (statusList == null || statusList.isEmpty()) { String msg = "Error occurred while fetching the list of devices. Status List can't " + - "be null or empty"; + "be null or empty"; log.error(msg); throw new DeviceManagementDAOException(msg); } sql += buildStatusQuery(statusList); sql += ") e, " + - "DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID " + - "AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? " + - "LIMIT ? OFFSET ?"; + "DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID " + + "AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? " + + "LIMIT ? OFFSET ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIdx = 1; @@ -470,7 +474,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices that matches to status " + - request.getStatusList().toString(); + request.getStatusList().toString(); log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -486,21 +490,22 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { String ownership = request.getOwnership(); String sql = "SELECT " + - "d.ID AS DEVICE_ID, " + - "d.DESCRIPTION,d.NAME AS DEVICE_NAME, " + - "t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE," + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " + - "WHERE d.ID = e.DEVICE_ID AND " + - "d.DEVICE_TYPE_ID = t.ID AND " + - "e.TENANT_ID = ? AND " + - "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; + "d.ID AS DEVICE_ID, " + + "d.DESCRIPTION,d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.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_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " + + "WHERE d.ID = e.DEVICE_ID AND " + + "d.DEVICE_TYPE_ID = t.ID AND " + + "e.TENANT_ID = ? AND " + + "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; if (statusList != null && !statusList.isEmpty()) { sql += buildStatusQuery(statusList); isStatusProvided = true; @@ -537,7 +542,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + - "registered devices under tenant id " + tenantId; + "registered devices under tenant id " + tenantId; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -550,7 +555,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override public List getCountOfDevicesByDuration(PaginationRequest request, List statusList, int tenantId, - String fromDate, String toDate) + String fromDate, String toDate) throws DeviceManagementDAOException { List countList = new ArrayList<>(); String ownership = request.getOwnership(); @@ -560,7 +565,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { "SELECT " + "SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) AS ENROLMENT_DATE, " + "COUNT(SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10)) AS ENROLMENT_COUNT " + - "FROM DM_DEVICE AS d " + + "FROM DM_DEVICE AS d " + "INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " + "INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " + "AND e.TENANT_ID = ? " + @@ -624,7 +629,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } sqlBuilder.append(")"); return true; - }else { + } else { return false; } } @@ -658,11 +663,11 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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.NAME, " + - "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + - ") d1 WHERE d1.ID = e.DEVICE_ID OFFSET ? LIMIT ?"; + "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + + ") d1 WHERE d1.ID = e.DEVICE_ID OFFSET ? LIMIT ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -688,7 +693,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices corresponding" + - "to the mentioned filtering criteria"; + "to the mentioned filtering criteria"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } finally { @@ -721,6 +726,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { + "DM_ENROLMENT.DATE_OF_ENROLMENT, " + "DM_ENROLMENT.DATE_OF_LAST_UPDATE, " + "DM_ENROLMENT.STATUS, " + + "DM_ENROLMENT.IS_TRANSFERRED, " + "device_types.NAME AS DEVICE_TYPE " + "FROM DM_DEVICE " + "INNER JOIN DM_ENROLMENT ON " @@ -764,7 +770,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all registered devices " + - "according to device ids and the limit area."; + "according to device ids and the limit area."; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -778,8 +784,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { int index = 1; StringJoiner joiner = new StringJoiner(",", "SELECT " + - "COUNT(e.DEVICE_ID) AS DEVICE_ID "+ - "FROM DM_ENROLMENT AS e, DM_DEVICE AS f "+ + "COUNT(e.DEVICE_ID) AS DEVICE_ID " + + "FROM DM_ENROLMENT AS e, DM_DEVICE AS f " + "WHERE " + "e.DEVICE_ID=f.ID AND " + "e.DEVICE_ID IN (", ") AND e.TENANT_ID = ?"); @@ -822,39 +828,40 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { try { Long osValue = (Long) request.getProperty(Constants.OS_VALUE); Connection conn = getConnection(); - String sql="SELECT " + - "d1.DEVICE_TYPE, " + - "d1.DEVICE_ID, " + - "d1.DEVICE_NAME, " + - "d1.DESCRIPTION, " + - "d1.DEVICE_IDENTIFICATION, " + - "ddd.OS_VERSION, " + - "e.ID AS ENROLMENT_ID, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT " + - "FROM DM_DEVICE_INFO ddi, " + - "DM_DEVICE_DETAIL ddd, " + - "DM_ENROLMENT e, " + - "(SELECT dt.NAME AS DEVICE_TYPE, " + - "d.ID AS DEVICE_ID, " + - "d.NAME AS DEVICE_NAME, " + - "DESCRIPTION, " + - "DEVICE_IDENTIFICATION " + - " FROM DM_DEVICE_TYPE dt, " + - "DM_DEVICE d " + - "WHERE dt.NAME = ? " + - "AND PROVIDER_TENANT_ID = ? " + - "AND dt.ID = d.DEVICE_TYPE_ID " + - ") d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID " + - "AND d1.DEVICE_ID = ddi.DEVICE_ID " + - "AND d1.DEVICE_ID = ddd.DEVICE_ID " + - "AND ddi.KEY_FIELD = ? " + - "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " + - "LIMIT ? OFFSET ?"; + String sql = "SELECT " + + "d1.DEVICE_TYPE, " + + "d1.DEVICE_ID, " + + "d1.DEVICE_NAME, " + + "d1.DESCRIPTION, " + + "d1.DEVICE_IDENTIFICATION, " + + "ddd.OS_VERSION, " + + "e.ID AS ENROLMENT_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT " + + "FROM DM_DEVICE_INFO ddi, " + + "DM_DEVICE_DETAIL ddd, " + + "DM_ENROLMENT e, " + + "(SELECT dt.NAME AS DEVICE_TYPE, " + + "d.ID AS DEVICE_ID, " + + "d.NAME AS DEVICE_NAME, " + + "DESCRIPTION, " + + "DEVICE_IDENTIFICATION " + + " FROM DM_DEVICE_TYPE dt, " + + "DM_DEVICE d " + + "WHERE dt.NAME = ? " + + "AND PROVIDER_TENANT_ID = ? " + + "AND dt.ID = d.DEVICE_TYPE_ID " + + ") d1 " + + "WHERE d1.DEVICE_ID = e.DEVICE_ID " + + "AND d1.DEVICE_ID = ddi.DEVICE_ID " + + "AND d1.DEVICE_ID = ddd.DEVICE_ID " + + "AND ddi.KEY_FIELD = ? " + + "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " + + "LIMIT ? OFFSET ?"; try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, request.getDeviceType()); @@ -878,7 +885,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while building or executing queries to retrieve information " + - "of devices with an older OS build date"; + "of devices with an older OS build date"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -890,18 +897,18 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { try { Connection conn = getConnection(); String sql = "SELECT " + - "COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " + - "FROM DM_DEVICE_INFO ddi, " + - "(SELECT d.ID AS DEVICE_ID " + - "FROM DM_DEVICE_TYPE dt, " + - "DM_DEVICE d " + - "WHERE dt.NAME = ? " + - "AND PROVIDER_TENANT_ID = ? " + - "AND dt.ID = d.DEVICE_TYPE_ID " + - ") d1 " + - "WHERE d1.DEVICE_ID = ddi.DEVICE_ID " + - "AND ddi.KEY_FIELD = ? " + - "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?"; + "COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " + + "FROM DM_DEVICE_INFO ddi, " + + "(SELECT d.ID AS DEVICE_ID " + + "FROM DM_DEVICE_TYPE dt, " + + "DM_DEVICE d " + + "WHERE dt.NAME = ? " + + "AND PROVIDER_TENANT_ID = ? " + + "AND dt.ID = d.DEVICE_TYPE_ID " + + ") d1 " + + "WHERE d1.DEVICE_ID = ddi.DEVICE_ID " + + "AND ddi.KEY_FIELD = ? " + + "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?"; try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, deviceType); @@ -918,7 +925,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while building or executing queries to retrieve the count " + - "of devices with an older OS build date"; + "of devices with an older OS build date"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 64e8912db3..7aa74a1f1c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -72,23 +72,24 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, " + - "(SELECT d.ID, " + - "d.DESCRIPTION, " + - "d.NAME, " + - "d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM DM_DEVICE d, DM_DEVICE_TYPE t "; + "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, " + + "d.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE d, DM_DEVICE_TYPE t "; //Add the query to filter active devices on timestamp if (since != null) { sql = sql + ", DM_DEVICE_DETAIL dt"; @@ -169,7 +170,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + - "registered devices"; + "registered devices"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -199,34 +200,35 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = getConnection(); String sql = "SELECT d1.DEVICE_ID, " + - "d1.DESCRIPTION, " + - "d1.NAME AS DEVICE_NAME, " + - "d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, " + - "(SELECT gd.DEVICE_ID, " + - "gd.DESCRIPTION, " + - "gd.NAME, " + - "gd.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE " + - "FROM " + - "(SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, " + - "d.NAME, " + - "d.DEVICE_IDENTIFICATION, " + - "d.DEVICE_TYPE_ID " + - "FROM DM_DEVICE d, " + - "(SELECT dgm.DEVICE_ID " + - "FROM DM_DEVICE_GROUP_MAP dgm " + - "WHERE dgm.GROUP_ID = ?) dgm1 " + - "WHERE d.ID = dgm1.DEVICE_ID " + - "AND d.TENANT_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 gd.DEVICE_ID, " + + "gd.DESCRIPTION, " + + "gd.NAME, " + + "gd.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE " + + "FROM " + + "(SELECT d.ID AS DEVICE_ID, " + + "d.DESCRIPTION, " + + "d.NAME, " + + "d.DEVICE_IDENTIFICATION, " + + "d.DEVICE_TYPE_ID " + + "FROM DM_DEVICE d, " + + "(SELECT dgm.DEVICE_ID " + + "FROM DM_DEVICE_GROUP_MAP dgm " + + "WHERE dgm.GROUP_ID = ?) dgm1 " + + "WHERE d.ID = dgm1.DEVICE_ID " + + "AND d.TENANT_ID = ?"; //Add the query for device-name if (deviceName != null && !deviceName.isEmpty()) { sql = sql + " AND d.NAME LIKE ?"; @@ -308,7 +310,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of" + - " devices belonging to group : " + groupId; + " devices belonging to group : " + groupId; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -322,12 +324,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { List devices = new ArrayList<>(); try { conn = this.getConnection(); - String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," + - " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + - "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + - "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + - "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + - "AND t.ID = d.DEVICE_TYPE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, e1.DATE_OF_LAST_UPDATE," + + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + + "e.DEVICE_ID, e.STATUS, e.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + + "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "AND t.ID = d.DEVICE_TYPE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, request.getOwner()); @@ -341,7 +343,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + - request.getOwner() + "'", e); + request.getOwner() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -357,12 +359,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + - "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + - "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY ENROLMENT_ID " + - "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + "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.NAME, " + + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY ENROLMENT_ID " + + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setString(1, request.getDeviceName() + "%"); stmt.setInt(2, tenantId); @@ -377,7 +379,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches " + - "'" + request.getDeviceName() + "'", e); + "'" + request.getDeviceName() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -393,12 +395,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + - "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " + - "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + "d.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 (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, e.IS_TRANSFERRED, " + + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " + + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, request.getOwnership()); @@ -413,7 +415,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + - "'" + request.getOwnership() + "'", e); + "'" + request.getOwnership() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -430,41 +432,43 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = getConnection(); String sql = "SELECT d.ID AS DEVICE_ID, " + - "d.DESCRIPTION, " + - "d.NAME AS DEVICE_NAME, " + - "t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM " + - "(SELECT e.ID, " + - "e.DEVICE_ID, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_ENROLMENT, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e " + - "WHERE TENANT_ID = ?"; + "d.DESCRIPTION, " + + "d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.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 " + + "(SELECT e.ID, " + + "e.DEVICE_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_ENROLMENT, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e " + + "WHERE TENANT_ID = ?"; if (statusList == null || statusList.isEmpty()) { String msg = "Error occurred while fetching the list of devices. Status List can't " + - "be null or empty"; + "be null or empty"; log.error(msg); throw new DeviceManagementDAOException(msg); } sql += buildStatusQuery(statusList); sql += ") e, " + - "DM_DEVICE d, " + - "DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID " + - "AND d.DEVICE_TYPE_ID = t.ID " + - "AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " + - "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + "DM_DEVICE d, " + + "DM_DEVICE_TYPE t " + + "WHERE DEVICE_ID = e.DEVICE_ID " + + "AND d.DEVICE_TYPE_ID = t.ID " + + "AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " + + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { int paramIdx = 1; @@ -486,7 +490,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices that matches to status " + - request.getStatusList().toString(); + request.getStatusList().toString(); log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -520,11 +524,11 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { try { conn = this.getConnection(); String sql = "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.DATE_OF_LAST_UPDATE, " + + "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.NAME, " + - "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + - ") d1 WHERE d1.ID = e.DEVICE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + + ") d1 WHERE d1.ID = e.DEVICE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -550,7 +554,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices corresponding" + - "to the mentioned filtering criteria"; + "to the mentioned filtering criteria"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } finally { @@ -583,6 +587,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { + "DM_ENROLMENT.DATE_OF_ENROLMENT, " + "DM_ENROLMENT.DATE_OF_LAST_UPDATE, " + "DM_ENROLMENT.STATUS, " + + "DM_ENROLMENT.IS_TRANSFERRED, " + "device_types.NAME AS DEVICE_TYPE " + "FROM DM_DEVICE " + "INNER JOIN DM_ENROLMENT ON " @@ -626,7 +631,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all registered devices " + - "according to device ids and the limit area."; + "according to device ids and the limit area."; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -638,39 +643,40 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { try { Long osValue = (Long) request.getProperty(Constants.OS_VALUE); Connection conn = getConnection(); - String sql="SELECT " + - "d1.DEVICE_TYPE, " + - "d1.DEVICE_ID, " + - "d1.DEVICE_NAME, " + - "d1.DESCRIPTION, " + - "d1.DEVICE_IDENTIFICATION, " + - "ddd.OS_VERSION, " + - "e.ID AS ENROLMENT_ID, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT " + - "FROM DM_DEVICE_INFO ddi, " + - "DM_DEVICE_DETAIL ddd, " + - "DM_ENROLMENT e, " + - "(SELECT dt.NAME AS DEVICE_TYPE, " + - "d.ID AS DEVICE_ID, " + - "d.NAME AS DEVICE_NAME, " + - "DESCRIPTION, " + - "DEVICE_IDENTIFICATION " + - " FROM DM_DEVICE_TYPE dt, " + - "DM_DEVICE d " + - "WHERE dt.NAME = ? " + - "AND PROVIDER_TENANT_ID = ? " + - "AND dt.ID = d.DEVICE_TYPE_ID " + - ") d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID " + - "AND d1.DEVICE_ID = ddi.DEVICE_ID " + - "AND d1.DEVICE_ID = ddd.DEVICE_ID " + - "AND ddi.KEY_FIELD = ? " + - "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " + - "LIMIT ? OFFSET ?"; + String sql = "SELECT " + + "d1.DEVICE_TYPE, " + + "d1.DEVICE_ID, " + + "d1.DEVICE_NAME, " + + "d1.DESCRIPTION, " + + "d1.DEVICE_IDENTIFICATION, " + + "ddd.OS_VERSION, " + + "e.ID AS ENROLMENT_ID, " + + "e.OWNER, " + + "e.OWNERSHIP, " + + "e.STATUS, " + + "e.IS_TRANSFERRED, " + + "e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT " + + "FROM DM_DEVICE_INFO ddi, " + + "DM_DEVICE_DETAIL ddd, " + + "DM_ENROLMENT e, " + + "(SELECT dt.NAME AS DEVICE_TYPE, " + + "d.ID AS DEVICE_ID, " + + "d.NAME AS DEVICE_NAME, " + + "DESCRIPTION, " + + "DEVICE_IDENTIFICATION " + + " FROM DM_DEVICE_TYPE dt, " + + "DM_DEVICE d " + + "WHERE dt.NAME = ? " + + "AND PROVIDER_TENANT_ID = ? " + + "AND dt.ID = d.DEVICE_TYPE_ID " + + ") d1 " + + "WHERE d1.DEVICE_ID = e.DEVICE_ID " + + "AND d1.DEVICE_ID = ddi.DEVICE_ID " + + "AND d1.DEVICE_ID = ddd.DEVICE_ID " + + "AND ddi.KEY_FIELD = ? " + + "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ? " + + "LIMIT ? OFFSET ?"; try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, request.getDeviceType()); @@ -694,7 +700,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while building or executing queries to retrieve information " + - "of devices with an older OS build date"; + "of devices with an older OS build date"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -706,18 +712,18 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { try { Connection conn = getConnection(); String sql = "SELECT " + - "COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " + - "FROM DM_DEVICE_INFO ddi, " + - "(SELECT d.ID AS DEVICE_ID " + - "FROM DM_DEVICE_TYPE dt, " + - "DM_DEVICE d " + - "WHERE dt.NAME = ? " + - "AND PROVIDER_TENANT_ID = ? " + - "AND dt.ID = d.DEVICE_TYPE_ID " + - ") d1 " + - "WHERE d1.DEVICE_ID = ddi.DEVICE_ID " + - "AND ddi.KEY_FIELD = ? " + - "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?"; + "COUNT(ddi.DEVICE_ID) AS DEVICE_COUNT " + + "FROM DM_DEVICE_INFO ddi, " + + "(SELECT d.ID AS DEVICE_ID " + + "FROM DM_DEVICE_TYPE dt, " + + "DM_DEVICE d " + + "WHERE dt.NAME = ? " + + "AND PROVIDER_TENANT_ID = ? " + + "AND dt.ID = d.DEVICE_TYPE_ID " + + ") d1 " + + "WHERE d1.DEVICE_ID = ddi.DEVICE_ID " + + "AND ddi.KEY_FIELD = ? " + + "AND CAST( ddi.VALUE_FIELD AS BIGINT ) < ?"; try (PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, deviceType); @@ -734,7 +740,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while building or executing queries to retrieve the count " + - "of devices with an older OS build date"; + "of devices with an older OS build date"; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -754,21 +760,22 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { String ownership = request.getOwnership(); String sql = "SELECT " + - "d.ID AS DEVICE_ID, " + - "d.DESCRIPTION,d.NAME AS DEVICE_NAME, " + - "t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, " + - "e.OWNER, " + - "e.OWNERSHIP, " + - "e.STATUS, " + - "e.DATE_OF_LAST_UPDATE," + - "e.DATE_OF_ENROLMENT, " + - "e.ID AS ENROLMENT_ID " + - "FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " + - "WHERE d.ID = e.DEVICE_ID AND " + - "d.DEVICE_TYPE_ID = t.ID AND " + - "e.TENANT_ID = ? AND " + - "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; + "d.ID AS DEVICE_ID, " + + "d.DESCRIPTION,d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.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_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " + + "WHERE d.ID = e.DEVICE_ID AND " + + "d.DEVICE_TYPE_ID = t.ID AND " + + "e.TENANT_ID = ? AND " + + "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; if (statusList != null && !statusList.isEmpty()) { sql += buildStatusQuery(statusList); isStatusProvided = true; @@ -805,7 +812,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + - "registered devices under tenant id " + tenantId; + "registered devices under tenant id " + tenantId; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } @@ -818,7 +825,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override public List getCountOfDevicesByDuration(PaginationRequest request, List statusList, int tenantId, - String fromDate, String toDate) + String fromDate, String toDate) throws DeviceManagementDAOException { List countList = new ArrayList<>(); String ownership = request.getOwnership(); @@ -828,7 +835,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "SELECT " + "SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) AS ENROLMENT_DATE, " + "COUNT(SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10)) AS ENROLMENT_COUNT " + - "FROM DM_DEVICE AS d " + + "FROM DM_DEVICE AS d " + "INNER JOIN DM_ENROLMENT AS e ON d.ID = e.DEVICE_ID " + "INNER JOIN DM_DEVICE_TYPE AS t ON d.DEVICE_TYPE_ID = t.ID " + "AND e.TENANT_ID = ? " + @@ -892,7 +899,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } sqlBuilder.append(")"); return true; - }else { + } else { return false; } } @@ -905,8 +912,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { int index = 1; StringJoiner joiner = new StringJoiner(",", "SELECT " + - "COUNT(e.DEVICE_ID) AS DEVICE_ID "+ - "FROM DM_ENROLMENT AS e, DM_DEVICE AS f "+ + "COUNT(e.DEVICE_ID) AS DEVICE_ID " + + "FROM DM_ENROLMENT AS e, DM_DEVICE AS f " + "WHERE " + "e.DEVICE_ID=f.ID AND " + "e.DEVICE_ID IN (", ") AND e.TENANT_ID = ?"); @@ -945,7 +952,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override public List findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, - int geohashLength, int tenantId) throws DeviceManagementDAOException { + int geohashLength, int tenantId) throws DeviceManagementDAOException { List geoClusters = new ArrayList<>(); try { Connection conn = this.getConnection(); @@ -978,14 +985,14 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { + southWest.getLongitude() + " AND " + northEast.getLongitude() - +" AND " - + "DEVICE.TENANT_ID = " + tenantId +" AND " + + " AND " + + "DEVICE.TENANT_ID = " + tenantId + " AND " + "DEVICE.ID = DEVICE_LOCATION.DEVICE_ID AND " + "DEVICE.DEVICE_TYPE_ID = DEVICE_TYPE.ID "; if (deviceType != null && !deviceType.isEmpty()) { sql += "AND DEVICE_TYPE.NAME = " + deviceType; } - sql += "GROUP BY SUBSTRING(DEVICE_LOCATION.GEO_HASH,1,"+ geohashLength + ")"; + sql += "GROUP BY SUBSTRING(DEVICE_LOCATION.GEO_HASH,1," + geohashLength + ")"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (ResultSet rs = stmt.executeQuery()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java index ed64cc403a..d980e9e0ab 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/GenericGroupDAOImpl.java @@ -177,7 +177,7 @@ public class GenericGroupDAOImpl extends AbstractGroupDAOImpl { try { conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "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 gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "FROM " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/OracleGroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/OracleGroupDAOImpl.java index 68965a0ea7..4074840e0f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/OracleGroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/OracleGroupDAOImpl.java @@ -178,7 +178,7 @@ public class OracleGroupDAOImpl extends AbstractGroupDAOImpl { try { conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "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 gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "FROM " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/PostgreSQLGroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/PostgreSQLGroupDAOImpl.java index 07033c5033..4140a5c48a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/PostgreSQLGroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/PostgreSQLGroupDAOImpl.java @@ -218,7 +218,7 @@ public class PostgreSQLGroupDAOImpl extends AbstractGroupDAOImpl { try { conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "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 gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "FROM " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java index 8cb41221fd..879d450349 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/group/SQLServerGroupDAOImpl.java @@ -178,7 +178,7 @@ public class SQLServerGroupDAOImpl extends AbstractGroupDAOImpl { try { conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "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 gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "FROM " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java index f5e37ee778..2ca18ace80 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java @@ -144,6 +144,7 @@ public final class DeviceManagementDAOUtil { enrolmentInfo.setId(rs.getInt("ENROLMENT_ID")); enrolmentInfo.setOwner(rs.getString("OWNER")); enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP"))); + enrolmentInfo.setTransferred(rs.getBoolean("IS_TRANSFERRED")); enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime()); enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime()); enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS"))); @@ -198,7 +199,6 @@ public final class DeviceManagementDAOUtil { //This method will retrieve most appropriate device information when there are multiple device enrollments for //a single device. Here we'll consider only active status. public static Device loadActiveDevice(ResultSet rs, boolean deviceInfoIncluded) throws SQLException { - Map deviceMap = new HashMap<>(); Device device = loadDevice(rs); if (deviceInfoIncluded) { device.setDeviceInfo(loadDeviceInfo(rs)); @@ -209,7 +209,6 @@ public final class DeviceManagementDAOUtil { //This method will retrieve most appropriate device information when there are multiple device enrollments for //a single device. We'll give the highest priority to active devices. public static Device loadMatchingDevice(ResultSet rs, boolean deviceInfoIncluded) throws SQLException { - Map deviceMap = new HashMap<>(); Device device = loadDevice(rs); if (deviceInfoIncluded) { device.setDeviceInfo(loadDeviceInfo(rs)); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java index 83c79a24dd..7e1253ed21 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java @@ -60,6 +60,8 @@ public interface DeviceInformationManager { */ DeviceInfo getDeviceInfo(DeviceIdentifier deviceIdentifier) throws DeviceDetailsMgtException; + DeviceInfo getDeviceInfo(Device device) throws DeviceDetailsMgtException; + /** * This method will return device information for the supplied devices list. * @param deviceIdentifiers diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java index e8f0840f4c..9e69e3875d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java @@ -273,8 +273,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { conn = this.getConnection(); stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_LOCATION (DEVICE_ID, LATITUDE, LONGITUDE, STREET1, " + "STREET2, CITY, ZIP, STATE, COUNTRY, GEO_HASH, UPDATE_TIMESTAMP, ENROLMENT_ID, ALTITUDE, SPEED, BEARING, " + - "DISTANCE) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + "DISTANCE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setInt(1, deviceLocation.getDeviceId()); stmt.setDouble(2, deviceLocation.getLatitude()); stmt.setDouble(3, deviceLocation.getLongitude()); 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 b1133a02b4..5f8132df34 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 @@ -64,7 +64,7 @@ import java.util.Map; public class DeviceInformationManagerImpl implements DeviceInformationManager { - private DeviceDetailsDAO deviceDetailsDAO; + private final DeviceDetailsDAO deviceDetailsDAO; private DeviceDAO deviceDAO; private static final Log log = LogFactory.getLog(DeviceInformationManagerImpl.class); private static final String LOCATION_EVENT_STREAM_DEFINITION = "org.wso2.iot.LocationStream"; @@ -117,7 +117,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { addOSVersionValue(device, newDeviceInfo); for (String key : newDeviceInfo.getDeviceDetailsMap().keySet()) { if (previousDeviceProperties.containsKey(key)) { - updatableProps.put(key, newDeviceInfo.getDeviceDetailsMap().get(key)); + String val = previousDeviceProperties.get(key); + if (val != null &&!val.equals(newDeviceInfo.getDeviceDetailsMap().get(key))) { + updatableProps.put(key, newDeviceInfo.getDeviceDetailsMap().get(key)); + } } else { injectableProps.put(key, newDeviceInfo.getDeviceDetailsMap().get(key)); } @@ -160,20 +163,17 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { ); } } catch (TransactionManagementException e) { - DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceDetailsMgtException("Transactional error occurred while adding the device information.", e); } catch (DeviceDetailsMgtDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceDetailsMgtException("Error occurred while adding the device information.", e); } catch (DeviceManagementException e) { - DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceDetailsMgtException("Error occurred while retrieving the device information.", e); } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceDetailsMgtException("Error occurred while updating the last update timestamp of the " + "device", e); } catch (DataPublisherConfigurationException e) { - DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e); } finally { DeviceManagementDAOFactory.closeConnection(); @@ -226,17 +226,30 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { if (device == null) { return null; } + return getDeviceInfo(device); + } + + @Override + public DeviceInfo getDeviceInfo(Device device) throws DeviceDetailsMgtException { try { DeviceManagementDAOFactory.openConnection(); DeviceInfo deviceInfo = deviceDetailsDAO.getDeviceInformation(device.getId(), device.getEnrolmentInfo().getId()); + if (deviceInfo == null) { + deviceInfo = new DeviceInfo(); + } deviceInfo.setDeviceDetailsMap(deviceDetailsDAO.getDeviceProperties(device.getId(), device.getEnrolmentInfo().getId())); + DeviceLocation location = deviceDetailsDAO.getDeviceLocation(device.getId(), + device.getEnrolmentInfo().getId()); + if (location != null) { + //There are some cases where the device-info is not updated properly. Hence returning a null value. + deviceInfo.setLocation(location); + } return deviceInfo; - } catch (SQLException e) { - throw new DeviceDetailsMgtException("SQL error occurred while retrieving device " + deviceId.toString() - + "'s info from database.", e); + throw new DeviceDetailsMgtException("SQL error occurred while retrieving device " + + device.getDeviceIdentifier() + "'s info from database.", e); } catch (DeviceDetailsMgtDAOException e) { throw new DeviceDetailsMgtException("Exception occurred while retrieving device details.", e); } finally { @@ -263,11 +276,21 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } } DeviceManagementDAOFactory.openConnection(); + DeviceInfo deviceInfo; for (Device device : deviceIds) { - DeviceInfo deviceInfo = deviceDetailsDAO.getDeviceInformation(device.getId(), + deviceInfo = deviceDetailsDAO.getDeviceInformation(device.getId(), device.getEnrolmentInfo().getId()); + if (deviceInfo == null) { + deviceInfo = new DeviceInfo(); + } deviceInfo.setDeviceDetailsMap(deviceDetailsDAO.getDeviceProperties(device.getId(), device.getEnrolmentInfo().getId())); + DeviceLocation location = deviceDetailsDAO.getDeviceLocation(device.getId(), + device.getEnrolmentInfo().getId()); + if (location != null) { + //There are some cases where the device-info is not updated properly. Hence returning a null value. + deviceInfo.setLocation(location); + } deviceInfos.add(deviceInfo); } } catch (SQLException e) { @@ -367,7 +390,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { if (device == null) { if (log.isDebugEnabled()) { log.debug("No device is found upon the device identifier '" + deviceId.getId() + - "' and type '" + deviceId.getType() + "'. Therefore returning null"); + "' and type '" + deviceId.getType() + "'. Therefore returning null"); } return null; } @@ -401,7 +424,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { throw new DeviceDetailsMgtException("SQL error occurred while retrieving device from database.", e); } catch (DeviceDetailsMgtDAOException e) { throw new DeviceDetailsMgtException("Exception occurred while retrieving device locations.", e); - } finally{ + } finally { DeviceManagementDAOFactory.closeConnection(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/OperationResponseMeta.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/OperationResponseMeta.java new file mode 100644 index 0000000000..20a839e4d0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/OperationResponseMeta.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.device.mgt.core.dto.operation.mgt; + +import java.sql.Timestamp; + +public class OperationResponseMeta { + + private int id; + private int enrolmentId; + private int operationMappingId; + private boolean isLargeResponse; + private Timestamp receivedTimestamp; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getEnrolmentId() { + return enrolmentId; + } + + public void setEnrolmentId(int enrolmentId) { + this.enrolmentId = enrolmentId; + } + + public int getOperationMappingId() { + return operationMappingId; + } + + public void setOperationMappingId(int operationMappingId) { + this.operationMappingId = operationMappingId; + } + + public boolean isLargeResponse() { + return isLargeResponse; + } + + public void setLargeResponse(boolean largeResponse) { + isLargeResponse = largeResponse; + } + + public Timestamp getReceivedTimestamp() { + return receivedTimestamp; + } + + public void setReceivedTimestamp(Timestamp receivedTimestamp) { + this.receivedTimestamp = receivedTimestamp; + } +} 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 f1cdd695a9..c948f6374f 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 @@ -28,6 +28,7 @@ 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; @@ -45,11 +46,13 @@ import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationExecu import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationProvider; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO; +import org.wso2.carbon.device.mgt.core.dto.operation.mgt.OperationResponseMeta; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationDAO; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; @@ -66,12 +69,14 @@ import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; +import java.util.Arrays; import java.util.Calendar; -import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; /** * This class implements all the functionality exposed as part of the OperationManager. Any transaction initiated @@ -84,19 +89,21 @@ public class OperationManagerImpl implements OperationManager { private static final int CACHE_VALIDITY_PERIOD = 5 * 60 * 1000; private static final String NOTIFIER_TYPE_LOCAL = "LOCAL"; private static final String SYSTEM = "system"; - - private OperationDAO commandOperationDAO; - private OperationDAO configOperationDAO; - private OperationDAO profileOperationDAO; - private OperationDAO policyOperationDAO; - private OperationMappingDAO operationMappingDAO; - private OperationDAO operationDAO; - private DeviceDAO deviceDAO; - private EnrollmentDAO enrollmentDAO; + public static final int maxOperationCacheSize = 100; + + private final OperationDAO commandOperationDAO; + private final OperationDAO configOperationDAO; + private final OperationDAO profileOperationDAO; + private final OperationDAO policyOperationDAO; + private final OperationMappingDAO operationMappingDAO; + private final OperationDAO operationDAO; + private final DeviceDAO deviceDAO; + private final EnrollmentDAO enrollmentDAO; private String deviceType; private DeviceManagementService deviceManagementService; - private Map notificationStrategies; - private Map lastUpdatedTimeStamps; + private final Map notificationStrategies; + private final Map lastUpdatedTimeStamps; + private final ConcurrentMap operationsInitBy; public OperationManagerImpl() { commandOperationDAO = OperationManagementDAOFactory.getCommandOperationDAO(); @@ -109,6 +116,7 @@ public class OperationManagerImpl implements OperationManager { enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); notificationStrategies = new HashMap<>(); lastUpdatedTimeStamps = new HashMap<>(); + operationsInitBy = new ConcurrentHashMap<>(); } public OperationManagerImpl(String deviceType, DeviceManagementService deviceManagementService) { @@ -124,7 +132,7 @@ public class OperationManagerImpl implements OperationManager { // type specific notification strategy. int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(false); long lastUpdatedTimeStamp = 0; - if (lastUpdatedTimeStamps.containsKey(tenantId)){ + if (lastUpdatedTimeStamps.containsKey(tenantId)) { lastUpdatedTimeStamp = lastUpdatedTimeStamps.get(tenantId); } if (Calendar.getInstance().getTimeInMillis() - lastUpdatedTimeStamp > CACHE_VALIDITY_PERIOD) { @@ -134,11 +142,11 @@ public class OperationManagerImpl implements OperationManager { .getPushNotificationProviderRepository().getProvider(pushNoteConfig.getType()); if (provider == null) { log.error("No registered push notification provider found for the type '" + - pushNoteConfig.getType() + "' under tenant ID '" + tenantId + "'."); + pushNoteConfig.getType() + "' under tenant ID '" + tenantId + "'."); return null; } notificationStrategies.put(tenantId, provider.getNotificationStrategy(pushNoteConfig)); - } else if (notificationStrategies.containsKey(tenantId)){ + } else if (notificationStrategies.containsKey(tenantId)) { notificationStrategies.remove(tenantId); } lastUpdatedTimeStamps.put(tenantId, Calendar.getInstance().getTimeInMillis()); @@ -159,140 +167,253 @@ public class OperationManagerImpl implements OperationManager { try { DeviceIDHolder deviceValidationResult = DeviceManagerUtil.validateDeviceIdentifiers(deviceIds); List validDeviceIds = deviceValidationResult.getValidDeviceIDList(); + if (validDeviceIds.size() > 0) { + DeviceIDHolder deviceAuthorizationResult = this.authorizeDevices(operation, validDeviceIds); + List authorizedDeviceIds = deviceAuthorizationResult.getValidDeviceIDList(); + if (authorizedDeviceIds.size() <= 0) { + log.warn("User : " + getUser() + " is not authorized to perform operations on given device-list."); + Activity activity = new Activity(); + //Send the operation statuses only for admin triggered operations + activity.setActivityStatus(this.getActivityStatus(deviceValidationResult, + deviceAuthorizationResult)); + return activity; + } - if (validDeviceIds.isEmpty()) { - String msg = "Invalid device Identifiers found."; - log.error(msg); - throw new InvalidDeviceException(msg); - } - if (log.isDebugEnabled() && deviceIds.get(0).getType() != null) { - log.debug("Adding operation for Device type : " + deviceIds.get(0).getType() + ", tenant ID:" - + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId() + ", domain:" - + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain() + ", device count:" - + deviceIds.size() + " operation type:" + operation.getCode()); - } - DeviceIDHolder deviceAuthorizationResult = this.authorizeDevices(operation, validDeviceIds); - List authorizedDeviceIds = deviceAuthorizationResult.getValidDeviceIDList(); - if (authorizedDeviceIds.isEmpty()) { - log.warn("User : " + getUser() + " is not authorized to perform operations on given device-list."); - Activity activity = new Activity(); - //Send the operation statuses only for admin triggered operations - activity.setActivityStatus( - this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult)); - return activity; - } + boolean isScheduledOperation = this.isTaskScheduledOperation(operation); + String initiatedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + if (initiatedBy == null && isScheduledOperation) { + if (log.isDebugEnabled()) { + log.debug("initiatedBy : " + SYSTEM); + } + operation.setInitiatedBy(SYSTEM); + } else { + if (log.isDebugEnabled()) { + log.debug("initiatedBy : " + initiatedBy); + } + operation.setInitiatedBy(initiatedBy); + } - boolean isScheduledOperation = this.isTaskScheduledOperation(operation); - String initiatedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - if (initiatedBy == null && isScheduledOperation) { - if (log.isDebugEnabled()) { - log.debug("initiatedBy : " + SYSTEM); + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto = + OperationDAOUtil.convertOperation(operation); + String operationCode = operationDto.getCode(); + Map enrolments = new HashMap<>(); + Device device; + for (DeviceIdentifier deviceId : authorizedDeviceIds) { + device = getDevice(deviceId); + enrolments.put(device.getEnrolmentInfo().getId(), device); } - operation.setInitiatedBy(SYSTEM); - } else { - if (log.isDebugEnabled()) { - log.debug("initiatedBy : " + initiatedBy); + + OperationManagementDAOFactory.beginTransaction(); + 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); + 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. + if (log.isDebugEnabled()) { + log.debug("All the devices contain a pending operation for the Operation Code: " + + 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; + } } - operation.setInitiatedBy(initiatedBy); - } - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto = OperationDAOUtil - .convertOperation(operation); - int enrolmentId; - String operationCode = operationDto.getCode(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + int operationId = this.lookupOperationDAO(operation).addOperation(operationDto); + operationDto.setId(operationId); - List authorizedDevices = new ArrayList<>(); - List ignoredDevices = new ArrayList<>(); - for (DeviceIdentifier deviceId : authorizedDeviceIds) { - Device device = getDevice(deviceId); - authorizedDevices.add(device); - } + boolean isScheduled = false; + NotificationStrategy notificationStrategy = getNotificationStrategy(); - OperationManagementDAOFactory.beginTransaction(); - if (operationDto.getControl() - == org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT) { - int existingOperationID; - for (Device device : authorizedDevices) { - enrolmentId = device.getEnrolmentInfo().getId(); - existingOperationID = operationDAO.getExistingOperationID(enrolmentId, operationCode); - if (existingOperationID > 0) { - ignoredDevices.add(device); - operation.setId(existingOperationID); - this.sendNotification(operation, device); + // 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 (!ignoredDevices.isEmpty()) { - if (authorizedDevices.size() == ignoredDevices.size()) { - if (log.isDebugEnabled()) { - log.debug( - "All the devices contain a pending operation for the Operation Code: " + operationCode); + if (!isScheduled && notificationStrategy != null) { + for (Device d : enrolments.values()) { + this.sendNotification(operation, d); } - Activity activity = new Activity(); - //Send the operation statuses only for admin triggered operations - activity.setActivityStatus( - this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult)); - return activity; - } else { - authorizedDevices.removeAll(ignoredDevices); } + + Activity activity = new Activity(); + activity.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + operationId); + 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)); + } + return activity; + } else { + throw new InvalidDeviceException("Invalid device Identifiers found."); } + } catch (OperationManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + throw new OperationManagementException("Error occurred while adding operation", e); + } catch (TransactionManagementException e) { + throw new OperationManagementException("Error occurred while initiating the transaction", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + } - int operationId = this.lookupOperationDAO(operation).addOperation(operationDto); - operation.setId(operationId); + @Override + public void addTaskOperation(String deviceType, Operation operation) throws OperationManagementException { + List validStatuses = Arrays.asList(EnrolmentInfo.Status.ACTIVE.toString(), + EnrolmentInfo.Status.INACTIVE.toString(), + EnrolmentInfo.Status.UNREACHABLE.toString()); + int batchSize = 2000; + try { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + PaginationRequest paginationRequest; + boolean hasRecords; + int start = 0; + OperationManagementDAOFactory.beginTransaction(); + DeviceManagementDAOFactory.beginTransaction(); + do { + paginationRequest = new PaginationRequest(start, batchSize); + paginationRequest.setStatusList(validStatuses); + paginationRequest.setDeviceType(deviceType); + List devices = deviceDAO.getDevices(paginationRequest, tenantId); + if (devices.size() == batchSize) { + hasRecords = true; + start += batchSize; + } else if (devices.size() == 0) { + break; + } else { + hasRecords = false; + } + 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. + break; + } + } - boolean isScheduled = false; - NotificationStrategy notificationStrategy = getNotificationStrategy(); + int operationId = this.lookupOperationDAO(operation).addOperation(operationDto); + operationDto.setId(operationId); - // 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(); - } + boolean isScheduled = false; + NotificationStrategy notificationStrategy = getNotificationStrategy(); - List enrolmentIds = new ArrayList<>(); - for (Device device : authorizedDevices) { - enrolmentId = device.getEnrolmentInfo().getId(); - enrolmentIds.add(enrolmentId); - } - operationMappingDAO.addOperationMapping(operationId, enrolmentIds, isScheduled); - OperationManagementDAOFactory.commitTransaction(); - if (!isScheduled && notificationStrategy != null) { - for (Device device : authorizedDevices) { - this.sendNotification(operation, device); + // 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(); } - } - - Activity activity = new Activity(); - activity.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + operationId); - 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) { - activity.setActivityStatus( - this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult)); - } - return activity; + 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); + } + } + try { + Thread.sleep(2000); + } catch (InterruptedException ignore) { + break; + } + } while (hasRecords); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while getting devices to add operations", e); } catch (OperationManagementDAOException e) { OperationManagementDAOFactory.rollbackTransaction(); throw new OperationManagementException("Error occurred while adding operation", e); } catch (TransactionManagementException e) { throw new OperationManagementException("Error occurred while initiating the transaction", e); } finally { + DeviceManagementDAOFactory.closeConnection(); OperationManagementDAOFactory.closeConnection(); } } private void sendNotification(Operation operation, Device device) { - if (log.isDebugEnabled()) { - log.debug("Sending notification for device id: " + device.getDeviceIdentifier() + ", type:" + device - .getType() + ", tenant:" + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId() - + ", domain:" + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()); - } NotificationStrategy notificationStrategy = getNotificationStrategy(); /* * If notification strategy has not enable to send push notification using scheduler task we will send @@ -309,43 +430,61 @@ public class OperationManagerImpl implements OperationManager { notificationStrategy.execute(new NotificationContext(deviceIdentifier, operation)); } catch (PushNotificationExecutionFailedException e) { log.error("Error occurred while sending push notifications to " + device.getType() + - " device carrying id '" + device.getDeviceIdentifier() + "'", e); + " device carrying id '" + device.getDeviceIdentifier() + "'", e); /* * Reschedule if push notification failed. Doing db transactions in atomic way to prevent * deadlocks. */ - try { - operationMappingDAO.updateOperationMapping(operation.getId(), device.getEnrolmentInfo().getId(), org.wso2.carbon - .device.mgt.core.dto.operation.mgt.Operation.PushNotificationStatus.SCHEDULED); - OperationManagementDAOFactory.commitTransaction(); - } catch (OperationManagementDAOException ex) { - // Not throwing this exception in order to keep scheduling remaining notifications if any. - log.error("Error occurred while setting push notification status to SCHEDULED.", ex); - OperationManagementDAOFactory.rollbackTransaction(); + int failAttempts = 0; + while (true) { + try { + operationMappingDAO.updateOperationMapping(operation.getId(), device.getEnrolmentInfo().getId(), + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.PushNotificationStatus.SCHEDULED); + OperationManagementDAOFactory.commitTransaction(); + break; + } catch (OperationManagementDAOException ex) { + OperationManagementDAOFactory.rollbackTransaction(); + if (++failAttempts > 3) { + String msg = "Error occurred while setting push notification status to SCHEDULED. Operation ID: " + + operation.getId() + ", Enrollment ID: " + device.getEnrolmentInfo().getId() + + ", Device ID:" + device.getDeviceIdentifier(); + log.error(msg, e); + break; + } + log.warn("Unable to set push notification status to SCHEDULED. Operation ID: " + + operation.getId() + ", Enrollment ID: " + device.getEnrolmentInfo().getId() + + ", Device ID:" + device.getDeviceIdentifier() + ", Attempt: " + failAttempts + + ", Error: " + e.getMessage()); + try { + Thread.sleep(2000); + } catch (InterruptedException ignore) { + break; + } + } } } catch (Exception e) { - log.error("Error occurred while sending notifications to " + device.getType() + " device carrying id '" - + device.getDeviceIdentifier() + "'", e); + log.error("Error occurred while sending notifications to " + device.getType() + + " device carrying id '" + device.getDeviceIdentifier() + "'", e); } } } private List getActivityStatus(DeviceIDHolder deviceIdValidationResult, - DeviceIDHolder deviceAuthResult) { + DeviceIDHolder deviceAuthResult) { List activityStatuses = new ArrayList<>(); ActivityStatus activityStatus; //Add the invalid DeviceIds - for (DeviceIdentifier id : deviceIdValidationResult.getErrorDeviceIdList()) { + for (DeviceIdentifier deviceIdentifier : deviceIdValidationResult.getErrorDeviceIdList()) { activityStatus = new ActivityStatus(); - activityStatus.setDeviceIdentifier(id); + activityStatus.setDeviceIdentifier(deviceIdentifier); activityStatus.setStatus(ActivityStatus.Status.INVALID); activityStatuses.add(activityStatus); } //Add the unauthorized DeviceIds - for (DeviceIdentifier id : deviceAuthResult.getErrorDeviceIdList()) { + for (DeviceIdentifier deviceIdentifier : deviceAuthResult.getErrorDeviceIdList()) { activityStatus = new ActivityStatus(); - activityStatus.setDeviceIdentifier(id); + activityStatus.setDeviceIdentifier(deviceIdentifier); activityStatus.setStatus(ActivityStatus.Status.UNAUTHORIZED); activityStatuses.add(activityStatus); } @@ -401,7 +540,7 @@ public class OperationManagerImpl implements OperationManager { @Override public List getOperations(DeviceIdentifier deviceId) throws OperationManagementException { - List operations = null; + List operations; if (!isActionAuthorized(deviceId)) { throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" + @@ -440,7 +579,7 @@ public class OperationManagerImpl implements OperationManager { @Override public PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException { - PaginationResult paginationResult = null; + PaginationResult paginationResult; List operations = new ArrayList<>(); String owner = request.getOwner(); try { @@ -492,14 +631,36 @@ public class OperationManagerImpl implements OperationManager { return paginationResult; } + @Override + public List getOperations(DeviceIdentifier deviceId, Operation.Status status) + throws OperationManagementException { + if (log.isDebugEnabled()) { + log.debug("Device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]"); + } + + if (!isActionAuthorized(deviceId)) { + throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" + + deviceId.getType() + "' device, which carries the identifier '" + + deviceId.getId() + "'"); + } + PaginationRequest request = new PaginationRequest(0, 0); + request.setOwner(getUser()); + EnrolmentInfo enrolmentInfo = this.getEnrolmentInfo(deviceId, request); + if (enrolmentInfo == null) { + throw new OperationManagementException("Device not found for the given device Identifier:" + + deviceId.getId() + " and given type:" + + deviceId.getType()); + } + int enrolmentId = enrolmentInfo.getId(); + return getOperations(deviceId, status, enrolmentId); + } + @Override public List getPendingOperations(DeviceIdentifier deviceId) throws OperationManagementException { if (log.isDebugEnabled()) { log.debug("Device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]"); } - List operations = new ArrayList<>(); - List dtoOperationList = new ArrayList<>(); EnrolmentInfo enrolmentInfo = this.getActiveEnrolmentInfo(deviceId); if (enrolmentInfo == null) { @@ -513,36 +674,12 @@ public class OperationManagerImpl implements OperationManager { case INACTIVE: case UNREACHABLE: this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + DeviceCacheManagerImpl.getInstance().removeDeviceFromCache(deviceId, tenantId); break; } - try { - OperationManagementDAOFactory.openConnection(); - dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus( - enrolmentId, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); - Operation operation; - for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : dtoOperationList) { - operation = OperationDAOUtil.convertOperation(dtoOperation); - operations.add(operation); - } - Collections.sort(operations, new OperationIdComparator()); - } catch (OperationManagementDAOException e) { - throw new OperationManagementException("Error occurred while retrieving the list of " + - "pending operations assigned for '" + deviceId.getType() + - "' device '" + deviceId.getId() + "'", e); - } catch (SQLException e) { - throw new OperationManagementException( - "Error occurred while opening a connection to the data source", e); - } finally { - OperationManagementDAOFactory.closeConnection(); - } - return operations; + return getOperations(deviceId, Operation.Status.PENDING, enrolmentId); } @Override @@ -553,17 +690,21 @@ public class OperationManagerImpl implements OperationManager { device.getId() + " and given type:" + device.getType()); } + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setType(device.getType()); + deviceIdentifier.setId(device.getDeviceIdentifier()); int enrolmentId = enrolmentInfo.getId(); //Changing the enrollment status & attempt count if the device is marked as inactive or unreachable switch (enrolmentInfo.getStatus()) { case INACTIVE: case UNREACHABLE: this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + DeviceCacheManagerImpl.getInstance().addDeviceToCache(deviceIdentifier, device, tenantId); break; } - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setType(device.getType()); - deviceIdentifier.setId(device.getDeviceIdentifier()); return getOperations(deviceIdentifier, Operation.Status.PENDING, enrolmentId); } @@ -599,6 +740,8 @@ public class OperationManagerImpl implements OperationManager { case INACTIVE: case UNREACHABLE: this.setEnrolmentStatus(enrolmentId, EnrolmentInfo.Status.ACTIVE); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + DeviceCacheManagerImpl.getInstance().removeDeviceFromCache(deviceId, tenantId); break; } @@ -673,29 +816,136 @@ public class OperationManagerImpl implements OperationManager { "Device not found for device id:" + deviceId.getId() + " " + "type:" + deviceId.getType()); } - updateOperation(enrolmentInfo.getId(), operation); + updateOperation(enrolmentInfo.getId(), operation, deviceId); } @Override - public void updateOperation(int enrolmentId, Operation operation) throws OperationManagementException { + public void updateOperation(int enrolmentId, Operation operation, DeviceIdentifier deviceId) + throws OperationManagementException { int operationId = operation.getId(); try { OperationManagementDAOFactory.beginTransaction(); if (operation.getStatus() != null) { - operationDAO.updateOperationStatus(enrolmentId, operationId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt. - Operation.Status.valueOf(operation.getStatus(). - toString())); + int failAttempts = 0; + while (true) { + try { + operationDAO.updateOperationStatus(enrolmentId, operationId, + org.wso2.carbon.device.mgt.core.dto.operation.mgt. + Operation.Status.valueOf(operation.getStatus(). + toString())); + OperationManagementDAOFactory.commitTransaction(); + break; + } catch (OperationManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + if (++failAttempts > 3) { + String msg = "Error occurred while updating operation status. Operation ID: " + + operationId + ", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId; + log.error(msg, e); + throw new OperationManagementException(msg, e); + } + log.warn("Unable to update operation status. Operation ID: " + operationId + + ", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId + ", Attempt: " + failAttempts + + ", Error: " + e.getMessage()); + try { + Thread.sleep(2000); + } catch (InterruptedException ignore) { + break; + } + } + } } if (operation.getOperationResponse() != null) { - operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse()); + OperationMonitoringTaskConfig operationMonitoringTaskConfig = DeviceManagementDataHolder + .getInstance().getDeviceManagementProvider().getDeviceMonitoringConfig(deviceId.getType()); + List monitoringOperations = operationMonitoringTaskConfig.getMonitoringOperation(); + MonitoringOperation currentMonitoringOperation = null; + for (MonitoringOperation monitoringOperation : monitoringOperations) { + if (operation.getCode().equals(monitoringOperation.getTaskName())) { + currentMonitoringOperation = monitoringOperation; + break; + } + } + if (currentMonitoringOperation != null && !currentMonitoringOperation.hasResponsePersistence()) { + String initiatedBy = operationsInitBy.get(operationId); + if (initiatedBy == null) { + try { + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation operationDto = + operationDAO.getOperation(operationId); + operation.setInitiatedBy(operationDto.getInitiatedBy()); + if (operationsInitBy.size() > maxOperationCacheSize) { + Integer obsoleteOperationId = (Integer) operationsInitBy.keySet().toArray()[0]; + operationsInitBy.remove(obsoleteOperationId); + } + operationsInitBy.put(operationId, operation.getInitiatedBy()); + } catch (OperationManagementDAOException e) { + log.warn("Unable to get operationDTO for Operation ID: " + operationId + + ", Error: " + e.getErrorMessage()); + } + } else { + operation.setInitiatedBy(initiatedBy); + } + if (SYSTEM.equals(operation.getInitiatedBy())) { + return; + } + } + } + OperationResponseMeta responseMeta = null; + if (operation.getOperationResponse() != null) { + int failAttempts = 0; + while (true) { + try { + responseMeta = operationDAO.addOperationResponse(enrolmentId, operation, deviceId.getId()); + OperationManagementDAOFactory.commitTransaction(); + break; + } catch (OperationManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + if (++failAttempts > 3) { + String msg = "Error occurred while updating operation response. Operation ID: " + + operationId + ", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId; + log.error(msg, e); + throw new OperationManagementException(msg, e); + } + log.warn("Unable to update operation response. Operation ID: " + operationId + + ", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId + " Attempt: " + failAttempts + + ", Error: " + e.getErrorMessage()); + try { + Thread.sleep(2000); + } catch (InterruptedException ignore) { + break; + } + } + } + } + if (responseMeta != null && responseMeta.isLargeResponse() && responseMeta.getId() > 0) { + int failAttempts = 0; + while (true) { + try { + operationDAO.addOperationResponseLarge(responseMeta, operation, deviceId.getId()); + OperationManagementDAOFactory.commitTransaction(); + break; + } catch (OperationManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + if (++failAttempts > 3) { + String msg = "Error occurred while updating large operation response. " + + "Enrollment Mapping ID: " + responseMeta.getOperationMappingId() + + ", Response ID: " + responseMeta.getId() + ", Operation ID: " + operationId + + ", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId; + log.error(msg, e); + throw new OperationManagementException(msg, e); + } + log.warn("Unable to update large operation response. " + + "Enrollment Mapping ID: " + responseMeta.getOperationMappingId() + + ", Response ID: " + responseMeta.getId() + ", Operation ID: " + operationId + + ", Enrollment ID: " + enrolmentId + ", Device ID:" + deviceId + + ", Attempt: " + failAttempts + ", Error: " + e.getMessage()); + try { + Thread.sleep(2000); + } catch (InterruptedException ignore) { + break; + } + } + } } - OperationManagementDAOFactory.commitTransaction(); - } catch (OperationManagementDAOException e) { - OperationManagementDAOFactory.rollbackTransaction(); - throw new OperationManagementException( - "Error occurred while updating the operation: " + operationId + " status:" + - operation.getStatus(), e); } catch (TransactionManagementException e) { throw new OperationManagementException("Error occurred while initiating a transaction", e); } finally { @@ -706,7 +956,7 @@ public class OperationManagerImpl implements OperationManager { @Override public Operation getOperationByDeviceAndOperationId(DeviceIdentifier deviceId, int operationId) throws OperationManagementException { - Operation operation = null; + Operation operation; if (log.isDebugEnabled()) { log.debug("Operation Id: " + operationId + " Device Type: " + deviceId.getType() + " Device Identifier: " + deviceId.getId()); @@ -913,7 +1163,8 @@ public class OperationManagerImpl implements OperationManager { } } - public Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) throws OperationManagementException { + public Activity getOperationByActivityIdAndDevice(String activity, DeviceIdentifier deviceId) + throws OperationManagementException { // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer. int operationId = Integer.parseInt( activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "")); @@ -957,7 +1208,7 @@ public class OperationManagerImpl implements OperationManager { @Override - public List getFilteredActivities(String operationCode, int limit, int offset) throws OperationManagementException{ + public List getFilteredActivities(String operationCode, int limit, int offset) throws OperationManagementException { try { OperationManagementDAOFactory.openConnection(); return operationDAO.getFilteredActivities(operationCode, limit, offset); @@ -972,7 +1223,7 @@ public class OperationManagerImpl implements OperationManager { } @Override - public int getTotalCountOfFilteredActivities(String operationCode) throws OperationManagementException{ + public int getTotalCountOfFilteredActivities(String operationCode) throws OperationManagementException { try { OperationManagementDAOFactory.openConnection(); return operationDAO.getTotalCountOfFilteredActivities(operationCode); @@ -1142,23 +1393,38 @@ public class OperationManagerImpl implements OperationManager { return enrolmentInfo; } - private boolean setEnrolmentStatus(int enrolmentId, EnrolmentInfo.Status status) throws OperationManagementException { - boolean updateStatus; + private void setEnrolmentStatus(int enrolmentId, EnrolmentInfo.Status status) throws OperationManagementException { try { DeviceManagementDAOFactory.beginTransaction(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - updateStatus = enrollmentDAO.setStatus(enrolmentId, status, tenantId); - DeviceManagementDAOFactory.commitTransaction(); - } catch (DeviceManagementDAOException e) { - DeviceManagementDAOFactory.rollbackTransaction(); - throw new OperationManagementException("Error occurred while updating enrollment status of device of " + - "enrolment-id '" + enrolmentId + "'", e); + int failAttempts = 0; + while (true) { + try { + enrollmentDAO.setStatus(enrolmentId, status, tenantId); + DeviceManagementDAOFactory.commitTransaction(); + break; + } catch (DeviceManagementDAOException e) { + OperationManagementDAOFactory.rollbackTransaction(); + if (++failAttempts > 3) { + String msg = "Error occurred while updating enrollment status of device of " + + "enrolment-id '" + enrolmentId + "'"; + log.error(msg, e); + throw new OperationManagementException(msg, e); + } + log.warn("Unable to update enrollment status of device of enrolment-id '" + + enrolmentId + ", Attempt: " + failAttempts + ", Error: " + e.getMessage()); + try { + Thread.sleep(2000); + } catch (InterruptedException ignore) { + break; + } + } + } } catch (TransactionManagementException e) { throw new OperationManagementException("Error occurred while initiating a transaction", e); } finally { DeviceManagementDAOFactory.closeConnection(); } - return updateStatus; } private boolean isTaskScheduledOperation(Operation operation) { @@ -1173,6 +1439,10 @@ public class OperationManagerImpl implements OperationManager { return false; } + private boolean isSameUser(String user, String owner) { + return user.equalsIgnoreCase(owner); + } + private List getOperations(DeviceIdentifier deviceId, Operation.Status status, int enrolmentId) throws OperationManagementException { List operations = new ArrayList<>(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java index 81d47cfc85..0b9d953ed2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java @@ -20,7 +20,9 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao; 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.OperationResponse; 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; import java.util.List; @@ -54,15 +56,24 @@ public interface OperationDAO { void updateEnrollmentOperationsStatus(int enrolmentId, String operationCode, Operation.Status existingStatus, Operation.Status newStatus) throws OperationManagementDAOException; - int getExistingOperationID(int enrolmentId, String operationCode) throws OperationManagementDAOException; + Map getExistingOperationIDs(Integer[] enrolmentIds, String operationCode) + throws OperationManagementDAOException; - void addOperationResponse(int enrolmentId, int operationId, Object operationResponse) + OperationResponseMeta addOperationResponse(int enrolmentId, org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation, String deviceId) throws OperationManagementDAOException; Activity getActivity(int operationId) throws OperationManagementDAOException; List getActivityList(List operationIds) throws OperationManagementDAOException; + void addOperationResponseLarge(OperationResponseMeta responseMeta, + org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation, + String deviceId) throws OperationManagementDAOException; + + Map>> getLargeOperationResponsesInBulk(List operationIds) throws OperationManagementDAOException; + + void populateLargeOperationResponses(List activities, List largeResponseIDs) throws OperationManagementDAOException; + Activity getActivityByDevice(int operationId, int deviceId) throws OperationManagementDAOException; List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOUtil.java index e39e1dde9b..b8d59547da 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOUtil.java @@ -37,14 +37,9 @@ public class OperationManagementDAOUtil { log.warn("Error occurred while closing the result set", e); } } - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing the statement", e); - } - } + cleanupResources(stmt); } + public static void cleanupResources(Statement stmt) { if (stmt != null) { try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java index 5077e15211..4b57829274 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationMappingDAO.java @@ -18,6 +18,8 @@ */ package org.wso2.carbon.device.mgt.core.operation.mgt.dao; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMapping; @@ -27,10 +29,9 @@ import java.util.Map; public interface OperationMappingDAO { - void addOperationMapping(int operationId, int enrollmentId, boolean isScheduled) - throws OperationManagementDAOException; + void addOperationMapping(Operation operation, Integer deviceId, boolean isScheduled, Device device, Integer tenantId) throws OperationManagementDAOException; - void addOperationMapping(int operationId, List enrollmentIds, boolean isScheduled) + void addOperationMapping(Operation operation, List devices, boolean isScheduled, Integer tenantId) throws OperationManagementDAOException; void removeOperationMapping(int operationId, Integer deviceId) throws OperationManagementDAOException; 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 3edc27791d..e20628da85 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 @@ -26,6 +26,7 @@ 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.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; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationDAO; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; @@ -33,10 +34,8 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOF import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil; -import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.sql.Connection; import java.sql.PreparedStatement; @@ -44,7 +43,6 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; -import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; @@ -81,7 +79,8 @@ public class GenericOperationDAOImpl implements OperationDAO { } return id; } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while adding operation metadata", e); + throw new OperationManagementDAOException("Error occurred while adding operation metadata. " + + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -106,7 +105,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while update device mapping operation status " + - "metadata", e); + "metadata. " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt); } @@ -151,70 +150,134 @@ public class GenericOperationDAOImpl implements OperationDAO { } @Override - public int getExistingOperationID(int enrolmentId, String operationCode) + public Map getExistingOperationIDs(Integer[] enrolmentIds, String operationCode) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; - int result = -1; + Map existingOperationIds = new HashMap<>(); try { Connection connection = OperationManagementDAOFactory.getConnection(); - String query = "SELECT DM.ID FROM DM_ENROLMENT_OP_MAPPING EOM INNER JOIN DM_OPERATION DM " - + "ON DM.ID = EOM.OPERATION_ID WHERE EOM.ENROLMENT_ID = ? AND DM.OPERATION_CODE = ? AND " - + "EOM.STATUS = ?"; - stmt = connection.prepareStatement(query); - stmt.setInt(1, enrolmentId); - stmt.setString(2, operationCode); - stmt.setString(3, Operation.Status.PENDING.toString()); - // This will return only one result always. + StringBuilder query = new StringBuilder("SELECT OPERATION_ID, ENROLMENT_ID FROM DM_ENROLMENT_OP_MAPPING " + + "WHERE OPERATION_CODE = ? AND STATUS = ? AND ENROLMENT_ID IN ("); + for (int i = 0; i < enrolmentIds.length; i++) { + query.append(" ?,"); + } + query.deleteCharAt(query.length() - 1); + query.append(")"); + stmt = connection.prepareStatement(query.toString()); + stmt.setString(1, operationCode); + stmt.setString(2, Operation.Status.PENDING.toString()); + + for (int i = 0; i < enrolmentIds.length; i++) { + stmt.setInt(i + 3, enrolmentIds[i]); + } + rs = stmt.executeQuery(); - if (rs.next()) { - result = rs.getInt("ID"); + int operationId; + int enrollmentId; + while (rs.next()) { + enrollmentId = rs.getInt("ENROLMENT_ID"); + operationId = rs.getInt("OPERATION_ID"); + existingOperationIds.put(enrollmentId, operationId); } } catch (SQLException e) { - throw new OperationManagementDAOException( - "Error occurred while update device mapping operation status " + "metadata", e); + throw new OperationManagementDAOException("Error occurred while update device mapping operation status " + + "metadata. " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } - return result; + return existingOperationIds; } @Override - public void addOperationResponse(int enrolmentId, int operationId, Object operationResponse) - throws OperationManagementDAOException { + public OperationResponseMeta addOperationResponse(int enrolmentId, + org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation, + String deviceId) throws OperationManagementDAOException { PreparedStatement stmt = null; - ByteArrayOutputStream bao = null; - ObjectOutputStream oos = null; ResultSet rs = null; + boolean isLargeResponse = false; try { Connection connection = OperationManagementDAOFactory.getConnection(); stmt = connection.prepareStatement("SELECT ID FROM DM_ENROLMENT_OP_MAPPING WHERE ENROLMENT_ID = ? " + "AND OPERATION_ID = ?"); stmt.setInt(1, enrolmentId); - stmt.setInt(2, operationId); + stmt.setInt(2, operation.getId()); rs = stmt.executeQuery(); int enPrimaryId = 0; - if(rs.next()){ + if (rs.next()) { enPrimaryId = rs.getInt("ID"); } stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLMENT_ID, " + - "EN_OP_MAP_ID, OPERATION_RESPONSE, RECEIVED_TIMESTAMP) VALUES(?, ?, ?, ?, ?)"); - bao = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(bao); - oos.writeObject(operationResponse); - - stmt.setInt(1, operationId); + "EN_OP_MAP_ID, OPERATION_RESPONSE, IS_LARGE_RESPONSE, RECEIVED_TIMESTAMP) VALUES(?, ?, ?, ?, ?, ?)", + new String[]{"ID"}); + stmt.setInt(1, operation.getId()); stmt.setInt(2, enrolmentId); stmt.setInt(3, enPrimaryId); - stmt.setBytes(4, bao.toByteArray()); - stmt.setTimestamp(5, new Timestamp(new Date().getTime())); + + if (operation.getOperationResponse() != null && operation.getOperationResponse().length() >= 1000) { + isLargeResponse = true; + stmt.setBytes(4, null); + } else { + stmt.setString(4, operation.getOperationResponse()); + } + stmt.setBoolean(5, isLargeResponse); + + Timestamp receivedTimestamp = new Timestamp(new Date().getTime()); + stmt.setTimestamp(6, receivedTimestamp); + stmt.executeUpdate(); + + rs = stmt.getGeneratedKeys(); + int opResID = -1; + if (rs.next()) { + opResID = rs.getInt(1); + } + + OperationResponseMeta responseMeta = new OperationResponseMeta(); + responseMeta.setId(opResID); + responseMeta.setEnrolmentId(enrolmentId); + responseMeta.setOperationMappingId(enPrimaryId); + responseMeta.setReceivedTimestamp(receivedTimestamp); + responseMeta.setLargeResponse(isLargeResponse); + return responseMeta; + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while inserting operation response. " + + e.getMessage(), e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public void addOperationResponseLarge(OperationResponseMeta responseMeta, + org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation, + String deviceId) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ByteArrayOutputStream bao = null; + ObjectOutputStream oos = null; + ResultSet rs = null; + try { + Connection connection = OperationManagementDAOFactory.getConnection(); + stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE_LARGE " + + "(ID, OPERATION_RESPONSE, OPERATION_ID, EN_OP_MAP_ID, RECEIVED_TIMESTAMP, DEVICE_IDENTIFICATION) " + + "VALUES(?, ?, ?, ?, ?, ?)"); + bao = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(bao); + oos.writeObject(operation.getOperationResponse()); + stmt.setInt(1, responseMeta.getId()); + stmt.setBytes(2, bao.toByteArray()); + stmt.setInt(3, operation.getId()); + stmt.setInt(4, responseMeta.getOperationMappingId()); + stmt.setTimestamp(5, responseMeta.getReceivedTimestamp()); + stmt.setString(6, deviceId); stmt.executeUpdate(); } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while inserting operation response", e); + throw new OperationManagementDAOException("Error occurred while inserting operation response. " + + e.getMessage(), e); } catch (IOException e) { - throw new OperationManagementDAOException("Error occurred while serializing policy operation object", e); + throw new OperationManagementDAOException("Error occurred while serializing operation response object. " + + e.getMessage(), e); } finally { if (bao != null) { try { @@ -234,6 +297,93 @@ public class GenericOperationDAOImpl implements OperationDAO { } } + @Override + public Map>> getLargeOperationResponsesInBulk(List operationResponseIds) + throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Map>> operationResponseMapping = new HashMap<>(); + Map> operationDeviceMappings; + List responseList; + + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + + String sql1 = "SELECT * FROM DM_DEVICE_OPERATION_RESPONSE_LARGE WHERE ID IN ("; + + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < operationResponseIds.size(); i++) { + builder.append("?,"); + } + sql1 += builder.deleteCharAt(builder.length() - 1).toString() + ")"; + stmt = conn.prepareStatement(sql1); + int i; + for (i = 0; i < operationResponseIds.size(); i++) { + stmt.setInt(i + 1, operationResponseIds.get(i)); + } + rs = stmt.executeQuery(); + + while (rs.next()) { + String activityID = OperationDAOUtil.getActivityId(rs.getInt("OPERATION_ID")); + String deviceID = rs.getString("DEVICE_IDENTIFICATION"); + + if (operationResponseMapping.containsKey(activityID)) { + operationDeviceMappings = operationResponseMapping.get(activityID); + if (operationDeviceMappings.containsKey(deviceID)) { + responseList = operationDeviceMappings.get(deviceID); + } else { + responseList = new ArrayList<>(); + operationDeviceMappings.put(deviceID, responseList); + } + + } else { + responseList = new ArrayList<>(); + operationDeviceMappings = new HashMap<>(); + operationDeviceMappings.put(deviceID, responseList); + operationResponseMapping.put(activityID, operationDeviceMappings); + } + responseList.add(OperationDAOUtil.getLargeOperationResponse(rs)); + } + + } catch (SQLException e) { + throw new OperationManagementDAOException( + "Error occurred while getting the operation details from the database. " + e.getMessage(), e); + } catch (ClassNotFoundException e) { + throw new OperationManagementDAOException( + "Error occurred while converting the operation response to string.. " + e.getMessage(), e); + } catch (IOException e) { + throw new OperationManagementDAOException( + "IO exception occurred while converting the operations responses. " + e.getMessage(), e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operationResponseMapping; + } + + @Override + public void populateLargeOperationResponses(List activities, + List largeResponseIDs) + throws OperationManagementDAOException { + if (!largeResponseIDs.isEmpty()) { + Map>> largeOperationResponses = getLargeOperationResponsesInBulk(largeResponseIDs); + if (!largeOperationResponses.isEmpty()) { + for (Activity tempActivity : activities) { + if (largeOperationResponses.containsKey(tempActivity.getActivityId())) { + List activityStatuses = tempActivity.getActivityStatus(); + Map> deviceOpResponseMap = largeOperationResponses.get(tempActivity.getActivityId()); + for (Map.Entry> deviceOpRes : deviceOpResponseMap.entrySet()) { + for (ActivityStatus status : activityStatuses) { + if (deviceOpRes.getKey().equalsIgnoreCase(status.getDeviceIdentifier().getId())) { + status.getResponses().addAll(deviceOpRes.getValue()); + } + } + } + } + } + } + } + } + @Override public Activity getActivity(int operationId) throws OperationManagementDAOException { @@ -243,18 +393,29 @@ public class GenericOperationDAOImpl implements OperationDAO { List activityStatusList = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT eom.ENROLMENT_ID, eom.OPERATION_ID, eom.ID AS EOM_MAPPING_ID, dor.ID AS OP_RES_ID,\n" + - "de.DEVICE_ID, d.DEVICE_IDENTIFICATION, \n" + - "d.DEVICE_TYPE_ID, dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, \n" + - "eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, dor.OPERATION_RESPONSE, \n" + - "dor.RECEIVED_TIMESTAMP, op.INITIATED_BY FROM DM_ENROLMENT_OP_MAPPING eom \n" + - "INNER JOIN DM_OPERATION op ON op.ID=eom.OPERATION_ID\n" + - "INNER JOIN DM_ENROLMENT de ON de.ID=eom.ENROLMENT_ID\n" + - "INNER JOIN DM_DEVICE d ON d.ID=de.DEVICE_ID \n" + - "INNER JOIN DM_DEVICE_TYPE dt ON dt.ID=d.DEVICE_TYPE_ID\n" + - "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE dor ON dor.ENROLMENT_ID=de.id \n" + - "AND dor.OPERATION_ID = eom.OPERATION_ID\n" + - "WHERE eom.OPERATION_ID = ? AND de.TENANT_ID = ?"; + String sql = "SELECT " + + " eom.ENROLMENT_ID," + + " eom.CREATED_TIMESTAMP," + + " eom.UPDATED_TIMESTAMP," + + " eom.OPERATION_ID," + + " eom.OPERATION_CODE," + + " eom.INITIATED_BY," + + " eom.TYPE AS OPERATION_TYPE," + + " eom.STATUS," + + " eom.DEVICE_ID," + + " eom.DEVICE_IDENTIFICATION," + + " eom.DEVICE_TYPE AS DEVICE_TYPE_NAME," + + " eom.ID AS EOM_MAPPING_ID," + + " opr.ID AS OP_RES_ID," + + " opr.RECEIVED_TIMESTAMP," + + " opr.OPERATION_RESPONSE," + + " opr.IS_LARGE_RESPONSE " + + "FROM " + + " DM_ENROLMENT_OP_MAPPING eom " + + " LEFT JOIN " + + " DM_DEVICE_OPERATION_RESPONSE opr ON opr.EN_OP_MAP_ID = eom.ID " + + "WHERE " + + " eom.OPERATION_ID = ? AND eom.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, operationId); @@ -263,7 +424,8 @@ public class GenericOperationDAOImpl implements OperationDAO { int enrolmentId = 0; ActivityStatus activityStatus = null; - + int responseId = 0; + List largeResponseIDs = new ArrayList<>(); while (rs.next()) { if (enrolmentId == 0) { activity = new Activity(); @@ -295,17 +457,40 @@ public class GenericOperationDAOImpl implements OperationDAO { activity.setActivityStatus(activityStatusList); } else { if (rs.getInt("UPDATED_TIMESTAMP") != 0) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + if (activityStatus == null) { + activityStatus = new ActivityStatus(); + } + if (activityStatus.getResponses() == null) { + activityStatus.setResponses(new ArrayList<>()); + } + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } + } + } + } + if (!largeResponseIDs.isEmpty()) { + Map>> largeOperationResponses = getLargeOperationResponsesInBulk(largeResponseIDs); + if (!largeOperationResponses.isEmpty()) { + List activityStatuses = activity.getActivityStatus(); + if (activityStatuses != null) { + Map> deviceOpResponseMap = largeOperationResponses.get(activity.getActivityId()); + for (Map.Entry> deviceOpRes : deviceOpResponseMap.entrySet()) { + for (ActivityStatus status : activityStatuses) { + if (deviceOpRes.getKey().equalsIgnoreCase(status.getDeviceIdentifier().getId())) { + status.getResponses().addAll(deviceOpRes.getValue()); + } + } + } } } } } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while getting the operation details from " + - "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e); + "the database. " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -328,12 +513,12 @@ public class GenericOperationDAOImpl implements OperationDAO { + "dor.ID AS OP_RES_ID, de.DEVICE_ID, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID, " + "dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, " + "eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, " - + "dor.OPERATION_RESPONSE, op.INITIATED_BY, dor.RECEIVED_TIMESTAMP FROM " + + "dor.OPERATION_RESPONSE, op.INITIATED_BY, dor.RECEIVED_TIMESTAMP, dor.IS_LARGE_RESPONSE FROM " + "DM_ENROLMENT_OP_MAPPING eom INNER JOIN DM_OPERATION op " + "ON op.ID=eom.OPERATION_ID INNER JOIN DM_ENROLMENT de " - + "ON de.ID=eom.ENROLMENT_ID INNER JOIN DM_DEVICE d ON d.ID=de.DEVICE_ID \n" - + "INNER JOIN DM_DEVICE_TYPE dt ON dt.ID=d.DEVICE_TYPE_ID\n" - + "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE dor ON dor.ENROLMENT_ID=de.id \n" + + "ON de.ID=eom.ENROLMENT_ID INNER JOIN DM_DEVICE d ON d.ID=de.DEVICE_ID " + + "INNER JOIN DM_DEVICE_TYPE dt ON dt.ID=d.DEVICE_TYPE_ID " + + "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE dor ON dor.ENROLMENT_ID=de.id " + "AND dor.OPERATION_ID = eom.OPERATION_ID WHERE eom.OPERATION_ID " + "IN (SELECT * FROM TABLE(x INT = ?)) AND de.TENANT_ID = ?"; @@ -347,6 +532,7 @@ public class GenericOperationDAOImpl implements OperationDAO { int enrolmentId = 0; int responseId = 0; ActivityStatus activityStatus = new ActivityStatus(); + List largeResponseIDs = new ArrayList<>(); while (rs.next()) { activity = new Activity(); @@ -379,8 +565,14 @@ public class GenericOperationDAOImpl implements OperationDAO { } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); - responseId = rs.getInt("OP_RES_ID"); + if (rs.getInt("UPDATED_TIMESTAMP") != 0) { + responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } + } } activityStatus.setResponses(operationResponses); statusList.add(activityStatus); @@ -409,8 +601,12 @@ public class GenericOperationDAOImpl implements OperationDAO { new java.util.Date(rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); activity.getActivityStatus().add(activityStatus); @@ -420,20 +616,21 @@ public class GenericOperationDAOImpl implements OperationDAO { if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID") && rs.getTimestamp( "RECEIVED_TIMESTAMP") != null) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } } } + if (!largeResponseIDs.isEmpty()) { + populateLargeOperationResponses(activities, largeResponseIDs); + } } catch (SQLException e) { throw new OperationManagementDAOException( - "Error occurred while getting the operation details from " + "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException( - "Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException( - "IO exception occurred while converting the operations responses.", e); + "Error occurred while getting the operation details from the database. " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -445,6 +642,7 @@ public class GenericOperationDAOImpl implements OperationDAO { PreparedStatement stmt = null; ResultSet rs = null; Activity activity = null; + int responseId = 0; List activityStatusList = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); @@ -452,7 +650,7 @@ public class GenericOperationDAOImpl implements OperationDAO { "de.DEVICE_ID, d.DEVICE_IDENTIFICATION, \n" + "d.DEVICE_TYPE_ID, dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, \n" + "eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, dor.OPERATION_RESPONSE, \n" + - "dor.RECEIVED_TIMESTAMP, op.INITIATED_BY FROM DM_ENROLMENT_OP_MAPPING AS eom \n" + + "dor.RECEIVED_TIMESTAMP, dor.IS_LARGE_RESPONSE, op.INITIATED_BY FROM DM_ENROLMENT_OP_MAPPING AS eom \n" + "INNER JOIN DM_OPERATION AS op ON op.ID=eom.OPERATION_ID\n" + "INNER JOIN DM_ENROLMENT AS de ON de.ID=eom.ENROLMENT_ID\n" + "INNER JOIN DM_DEVICE AS d ON d.ID=de.DEVICE_ID \n" + @@ -469,6 +667,7 @@ public class GenericOperationDAOImpl implements OperationDAO { int enrolmentId = 0; ActivityStatus activityStatus = null; + List largeResponseIDs = new ArrayList<>(); while (rs.next()) { if (enrolmentId == 0) { @@ -501,17 +700,35 @@ public class GenericOperationDAOImpl implements OperationDAO { activity.setActivityStatus(activityStatusList); } else { if (rs.getInt("UPDATED_TIMESTAMP") != 0) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } + } + } + } + + if (!largeResponseIDs.isEmpty()) { + Map>> largeOperationResponses = getLargeOperationResponsesInBulk(largeResponseIDs); + if (!largeOperationResponses.isEmpty()) { + List activityStatuses = activity.getActivityStatus(); + if (activityStatuses != null) { + Map> deviceOpResponseMap = largeOperationResponses.get(activity.getActivityId()); + for (Map.Entry> deviceOpRes : deviceOpResponseMap.entrySet()) { + for (ActivityStatus status : activityStatuses) { + if (deviceOpRes.getKey().equalsIgnoreCase(status.getDeviceIdentifier().getId())) { + status.getResponses().addAll(deviceOpRes.getValue()); + } + } + } } } } } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while getting the operation details from " + - "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e); + "the database. " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -520,11 +737,11 @@ public class GenericOperationDAOImpl implements OperationDAO { @Override public List getFilteredActivities(String operationCode, int limit, int offset) - throws OperationManagementDAOException{ + throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; List activities = new ArrayList<>(); - try{ + try { Connection conn = OperationManagementDAOFactory.getConnection(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); String sql = "SELECT " + @@ -539,8 +756,9 @@ public class GenericOperationDAOImpl implements OperationDAO { " opr.DEVICE_IDENTIFICATION, " + " opr.DEVICE_TYPE, " + " ops.RECEIVED_TIMESTAMP, " + - " ops.ID OP_RES_ID, " + + " ops.ID AS OP_RES_ID, " + " ops.OPERATION_RESPONSE, " + + " ops.IS_LARGE_RESPONSE, " + " opr.INITIATED_BY " + " FROM " + " (SELECT " + @@ -551,11 +769,11 @@ public class GenericOperationDAOImpl implements OperationDAO { " opm.OPERATION_ID, " + " op.OPERATION_CODE, " + " op.INITIATED_BY, " + - " op.TYPE OPERATION_TYPE, " + + " op.TYPE AS OPERATION_TYPE, " + " opm.STATUS, " + " en.DEVICE_ID, " + " de.DEVICE_IDENTIFICATION, " + - " dt.NAME DEVICE_TYPE, " + + " dt.NAME AS DEVICE_TYPE, " + " de.TENANT_ID " + " FROM" + " DM_ENROLMENT_OP_MAPPING opm " + @@ -588,6 +806,7 @@ public class GenericOperationDAOImpl implements OperationDAO { int responseId = 0; Activity activity = null; ActivityStatus activityStatus = null; + List largeResponseIDs = new ArrayList<>(); while (rs.next()) { if (operationId != rs.getInt("OPERATION_ID")) { @@ -618,8 +837,12 @@ public class GenericOperationDAOImpl implements OperationDAO { } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); statusList.add(activityStatus); @@ -648,8 +871,12 @@ public class GenericOperationDAOImpl implements OperationDAO { rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); activity.getActivityStatus().add(activityStatus); @@ -659,19 +886,22 @@ public class GenericOperationDAOImpl implements OperationDAO { if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) { if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } } } } + if (!largeResponseIDs.isEmpty()) { + populateLargeOperationResponses(activities, largeResponseIDs); + } } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while getting the operation details from " + - "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e); + "the database. " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -680,7 +910,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } @Override - public int getTotalCountOfFilteredActivities(String operationCode)throws OperationManagementDAOException { + public int getTotalCountOfFilteredActivities(String operationCode) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; try { @@ -699,7 +929,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } } catch (SQLException e) { throw new OperationManagementDAOException( - "Error occurred while getting the activity count from " + "the database.", e); + "Error occurred while getting the activity count from the database. " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -728,8 +958,9 @@ public class GenericOperationDAOImpl implements OperationDAO { " opr.DEVICE_IDENTIFICATION, " + " opr.DEVICE_TYPE, " + " ops.RECEIVED_TIMESTAMP, " + - " ops.ID OP_RES_ID, " + + " ops.ID AS OP_RES_ID, " + " ops.OPERATION_RESPONSE , " + + " ops.IS_LARGE_RESPONSE , " + " opr.INITIATED_BY " + " FROM " + " (SELECT " + @@ -740,11 +971,11 @@ public class GenericOperationDAOImpl implements OperationDAO { " opm.OPERATION_ID, " + " op.OPERATION_CODE, " + " op.INITIATED_BY, " + - " op.TYPE OPERATION_TYPE, " + + " op.TYPE AS OPERATION_TYPE, " + " opm.STATUS, " + " en.DEVICE_ID, " + " de.DEVICE_IDENTIFICATION, " + - " dt.NAME DEVICE_TYPE, " + + " dt.NAME AS DEVICE_TYPE, " + " de.TENANT_ID " + " FROM" + " DM_ENROLMENT_OP_MAPPING opm " + @@ -780,6 +1011,7 @@ public class GenericOperationDAOImpl implements OperationDAO { int responseId = 0; Activity activity = null; ActivityStatus activityStatus = null; + List largeResponseIDs = new ArrayList<>(); while (rs.next()) { if (operationId != rs.getInt("OPERATION_ID")) { @@ -810,8 +1042,12 @@ public class GenericOperationDAOImpl implements OperationDAO { } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); statusList.add(activityStatus); @@ -840,8 +1076,12 @@ public class GenericOperationDAOImpl implements OperationDAO { rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); activity.getActivityStatus().add(activityStatus); @@ -851,18 +1091,21 @@ public class GenericOperationDAOImpl implements OperationDAO { if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) { if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } } } } + if (!largeResponseIDs.isEmpty()) { + populateLargeOperationResponses(activities, largeResponseIDs); + } } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while getting the operation details from " + - "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e); + "the database. " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -871,13 +1114,13 @@ public class GenericOperationDAOImpl implements OperationDAO { } - @Override public List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; List activities = new ArrayList<>(); + List largeResponseIDs = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); @@ -893,7 +1136,8 @@ public class GenericOperationDAOImpl implements OperationDAO { " opr.DEVICE_IDENTIFICATION, " + " opr.DEVICE_TYPE, " + " ops.RECEIVED_TIMESTAMP, " + - " ops.ID OP_RES_ID, " + + " ops.IS_LARGE_RESPONSE, " + + " ops.ID AS OP_RES_ID, " + " ops.OPERATION_RESPONSE " + " FROM " + " (SELECT " + @@ -903,11 +1147,11 @@ public class GenericOperationDAOImpl implements OperationDAO { " opm.UPDATED_TIMESTAMP, " + " opm.OPERATION_ID, " + " op.OPERATION_CODE, " + - " op.TYPE OPERATION_TYPE, " + + " op.TYPE AS OPERATION_TYPE, " + " opm.STATUS, " + " en.DEVICE_ID, " + " de.DEVICE_IDENTIFICATION, " + - " dt.NAME DEVICE_TYPE, " + + " dt.NAME AS DEVICE_TYPE, " + " de.TENANT_ID " + " FROM" + " DM_ENROLMENT_OP_MAPPING opm " + @@ -970,8 +1214,12 @@ public class GenericOperationDAOImpl implements OperationDAO { } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); statusList.add(activityStatus); @@ -1000,8 +1248,12 @@ public class GenericOperationDAOImpl implements OperationDAO { rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); activity.getActivityStatus().add(activityStatus); @@ -1011,18 +1263,21 @@ public class GenericOperationDAOImpl implements OperationDAO { if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) { if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } } } } + if (!largeResponseIDs.isEmpty()) { + populateLargeOperationResponses(activities, largeResponseIDs); + } } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while getting the operation details from " + - "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e); + "the database. " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -1035,9 +1290,8 @@ public class GenericOperationDAOImpl implements OperationDAO { ResultSet rs = null; try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT COUNT(*) AS COUNT FROM DM_ENROLMENT_OP_MAPPING m \n" - + "INNER JOIN DM_ENROLMENT d ON m.ENROLMENT_ID = d.ID \n" - + "WHERE m.UPDATED_TIMESTAMP > ? AND d.TENANT_ID = ?"; + String sql = "SELECT COUNT(*) AS COUNT FROM DM_ENROLMENT_OP_MAPPING WHERE " + + "UPDATED_TIMESTAMP > ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setLong(1, timestamp); stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); @@ -1047,7 +1301,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } } catch (SQLException e) { throw new OperationManagementDAOException( - "Error occurred while getting the activity count from " + "the database.", e); + "Error occurred while getting the activity count from the database. " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -1060,17 +1314,13 @@ public class GenericOperationDAOImpl implements OperationDAO { ResultSet rs = null; try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT \n" + - " COUNT(*) AS COUNT\n" + - "FROM\n" + - " DM_ENROLMENT_OP_MAPPING AS m\n" + - " INNER JOIN\n" + - " DM_ENROLMENT AS d ON m.ENROLMENT_ID = d.ID\n" + - " INNER JOIN \n" + - " DM_OPERATION dp ON dp.ID = m.OPERATION_ID \n" + - "WHERE\n" + - " m.UPDATED_TIMESTAMP > ? AND dp.INITIATED_BY = ?\n" + - " AND d.TENANT_ID = ?"; + String sql = "SELECT COUNT(*) AS COUNT " + + "FROM DM_ENROLMENT_OP_MAPPING AS m " + + " INNER JOIN " + + " DM_OPERATION dp ON dp.ID = m.OPERATION_ID " + + "WHERE m.UPDATED_TIMESTAMP > ?" + + " AND dp.INITIATED_BY = ?" + + " AND m.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setLong(1, timestamp); stmt.setString(2, user); @@ -1081,7 +1331,7 @@ public class GenericOperationDAOImpl implements OperationDAO { } } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while getting the activity count from " + - "the database.", e); + "the database. " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -1095,7 +1345,7 @@ public class GenericOperationDAOImpl implements OperationDAO { Operation operation = null; try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE FROM " + + String sql = "SELECT ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE, INITIATED_BY FROM " + "DM_OPERATION WHERE id = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, id); @@ -1112,6 +1362,7 @@ public class GenericOperationDAOImpl implements OperationDAO { operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); } operation.setCode(rs.getString("OPERATION_CODE")); + operation.setInitiatedBy(rs.getString("INITIATED_BY")); } } catch (SQLException e) { @@ -1270,8 +1521,8 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + - "OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + + String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + + "o.OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID " + "ORDER BY o.CREATED_TIMESTAMP DESC, o.ID DESC"; @@ -1312,8 +1563,8 @@ public class GenericOperationDAOImpl implements OperationDAO { List operations = new ArrayList(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + - "OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + + String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + + "o.OPERATION_CODE, om.STATUS, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID " + "ORDER BY o.CREATED_TIMESTAMP DESC, o.ID DESC LIMIT ?,?"; @@ -1364,7 +1615,7 @@ public class GenericOperationDAOImpl implements OperationDAO { operationCount = rs.getInt("OPERATION_COUNT"); } } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while getting the operations count for enrolment : " + throw new OperationManagementDAOException("Error occurred while getting the operations count for enrolment: " + enrolmentId, e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); @@ -1378,8 +1629,8 @@ public class GenericOperationDAOImpl implements OperationDAO { ResultSet rs = null; try { Connection connection = OperationManagementDAOFactory.getConnection(); - stmt = connection.prepareStatement("SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + - "OPERATION_CODE, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + + stmt = connection.prepareStatement("SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + + "o.OPERATION_CODE, om.ID AS OM_MAPPING_ID, om.UPDATED_TIMESTAMP FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID " + "ORDER BY om.UPDATED_TIMESTAMP ASC, om.ID ASC LIMIT 1"); @@ -1406,19 +1657,19 @@ public class GenericOperationDAOImpl implements OperationDAO { } return operation; } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while adding operation metadata", e); + throw new OperationManagementDAOException("Error occurred while getting operation metadata. " + + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } } - public List getOperationsByDeviceStatusAndType( int enrolmentId, Operation.Status status, Operation.Type type) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; Operation operation; - List operations = new ArrayList(); + List operations = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); String sql = "SELECT o.ID, TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, OPERATION_CODE, om.ID AS OM_MAPPING_ID, " + @@ -1499,7 +1750,8 @@ public class GenericOperationDAOImpl implements OperationDAO { operationMappings.add(operationMapping); } } catch (SQLException e) { - throw new OperationManagementDAOException("SQL error while getting operation mappings from database. ", e); + throw new OperationManagementDAOException("SQL error while getting operation mappings from database. " + + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } 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/OperationMappingDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java index dfe523f414..b57d313bdf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationMappingDAOImpl.java @@ -18,6 +18,7 @@ */ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping; @@ -39,17 +40,18 @@ import java.util.Map; public class OperationMappingDAOImpl implements OperationMappingDAO { @Override - public void addOperationMapping(int operationId, int enrollmentId, boolean isScheduled) throws + public void addOperationMapping(Operation operation, Integer deviceId, boolean isScheduled, Device device, Integer tenantId) throws OperationManagementDAOException { PreparedStatement stmt = null; try { long time = System.currentTimeMillis() / 1000; Connection conn = OperationManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID, OPERATION_ID, STATUS, " + - "PUSH_NOTIFICATION_STATUS, CREATED_TIMESTAMP, UPDATED_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?)"; + "PUSH_NOTIFICATION_STATUS, CREATED_TIMESTAMP, UPDATED_TIMESTAMP, OPERATION_CODE, INITIATED_BY, " + + "TYPE, DEVICE_TYPE, DEVICE_ID, DEVICE_IDENTIFICATION, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(sql); - stmt.setInt(1, enrollmentId); - stmt.setInt(2, operationId); + stmt.setInt(1, deviceId); + stmt.setInt(2, operation.getId()); stmt.setString(3, Operation.Status.PENDING.toString()); if (isScheduled) { stmt.setString(4, Operation.PushNotificationStatus.SCHEDULED.toString()); @@ -58,27 +60,36 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { } stmt.setLong(5, time); stmt.setLong(6, time); + stmt.setString(7, operation.getCode()); + stmt.setString(8, operation.getInitiatedBy()); + stmt.setString(9, operation.getType().toString()); + stmt.setString(10, device.getType()); + stmt.setInt(11, device.getId()); + stmt.setString(12, device.getDeviceIdentifier()); + stmt.setInt(13, tenantId); stmt.executeUpdate(); } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while persisting device operation mappings", e); + throw new OperationManagementDAOException("Error occurred while persisting device operation mappings. " + + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, null); } } @Override - public void addOperationMapping(int operationId, List enrollmentIds, boolean isScheduled) throws + public void addOperationMapping(Operation operation, List devices, boolean isScheduled, Integer tenantId) throws OperationManagementDAOException { PreparedStatement stmt = null; try { long time = System.currentTimeMillis() / 1000; Connection conn = OperationManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID, OPERATION_ID, STATUS, " + - "PUSH_NOTIFICATION_STATUS, CREATED_TIMESTAMP, UPDATED_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?)"; + "PUSH_NOTIFICATION_STATUS, CREATED_TIMESTAMP, UPDATED_TIMESTAMP, OPERATION_CODE, INITIATED_BY, " + + "TYPE, DEVICE_TYPE, DEVICE_ID, DEVICE_IDENTIFICATION, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(sql); - for (int enrollmentId : enrollmentIds) { - stmt.setInt(1, enrollmentId); - stmt.setInt(2, operationId); + for (Device device : devices) { + stmt.setInt(1, device.getEnrolmentInfo().getId()); + stmt.setInt(2, operation.getId()); stmt.setString(3, Operation.Status.PENDING.toString()); if (isScheduled) { stmt.setString(4, Operation.PushNotificationStatus.SCHEDULED.toString()); @@ -87,11 +98,19 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { } stmt.setLong(5, time); stmt.setLong(6, time); + stmt.setString(7, operation.getCode()); + stmt.setString(8, operation.getInitiatedBy()); + stmt.setString(9, operation.getType().toString()); + stmt.setString(10, device.getType()); + stmt.setInt(11, device.getId()); + stmt.setString(12, device.getDeviceIdentifier()); + stmt.setInt(13, tenantId); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while persisting device operation mappings", e); + throw new OperationManagementDAOException("Error occurred while persisting device operation mappings. " + + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, null); } @@ -109,14 +128,17 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { stmt.setInt(2, operationId); stmt.executeUpdate(); } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while persisting device operation mappings", e); + throw new OperationManagementDAOException("Error occurred while persisting device operation mappings. " + + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, null); } } @Override - public void updateOperationMapping(int operationId, Integer deviceId, Operation.PushNotificationStatus pushNotificationStatus) throws OperationManagementDAOException { + public void updateOperationMapping(int operationId, Integer deviceId, + Operation.PushNotificationStatus pushNotificationStatus) + throws OperationManagementDAOException { PreparedStatement stmt = null; try { Connection conn = OperationManagementDAOFactory.getConnection(); @@ -128,7 +150,8 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { stmt.setInt(3, operationId); stmt.executeUpdate(); } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while updating device operation mappings", e); + throw new OperationManagementDAOException("Error occurred while updating device operation mappings. " + + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, null); } @@ -161,7 +184,7 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { } } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while updating device operation mappings as " + - "batch ", e); + "batch . " + e.getMessage(), e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, null); } @@ -172,7 +195,7 @@ public class OperationMappingDAOImpl implements OperationMappingDAO { long maxDuration, int deviceTypeId) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; - List enrolmentOperationMappingList = null; + List enrolmentOperationMappingList; try { Connection conn = OperationManagementDAOFactory.getConnection(); //We are specifically looking for operation mappings in 'Pending' & 'Repeated' states. Further we want 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/PolicyOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java index 8801921c1f..39b6212e50 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java @@ -61,7 +61,7 @@ public class PolicyOperationDAOImpl extends GenericOperationDAOImpl { oos = new ObjectOutputStream(bao); oos.writeObject(operation); - stmt.setObject(6, operation); + stmt.setBytes(6, bao.toByteArray()); stmt.setBoolean(7, operation.isEnabled()); stmt.executeUpdate(); 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/operation/MySQLOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/MySQLOperationDAOImpl.java index e5d8fc36ce..d65f7a49d5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/MySQLOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/MySQLOperationDAOImpl.java @@ -18,19 +18,19 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; 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.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil; -import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -43,6 +43,8 @@ import java.util.List; */ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { + private static final Log log = LogFactory.getLog(MySQLOperationDAOImpl.class); + @Override public List getActivityList(List activityIds) throws OperationManagementDAOException { PreparedStatement stmt = null; @@ -53,23 +55,34 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql1 = "SELECT eom.ENROLMENT_ID, eom.OPERATION_ID, eom.ID AS EOM_MAPPING_ID, " - + "dor.ID AS OP_RES_ID, de.DEVICE_ID, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID, " - + "dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, " - + "eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, " - + "dor.OPERATION_RESPONSE, dor.RECEIVED_TIMESTAMP, op.INITIATED_BY FROM " - + "DM_ENROLMENT_OP_MAPPING eom INNER JOIN DM_OPERATION op " - + "ON op.ID=eom.OPERATION_ID INNER JOIN DM_ENROLMENT de " - + "ON de.ID=eom.ENROLMENT_ID INNER JOIN DM_DEVICE d ON d.ID=de.DEVICE_ID \n" - + "INNER JOIN DM_DEVICE_TYPE dt ON dt.ID=d.DEVICE_TYPE_ID\n" - + "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE dor ON dor.ENROLMENT_ID=de.id \n" - + "AND dor.OPERATION_ID = eom.OPERATION_ID WHERE eom.OPERATION_ID " + "IN ("; + String sql1 = "SELECT " + + " eom.ENROLMENT_ID," + + " eom.CREATED_TIMESTAMP," + + " eom.UPDATED_TIMESTAMP," + + " eom.OPERATION_ID," + + " eom.OPERATION_CODE," + + " eom.INITIATED_BY," + + " eom.TYPE," + + " eom.STATUS," + + " eom.DEVICE_ID," + + " eom.DEVICE_IDENTIFICATION," + + " eom.DEVICE_TYPE," + + " opr.ID AS OP_RES_ID," + + " opr.RECEIVED_TIMESTAMP," + + " opr.OPERATION_RESPONSE," + + " opr.IS_LARGE_RESPONSE " + + "FROM " + + " DM_ENROLMENT_OP_MAPPING eom " + + " LEFT JOIN " + + " DM_DEVICE_OPERATION_RESPONSE opr ON opr.EN_OP_MAP_ID = eom.ID " + + "WHERE " + + " eom.OPERATION_ID IN ("; StringBuilder builder = new StringBuilder(); for (int i = 0; i < activityIds.size(); i++) { builder.append("?,"); } - sql1 += builder.deleteCharAt(builder.length() - 1).toString() + ") AND de.TENANT_ID = ?"; + sql1 += builder.deleteCharAt(builder.length() - 1).toString() + ") AND eom.TENANT_ID = ?"; stmt = conn.prepareStatement(sql1); int i; for (i = 0; i < activityIds.size(); i++) { @@ -83,6 +96,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { int enrolmentId = 0; int responseId = 0; ActivityStatus activityStatus = new ActivityStatus(); + List largeResponseIDs = new ArrayList<>(); while (rs.next()) { activity = new Activity(); @@ -94,7 +108,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { operationId = rs.getInt("OPERATION_ID"); enrolmentId = rs.getInt("ENROLMENT_ID"); - activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); + activity.setType(Activity.Type.valueOf(rs.getString("TYPE"))); activity.setCreatedTimeStamp( new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); activity.setCode(rs.getString("OPERATION_CODE")); @@ -102,7 +116,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); - deviceIdentifier.setType(rs.getString("DEVICE_TYPE_NAME")); + deviceIdentifier.setType(rs.getString("DEVICE_TYPE")); activityStatus.setDeviceIdentifier(deviceIdentifier); @@ -115,8 +129,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); statusList.add(activityStatus); @@ -127,7 +145,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { if (operationId == rs.getInt("OPERATION_ID") && enrolmentId != rs.getInt("ENROLMENT_ID")) { activityStatus = new ActivityStatus(); - activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); + activity.setType(Activity.Type.valueOf(rs.getString("TYPE"))); activity.setCreatedTimeStamp( new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); activity.setCode(rs.getString("OPERATION_CODE")); @@ -135,7 +153,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); - deviceIdentifier.setType(rs.getString("DEVICE_TYPE_NAME")); + deviceIdentifier.setType(rs.getString("DEVICE_TYPE")); activityStatus.setDeviceIdentifier(deviceIdentifier); activityStatus.setStatus(ActivityStatus.Status.valueOf(rs.getString("STATUS"))); @@ -146,8 +164,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { new java.util.Date(rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); activity.getActivityStatus().add(activityStatus); @@ -157,31 +179,30 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID") && rs.getTimestamp( "RECEIVED_TIMESTAMP") != null) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } } } - + if(!largeResponseIDs.isEmpty()) { + populateLargeOperationResponses(activities, largeResponseIDs); + } } catch (SQLException e) { throw new OperationManagementDAOException( "Error occurred while getting the operation details from " + "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException( - "Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException( - "IO exception occurred while converting the operations responses.", e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } return activities; } - - @Override public List getActivitiesUpdatedAfter(long timestamp, int limit, - int offset) throws OperationManagementDAOException { + int offset) + throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; List activities = new ArrayList<>(); @@ -189,51 +210,32 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { Connection conn = OperationManagementDAOFactory.getConnection(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String sql = "SELECT " + - " opr.ENROLMENT_ID, " + - " opr.CREATED_TIMESTAMP, " + - " opr.UPDATED_TIMESTAMP, " + - " opr.OPERATION_ID, " + - " opr.OPERATION_CODE, " + - " opr.INITIATED_BY, " + - " opr.OPERATION_TYPE, " + - " opr.STATUS, " + - " opr.DEVICE_ID, " + - " opr.DEVICE_IDENTIFICATION, " + - " opr.DEVICE_TYPE, " + - " ops.RECEIVED_TIMESTAMP, " + - " ops.ID OP_RES_ID, " + - " ops.OPERATION_RESPONSE " + - " FROM " + - " (SELECT " + - " opm.ID MAPPING_ID, " + - " opm.ENROLMENT_ID, " + - " opm.CREATED_TIMESTAMP, " + - " opm.UPDATED_TIMESTAMP, " + - " opm.OPERATION_ID, " + - " op.OPERATION_CODE, " + - " op.INITIATED_BY, " + - " op.TYPE OPERATION_TYPE, " + - " opm.STATUS, " + - " en.DEVICE_ID, " + - " de.DEVICE_IDENTIFICATION, " + - " dt.NAME DEVICE_TYPE, " + - " de.TENANT_ID " + - " FROM" + - " DM_ENROLMENT_OP_MAPPING opm FORCE INDEX (IDX_ENROLMENT_OP_MAPPING) " + - " INNER JOIN DM_OPERATION op ON opm.OPERATION_ID = op.ID " + - " INNER JOIN DM_ENROLMENT en ON opm.ENROLMENT_ID = en.ID " + - " INNER JOIN DM_DEVICE de ON en.DEVICE_ID = de.ID " + - " INNER JOIN DM_DEVICE_TYPE dt ON dt.ID = de.DEVICE_TYPE_ID " + - " WHERE" + - " opm.UPDATED_TIMESTAMP > ? " + - " AND de.TENANT_ID = ? " + - " ORDER BY opm.UPDATED_TIMESTAMP " + - " LIMIT ? OFFSET ?) opr " + - " LEFT JOIN DM_DEVICE_OPERATION_RESPONSE ops ON opr.MAPPING_ID = ops.EN_OP_MAP_ID " + - " WHERE " + - " opr.UPDATED_TIMESTAMP > ? " + - " AND opr.TENANT_ID = ? "; + " eom.ENROLMENT_ID," + + " eom.CREATED_TIMESTAMP," + + " eom.UPDATED_TIMESTAMP," + + " eom.OPERATION_ID," + + " eom.OPERATION_CODE," + + " eom.INITIATED_BY," + + " eom.TYPE," + + " eom.STATUS," + + " eom.DEVICE_ID," + + " eom.DEVICE_IDENTIFICATION," + + " eom.DEVICE_TYPE," + + " opr.ID AS OP_RES_ID," + + " opr.RECEIVED_TIMESTAMP," + + " opr.OPERATION_RESPONSE," + + " opr.IS_LARGE_RESPONSE " + + "FROM " + + " DM_ENROLMENT_OP_MAPPING eom FORCE INDEX (IDX_ENROLMENT_OP_MAPPING) " + + " LEFT JOIN " + + " DM_DEVICE_OPERATION_RESPONSE opr ON opr.EN_OP_MAP_ID = eom.ID " + + "WHERE " + + " eom.UPDATED_TIMESTAMP > ? " + + " AND eom.TENANT_ID = ? " + + "ORDER BY eom.UPDATED_TIMESTAMP " + + "LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); @@ -241,8 +243,6 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { stmt.setInt(2, tenantId); stmt.setInt(3, limit); stmt.setInt(4, offset); - stmt.setLong(5, timestamp); - stmt.setInt(6, tenantId); rs = stmt.executeQuery(); @@ -251,6 +251,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { int responseId = 0; Activity activity = null; ActivityStatus activityStatus = null; + List largeResponseIDs = new ArrayList<>(); while (rs.next()) { if (operationId != rs.getInt("OPERATION_ID")) { @@ -262,7 +263,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { operationId = rs.getInt("OPERATION_ID"); enrolmentId = rs.getInt("ENROLMENT_ID"); - activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); + activity.setType(Activity.Type.valueOf(rs.getString("TYPE"))); activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); activity.setCode(rs.getString("OPERATION_CODE")); activity.setInitiatedBy(rs.getString("INITIATED_BY")); @@ -281,8 +282,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); statusList.add(activityStatus); @@ -294,7 +299,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { if (operationId == rs.getInt("OPERATION_ID") && enrolmentId != rs.getInt("ENROLMENT_ID")) { activityStatus = new ActivityStatus(); - activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); + activity.setType(Activity.Type.valueOf(rs.getString("TYPE"))); activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); activity.setCode(rs.getString("OPERATION_CODE")); activity.setInitiatedBy(rs.getString("INITIATED_BY")); @@ -312,8 +317,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); activity.getActivityStatus().add(activityStatus); @@ -323,18 +332,21 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) { if (rs.getTimestamp("RECEIVED_TIMESTAMP") != null) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } } } } + if(!largeResponseIDs.isEmpty()) { + populateLargeOperationResponses(activities, largeResponseIDs); + } } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while getting the operation details from " + "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -347,66 +359,55 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { PreparedStatement stmt = null; ResultSet rs = null; List activities = new ArrayList<>(); + List largeResponseIDs = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + String sql = "SELECT " + - " opr.ENROLMENT_ID, " + - " opr.CREATED_TIMESTAMP, " + - " opr.UPDATED_TIMESTAMP, " + - " opr.OPERATION_ID, " + - " opr.OPERATION_CODE, " + - " opr.INITIATED_BY, " + - " opr.OPERATION_TYPE, " + - " opr.STATUS, " + - " opr.DEVICE_ID, " + - " opr.DEVICE_IDENTIFICATION, " + - " opr.DEVICE_TYPE, " + - " ops.RECEIVED_TIMESTAMP, " + - " ops.ID OP_RES_ID, " + - " ops.OPERATION_RESPONSE " + - " FROM " + - " (SELECT " + - " opm.ID MAPPING_ID, " + - " opm.ENROLMENT_ID, " + - " opm.CREATED_TIMESTAMP, " + - " opm.UPDATED_TIMESTAMP, " + - " opm.OPERATION_ID, " + - " op.OPERATION_CODE, " + - " op.INITIATED_BY, " + - " op.TYPE OPERATION_TYPE, " + - " opm.STATUS, " + - " en.DEVICE_ID, " + - " de.DEVICE_IDENTIFICATION, " + - " dt.NAME DEVICE_TYPE, " + - " de.TENANT_ID " + - " FROM" + - " DM_ENROLMENT_OP_MAPPING opm FORCE INDEX (IDX_ENROLMENT_OP_MAPPING) " + - " INNER JOIN DM_OPERATION op ON opm.OPERATION_ID = op.ID " + - " INNER JOIN DM_ENROLMENT en ON opm.ENROLMENT_ID = en.ID " + - " INNER JOIN DM_DEVICE de ON en.DEVICE_ID = de.ID " + - " INNER JOIN DM_DEVICE_TYPE dt ON dt.ID = de.DEVICE_TYPE_ID " + - " WHERE" + - " opm.UPDATED_TIMESTAMP > ? AND op.INITIATED_BY = ?" + - " AND de.TENANT_ID = ? " + - " ORDER BY opm.UPDATED_TIMESTAMP " + - " LIMIT ? OFFSET ?) opr " + - " LEFT JOIN DM_DEVICE_OPERATION_RESPONSE ops ON opr.MAPPING_ID = ops.EN_OP_MAP_ID " + - " WHERE " + - " opr.UPDATED_TIMESTAMP > ? AND opr.INITIATED_BY = ? " + - " AND opr.TENANT_ID = ? "; + " eom.ENROLMENT_ID," + + " eom.CREATED_TIMESTAMP," + + " eom.UPDATED_TIMESTAMP," + + " eom.OPERATION_ID," + + " eom.OPERATION_CODE," + + " eom.INITIATED_BY," + + " eom.TYPE," + + " eom.STATUS," + + " eom.DEVICE_ID," + + " eom.DEVICE_IDENTIFICATION," + + " eom.DEVICE_TYPE," + + " opr.ID AS OP_RES_ID," + + " opr.RECEIVED_TIMESTAMP," + + " opr.OPERATION_RESPONSE," + + " opr.IS_LARGE_RESPONSE " + + "FROM " + + " DM_ENROLMENT_OP_MAPPING eom FORCE INDEX (IDX_ENROLMENT_OP_MAPPING) " + + " LEFT JOIN " + + " DM_DEVICE_OPERATION_RESPONSE opr ON opr.EN_OP_MAP_ID = eom.ID " + + "WHERE " + + " eom.UPDATED_TIMESTAMP > ? " + + " AND eom.TENANT_ID = ? " + + " AND eom.INITIATED_BY = ? " + + "ORDER BY eom.UPDATED_TIMESTAMP " + + "LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setLong(1, timestamp); - stmt.setString(2, user); - stmt.setInt(3, tenantId); + stmt.setInt(2, tenantId); + stmt.setString(3, user); stmt.setInt(4, limit); stmt.setInt(5, offset); - stmt.setLong(6, timestamp); - stmt.setString(7, user); - stmt.setInt(8, tenantId); + +// stmt.setLong(1, timestamp); +// stmt.setString(2, user); +// stmt.setInt(3, tenantId); +// stmt.setInt(4, limit); +// stmt.setInt(5, offset); +// stmt.setLong(6, timestamp); +// stmt.setString(7, user); +// stmt.setInt(8, tenantId); rs = stmt.executeQuery(); @@ -426,7 +427,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { operationId = rs.getInt("OPERATION_ID"); enrolmentId = rs.getInt("ENROLMENT_ID"); - activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); + activity.setType(Activity.Type.valueOf(rs.getString("TYPE"))); activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); activity.setCode(rs.getString("OPERATION_CODE")); activity.setInitiatedBy(rs.getString("INITIATED_BY")); @@ -445,8 +446,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); statusList.add(activityStatus); @@ -458,7 +463,7 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { if (operationId == rs.getInt("OPERATION_ID") && enrolmentId != rs.getInt("ENROLMENT_ID")) { activityStatus = new ActivityStatus(); - activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); + activity.setType(Activity.Type.valueOf(rs.getString("TYPE"))); activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); activity.setCode(rs.getString("OPERATION_CODE")); activity.setInitiatedBy(rs.getString("INITIATED_BY")); @@ -476,8 +481,12 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); activity.getActivityStatus().add(activityStatus); @@ -487,31 +496,25 @@ public class MySQLOperationDAOImpl extends GenericOperationDAOImpl { if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) { if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } } } } + if(!largeResponseIDs.isEmpty()) { + populateLargeOperationResponses(activities, largeResponseIDs); + } } catch (SQLException e) { throw new OperationManagementDAOException("Error occurred while getting the operation details from " + "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } return activities; } - private Integer[] getIntArrayOfActivityIds(List activityIds) { - Integer[] arr = new Integer[activityIds.size()]; - int x = 0; - for (Integer activityId : activityIds) { - arr[x] = activityId; - x++; - } - return arr; - } } \ 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/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java index f7a61fe8a7..45d656e194 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java @@ -188,6 +188,7 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { PreparedStatement stmt = null; ResultSet rs = null; List activities = new ArrayList<>(); + List largeResponseIDs = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); /*String sql = "SELECT opm.ENROLMENT_ID, opm.CREATED_TIMESTAMP, opm.UPDATED_TIMESTAMP, opm.OPERATION_ID,\n" @@ -224,6 +225,7 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { " opr.DEVICE_TYPE, " + " ops.RECEIVED_TIMESTAMP, " + " ops.ID OP_RES_ID, " + + " ops.IS_LARGE_RESPONSE, " + " ops.OPERATION_RESPONSE " + " FROM " + " (SELECT " + @@ -301,8 +303,12 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); statusList.add(activityStatus); @@ -332,8 +338,12 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { new java.util.Date(rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); activity.getActivityStatus().add(activityStatus); @@ -343,20 +353,21 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) { if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } } } } + if(!largeResponseIDs.isEmpty()) { + populateLargeOperationResponses(activities, largeResponseIDs); + } } catch (SQLException e) { throw new OperationManagementDAOException( "Error occurred while getting the operation details from " + "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException( - "Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException( - "IO exception occurred while converting the operations responses.", e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } 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/operation/PostgreSQLOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java index a43f5f235d..17ccdb27ce 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation; import org.wso2.carbon.device.mgt.common.PaginationRequest; 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.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; @@ -30,7 +31,9 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Timestamp; import java.util.ArrayList; +import java.util.Date; import java.util.List; /** @@ -126,4 +129,63 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { } return operations; } + + @Override + public OperationResponseMeta addOperationResponse(int enrolmentId, org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation, + String deviceId) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + boolean isLargeResponse = false; + try { + Connection connection = OperationManagementDAOFactory.getConnection(); + + stmt = connection.prepareStatement("SELECT ID FROM DM_ENROLMENT_OP_MAPPING WHERE ENROLMENT_ID = ? " + + "AND OPERATION_ID = ?"); + stmt.setInt(1, enrolmentId); + stmt.setInt(2, operation.getId()); + + rs = stmt.executeQuery(); + int enPrimaryId = 0; + if (rs.next()) { + enPrimaryId = rs.getInt("ID"); + } + stmt = connection.prepareStatement("INSERT INTO DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLMENT_ID, " + + "EN_OP_MAP_ID, OPERATION_RESPONSE, IS_LARGE_RESPONSE, RECEIVED_TIMESTAMP) VALUES(?, ?, ?, ?, ?, ?)", + new String[]{"id"}); + stmt.setInt(1, operation.getId()); + stmt.setInt(2, enrolmentId); + stmt.setInt(3, enPrimaryId); + + if (operation.getOperationResponse() != null && operation.getOperationResponse().length() >= 1000) { + isLargeResponse = true; + stmt.setBytes(4, null); + } else { + stmt.setString(4, operation.getOperationResponse()); + } + stmt.setBoolean(5, isLargeResponse); + + Timestamp receivedTimestamp = new Timestamp(new Date().getTime()); + stmt.setTimestamp(6, receivedTimestamp); + stmt.executeUpdate(); + + rs = stmt.getGeneratedKeys(); + int opResID = -1; + if (rs.next()) { + opResID = rs.getInt(1); + } + + OperationResponseMeta responseMeta = new OperationResponseMeta(); + responseMeta.setId(opResID); + responseMeta.setEnrolmentId(enrolmentId); + responseMeta.setOperationMappingId(enPrimaryId); + responseMeta.setReceivedTimestamp(receivedTimestamp); + responseMeta.setLargeResponse(isLargeResponse); + return responseMeta; + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while inserting operation response. " + + e.getMessage(), e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + } } 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/operation/SQLServerOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java index c07735a6f6..5c486bac29 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java @@ -166,6 +166,7 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { PreparedStatement stmt = null; ResultSet rs = null; List activities = new ArrayList<>(); + List largeResponseIDs = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); /*String sql = "SELECT opm.ENROLMENT_ID, opm.CREATED_TIMESTAMP, opm.UPDATED_TIMESTAMP, opm.OPERATION_ID,\n" @@ -201,6 +202,7 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { " opr.DEVICE_TYPE, " + " ops.RECEIVED_TIMESTAMP, " + " ops.ID OP_RES_ID, " + + " ops.IS_LARGE_RESPONSE, " + " ops.OPERATION_RESPONSE " + " FROM " + " (SELECT " + @@ -277,8 +279,12 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); statusList.add(activityStatus); @@ -308,8 +314,12 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { new java.util.Date(rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); } if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); + } } activityStatus.setResponses(operationResponses); activity.getActivityStatus().add(activityStatus); @@ -319,20 +329,21 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) { if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); responseId = rs.getInt("OP_RES_ID"); + if (rs.getBoolean("IS_LARGE_RESPONSE")) { + largeResponseIDs.add(responseId); + } else { + activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); + } } } } + if(!largeResponseIDs.isEmpty()) { + populateLargeOperationResponses(activities, largeResponseIDs); + } } catch (SQLException e) { throw new OperationManagementDAOException( "Error occurred while getting the operation details from " + "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException( - "Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException( - "IO exception occurred while converting the operations responses.", e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java index efabf9bee6..65fe7b99f3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java @@ -123,8 +123,8 @@ public class OperationDAOUtil { return operation; } - public static OperationResponse getOperationResponse(ResultSet rs) throws - ClassNotFoundException, IOException, SQLException { + public static OperationResponse getLargeOperationResponse(ResultSet rs) throws + ClassNotFoundException, IOException, SQLException { OperationResponse response = new OperationResponse(); if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); @@ -158,6 +158,18 @@ public class OperationDAOUtil { return response; } + + public static OperationResponse getOperationResponse(ResultSet rs) throws SQLException { + OperationResponse response = new OperationResponse(); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { + response.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + if (rs.getString("OPERATION_RESPONSE") != null) { + response.setResponse(rs.getString("OPERATION_RESPONSE")); + } + return response; + } + public static Operation.Type getType(String type) { return Operation.Type.valueOf(type); } 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 a2f42c4e37..5bb5c70f54 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 @@ -89,6 +89,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; @@ -659,10 +660,7 @@ public interface DeviceManagementProviderService { boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) throws DeviceManagementException; - boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException; - - boolean setStatus(DeviceIdentifier deviceId, String currentOwner, - EnrolmentInfo.Status status) throws DeviceManagementException; + boolean setStatus(Device device, EnrolmentInfo.Status status) throws DeviceManagementException; boolean setStatus(String currentOwner, EnrolmentInfo.Status status) throws DeviceManagementException; @@ -672,11 +670,16 @@ public interface DeviceManagementProviderService { Activity addOperation(String type, Operation operation, List devices) throws OperationManagementException, InvalidDeviceException; + void addTaskOperation(String deviceType, Operation operation) throws OperationManagementException; + List getOperations(DeviceIdentifier deviceId) throws OperationManagementException; PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException; + List getOperations(DeviceIdentifier deviceId, Operation.Status status) + throws OperationManagementException; + List getPendingOperations( DeviceIdentifier deviceId) throws OperationManagementException; @@ -805,7 +808,7 @@ public interface DeviceManagementProviderService { boolean bulkUpdateDeviceStatus(String deviceType, List deviceList, String status) throws DeviceManagementException; - boolean updateEnrollment(String owner, List deviceIdentifiers) + boolean updateEnrollment(String owner, boolean isTransfer, List deviceIdentifiers) throws DeviceManagementException, UserNotFoundException, InvalidDeviceException; boolean addDeviceTypeVersion(DeviceTypeVersion deviceTypeVersion) 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 26dae9327e..f736ed2140 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 @@ -14,42 +14,7 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - * - * - * 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 - * - * 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. - */ -/* - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. */ - package org.wso2.carbon.device.mgt.core.service; import org.apache.commons.collections.map.SingletonMap; @@ -67,45 +32,45 @@ import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; -import org.wso2.carbon.device.mgt.common.DeviceManager; -import org.wso2.carbon.device.mgt.common.FeatureManager; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceEnrollmentInfoNotification; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManager; +import org.wso2.carbon.device.mgt.common.DeviceNotification; +import org.wso2.carbon.device.mgt.common.DevicePropertyNotification; +import org.wso2.carbon.device.mgt.common.DeviceTransferRequest; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.InitialOperationConfig; 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.StartupOperationConfig; -import org.wso2.carbon.device.mgt.common.InitialOperationConfig; -import org.wso2.carbon.device.mgt.common.DeviceTransferRequest; -import org.wso2.carbon.device.mgt.common.DevicePropertyNotification; -import org.wso2.carbon.device.mgt.common.DeviceEnrollmentInfoNotification; -import org.wso2.carbon.device.mgt.common.DeviceNotification; -import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; -import org.wso2.carbon.device.mgt.common.configuration.mgt.EnrollmentConfiguration; -import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot; -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; -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.exceptions.UnauthorizedDeviceAccessException; -import org.wso2.carbon.device.mgt.common.exceptions.UserNotFoundException; -import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException; import org.wso2.carbon.device.mgt.common.app.mgt.Application; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfigurationException; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.DeviceConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.DevicePropertyInfo; +import org.wso2.carbon.device.mgt.common.configuration.mgt.EnrollmentConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.device.details.DeviceData; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot; 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; +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.exceptions.UnauthorizedDeviceAccessException; +import org.wso2.carbon.device.mgt.common.exceptions.UserNotFoundException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; @@ -138,8 +103,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.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.dto.DeviceTypeServiceIdentifier; @@ -169,12 +132,12 @@ import java.io.StringWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; +import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; -import java.util.Arrays; import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; @@ -182,31 +145,28 @@ import java.util.stream.Collectors; public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, PluginInitializationListener { - private static Log log = LogFactory.getLog(DeviceManagementProviderServiceImpl.class); + private static final Log log = LogFactory.getLog(DeviceManagementProviderServiceImpl.class); + private static final String OPERATION_RESPONSE_EVENT_STREAM_DEFINITION = "org.wso2.iot.OperationResponseStream"; - private DeviceDAO deviceDAO; - private DeviceDetailsDAO deviceInfoDAO; - private DeviceTypeDAO deviceTypeDAO; - private EnrollmentDAO enrollmentDAO; - private ApplicationDAO applicationDAO; - private DeviceManagementPluginRepository pluginRepository; - private DeviceInformationManager deviceInformationManager; + private final DeviceManagementPluginRepository pluginRepository; + private final DeviceInformationManager deviceInformationManager; + private final DeviceDAO deviceDAO; + private final DeviceTypeDAO deviceTypeDAO; + private final EnrollmentDAO enrollmentDAO; + private final ApplicationDAO applicationDAO; public DeviceManagementProviderServiceImpl() { this.pluginRepository = new DeviceManagementPluginRepository(); this.deviceInformationManager = new DeviceInformationManagerImpl(); - initDataAccessObjects(); - /* Registering a listener to retrieve events when some device management service plugin is installed after - * the component is done getting initialized */ - DeviceManagementServiceComponent.registerPluginInitializationListener(this); - } - private void initDataAccessObjects() { this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); - this.deviceInfoDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO(); this.applicationDAO = DeviceManagementDAOFactory.getApplicationDAO(); this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); this.enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); + + /* Registering a listener to retrieve events when some device management service plugin is installed after + * the component is done getting initialized */ + DeviceManagementServiceComponent.registerPluginInitializationListener(this); } @Override @@ -251,11 +211,23 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.error(msg); throw new DeviceManagementException(msg); } + if (device.getEnrolmentInfo() == null) { + String msg = "Received device without valid enrollment info for device enrollment"; + log.error(msg); + throw new DeviceManagementException(msg); + } + if (device.getEnrolmentInfo().getStatus() == null) { + device.getEnrolmentInfo().setStatus(EnrolmentInfo.Status.ACTIVE); + } + if (log.isDebugEnabled()) { + log.debug("Enrolling the device " + device.getId() + "of type '" + device.getType() + "'"); + } + DeviceManager deviceManager = this.getDeviceManager(device.getType()); if (deviceManager == null) { if (log.isDebugEnabled()) { log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + - "Therefore, not attempting method 'enrollDevice'"); + "Therefore, not attempting method 'enrollDevice'"); } return false; } @@ -264,10 +236,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv String deviceSerialNumber = null; if (enrollmentConfiguration != null) { deviceSerialNumber = DeviceManagerUtil.getPropertyString(device.getProperties(), - DeviceManagementConstants.Common.SERIAL); + DeviceManagementConstants.Common.SERIAL); if (!DeviceManagerUtil.isDeviceEnrollable(enrollmentConfiguration, deviceSerialNumber)) { String msg = "Serial number based enrollment has been enabled and device having the serial number '" - + deviceSerialNumber + "' is not configured to be enrolled."; + + deviceSerialNumber + "' is not configured to be enrolled."; log.error(msg); throw new DeviceManagementException(msg); } @@ -278,36 +250,44 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv boolean status = false; DeviceIdentifier deviceIdentifier = new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()); - deviceManager.enrollDevice(device); - if (deviceManager.isClaimable(deviceIdentifier)) { - device.getEnrolmentInfo().setStatus(EnrolmentInfo.Status.INACTIVE); - } else { - device.getEnrolmentInfo().setStatus(EnrolmentInfo.Status.ACTIVE); - } int tenantId = this.getTenantId(); - Device existingDevice = this.getDevice(deviceIdentifier, false); if (existingDevice != null) { + deviceManager.modifyEnrollment(device); EnrolmentInfo existingEnrolmentInfo = existingDevice.getEnrolmentInfo(); EnrolmentInfo newEnrolmentInfo = device.getEnrolmentInfo(); if (existingEnrolmentInfo != null && newEnrolmentInfo != null) { - //Get all the enrollments of current user for the same device - List enrolmentInfos = this.getEnrollmentsOfUser(existingDevice.getId(), - newEnrolmentInfo.getOwner()); - for (EnrolmentInfo enrolmentInfo : enrolmentInfos) { - //If the enrollments are same then we'll update the existing enrollment. - if (enrolmentInfo.equals(newEnrolmentInfo)) { - device.setId(existingDevice.getId()); - device.getEnrolmentInfo().setDateOfEnrolment(enrolmentInfo.getDateOfEnrolment()); - device.getEnrolmentInfo().setDateOfLastUpdate(enrolmentInfo.getDateOfLastUpdate()); - device.getEnrolmentInfo().setId(enrolmentInfo.getId()); - this.modifyEnrollment(device); - status = true; - break; + if (existingDevice.getEnrolmentInfo().isTransferred() + && existingDevice.getEnrolmentInfo().getStatus() != EnrolmentInfo.Status.REMOVED) { + newEnrolmentInfo = existingEnrolmentInfo; + status = true; + } else { + //Get all the enrollments of current user for the same device + List enrolmentInfos = this.getEnrollmentsOfUser(existingDevice.getId(), + newEnrolmentInfo.getOwner()); + for (EnrolmentInfo enrolmentInfo : enrolmentInfos) { + //If the enrollments are same (owner & ownership) then we'll update the existing enrollment. + if (enrolmentInfo.equals(newEnrolmentInfo)) { + newEnrolmentInfo.setDateOfEnrolment(enrolmentInfo.getDateOfEnrolment()); + newEnrolmentInfo.setId(enrolmentInfo.getId()); + //We are explicitly setting device status only if matching device enrollment is in + // removed status. + if (enrolmentInfo.getStatus() == EnrolmentInfo.Status.REMOVED) { + newEnrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + } else { + newEnrolmentInfo.setStatus(enrolmentInfo.getStatus()); + } + status = true; + break; + } } } - if (!status) { + if (status) { + device.setId(existingDevice.getId()); + device.setEnrolmentInfo(newEnrolmentInfo); + this.modifyEnrollment(device); + } else { int updateStatus = 0; EnrolmentInfo enrollment; try { @@ -315,13 +295,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.beginTransaction(); if (!EnrolmentInfo.Status.REMOVED.equals(existingEnrolmentInfo.getStatus())) { existingEnrolmentInfo.setStatus(EnrolmentInfo.Status.REMOVED); - updateStatus = enrollmentDAO.updateEnrollment(existingEnrolmentInfo); + updateStatus = enrollmentDAO.updateEnrollment(existingEnrolmentInfo, tenantId); } if ((updateStatus > 0) || EnrolmentInfo.Status.REMOVED. equals(existingEnrolmentInfo.getStatus())) { enrollment = enrollmentDAO .addEnrollment(existingDevice.getId(), newEnrolmentInfo, tenantId); - if (enrollment == null ){ + if (enrollment == null) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceManagementException( "Enrollment data persistence is failed in a re-enrollment. Existing device: " @@ -339,16 +319,16 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } status = true; } else { - log.warn("Unable to update device enrollment for device : " + device.toString()); + log.warn("Unable to update device enrollment for device : " + device.getDeviceIdentifier() + + " belonging to user : " + device.getEnrolmentInfo().getOwner()); } } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred while adding enrolment related metadata for device: " + - device.toString(); + String msg = "Error occurred while adding enrolment related metadata for device: " + device.getId(); log.error(msg, e); throw new DeviceManagementException(msg, e); } catch (Exception e) { - String msg = "Error occurred while enrolling device: " + device.toString(); + String msg = "Error occurred while enrolling device: " + device.getId(); log.error(msg, e); throw new DeviceManagementException(msg, e); } finally { @@ -357,14 +337,16 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } } } else { + deviceManager.enrollDevice(device); EnrolmentInfo enrollment; try { DeviceManagementDAOFactory.beginTransaction(); DeviceType type = deviceTypeDAO.getDeviceType(device.getType(), tenantId); if (type != null) { int deviceId = deviceDAO.addDevice(type.getId(), device, tenantId); + device.setId(deviceId); enrollment = enrollmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId); - if (enrollment == null ){ + if (enrollment == null) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceManagementException( "Enrollment data persistence is failed in a new enrollment. Device: " + device.toString()); @@ -379,7 +361,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred while adding metadata of device: " + device.toString(); + String msg = "Error occurred while adding metadata of '" + device.getType() + + "' device carrying the identifier '" + device.getDeviceIdentifier() + "'"; log.error(msg, e); throw new DeviceManagementException(msg, e); } catch (TransactionManagementException e) { @@ -402,11 +385,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } status = true; } + if (status) { addDeviceToGroups(deviceIdentifier, device.getEnrolmentInfo().getOwnership()); if (enrollmentConfiguration != null) { DeviceManagerUtil.addDeviceToConfiguredGroup(enrollmentConfiguration, deviceSerialNumber, - deviceIdentifier); + deviceIdentifier); } addInitialOperations(deviceIdentifier, device.getType()); sendNotification(device); @@ -457,7 +441,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv device.setName(currentDevice.getName()); } deviceDAO.updateDevice(device, tenantId); - enrollmentDAO.updateEnrollment(device.getEnrolmentInfo()); + enrollmentDAO.updateEnrollment(device.getEnrolmentInfo(), tenantId); DeviceManagementDAOFactory.commitTransaction(); this.removeDeviceFromCache(deviceIdentifier); } catch (DeviceManagementDAOException e) { @@ -553,7 +537,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); device.getEnrolmentInfo().setStatus(EnrolmentInfo.Status.REMOVED); DeviceManagementDAOFactory.beginTransaction(); - enrollmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), tenantId); + enrollmentDAO.updateEnrollment(device.getEnrolmentInfo(), tenantId); deviceDAO.updateDevice(device, tenantId); DeviceManagementDAOFactory.commitTransaction(); this.removeDeviceFromCache(deviceId); @@ -579,7 +563,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public boolean deleteDevices(List deviceIdentifiers) throws DeviceManagementException, - InvalidDeviceException { + InvalidDeviceException { if (deviceIdentifiers == null || deviceIdentifiers.isEmpty()) { String msg = "Required values of device identifiers are not set to permanently delete device/s."; log.error(msg); @@ -600,14 +584,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while permanently deleting '" + deviceIdentifiers + - "' devices"; + "' devices"; 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 { + } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -616,7 +600,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv for (Device device : existingDevices) { if (!EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())) { String msg = "Device " + device.getDeviceIdentifier() + " of type " + device.getType() - + " is not dis-enrolled to permanently delete the device"; + + " is not dis-enrolled to permanently delete the device"; log.error(msg); throw new InvalidDeviceException(msg); } @@ -631,12 +615,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (deviceIdentifierMap.containsKey(device.getType())) { deviceIdentifierMap.get(device.getType()).add(device.getDeviceIdentifier()); } else { - deviceIdentifierMap.put(device.getType(), - new ArrayList<>(Arrays.asList(device.getDeviceIdentifier()))); + deviceIdentifierMap.put(device.getType(), Collections.singletonList(device.getDeviceIdentifier())); DeviceManager deviceManager = this.getDeviceManager(device.getType()); if (deviceManager == null) { - log.error("Device Manager associated with the device type '" +device.getType() + - "' is null. Therefore, not attempting method 'deleteDevice'"); + log.error("Device Manager associated with the device type '" + device.getType() + + "' is null. Therefore, not attempting method 'deleteDevice'"); return false; } deviceManagerMap.put(device.getType(), deviceManager); @@ -762,7 +745,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - return this.getAllDeviceInfo(allDevices); + return this.populateAllDeviceInfo(allDevices); } return allDevices; } @@ -798,7 +781,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } if (!allDevices.isEmpty() && requireDeviceInfo) { - return this.getAllDeviceInfo(allDevices); + return this.populateAllDeviceInfo(allDevices); } return allDevices; } @@ -840,7 +823,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } if (requireDeviceInfo) { - return this.getAllDeviceInfo(allDevices); + return this.populateAllDeviceInfo(allDevices); } return allDevices; } @@ -866,7 +849,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int count; int tenantId = this.getTenantId(); String deviceType = request.getDeviceType(); - request = DeviceManagerUtil.validateDeviceListPageSize(request); + DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevices(request, tenantId); @@ -889,7 +872,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } if (requireDeviceInfo) { - paginationResult.setData(this.getAllDeviceInfo(allDevices)); + paginationResult.setData(this.populateAllDeviceInfo(allDevices)); } else { paginationResult.setData(allDevices); } @@ -919,22 +902,22 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List allDevices; int count = 0; int tenantId = this.getTenantId(); - request = DeviceManagerUtil.validateDeviceListPageSize(request); + DeviceManagerUtil.validateDeviceListPageSize(request); if (!StringUtils.isEmpty(request.getOwnerRole())) { devicesForRoles = this.getAllDevicesOfRole(request.getOwnerRole(), false); if (devicesForRoles != null) { count = devicesForRoles.size(); if (requireDeviceInfo) { - paginationResult.setData(getAllDeviceInfo(devicesForRoles)); + paginationResult.setData(populateAllDeviceInfo(devicesForRoles)); } } } else { try { DeviceManagementDAOFactory.openConnection(); - if(request.getGroupId()!=0){ + if (request.getGroupId() != 0) { allDevices = deviceDAO.searchDevicesInGroup(request, tenantId); count = deviceDAO.getCountOfDevicesInGroup(request, tenantId); - } else{ + } else { allDevices = deviceDAO.getDevices(request, tenantId); count = deviceDAO.getDeviceCount(request, tenantId); } @@ -954,7 +937,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo && !allDevices.isEmpty()) { - paginationResult.setData(getAllDeviceInfo(allDevices)); + paginationResult.setData(populateAllDeviceInfo(allDevices)); } else { paginationResult.setData(allDevices); } @@ -989,7 +972,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } return null; } - this.addDeviceToCache(deviceId, device); } catch (DeviceManagementDAOException e) { String msg = "Error occurred while obtaining the device for '" + deviceId.getId() + "'"; log.error(msg, e); @@ -1007,8 +989,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } } if (requireDeviceInfo) { - device = this.getAllDeviceInfo(device); + this.populateAllDeviceInfo(device); } + this.addDeviceToCache(deviceId, device); return device; } @@ -1054,7 +1037,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - device = this.getAllDeviceInfo(device); + this.populateAllDeviceInfo(device); } return device; } @@ -1067,41 +1050,49 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.error(msg); throw new DeviceManagementException(msg); } + if (owner == null) { + String msg = "Received null device owner for method getDevice"; + log.error(msg); + throw new DeviceManagementException(msg); + } if (log.isDebugEnabled()) { log.debug("Get device by device id :" + deviceId.getId() + " of type '" + deviceId.getType() + " and owner '" + owner + "' and requiredDeviceInfo: " + requireDeviceInfo); } - int tenantId = this.getTenantId(); - Device device; - try { - DeviceManagementDAOFactory.openConnection(); - device = deviceDAO.getDevice(deviceId, owner, tenantId); - if (device == null) { - String msg = "No device is found upon the type '" + deviceId.getType() + "' and id '" + - deviceId.getId() + "' and owner '" + owner + "'"; - if (log.isDebugEnabled()) { - log.debug(msg); + Device device = this.getDeviceFromCache(deviceId); + if (device == null || device.getEnrolmentInfo() == null + || !owner.equals(device.getEnrolmentInfo().getOwner())) { + int tenantId = this.getTenantId(); + try { + DeviceManagementDAOFactory.openConnection(); + device = deviceDAO.getDevice(deviceId, owner, tenantId); + if (device == null) { + String msg = "No device is found upon the type '" + deviceId.getType() + "' and id '" + + deviceId.getId() + "' and owner '" + owner + "'"; + if (log.isDebugEnabled()) { + log.debug(msg); + } + return null; } - return null; + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while obtaining the device for '" + deviceId.getId() + "' and owner '" + + owner + "'"; + 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); + throw new DeviceManagementException(msg, e); + } catch (Exception e) { + String msg = "Error occurred in getDevice: " + deviceId.getId() + " with owner: " + owner; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); } - } catch (DeviceManagementDAOException e) { - String msg = "Error occurred while obtaining the device for '" + deviceId.getId() + "' and owner '" - + owner + "'"; - 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); - throw new DeviceManagementException(msg, e); - } catch (Exception e) { - String msg = "Error occurred in getDevice: " + deviceId.getId() + " with owner: " + owner; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } finally { - DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - device = this.getAllDeviceInfo(device); + this.populateAllDeviceInfo(device); } return device; } @@ -1205,8 +1196,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv throw new DeviceManagementException(msg); } if (log.isDebugEnabled()) { - log.debug("Get tenanted device with id: " + deviceIdentifier.getId() + " of type " + - deviceIdentifier.getType()); + log.debug("Get tenanted device with id: " + deviceIdentifier.getId() + " of type '" + + deviceIdentifier.getType() + "'"); } SingletonMap deviceMap; @@ -1216,16 +1207,19 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (deviceMap == null) { if (log.isDebugEnabled()) { log.debug("Unable to find device for type " + deviceIdentifier.getType() + - " and id " + deviceIdentifier.getId()); + " and id " + deviceIdentifier.getId()); } } - } catch (DeviceManagementDAOException e) { - String msg = "Error occurred while obtaining the device for id " + deviceIdentifier.getId(); + String msg = "Error occurred while obtaining the device for id '" + deviceIdentifier.getId() + "'"; log.error(msg, e); throw new DeviceManagementException(msg, e); } catch (SQLException e) { - String msg = "Error occurred while opening a connection for the data source"; + String msg = "Error occurred while opening a connection to the data source"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } catch (Exception e) { + String msg = "Error occurred in getTenantedDevice device: " + deviceIdentifier.getId(); log.error(msg, e); throw new DeviceManagementException(msg, e); } finally { @@ -1233,7 +1227,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } if (requireDeviceInfo && deviceMap != null) { - getAllDeviceInfo((Device) deviceMap.getValue()); + populateAllDeviceInfo((Device) deviceMap.getValue()); } return deviceMap; } @@ -1316,7 +1310,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - device = this.getAllDeviceInfo(device); + this.populateAllDeviceInfo(device); } return device; } @@ -1333,7 +1327,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.debug("Get device by device identifier :" + deviceData.getDeviceIdentifier().getId() + " of type '" + deviceData.getDeviceIdentifier().getType() + "' and requiredDeviceInfo: " + requireDeviceInfo); } - Device device = null; + Device device; int tenantId = this.getTenantId(); try { DeviceManagementDAOFactory.openConnection(); @@ -1364,7 +1358,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - return this.getAllDeviceInfo(device); + this.populateAllDeviceInfo(device); } return device; } @@ -1387,7 +1381,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv devices = deviceDAO.getDeviceBasedOnDeviceProperties(deviceProps, tenantId); if (devices == null) { if (log.isDebugEnabled()) { - log.debug("No device is found against criteria : " + deviceProps + " and tenantId "+ tenantId); + log.debug("No device is found against criteria : " + deviceProps + " and tenantId " + tenantId); } return null; } @@ -1445,7 +1439,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - device = this.getAllDeviceInfo(device); + this.populateAllDeviceInfo(device); } return device; } @@ -1490,7 +1484,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - device = this.getAllDeviceInfo(device); + this.populateAllDeviceInfo(device); } return device; } @@ -1538,7 +1532,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - device = this.getAllDeviceInfo(device); + this.populateAllDeviceInfo(device); } return device; } @@ -1566,14 +1560,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } } if (publicSharedDeviceTypesInDB != null) { - for (String deviceType: publicSharedDeviceTypesInDB) { + for (String deviceType : publicSharedDeviceTypesInDB) { if (!deviceTypesResponse.contains(deviceType)) { deviceTypesResponse.add(deviceType); } } } if (registeredTypes != null) { - for (DeviceTypeServiceIdentifier deviceType: registeredTypes.keySet()) { + for (DeviceTypeServiceIdentifier deviceType : registeredTypes.keySet()) { if (!deviceTypesResponse.contains(deviceType.getDeviceType())) { deviceTypesResponse.add(deviceType.getDeviceType()); } @@ -1663,40 +1657,28 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException { - DeviceManager deviceManager = this.getDeviceManager(deviceId.getType()); - if (deviceManager == null) { - if (log.isDebugEnabled()) { - log.debug("Device Manager associated with the device type '" + deviceId.getType() + "' is null. " + - "Therefore, not attempting method 'isClaimable'"); - } - return false; - } - return deviceManager.isClaimable(deviceId); - } - - @Override - public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, - EnrolmentInfo.Status status) throws DeviceManagementException { - if (deviceId == null) { - String msg = "Received null deviceIdentifier for setStatus"; - log.error(msg); - throw new DeviceManagementException(msg); - } + public boolean setStatus(Device device, EnrolmentInfo.Status status) throws DeviceManagementException { if (log.isDebugEnabled()) { - log.debug("Set status of device: " + deviceId.getId()); + log.debug("Set status of device: " + device.getDeviceIdentifier()); } try { - boolean success = false; + boolean success; int tenantId = this.getTenantId(); - Device device = this.getDevice(deviceId, false); EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); DeviceManagementDAOFactory.beginTransaction(); - if (enrolmentInfo != null) { - success = enrollmentDAO.setStatus(enrolmentInfo.getId(), status, tenantId); + if (enrolmentInfo == null) { + enrolmentInfo = enrollmentDAO.getEnrollment(device.getId(), tenantId); + if (enrolmentInfo == null) { + String msg = "Error occurred in getting enrollment for device :" + device.getDeviceIdentifier(); + log.error(msg); + throw new DeviceManagementException(msg); + } } + success = enrollmentDAO.setStatus(enrolmentInfo.getId(), status, tenantId); DeviceManagementDAOFactory.commitTransaction(); - this.removeDeviceFromCache(deviceId); + enrolmentInfo.setStatus(status); + device.setEnrolmentInfo(enrolmentInfo); + this.addDeviceToCache(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()), device); return success; } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); @@ -1708,7 +1690,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.error(msg, e); throw new DeviceManagementException(msg, e); } catch (Exception e) { - String msg = "Error occurred in setStatus for device :" + deviceId.getId(); + String msg = "Error occurred in setStatus for device :" + device.getDeviceIdentifier(); log.error(msg, e); throw new DeviceManagementException(msg, e); } finally { @@ -1717,8 +1699,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public boolean setStatus(String currentOwner, - EnrolmentInfo.Status status) throws DeviceManagementException { + public boolean setStatus(String currentOwner, EnrolmentInfo.Status status) throws DeviceManagementException { if (log.isDebugEnabled()) { log.debug("Update enrollment with status"); } @@ -1837,6 +1818,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return pluginRepository.getOperationManager(type, this.getTenantId()).addOperation(operation, devices); } + @Override + public void addTaskOperation(String type, Operation operation) throws OperationManagementException { + pluginRepository.getOperationManager(type, this.getTenantId()).addTaskOperation(type, operation); + } + @Override public List getOperations(DeviceIdentifier deviceId) throws OperationManagementException { return pluginRepository.getOperationManager(deviceId.getType(), this.getTenantId()).getOperations(deviceId); @@ -1845,8 +1831,16 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException { + DeviceManagerUtil.validateOperationListPageSize(request); + return pluginRepository.getOperationManager(deviceId.getType(), this.getTenantId()) + .getOperations(deviceId, request); + } + + @Override + public List getOperations(DeviceIdentifier deviceId, Operation.Status status) + throws OperationManagementException { return pluginRepository.getOperationManager(deviceId.getType(), this.getTenantId()) - .getOperations(deviceId, DeviceManagerUtil.validateOperationListPageSize(request)); + .getOperations(deviceId, status); } @Override @@ -1864,7 +1858,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public Operation getNextPendingOperation(DeviceIdentifier deviceId) throws OperationManagementException { - // // setting notNowOperationFrequency to -1 to avoid picking notnow operations + // // setting notNowOperationFrequency to -1 to avoid picking not now operations return pluginRepository.getOperationManager(deviceId.getType(), this.getTenantId()) .getNextPendingOperation(deviceId, -1); } @@ -1927,7 +1921,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv throw new BadRequestException(msg); } pluginRepository.getOperationManager(device.getType(), this.getTenantId()) - .updateOperation(enrolmentInfo.getId(), operation); + .updateOperation(deviceIdentifier, operation); if (DeviceManagerUtil.isPublishOperationResponseEnabled()) { List permittedOperations = DeviceManagerUtil.getEnabledOperationsForResponsePublish(); if (permittedOperations.contains(operation.getCode()) @@ -1955,7 +1949,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.error(msg, e); throw new OperationManagementException(msg, e); } catch (BadRequestException e) { - String msg = "Error occured due to invalid request"; + String msg = "Error occurred due to invalid request"; log.error(msg, e); throw new OperationManagementException(msg, e); } @@ -2061,7 +2055,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public List getStartupOperations(String deviceType) { + public List getStartupOperations(String deviceType) { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); DeviceManagementService dms = pluginRepository.getDeviceManagementService(deviceType, tenantId); @@ -2147,7 +2141,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } if (requireDeviceInfo) { - return this.getAllDeviceInfo(userDevices); + return this.populateAllDeviceInfo(userDevices); } return userDevices; } @@ -2191,7 +2185,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } if (requireDeviceInfo) { - return this.getAllDeviceInfo(userDevices); + return this.populateAllDeviceInfo(userDevices); } return userDevices; } @@ -2218,7 +2212,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int tenantId = this.getTenantId(); String username = request.getOwner(); List userDevices; - request = DeviceManagerUtil.validateDeviceListPageSize(request); + DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); userDevices = deviceDAO.getDevicesOfUser(request, tenantId); @@ -2240,7 +2234,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } if (requireDeviceInfo) { - result.setData(this.getAllDeviceInfo(userDevices)); + result.setData(this.populateAllDeviceInfo(userDevices)); } else { result.setData(userDevices); } @@ -2272,7 +2266,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int deviceCount; int tenantId = this.getTenantId(); String ownerShip = request.getOwnership(); - request = DeviceManagerUtil.validateDeviceListPageSize(request); + DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevicesByOwnership(request, tenantId); @@ -2293,7 +2287,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - result.setData(this.getAllDeviceInfo(allDevices)); + result.setData(this.populateAllDeviceInfo(allDevices)); } else { result.setData(allDevices); } @@ -2351,7 +2345,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - this.getAllDeviceInfo(userDevices); + this.populateAllDeviceInfo(userDevices); } devices.addAll(userDevices); } @@ -2499,7 +2493,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } if (requireDeviceInfo) { - return this.getAllDeviceInfo(allDevices); + return this.populateAllDeviceInfo(allDevices); } return allDevices; } @@ -2524,7 +2518,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int tenantId = this.getTenantId(); List allDevices; String deviceName = request.getDeviceName(); - request = DeviceManagerUtil.validateDeviceListPageSize(request); + DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevicesByName(request, tenantId); @@ -2547,7 +2541,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - result.setData(this.getAllDeviceInfo(allDevices)); + result.setData(this.populateAllDeviceInfo(allDevices)); } else { result.setData(allDevices); } @@ -2618,7 +2612,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - return this.getAllDeviceInfo(allDevices); + return this.populateAllDeviceInfo(allDevices); } return allDevices; } @@ -2643,22 +2637,22 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List statusList = request.getStatusList(); if (statusList == null || statusList.isEmpty()) { String msg = "Invalid enrollment status type received. Status can't be null or empty" + - "Valid status types are ACTIVE | INACTIVE | UNCLAIMED | UNREACHABLE " + - "| SUSPENDED | DISENROLLMENT_REQUESTED | REMOVED | BLOCKED | CREATED"; + "Valid status types are ACTIVE | INACTIVE | UNCLAIMED | UNREACHABLE " + + "| SUSPENDED | DISENROLLMENT_REQUESTED | REMOVED | BLOCKED | CREATED"; log.error(msg); throw new DeviceManagementException(msg); } if (statusList.size() > 1) { String msg = "Invalid enrollment status received. Devices can only be filtered by one " + - "type of status, more than one are not allowed"; + "type of status, more than one are not allowed"; log.error(msg); throw new DeviceManagementException(msg); } String status = statusList.get(0); - if (StringUtils.isBlank(status)){ + if (StringUtils.isBlank(status)) { String msg = "Invalid enrollment status type received. Status can't be null or empty" + - "Valid status types are ACTIVE | INACTIVE | UNCLAIMED | UNREACHABLE " + - "| SUSPENDED | DISENROLLMENT_REQUESTED | REMOVED | BLOCKED | CREATED"; + "Valid status types are ACTIVE | INACTIVE | UNCLAIMED | UNREACHABLE " + + "| SUSPENDED | DISENROLLMENT_REQUESTED | REMOVED | BLOCKED | CREATED"; log.error(msg); throw new DeviceManagementException(msg); } @@ -2673,8 +2667,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv result.setRecordsTotal(deviceCount); result.setRecordsFiltered(deviceCount); } catch (DeviceManagementDAOException e) { - String msg = "Error occurred while fetching the list of devices that matches to status: " + - status; + String msg = "Error occurred while fetching the list of devices that matches to status: '" + status + "'"; log.error(msg, e); throw new DeviceManagementException(msg, e); } catch (SQLException e) { @@ -2689,7 +2682,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { - result.setData(this.getAllDeviceInfo(allDevices)); + result.setData(this.populateAllDeviceInfo(allDevices)); } else { result.setData(allDevices); } @@ -2737,14 +2730,22 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv Device device = getDevice(deviceIdentifier, false); int deviceId = device.getId(); EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); - enrolmentInfo.setStatus(newStatus); + if (enrolmentInfo.getStatus().equals(newStatus)) { + return false; //New status is similar to current + } int tenantId = this.getTenantId(); switch (newStatus) { case ACTIVE: isDeviceUpdated = updateEnrollment(deviceId, enrolmentInfo, tenantId); break; case INACTIVE: - isDeviceUpdated = updateEnrollment(deviceId, enrolmentInfo, tenantId); + enrolmentInfo = device.getEnrolmentInfo(); + if (enrolmentInfo.getStatus() != newStatus) { + enrolmentInfo.setStatus(newStatus); + isDeviceUpdated = updateEnrollment(deviceId, enrolmentInfo, tenantId); + } else { + isDeviceUpdated = false; + } break; case REMOVED: isDeviceUpdated = disenrollDevice(deviceIdentifier); @@ -2786,12 +2787,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.debug("Update enrollment of device: " + deviceId); } boolean isUpdatedEnrollment = false; - boolean isAutoCommit = true; try { DeviceManagementDAOFactory.openConnection(); - isAutoCommit = DeviceManagementDAOFactory.getConnection().getAutoCommit(); - DeviceManagementDAOFactory.getConnection().setAutoCommit(true); - int updatedRows = enrollmentDAO.updateEnrollment(deviceId, enrolmentInfo, tenantId); + int updatedRows = enrollmentDAO.updateEnrollment(enrolmentInfo, tenantId); if (updatedRows > 0) { isUpdatedEnrollment = true; } @@ -2800,6 +2798,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.error(msg, e); throw new DeviceManagementException(msg, e); } catch (DeviceManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while updating the enrollment information device for" + "id '" + deviceId + "' ."; log.error(msg, e); @@ -2809,11 +2808,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.error(msg, e); throw new DeviceManagementException(msg, e); } finally { - try { - DeviceManagementDAOFactory.getConnection().setAutoCommit(isAutoCommit); - } catch (SQLException e) { - log.error("Exception occurred while setting auto commit."); - } DeviceManagementDAOFactory.closeConnection(); } return isUpdatedEnrollment; @@ -3116,35 +3110,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (log.isDebugEnabled()) { log.debug("Get device info of device: " + device.getId() + " of type '" + device.getType() + "'"); } - DeviceInfo info = null; + DeviceInfo info; try { - DeviceManagementDAOFactory.openConnection(); - info = deviceInfoDAO.getDeviceInformation(device.getId(), device.getEnrolmentInfo().getId()); - DeviceLocation location = deviceInfoDAO.getDeviceLocation(device.getId(), - device.getEnrolmentInfo().getId()); - if (location != null) { - //There are some cases where the device-info is not updated properly. Hence returning a null value. - if (info != null) { - info.setLocation(location); - } else { - info = new DeviceInfo(); - info.setLocation(location); - } - } - } catch (DeviceDetailsMgtDAOException e) { + info = deviceInformationManager.getDeviceInfo(device); + } catch (DeviceDetailsMgtException e) { String msg = "Error occurred while retrieving advance info of '" + device.getType() + "' that carries the id '" + device.getDeviceIdentifier() + "'"; log.error(msg); 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); - } catch (Exception e) { - String msg = "Error occurred in getDeviceInfo for device: " + device.getId(); - log.error(msg, e); - } finally { - DeviceManagementDAOFactory.closeConnection(); } return info; } @@ -3186,7 +3159,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv * Returns all the available information (device-info, location, applications and plugin-db data) * of the given device list. */ - private List getAllDeviceInfo(List allDevices) throws DeviceManagementException { + private List populateAllDeviceInfo(List allDevices) throws DeviceManagementException { if (log.isDebugEnabled()) { log.debug("Get all device info of devices, num of devices: " + allDevices.size()); } @@ -3218,7 +3191,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv * Returns all the available information (device-info, location, applications and plugin-db data) * of a given device. */ - private Device getAllDeviceInfo(Device device) throws DeviceManagementException { + private void populateAllDeviceInfo(Device device) throws DeviceManagementException { if (device == null) { String msg = "Received empty device for getAllDeviceInfo"; log.error(msg); @@ -3236,7 +3209,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.debug("Device Manager associated with the device type '" + device.getType() + "' is null. " + "Therefore, not attempting method 'isEnrolled'"); } - return device; + return; } Device dmsDevice = deviceManager.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); @@ -3244,7 +3217,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv device.setFeatures(dmsDevice.getFeatures()); device.setProperties(dmsDevice.getProperties()); } - return device; } private Device getDeviceFromCache(DeviceIdentifier deviceIdentifier) { @@ -3303,7 +3275,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.openConnection(); return deviceDAO.getDeviceCount(deviceType, deviceStatus, getTenantId()); } catch (DeviceManagementDAOException e) { - String msg = "Error occurred in while retrieving device count by status for deviceType :" +deviceType + " status : " + deviceStatus; + String msg = "Error occurred in while retrieving device count by status for deviceType :" + deviceType + " status : " + deviceStatus; log.error(msg, e); throw new DeviceManagementException(msg, e); } catch (SQLException e) { @@ -3322,7 +3294,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.openConnection(); deviceIds = deviceDAO.getDeviceIdentifiers(deviceType, deviceStatus, getTenantId()); } catch (DeviceManagementDAOException e) { - String msg = "Error occurred in while retrieving devices by status for deviceType :" +deviceType + " status : " + deviceStatus; + String msg = "Error occurred in while retrieving devices by status for deviceType :" + deviceType + " status : " + deviceStatus; log.error(msg, e); throw new DeviceManagementException(msg, e); } catch (SQLException e) { @@ -3358,43 +3330,57 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return success; } - public boolean updateEnrollment(String owner, List deviceIdentifiers) + @Override + public boolean updateEnrollment(String owner, boolean isTransfer, List deviceIdentifiers) throws DeviceManagementException, UserNotFoundException, InvalidDeviceException { - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - List existingDevices; - owner = validateOwner(owner, tenantId); - try { - DeviceManagementDAOFactory.beginTransaction(); - existingDevices = deviceDAO.getDevicesByIdentifiers(deviceIdentifiers, tenantId); - if (existingDevices.size() != deviceIdentifiers.size()) { - for (Device device : existingDevices) { - deviceIdentifiers.remove(device.getDeviceIdentifier()); - } - String msg = - "Couldn't find device ids for requested all device identifiers. Therefore payload should " - + "contains device identifiers which are not in the system. Invalid device " - + "identifiers are " + deviceIdentifiers.toString(); - log.error(msg); - throw new InvalidDeviceException(msg); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + List existingDevices; + List existingNonRemovedDevices = new ArrayList<>(); + owner = validateOwner(owner, tenantId); + try { + DeviceManagementDAOFactory.beginTransaction(); + existingDevices = deviceDAO.getDevicesByIdentifiers(deviceIdentifiers, tenantId); + if (log.isDebugEnabled()) { + log.debug("Requested devices: " + deviceIdentifiers.toString()); + } + for (Device device : existingDevices) { + if (device.getEnrolmentInfo().getStatus() != EnrolmentInfo.Status.REMOVED) { + device.getEnrolmentInfo().setTransferred(isTransfer); + existingNonRemovedDevices.add(device); + deviceIdentifiers.remove(device.getDeviceIdentifier()); } - if (enrollmentDAO.updateOwnerOfEnrollment(existingDevices, owner, tenantId)) { - DeviceManagementDAOFactory.commitTransaction(); - return true; + } + if (log.isDebugEnabled()) { + log.debug("Valid devices: " + existingNonRemovedDevices.toString()); + } + if (deviceIdentifiers.size() > 0) { + String msg = "Couldn't find valid devices for invalid device identifiers: " + + deviceIdentifiers.toString(); + log.error(msg); + throw new InvalidDeviceException(msg); + } + if (enrollmentDAO.updateOwnerOfEnrollment(existingNonRemovedDevices, owner, tenantId)) { + DeviceManagementDAOFactory.commitTransaction(); + for (Device device : existingNonRemovedDevices) { + this.removeDeviceFromCache(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); } - DeviceManagementDAOFactory.rollbackTransaction(); - return false; - } catch (TransactionManagementException e) { - String msg = "Error occurred while initiating the transaction."; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } catch (DeviceManagementDAOException e) { - String msg = "Error occurred either verifying existence of device ids or updating owner of the device."; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } finally { - DeviceManagementDAOFactory.closeConnection(); + return true; } + DeviceManagementDAOFactory.rollbackTransaction(); + return false; + } catch (TransactionManagementException e) { + String msg = "Error occurred while initiating the transaction."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred either verifying existence of device ids or updating owner of the device."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } private String validateOwner(String owner, int tenantId) throws UserNotFoundException, DeviceManagementException { @@ -3402,9 +3388,9 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (StringUtils.isEmpty(owner)) { owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); } else { - boolean isUserExisit = DeviceManagementDataHolder.getInstance().getRealmService() + boolean isUserExist = DeviceManagementDataHolder.getInstance().getRealmService() .getTenantUserRealm(tenantId).getUserStoreManager().isExistingUser(owner); - if (!isUserExisit) { + if (!isUserExist) { String msg = "Owner does not exist in the user storage. Owner: " + owner; log.error(msg); throw new UserNotFoundException(msg); @@ -3416,10 +3402,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.error(msg, e); throw new DeviceManagementException(msg, e); } + } /** * Extracting device location properties + * * @param device Device object */ private void extractDeviceLocationToUpdate(Device device) { @@ -3453,7 +3441,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(altitude) && StringUtils.isNotBlank(speed) && - StringUtils.isNotBlank(bearing) && StringUtils.isNotBlank(distance)) { + StringUtils.isNotBlank(bearing) && StringUtils.isNotBlank(distance)) { DeviceLocation deviceLocation = new DeviceLocation(); deviceLocation.setDeviceId(device.getId()); deviceLocation.setDeviceIdentifier(new DeviceIdentifier(device.getDeviceIdentifier(), @@ -3778,7 +3766,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv deviceIdentifiers = devices.stream() .map(Device::getDeviceIdentifier).collect(Collectors.toList()); try { - if(!deleteDevices(deviceIdentifiers)){ + if (!deleteDevices(deviceIdentifiers)) { log.error("Failed to delete devices of device type: " + deviceTypeName); return false; } @@ -3832,12 +3820,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv device.getEnrolmentInfo().setStatus(EnrolmentInfo.Status.REMOVED); // different try blocks are used to isolate transactions try { - enrollmentDAO.updateEnrollment(device.getId(), device.getEnrolmentInfo(), - tenantId); + enrollmentDAO.updateEnrollment(device.getEnrolmentInfo(), tenantId); } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while dis-enrolling device: " + - device.getName(); + device.getName(); log.error(msg, e); throw new DeviceManagementException(msg, e); } @@ -3846,7 +3833,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while updating device: " + - device.getName(); + device.getName(); log.error(msg, e); throw new DeviceManagementException(msg, e); } @@ -3874,7 +3861,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv if (deviceTypeVersions == null || deviceTypeVersions.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Device of type: " + deviceTypeName + "doesn't have any type " + - "versions"); + "versions"); } } else { for (DeviceTypeVersion deviceTypeVersion : deviceTypeVersions) { @@ -3882,7 +3869,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv , deviceTypeVersion.getVersionName(), getTenantId()); if (!result) { String msg = "Device type of: " + deviceTypeName + "is unauthorized to " + - "modify version"; + "modify version"; log.error(msg); return false; } @@ -3915,7 +3902,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public DeviceConfiguration getDeviceConfiguration(Map deviceProps) throws DeviceManagementException, DeviceNotFoundException, UnauthorizedDeviceAccessException, - AmbiguousConfigurationException { + AmbiguousConfigurationException { if (log.isDebugEnabled()) { log.debug("Attempting to get device configurations based on properties."); @@ -3949,7 +3936,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv String msg = "Devices configuration retrieval criteria cannot be null or empty."; log.error(msg); throw new DeviceManagementException(msg, e); - } finally { + } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -3958,7 +3945,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); ctx.setTenantId(Integer.parseInt(deviceProperties.getTenantId()), true); Device device = this.getDevice(new DeviceIdentifier(deviceProperties.getDeviceIdentifier(), - deviceProperties.getDeviceTypeName()), false); + deviceProperties.getDeviceTypeName()), false); String owner = device.getEnrolmentInfo().getOwner(); PlatformConfiguration configuration = this.getConfiguration(device.getType()); List configurationEntries = new ArrayList<>(); @@ -4012,7 +3999,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.openConnection(); List movedDevices = new ArrayList<>(); for (String deviceId : enrolledDevices) { - if (deviceDAO.transferDevice(deviceTransferRequest.getDeviceType(), deviceId, owner, destinationTenantId)){ + if (deviceDAO.transferDevice(deviceTransferRequest.getDeviceType(), deviceId, owner, destinationTenantId)) { movedDevices.add(deviceId); } else { log.warn("Device '" + deviceId + "' not transferred to tenant " + destinationTenantId); @@ -4025,14 +4012,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv String msg = "Error in transferring devices to tenant '" + deviceTransferRequest.getDestinationTenant() + "'"; log.error(msg); throw new DeviceManagementException(msg, e); - } finally { + } finally { DeviceManagementDAOFactory.closeConnection(); } } @Override public PaginationResult getAppSubscribedDevices(int offsetValue, int limitValue, List devicesIds, - String status) throws DeviceManagementException { + String status) throws DeviceManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); if (log.isDebugEnabled()) { @@ -4044,7 +4031,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.openConnection(); subscribedDeviceDetails = deviceDAO .getSubscribedDevices(offsetValue, limitValue, devicesIds, tenantId, status); - if (subscribedDeviceDetails.isEmpty()){ + if (subscribedDeviceDetails.isEmpty()) { paginationResult.setData(new ArrayList<>()); paginationResult.setRecordsFiltered(0); paginationResult.setRecordsTotal(0); @@ -4064,7 +4051,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } finally { DeviceManagementDAOFactory.closeConnection(); } - paginationResult.setData(getAllDeviceInfo(subscribedDeviceDetails)); + paginationResult.setData(populateAllDeviceInfo(subscribedDeviceDetails)); return paginationResult; } @@ -4099,7 +4086,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv "to the data source"; log.error(msg, e); throw new ApplicationManagementException(msg, e); - } finally { + } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -4133,17 +4120,18 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv String msg = "Error occurred while retrieving Tenant ID"; log.error(msg, e); throw new ApplicationManagementException(msg, e); - } finally { + } finally { DeviceManagementDAOFactory.closeConnection(); } } /** * Wrap the device configuration data into DeviceConfiguration bean - * @param device Device queried using the properties - * @param tenantDomain tenant domain + * + * @param device Device queried using the properties + * @param tenantDomain tenant domain * @param configurationEntries platformConfiguration list - * @param deviceOwner name of the device owner + * @param deviceOwner name of the device owner * @return Wrapped {@link DeviceConfiguration} object with data */ private DeviceConfiguration wrapConfigurations(Device device, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java index 667f65b57c..1bffb03eb9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java @@ -21,10 +21,12 @@ package org.wso2.carbon.device.mgt.core.status.task.impl; import com.google.gson.Gson; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; +import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationEnrolmentMapping; @@ -65,52 +67,57 @@ public class DeviceStatusMonitoringTask implements Task { @Override public void execute() { - List operationEnrolmentMappings = null; + List operationEnrolmentMappings; List enrolmentInfoTobeUpdated = new ArrayList<>(); - List identifiers = new ArrayList<>(); Map lastActivities = null; EnrolmentInfo enrolmentInfo; DeviceIdentifier deviceIdentifier; + Device device; try { operationEnrolmentMappings = this.getOperationEnrolmentMappings(); - if (operationEnrolmentMappings != null && operationEnrolmentMappings.size() > 0) { + if (operationEnrolmentMappings.size() > 0) { lastActivities = this.getLastDeviceActivities(); } } catch (DeviceStatusTaskException e) { log.error("Error occurred while fetching OperationEnrolment mappings of deviceType '" + deviceType + "'", e); + return; } - for (OperationEnrolmentMapping mapping:operationEnrolmentMappings) { + for (OperationEnrolmentMapping mapping : operationEnrolmentMappings) { long lastActivity = -1; if (lastActivities != null && lastActivities.containsKey(mapping.getEnrolmentId())) { lastActivity = lastActivities.get(mapping.getEnrolmentId()); } EnrolmentInfo.Status newStatus = this.determineDeviceStatus(mapping, lastActivity); if (newStatus != mapping.getDeviceStatus()) { - enrolmentInfo = new EnrolmentInfo(); - enrolmentInfo.setId(mapping.getEnrolmentId()); - enrolmentInfo.setStatus(newStatus); - enrolmentInfoTobeUpdated.add(enrolmentInfo); - deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(mapping.getDeviceId()); deviceIdentifier.setId(mapping.getDeviceType()); - identifiers.add(deviceIdentifier); + device = DeviceCacheManagerImpl.getInstance().getDeviceFromCache(deviceIdentifier, mapping.getTenantId()); + if (device == null) { + enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setId(mapping.getEnrolmentId()); + enrolmentInfo.setStatus(newStatus); + } else { + enrolmentInfo = device.getEnrolmentInfo(); + enrolmentInfo.setStatus(newStatus); + device.setEnrolmentInfo(enrolmentInfo); + DeviceCacheManagerImpl.getInstance().addDeviceToCache(deviceIdentifier, device, mapping.getTenantId()); + } + enrolmentInfoTobeUpdated.add(enrolmentInfo); } } if (enrolmentInfoTobeUpdated.size() > 0) { try { this.updateDeviceStatus(enrolmentInfoTobeUpdated); - //Remove updated entries from cache - //DeviceCacheManagerImpl.getInstance().removeDevicesFromCache(identifiers); } catch (DeviceStatusTaskException e) { - log.error("Error occurred while updating non-responsive device-status of devices of type '" + deviceType + "'",e); + log.error("Error occurred while updating non-responsive device-status of devices of type '" + deviceType + "'", e); } } } private EnrolmentInfo.Status determineDeviceStatus(OperationEnrolmentMapping opMapping, long lastActivityTime) { - long lastPendingOpBefore = (System.currentTimeMillis()/1000) - opMapping.getCreatedTime(); + long lastPendingOpBefore = (System.currentTimeMillis() / 1000) - opMapping.getCreatedTime(); EnrolmentInfo.Status newStatus = null; if (lastPendingOpBefore >= this.deviceStatusTaskPluginConfig.getIdleTimeToMarkInactive()) { newStatus = EnrolmentInfo.Status.INACTIVE; @@ -118,7 +125,7 @@ public class DeviceStatusMonitoringTask implements Task { newStatus = EnrolmentInfo.Status.UNREACHABLE; } if (lastActivityTime != -1) { - long lastActivityBefore = (System.currentTimeMillis()/1000) - lastActivityTime; + long lastActivityBefore = (System.currentTimeMillis() / 1000) - lastActivityTime; if (lastActivityBefore < lastPendingOpBefore) { return opMapping.getDeviceStatus(); } @@ -127,12 +134,12 @@ public class DeviceStatusMonitoringTask implements Task { } private long getMinTimeWindow() { - return (System.currentTimeMillis()/1000) - this.deviceStatusTaskPluginConfig.getIdleTimeToMarkUnreachable(); + return (System.currentTimeMillis() / 1000) - this.deviceStatusTaskPluginConfig.getIdleTimeToMarkUnreachable(); } private long getMaxTimeWindow() { //Need to consider the frequency of the task as well - return (System.currentTimeMillis()/1000) - this.deviceStatusTaskPluginConfig.getIdleTimeToMarkInactive() - + return (System.currentTimeMillis() / 1000) - this.deviceStatusTaskPluginConfig.getIdleTimeToMarkInactive() - this.deviceStatusTaskPluginConfig.getFrequency(); } @@ -149,7 +156,7 @@ public class DeviceStatusMonitoringTask implements Task { + deviceType + "'", e); } catch (TransactionManagementException e) { throw new DeviceStatusTaskException("Error occurred while initiating a transaction for updating the device " + - "status of type '" + deviceType +"'", e); + "status of type '" + deviceType + "'", e); } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -157,7 +164,7 @@ public class DeviceStatusMonitoringTask implements Task { } private List getOperationEnrolmentMappings() throws DeviceStatusTaskException { - List operationEnrolmentMappings = null; + List operationEnrolmentMappings; try { OperationManagementDAOFactory.openConnection(); operationEnrolmentMappings = OperationManagementDAOFactory. @@ -176,7 +183,7 @@ public class DeviceStatusMonitoringTask implements Task { } private Map getLastDeviceActivities() throws DeviceStatusTaskException { - Map lastActivities = null; + Map lastActivities; try { OperationManagementDAOFactory.openConnection(); lastActivities = OperationManagementDAOFactory. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/TaskOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/TaskOperation.java deleted file mode 100644 index 6777841ed3..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/TaskOperation.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -package org.wso2.carbon.device.mgt.core.task; - - -import java.util.List; - -/** - * This is the bean for the operations added by the task. - */ -public class TaskOperation { - - private String taskName; - private int recurrentTimes; - private List taskPlatforms; - - public List getTaskPlatforms() { - return taskPlatforms; - } - - public void setTaskPlatforms(List taskPlatforms) { - this.taskPlatforms = taskPlatforms; - } - - public String getTaskName() { - return taskName; - } - - public void setTaskName(String taskName) { - this.taskName = taskName; - } - - public int getRecurrentTimes() { - return recurrentTimes; - } - - public void setRecurrentTimes(int recurrentTimes) { - this.recurrentTimes = recurrentTimes; - } - -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/Utils.java index bf3db9c6b3..e0a0de0b0a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/Utils.java @@ -33,7 +33,6 @@ * under the License. */ - package org.wso2.carbon.device.mgt.core.task; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -86,4 +85,3 @@ public class Utils { } } - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/ArchivalTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/ArchivalTask.java index 6bf3132909..12f59e75b8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/ArchivalTask.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/ArchivalTask.java @@ -30,9 +30,9 @@ import java.util.Date; import java.util.Map; import java.util.concurrent.TimeUnit; - public class ArchivalTask implements Task { - private static Log log = LogFactory.getLog(ArchivalTask.class); + + private static final Log log = LogFactory.getLog(ArchivalTask.class); private ArchivalService archivalService; @@ -72,16 +72,6 @@ public class ArchivalTask implements Task { millis -= TimeUnit.MINUTES.toMillis(minutes); long seconds = TimeUnit.MILLISECONDS.toSeconds(millis); - StringBuilder sb = new StringBuilder(64); - sb.append(days); - sb.append(" Days "); - sb.append(hours); - sb.append(" Hours "); - sb.append(minutes); - sb.append(" Minutes "); - sb.append(seconds); - sb.append(" Seconds"); - - return (sb.toString()); + return (days + " Days " + hours + " Hours " + minutes + " Minutes " + seconds + " Seconds"); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/ArchivalTaskManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/ArchivalTaskManagerImpl.java index 5207a3d639..1040e4b063 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/ArchivalTaskManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/ArchivalTaskManagerImpl.java @@ -124,5 +124,4 @@ public class ArchivalTaskManagerImpl implements ArchivalTaskManager { } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java index 6620774df6..1b15091cde 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceTaskManagerImpl.java @@ -32,19 +32,16 @@ * under the License. */ - package org.wso2.carbon.device.mgt.core.task.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.ServerConfiguration; -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.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.StartupOperationConfig; +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.core.internal.DeviceManagementDataHolder; @@ -54,16 +51,19 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManager; import org.wso2.carbon.device.mgt.core.task.Utils; -import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class DeviceTaskManagerImpl implements DeviceTaskManager { - private static Log log = LogFactory.getLog(DeviceTaskManagerImpl.class); - private String deviceType; + private static final Log log = LogFactory.getLog(DeviceTaskManagerImpl.class); + private final String deviceType; static volatile Map>> map = new HashMap<>(); - private static volatile Map> startupConfigMap = new HashMap<>(); + private static final Map> startupConfigMap = new HashMap<>(); private OperationMonitoringTaskConfig operationMonitoringTaskConfig; private StartupOperationConfig startupOperationConfig; @@ -118,58 +118,25 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager { public void addOperations() throws DeviceMgtTaskException { DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder.getInstance(). getDeviceManagementProvider(); - try { - //list operations for device type - List operations = this.getValidOperationNames(); - if (operations.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("No operations are available."); - } - return; + //list operations for device type + List operations = this.getValidOperationNames(); + if (operations.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("No operations are available."); } - List validDeviceIdentifiers; - List startupOperations; - //list devices of device type - List devices = deviceManagementProviderService.getAllDevices(deviceType, false); + return; + } - if (!devices.isEmpty()) { - if (log.isDebugEnabled() && deviceType != null) { - log.info("Devices exist to add operations and the total number of devices are " + devices.size()); - } - validDeviceIdentifiers = DeviceManagerUtil.getValidDeviceIdentifiers(devices); - if (!validDeviceIdentifiers.isEmpty()) { - if (log.isDebugEnabled() && deviceType != null) { - log.debug("Number of valid device identifier size to add operations: " + validDeviceIdentifiers - .size()); - } - for (String str : operations) { - CommandOperation operation = new CommandOperation(); - operation.setEnabled(true); - operation.setType(Operation.Type.COMMAND); - operation.setCode(str); - deviceManagementProviderService.addOperation(deviceType, operation, validDeviceIdentifiers); - } - startupOperations = getStartupOperations(); - if (startupOperations != null && !startupOperations.isEmpty()) { - addStartupOperations(startupOperations, validDeviceIdentifiers, - deviceManagementProviderService); - } - } else { - if (log.isDebugEnabled()) { - log.debug("No valid devices are available."); - } - } - } else { - if (log.isDebugEnabled()) { - log.debug("No devices are available to perform the operations."); - } + for (String str : operations) { + CommandOperation operation = new CommandOperation(); + operation.setEnabled(true); + operation.setType(Operation.Type.COMMAND); + operation.setCode(str); + try { + deviceManagementProviderService.addTaskOperation(deviceType, operation); + } catch (OperationManagementException e) { + throw new DeviceMgtTaskException("Error occurred while adding task operations to devices", e); } - } catch (InvalidDeviceException e) { - throw new DeviceMgtTaskException("Invalid DeviceIdentifiers found.", e); - } catch (DeviceManagementException e) { - throw new DeviceMgtTaskException("Error occurred while retrieving the device list.", e); - } catch (OperationManagementException e) { - throw new DeviceMgtTaskException("Error occurred while adding the operations to devices", e); } } @@ -187,7 +154,7 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager { mp.put(top.getTaskName(), milliseconds); } else { Long lastExecutedTime = mp.get(top.getTaskName()); - Long evalTime = lastExecutedTime + (frequency * top.getRecurrentTimes()); + long evalTime = lastExecutedTime + (frequency * top.getRecurrentTimes()); if (evalTime <= milliseconds) { opNames.add(top.getTaskName()); mp.put(top.getTaskName(), milliseconds); @@ -230,9 +197,7 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager { private List getOperationListforTask() throws DeviceMgtTaskException { DeviceManagementProviderService deviceManagementProviderService = DeviceManagementDataHolder - .getInstance(). - getDeviceManagementProvider(); - + .getInstance().getDeviceManagementProvider(); return deviceManagementProviderService.getMonitoringOperationList( deviceType);//Get task list from each device type } @@ -265,9 +230,7 @@ public class DeviceTaskManagerImpl implements DeviceTaskManager { } catch (DeviceMgtTaskException e) { // ignoring the error, no need to throw, If error occurs, return value will be false. } - return false; - } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index 389f0a06ce..049188bdd4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -14,29 +14,12 @@ * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. */ package org.wso2.carbon.device.mgt.core.util; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; -import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; @@ -56,15 +39,15 @@ import org.wso2.carbon.device.mgt.common.ApplicationRegistration; import org.wso2.carbon.device.mgt.common.ApplicationRegistrationException; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.EnrollmentConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; -import org.wso2.carbon.device.mgt.common.configuration.mgt.EnrollmentConfiguration; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; @@ -112,7 +95,6 @@ import java.io.IOException; import java.io.InputStreamReader; import java.sql.SQLException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Base64; import java.util.HashMap; import java.util.Hashtable; @@ -124,8 +106,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; - - public final class DeviceManagerUtil { +public final class DeviceManagerUtil { private static final Log log = LogFactory.getLog(DeviceManagerUtil.class); public static final String GENERAL_CONFIG_RESOURCE_PATH = "general"; @@ -166,7 +147,7 @@ import java.util.stream.IntStream; List jndiPropertyList = jndiConfig.getJndiProperties(); if (jndiPropertyList != null) { - Hashtable jndiProperties = new Hashtable(); + Hashtable jndiProperties = new Hashtable<>(); for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { jndiProperties.put(prop.getName(), prop.getValue()); } @@ -186,8 +167,8 @@ import java.util.stream.IntStream; * @param isSharedWithAllTenants is this device type shared with all tenants. * @return status of the operation */ - public static boolean registerDeviceType(String typeName, int tenantId, boolean isSharedWithAllTenants - , DeviceTypeMetaDefinition deviceTypeDefinition) + public static boolean registerDeviceType(String typeName, int tenantId, boolean isSharedWithAllTenants, + DeviceTypeMetaDefinition deviceTypeDefinition) throws DeviceManagementException { boolean status; try { @@ -210,11 +191,11 @@ import java.util.stream.IntStream; } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceManagementException("Error occurred while registering the device type '" - + typeName + "'", e); + + typeName + "'", e); } catch (TransactionManagementException e) { DeviceManagementDAOFactory.rollbackTransaction(); throw new DeviceManagementException("SQL occurred while registering the device type '" - + typeName + "'", e); + + typeName + "'", e); } finally { DeviceManagementDAOFactory.closeConnection(); } @@ -229,7 +210,7 @@ import java.util.stream.IntStream; * @return DeviceType which contains info about the device-type. */ public static DeviceType getDeviceType(String typeName, int tenantId) throws DeviceManagementException { - DeviceType deviceType = null; + DeviceType deviceType; try { DeviceManagementDAOFactory.openConnection(); DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); @@ -316,7 +297,6 @@ import java.util.stream.IntStream; return deviceIdentifiers; } - public static String getServerBaseHttpsUrl() { String hostName = "localhost"; try { @@ -356,10 +336,6 @@ import java.util.stream.IntStream; /** * returns the tenant Id of the specific tenant Domain - * - * @param tenantDomain - * @return - * @throws DeviceManagementException */ public static int getTenantId(String tenantDomain) throws DeviceManagementException { try { @@ -390,14 +366,14 @@ import java.util.stream.IntStream; return deviceManagementConfig.getPaginationConfiguration().getActivityListPageSize(); } else { throw new OperationManagementException("Device-Mgt configuration has not initialized. Please check the " + - "cdm-config.xml file."); + "cdm-config.xml file."); } } return limit; } - public static PaginationRequest validateOperationListPageSize(PaginationRequest paginationRequest) throws - OperationManagementException { + public static PaginationRequest validateOperationListPageSize(PaginationRequest paginationRequest) + throws OperationManagementException { if (paginationRequest.getRowCount() == 0) { DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). getDeviceManagementConfig(); @@ -406,14 +382,14 @@ import java.util.stream.IntStream; getOperationListPageSize()); } else { throw new OperationManagementException("Device-Mgt configuration has not initialized. Please check the " + - "cdm-config.xml file."); + "cdm-config.xml file."); } } return paginationRequest; } - public static PaginationRequest validateNotificationListPageSize(PaginationRequest paginationRequest) throws - NotificationManagementException { + public static PaginationRequest validateNotificationListPageSize(PaginationRequest paginationRequest) + throws NotificationManagementException { if (paginationRequest.getRowCount() == 0) { DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). getDeviceManagementConfig(); @@ -421,15 +397,15 @@ import java.util.stream.IntStream; paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration(). getNotificationListPageSize()); } else { - throw new NotificationManagementException("Device-Mgt configuration has not initialized. Please check the " + - "cdm-config.xml file."); + throw new NotificationManagementException("Device-Mgt configuration has not initialized. " + + "Please check the cdm-config.xml file."); } } return paginationRequest; } - public static PaginationRequest validateDeviceListPageSize(PaginationRequest paginationRequest) throws - DeviceManagementException { + public static PaginationRequest validateDeviceListPageSize(PaginationRequest paginationRequest) + throws DeviceManagementException { if (paginationRequest.getRowCount() == 0) { DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). getDeviceManagementConfig(); @@ -437,24 +413,24 @@ import java.util.stream.IntStream; paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration(). getDeviceListPageSize()); } else { - throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " + - "cdm-config.xml file."); + throw new DeviceManagementException("Device-Mgt configuration has not initialized. " + + "Please check the cdm-config.xml file."); } } return paginationRequest; } - public static GroupPaginationRequest validateGroupListPageSize(GroupPaginationRequest paginationRequest) throws - GroupManagementException { + public static GroupPaginationRequest validateGroupListPageSize(GroupPaginationRequest paginationRequest) + throws GroupManagementException { if (paginationRequest.getRowCount() == 0) { DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance() .getDeviceManagementConfig(); if (deviceManagementConfig != null) { paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration() - .getDeviceListPageSize()); + .getDeviceListPageSize()); } else { - throw new GroupManagementException("Device-Mgt configuration has not initialized. Please check the " + - "cdm-config.xml file."); + throw new GroupManagementException("Device-Mgt configuration has not initialized. " + + "Please check the cdm-config.xml file."); } } return paginationRequest; @@ -467,8 +443,8 @@ import java.util.stream.IntStream; if (deviceManagementConfig != null) { return deviceManagementConfig.getPaginationConfiguration().getDeviceListPageSize(); } else { - throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " + - "cdm-config.xml file."); + throw new DeviceManagementException("Device-Mgt configuration has not initialized. " + + "Please check the cdm-config.xml file."); } } return limit; @@ -480,8 +456,8 @@ import java.util.stream.IntStream; if (deviceManagementConfig != null) { return deviceManagementConfig.getOperationAnalyticsConfiguration().isPublishLocationResponseEnabled(); } else { - throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " + - "cdm-config.xml file."); + throw new DeviceManagementException("Device-Mgt configuration has not initialized. " + + "Please check the cdm-config.xml file."); } } @@ -491,8 +467,8 @@ import java.util.stream.IntStream; if (deviceManagementConfig != null) { return deviceManagementConfig.getOperationAnalyticsConfiguration().isPublishDeviceInfoResponseEnabled(); } else { - throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " + - "cdm-config.xml file."); + throw new DeviceManagementException("Device-Mgt configuration has not initialized. " + + "Please check the cdm-config.xml file."); } } @@ -503,8 +479,8 @@ import java.util.stream.IntStream; return deviceManagementConfig.getOperationAnalyticsConfiguration() .getOperationResponseConfigurations().isEnabled(); } else { - throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " + - "cdm-config.xml file."); + throw new DeviceManagementException("Device-Mgt configuration has not initialized. " + + "Please check the cdm-config.xml file."); } } @@ -515,8 +491,8 @@ import java.util.stream.IntStream; return deviceManagementConfig.getOperationAnalyticsConfiguration() .getOperationResponseConfigurations().getOperations(); } else { - throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " + - "cdm-config.xml file."); + throw new DeviceManagementException("Device-Mgt configuration has not initialized. " + + "Please check the cdm-config.xml file."); } } @@ -540,6 +516,7 @@ import java.util.stream.IntStream; errorDeviceIdList.add(deviceIdentifier); } } + DeviceIDHolder deviceIDHolder = new DeviceIDHolder(); deviceIDHolder.setValidDeviceIDList(validDeviceIDList); deviceIDHolder.setErrorDeviceIdList(errorDeviceIdList); @@ -553,8 +530,10 @@ import java.util.stream.IntStream; if (device == null || device.getDeviceIdentifier() == null || device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null) { return false; - } else - return !EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus()); + } else if (EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())) { + return false; + } + return true; } public static boolean isDeviceExists(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { @@ -595,7 +574,7 @@ import java.util.stream.IntStream; deviceCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration. Duration(TimeUnit.SECONDS, deviceCacheExpiry)).setStoreByValue(true).build(); if(deviceCacheCapacity > 0 ) { - ((CacheImpl)(manager.getCache(DeviceManagementConstants.DEVICE_CACHE))). + ((CacheImpl) manager.getCache(DeviceManagementConstants.DEVICE_CACHE)). setCapacity(deviceCacheCapacity); } } else { @@ -627,10 +606,10 @@ import java.util.stream.IntStream; initializeDeviceCache(); } if (manager != null) { - deviceCache = manager.getCache(DeviceManagementConstants.DEVICE_CACHE); + deviceCache = manager.getCache(DeviceManagementConstants.DEVICE_CACHE); } else { - deviceCache = Caching.getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER). - getCache(DeviceManagementConstants.DEVICE_CACHE); + deviceCache = Caching.getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER) + .getCache(DeviceManagementConstants.DEVICE_CACHE); } } return deviceCache; @@ -645,7 +624,7 @@ import java.util.stream.IntStream; */ @SuppressWarnings("PackageAccessibility") public static AppRegistrationCredentials getApplicationRegistrationCredentials(String host, String port, - String username, String password) + String username, String password) throws ApplicationRegistrationException { if (host == null || port == null) { String msg = "Required gatewayHost or gatewayPort system property is null"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManager.java index d9931fd2ca..bf73ef98a2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManager.java @@ -118,11 +118,6 @@ public class TestDeviceManager implements DeviceManager { return true; } - @Override - public boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException { - return false; - } - @Override public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrolmentInfo.Status status) throws DeviceManagementException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java index 1320f99e5b..8596a8a207 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java @@ -45,7 +45,7 @@ public class TestDataHolder { public static Device generateDummyDeviceData(String deviceType) { Device device = new Device(); device.setEnrolmentInfo(generateEnrollmentInfo(new Date().getTime(), new Date().getTime(), OWNER, EnrolmentInfo - .OwnerShip.BYOD, EnrolmentInfo.Status.CREATED)); + .OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE)); device.setDescription("Test Description"); device.setDeviceIdentifier(initialDeviceIdentifier); device.setType(deviceType); @@ -118,7 +118,7 @@ public class TestDataHolder { enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); enrolmentInfo.setOwner(OWNER); enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); - enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); device.setEnrolmentInfo(enrolmentInfo); device.setDescription("Test Description"); device.setDeviceIdentifier(deviceId.getId()); @@ -131,7 +131,7 @@ public class TestDataHolder { public static Device generateDummyDeviceData(DeviceIdentifier deviceIdentifier) { Device device = new Device(); device.setEnrolmentInfo(generateEnrollmentInfo(new Date().getTime(), new Date().getTime(), OWNER, EnrolmentInfo - .OwnerShip.BYOD, EnrolmentInfo.Status.CREATED)); + .OwnerShip.BYOD, EnrolmentInfo.Status.ACTIVE)); device.setDescription("Test Description"); device.setDeviceIdentifier(deviceIdentifier.getId()); device.setType(deviceIdentifier.getType()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java index 5ab8c7577d..92647cea28 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java @@ -42,7 +42,7 @@ public class EnrolmentPersistenceTests extends BaseDeviceManagementTest { /* Initializing source enrolment configuration bean to be tested */ EnrolmentInfo source = new EnrolmentInfo(owner, EnrolmentInfo.OwnerShip.BYOD, - EnrolmentInfo.Status.CREATED); + EnrolmentInfo.Status.ACTIVE); /* Adding dummy enrolment configuration to the device management metadata store */ try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/operation/OperationManagementTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/operation/OperationManagementTests.java index a5526ceb8c..9383e530bc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/operation/OperationManagementTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/operation/OperationManagementTests.java @@ -238,7 +238,7 @@ public class OperationManagementTests extends BaseDeviceManagementTest { @Test(dependsOnMethods = "addProfileOperation") public void getOperations() throws DeviceManagementException, OperationManagementException, InvalidDeviceException { for (DeviceIdentifier deviceIdentifier : deviceIds) { - List operations = this.operationMgtService.getOperations(deviceIdentifier); + List operations = this.operationMgtService.getOperations(deviceIdentifier); Assert.assertEquals(operations.size(), 4, "The operations should be 4, but found only " + operations.size()); } } @@ -611,14 +611,16 @@ public class OperationManagementTests extends BaseDeviceManagementTest { private void changeStatus(EnrolmentInfo.Status status) throws DeviceManagementException, OperationManagementException { - Device device = this.deviceMgmtProvider.getDevice(this.deviceIds.get(1)); + Device device = this.deviceMgmtProvider.getDevice(this.deviceIds.get(1), false); Assert.assertTrue(device != null); Assert.assertEquals(device.getType(), DEVICE_TYPE); Assert.assertTrue(device.getEnrolmentInfo() != null); - device.getEnrolmentInfo().setStatus(status); boolean modified = this.deviceMgmtProvider.changeDeviceStatus(this.deviceIds.get(1), status); - Assert.assertTrue(modified); - device = this.deviceMgmtProvider.getDevice(this.deviceIds.get(1)); + if (device.getEnrolmentInfo().getStatus() != status) { + Assert.assertTrue(modified); + device.getEnrolmentInfo().setStatus(status); + } + device = this.deviceMgmtProvider.getDevice(this.deviceIds.get(1), false); Assert.assertEquals(device.getEnrolmentInfo().getStatus(), status); } 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 1fcce383aa..619ded45e9 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 @@ -108,10 +108,8 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes private static final Log log = LogFactory.getLog(DeviceManagementProviderServiceTest.class); public static final String DEVICE_ID = "9999"; private static final String ALTERNATE_DEVICE_ID = "1128"; - private DeviceManagementProviderService providerService; private static final String DEVICE_TYPE = "RANDOM_DEVICE_TYPE"; - private static final String DEVICE_OWNER = "admin"; - private DeviceDetailsDAO deviceDetailsDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO(); + private final DeviceDetailsDAO deviceDetailsDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO(); DeviceManagementProviderService deviceMgtService; @@ -253,7 +251,7 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); enrolmentInfo.setOwner("user1"); enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); - enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); Device alternateDevice = TestDataHolder.generateDummyDeviceData(DEVICE_ID, DEVICE_TYPE, enrolmentInfo); @@ -884,8 +882,8 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes @Test(dependsOnMethods = {"testReEnrollmentofSameDeviceUnderSameUser"}) public void testUpdateDevicesStatusWithDeviceID() throws DeviceManagementException { if (!isMock()) { - boolean status = deviceMgtService.setStatus(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE), "user1", - EnrolmentInfo.Status.ACTIVE); + Device device = TestDataHolder.generateDummyDeviceData("abc"); + boolean status = deviceMgtService.setStatus(device, EnrolmentInfo.Status.ACTIVE); Assert.assertTrue(status); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index f13715cedd..a380bf5204 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -89,6 +89,7 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( OWNER VARCHAR(50) NOT NULL, OWNERSHIP VARCHAR(45) DEFAULT NULL, STATUS VARCHAR(50) NULL, + IS_TRANSFERRED BOOLEAN NOT NULL DEFAULT FALSE, DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, TENANT_ID INT NOT NULL, @@ -106,6 +107,13 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL, CREATED_TIMESTAMP INT NOT NULL, UPDATED_TIMESTAMP INT NOT NULL, + OPERATION_CODE VARCHAR(50) NOT NULL, + INITIATED_BY VARCHAR(100) NULL, + TYPE VARCHAR(20) NOT NULL, + DEVICE_ID INTEGER DEFAULT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, @@ -118,7 +126,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, EN_OP_MAP_ID INTEGER NOT NULL, - OPERATION_RESPONSE LONGBLOB DEFAULT NULL, + OPERATION_RESPONSE VARCHAR(1024) DEFAULT NULL , + IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE, RECEIVED_TIMESTAMP TIMESTAMP NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES @@ -129,6 +138,21 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); +CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE ( + ID INTEGER NOT NULL, + OPERATION_RESPONSE LONGBLOB DEFAULT NULL, + OPERATION_ID INTEGER NOT NULL, + EN_OP_MAP_ID INTEGER NOT NULL, + RECEIVED_TIMESTAMP TIMESTAMP NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + CONSTRAINT fk_dm_device_operation_response_large_mapping FOREIGN KEY (ID) + REFERENCES DM_DEVICE_OPERATION_RESPONSE (ID) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_en_op_map_response_large FOREIGN KEY (EN_OP_MAP_ID) + REFERENCES DM_ENROLMENT_OP_MAPPING (ID) + ON DELETE NO ACTION ON UPDATE NO ACTION +); + -- POLICY RELATED TABLES -- CREATE TABLE IF NOT EXISTS DM_PROFILE ( @@ -358,16 +382,14 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NULL, TENANT_ID INTEGER NOT NULL, STATUS VARCHAR(10) NULL, DESCRIPTION VARCHAR(1000) NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, PRIMARY KEY (NOTIFICATION_ID), CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -- NOTIFICATION TABLE END -- diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java index 2a142cdc83..f51b9cce74 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManager.java @@ -40,21 +40,21 @@ import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.FeatureManager; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager; -import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; -import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceDetails; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DataSource; -import org.wso2.carbon.device.mgt.extensions.device.type.template.config.TableConfig; -import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Table; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceDetails; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Feature; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Table; +import org.wso2.carbon.device.mgt.extensions.device.type.template.config.TableConfig; import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceDAODefinition; import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager; import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; @@ -80,7 +80,7 @@ import javax.xml.stream.XMLStreamReader; import java.io.File; import java.io.StringReader; import java.io.StringWriter; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.List; /** @@ -90,19 +90,18 @@ import java.util.List; public class DeviceTypeManager implements DeviceManager { private static final Log log = LogFactory.getLog(DeviceTypeManager.class); - private String deviceType; - private DeviceTypePluginDAOManager deviceTypePluginDAOManager; - private LicenseManager licenseManager; - private PlatformConfiguration defaultPlatformConfiguration; - private boolean propertiesExist; - private boolean requiredDeviceTypeAuthorization; - private boolean claimable; + private final String deviceType; + private final LicenseManager licenseManager; + private final PlatformConfiguration defaultPlatformConfiguration; + private final boolean requiredDeviceTypeAuthorization; private static final String PATH_MOBILE_PLUGIN_CONF_DIR = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "device-mgt-plugin-configs" + File.separator + "mobile"; private FeatureManager featureManager; + private boolean propertiesExist; + private DeviceTypePluginDAOManager deviceTypePluginDAOManager; public DeviceTypeManager(DeviceTypeConfigIdentifier deviceTypeConfigIdentifier, DeviceTypeConfiguration deviceTypeConfiguration) { @@ -135,10 +134,6 @@ public class DeviceTypeManager implements DeviceManager { String msg = "Error occurred while adding default license for " + deviceType + " devices."; throw new DeviceTypeDeployerPayloadException(msg, e); } - claimable = false; - if (deviceTypeConfiguration.getClaimable() != null ) { - claimable = deviceTypeConfiguration.getClaimable().isEnabled(); - } // Loading default platform configuration try { @@ -295,8 +290,7 @@ public class DeviceTypeManager implements DeviceManager { factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLStreamReader reader = factory.createXMLStreamReader( - new StringReader(new String((byte[]) resource.getContent(), Charset - .forName(DeviceTypePluginConstants.CHARSET_UTF8)))); + new StringReader(new String((byte[]) resource.getContent(), StandardCharsets.UTF_8))); JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class); Unmarshaller unmarshaller = context.createUnmarshaller(); @@ -476,11 +470,6 @@ public class DeviceTypeManager implements DeviceManager { return true; } - @Override - public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { - return claimable; - } - @Override public boolean setStatus(DeviceIdentifier deviceIdentifier, String currentUser, EnrolmentInfo.Status status) throws DeviceManagementException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java index 520c81cf44..67b79bfeb4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerService.java @@ -80,17 +80,17 @@ public class DeviceTypeManagerService implements DeviceManagementService { private static final String NOTIFIER_PROPERTY = "notifierType"; private static final String NOTIFIER_TYPE_LOCAL = "LOCAL"; - private DeviceManager deviceManager; + private final DeviceManager deviceManager; private PushNotificationConfig pushNotificationConfig; private ProvisioningConfig provisioningConfig; private String type; - private OperationMonitoringTaskConfig operationMonitoringConfigs; - private List monitoringOperations; + private final OperationMonitoringTaskConfig operationMonitoringConfigs; + private List monitoringOperations = new ArrayList<>(); private PolicyMonitoringManager policyMonitoringManager; - private InitialOperationConfig initialOperationConfig; + private final InitialOperationConfig initialOperationConfig; private StartupOperationConfig startupOperationConfig; private PullNotificationSubscriber pullNotificationSubscriber; - private DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig; + private final DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig; private DeviceTypePlatformDetails deviceTypePlatformDetails; private GeneralConfig generalConfig; private boolean isRegistryBasedConfigs = false; @@ -141,6 +141,7 @@ public class DeviceTypeManagerService implements DeviceManagementService { MonitoringOperation monitoringOperation = new MonitoringOperation(); monitoringOperation.setTaskName(op.getOperationName()); monitoringOperation.setRecurrentTimes(op.getRecurrency()); + monitoringOperation.setResponsePersistence(op.getResponsePersistence()); monitoringOperations.add(monitoringOperation); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HTTPDeviceTypeManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HTTPDeviceTypeManagerService.java index 510b03a65b..eb72a6e410 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HTTPDeviceTypeManagerService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HTTPDeviceTypeManagerService.java @@ -25,7 +25,6 @@ import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfi import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeDefinitionProvider; import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; -import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Claimable; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceDetails; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Properties; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Features; @@ -60,9 +59,6 @@ public class HTTPDeviceTypeManagerService extends DeviceTypeManagerService imple DeviceTypeConfiguration deviceTypeConfiguration = new DeviceTypeConfiguration(); if (deviceTypeMetaDefinition != null) { - Claimable claimable = new Claimable(); - claimable.setEnabled(deviceTypeMetaDefinition.isClaimable()); - deviceTypeConfiguration.setClaimable(claimable); if (deviceTypeMetaDefinition.getProperties() != null && deviceTypeMetaDefinition.getProperties().size() > 0) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Claimable.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Claimable.java deleted file mode 100644 index fdd3039597..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/Claimable.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.extensions.device.type.template.config; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlValue; - - -/** - *

Java class for DeviceDetails complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="DeviceDetails">
- *   <simpleContent>
- *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
- *       <attribute name="table-id" type="{http://www.w3.org/2001/XMLSchema}string" />
- *     </extension>
- *   </simpleContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Claimable", propOrder = { - "value" -}) -public class Claimable { - - @XmlValue - protected String value; - @XmlAttribute(name = "enabled") - protected boolean enabled; - - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } - - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } - - /** - * Gets the value of the enabled property. - * - * @return - * possible object is - * {@link String } - * - */ - public boolean isEnabled() { - return enabled; - } - - /** - * Sets the value of the enabled property. - * - * @param enabled - * allowed object is - * {@link String } - * - */ - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java index 3701991881..f1c470829e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/DeviceTypeConfiguration.java @@ -78,8 +78,6 @@ public class DeviceTypeConfiguration { @XmlElement(name = "DeviceDetails", required = true) protected DeviceDetails deviceDetails; - @XmlElement(name = "Claimable", required = true) - protected Claimable claimable; @XmlElement(name = "Features", required = true) protected Features features; @XmlElement(name = "PolicyUIConfigurations", required = true) @@ -198,27 +196,6 @@ public class DeviceTypeConfiguration { this.deviceDetails = value; } - /** - * Gets the value of the Claimable property. - * - * @return possible object is - * {@link DeviceDetails } - */ - public Claimable getClaimable() { - return claimable; - } - - /** - * Sets the value of the deviceDetails property. - * - * @param value allowed object is - * {@link DeviceDetails } - */ - public void setClaimable(Claimable value) { - this.claimable = value; - } - - /** * Gets the value of the policyMonitoring property. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/TaskConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/TaskConfiguration.java index fd31754a83..4d25e2e793 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/TaskConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/config/TaskConfiguration.java @@ -67,6 +67,7 @@ public class TaskConfiguration { private String operationName; private int recurrency; + private boolean responsePersistence = true; @XmlElement(name = "Name", required = true) public String getOperationName() { @@ -86,6 +87,14 @@ public class TaskConfiguration { this.recurrency = recurrency; } + @XmlElement(name = "ResponsePersistence") + public boolean getResponsePersistence() { + return responsePersistence; + } + + public void setResponsePersistence(boolean responsePersistence) { + this.responsePersistence = responsePersistence; + } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypePluginConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypePluginConstants.java index 4ac7c2292c..140ff44cbe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypePluginConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/util/DeviceTypePluginConstants.java @@ -23,6 +23,5 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template.util; */ public class DeviceTypePluginConstants { public static final String MEDIA_TYPE_XML = "application/xml"; - public static final String CHARSET_UTF8 = "UTF8"; public static final String LANGUAGE_CODE_ENGLISH_US = "en_US"; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java index 7e7e14efd2..c6debc4352 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java @@ -220,7 +220,6 @@ public class HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest { deviceTypeMetaDefinition = new DeviceTypeMetaDefinition(); deviceTypeMetaDefinition.setPushNotificationConfig(pushNotificationConfig); deviceTypeMetaDefinition.setDescription("This is android_sense"); - deviceTypeMetaDefinition.setClaimable(true); deviceTypeMetaDefinition.setLicense(androidSenseLicense); deviceTypeMetaDefinition.setFeatures(features); } diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/ScopeValidationHandler.java b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/ScopeValidationHandler.java index e182c0b3a0..bef3cda94e 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/ScopeValidationHandler.java +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/handlers/ScopeValidationHandler.java @@ -23,21 +23,20 @@ import org.wso2.carbon.device.mgt.oauth.extensions.internal.OAuthExtensionsDataH import org.wso2.carbon.identity.oauth.cache.CacheEntry; import org.wso2.carbon.identity.oauth.cache.OAuthCache; import org.wso2.carbon.identity.oauth.cache.OAuthCacheKey; -import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; -import org.wso2.carbon.identity.oauth2.dao.TokenMgtDAO; +import org.wso2.carbon.identity.oauth2.dao.TokenManagementDAO; +import org.wso2.carbon.identity.oauth2.dao.TokenManagementDAOImpl; import org.wso2.carbon.identity.oauth2.model.AccessTokenDO; import org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry; import org.wso2.carbon.identity.oauth2.validators.OAuth2ScopeValidator; import java.util.Map; +@SuppressWarnings("unused") public class ScopeValidationHandler extends OAuth2ScopeValidator { private final static Log log = LogFactory.getLog(ScopeValidationHandler.class); - private Map scopeValidators; - - private final String DEFAULT_PREFIX = "default"; + private final Map scopeValidators; public ScopeValidationHandler() { scopeValidators = OAuthExtensionsDataHolder.getInstance().getScopeValidators(); @@ -47,7 +46,7 @@ public class ScopeValidationHandler extends OAuth2ScopeValidator { //returns true if scope validators are not defined if (scopeValidators == null || scopeValidators.isEmpty()) { - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug("OAuth2 scope validators are not loaded"); } return true; @@ -57,30 +56,31 @@ public class ScopeValidationHandler extends OAuth2ScopeValidator { //returns true if scope does not exist for the resource if (resourceScope == null) { - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug("Resource '" + resource + "' is not protected with a scope"); } return true; } - String scope[] = resourceScope.split(":"); + String[] scope = resourceScope.split(":"); String scopePrefix = scope[0]; OAuth2ScopeValidator scopeValidator = scopeValidators.get(scopePrefix); if (scopeValidator == null) { - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug("OAuth2 scope validator cannot be identified for '" + scopePrefix + "' scope prefix"); } // loading default scope validator if matching validator is not found + String DEFAULT_PREFIX = "default"; scopeValidator = scopeValidators.get(DEFAULT_PREFIX); - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug("Loading default scope validator"); } if (scopeValidator == null) { - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug("Default scope validator is not available"); } return true; @@ -95,35 +95,29 @@ public class ScopeValidationHandler extends OAuth2ScopeValidator { String resourceScope = null; boolean cacheHit = false; - // Check the cache, if caching is enabled. - if (OAuthServerConfiguration.getInstance().isCacheEnabled()) { - OAuthCache oauthCache = OAuthCache.getInstance(); - OAuthCacheKey cacheKey = new OAuthCacheKey(resource); - CacheEntry result = oauthCache.getValueFromCache(cacheKey); - - //Cache hit - if (result instanceof ResourceScopeCacheEntry) { - resourceScope = ((ResourceScopeCacheEntry) result).getScope(); - cacheHit = true; - } + + OAuthCache oauthCache = OAuthCache.getInstance(); + OAuthCacheKey cacheKey = new OAuthCacheKey(resource); + CacheEntry result = oauthCache.getValueFromCache(cacheKey); + + //Cache hit + if (result instanceof ResourceScopeCacheEntry) { + resourceScope = ((ResourceScopeCacheEntry) result).getScope(); + cacheHit = true; } - TokenMgtDAO tokenMgtDAO = new TokenMgtDAO(); if (!cacheHit) { + TokenManagementDAO tokenMgtDAO = new TokenManagementDAOImpl(); try { - resourceScope = tokenMgtDAO.findScopeOfResource(resource); + resourceScope = tokenMgtDAO.findTenantAndScopeOfResource(resource).getLeft(); } catch (IdentityOAuth2Exception e) { log.error("Error occurred while retrieving scope for resource '" + resource + "'"); } - if (OAuthServerConfiguration.getInstance().isCacheEnabled()) { - OAuthCache oauthCache = OAuthCache.getInstance(); - OAuthCacheKey cacheKey = new OAuthCacheKey(resource); - ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope); - //Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for - //which scopes haven't been defined). - oauthCache.addToCache(cacheKey, cacheEntry); - } + ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope); + //Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for + //which scopes haven't been defined). + oauthCache.addToCache(cacheKey, cacheEntry); } return resourceScope; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java index 050bfa8855..5914f223ca 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java @@ -74,8 +74,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { DeviceManagementProviderService service = this.getDeviceManagementProviderService(); for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) { Device device = service.getDevice(deviceIdentifier, false); - service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(), - EnrolmentInfo.Status.UNREACHABLE); + service.setStatus(device, EnrolmentInfo.Status.UNREACHABLE); } } catch (DeviceManagementException e) { String msg = "Error occurred while setting the device as unreachable"; @@ -91,8 +90,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { DeviceManagementProviderService service = this.getDeviceManagementProviderService(); for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) { Device device = service.getDevice(deviceIdentifier, false); - service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(), - EnrolmentInfo.Status.INACTIVE); + service.setStatus(device, EnrolmentInfo.Status.INACTIVE); } } catch (DeviceManagementException e) { String msg = "Error occurred while setting the device as inactive"; @@ -109,8 +107,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(device.getDeviceIdentifier()); deviceIdentifier.setType(device.getType()); - service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(), - EnrolmentInfo.Status.UNREACHABLE); + service.setStatus(device, EnrolmentInfo.Status.UNREACHABLE); } } catch (DeviceManagementException e) { String msg = "Error occurred while setting the device as unreachable"; @@ -126,8 +123,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { DeviceManagementProviderService service = this.getDeviceManagementProviderService(); Device device = service.getDevice(deviceIdentifier, false); - service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(), - EnrolmentInfo.Status.ACTIVE); + service.setStatus(device, EnrolmentInfo.Status.ACTIVE); } catch (DeviceManagementException e) { String msg = "Error occurred while setting the device as reachable for " + @@ -231,8 +227,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { try { DeviceManagementProviderService service = this.getDeviceManagementProviderService(); Device device = service.getDevice(deviceIdentifier, false); - service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(), - EnrolmentInfo.Status.ACTIVE); + service.setStatus(device, EnrolmentInfo.Status.ACTIVE); } catch (DeviceManagementException e) { String msg = "Error occurred while marking device as compliance " + deviceIdentifier.getId() + " - " + @@ -246,11 +241,9 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { public void deactivateDevice(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { try { - DeviceManagementProviderService service = this.getDeviceManagementProviderService(); Device device = service.getDevice(deviceIdentifier, false); - service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(), - EnrolmentInfo.Status.INACTIVE); + service.setStatus(device, EnrolmentInfo.Status.INACTIVE); } catch (DeviceManagementException e) { String msg = "Error occurred while deactivating the device " + deviceIdentifier.getId() + " - " + @@ -266,8 +259,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { try { DeviceManagementProviderService service = this.getDeviceManagementProviderService(); Device device = service.getDevice(deviceIdentifier, false); - service.setStatus(deviceIdentifier, device.getEnrolmentInfo().getOwner(), - EnrolmentInfo.Status.ACTIVE); + service.setStatus(device, EnrolmentInfo.Status.ACTIVE); } catch (DeviceManagementException e) { String msg = "Error occurred while activating the device " + deviceIdentifier.getId() + " - " + 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 550334d946..3fbe2d5834 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 @@ -150,15 +150,10 @@ public class MonitoringTask implements Task { deviceType); } for (Device device : devices) { - EnrolmentInfo.Status status = device.getEnrolmentInfo().getStatus(); - if (status.equals(EnrolmentInfo.Status.BLOCKED) || - status.equals(EnrolmentInfo.Status.REMOVED) || - status.equals(EnrolmentInfo.Status.UNCLAIMED) || - status.equals(EnrolmentInfo.Status.DISENROLLMENT_REQUESTED) || - status.equals(EnrolmentInfo.Status.SUSPENDED)) { - continue; - } else { + if (status.equals(EnrolmentInfo.Status.ACTIVE) || + status.equals(EnrolmentInfo.Status.INACTIVE) || + status.equals(EnrolmentInfo.Status.UNREACHABLE)) { notifiableDevices.add(device); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TypeXDeviceManager.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TypeXDeviceManager.java index d38eb9e881..cd3d1e56d4 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TypeXDeviceManager.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/mock/TypeXDeviceManager.java @@ -124,11 +124,6 @@ public class TypeXDeviceManager implements DeviceManager { return false; } - @Override - public boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException { - return false; - } - @Override public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrolmentInfo.Status status) throws DeviceManagementException { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index 8bacda908c..ccf48c1b0c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -56,6 +56,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_PROPERTIES ( PRIMARY KEY (DEVICE_TYPE_NAME, DEVICE_IDENTIFICATION, PROPERTY_NAME) ); +DROP TABLE IF EXISTS GROUP_PROPERTIES; CREATE TABLE IF NOT EXISTS GROUP_PROPERTIES ( GROUP_ID INTEGER NOT NULL, PROPERTY_NAME VARCHAR(100) DEFAULT 0, @@ -97,6 +98,7 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( OWNER VARCHAR(50) NOT NULL, OWNERSHIP VARCHAR(45) DEFAULT NULL, STATUS VARCHAR(50) NULL, + IS_TRANSFERRED BOOLEAN NOT NULL DEFAULT FALSE, DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, TENANT_ID INT NOT NULL, @@ -111,9 +113,16 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, STATUS VARCHAR(50) NULL, + PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL, CREATED_TIMESTAMP INT NOT NULL, UPDATED_TIMESTAMP INT NOT NULL, - PUSH_NOTIFICATION_STATUS VARCHAR(50), + OPERATION_CODE VARCHAR(50) NOT NULL, + INITIATED_BY VARCHAR(100) NULL, + TYPE VARCHAR(20) NOT NULL, + DEVICE_ID INTEGER DEFAULT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, @@ -126,13 +135,29 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( ID INTEGER AUTO_INCREMENT NOT NULL, ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, - OPERATION_RESPONSE BLOB DEFAULT NULL, + EN_OP_MAP_ID INTEGER NOT NULL, + OPERATION_RESPONSE VARCHAR(1024) DEFAULT NULL , + IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE, RECEIVED_TIMESTAMP TIMESTAMP NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_en_op_map_response FOREIGN KEY (EN_OP_MAP_ID) REFERENCES + DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +DROP TABLE IF EXISTS DM_DEVICE_OPERATION_RESPONSE_LARGE; +CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE ( + ID INTEGER NOT NULL, + OPERATION_RESPONSE LONGBLOB DEFAULT NULL, + OPERATION_ID INTEGER NOT NULL, + RECEIVED_TIMESTAMP TIMESTAMP NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + CONSTRAINT fk_dm_device_operation_response_large_mapping FOREIGN KEY (ID) + REFERENCES DM_DEVICE_OPERATION_RESPONSE (ID) + ON DELETE NO ACTION ON UPDATE NO ACTION ); -- POLICY RELATED TABLES -- @@ -174,6 +199,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( ON UPDATE NO ACTION ); +DROP TABLE IF EXISTS DM_POLICY_CORRECTIVE_ACTION; CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION ( ID INT(11) NOT NULL AUTO_INCREMENT, ACTION_TYPE VARCHAR(45) NOT NULL, @@ -268,7 +294,7 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( ); DROP TABLE IF EXISTS DM_DEVICE_POLICY_APPLIED; - CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( +CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( ID INT NOT NULL AUTO_INCREMENT , DEVICE_ID INT NOT NULL , ENROLMENT_ID INT(11) NOT NULL, @@ -287,7 +313,6 @@ DROP TABLE IF EXISTS DM_DEVICE_POLICY_APPLIED; ON UPDATE NO ACTION ); - DROP TABLE IF EXISTS DM_CRITERIA; CREATE TABLE IF NOT EXISTS DM_CRITERIA ( ID INT NOT NULL AUTO_INCREMENT, @@ -296,7 +321,6 @@ CREATE TABLE IF NOT EXISTS DM_CRITERIA ( PRIMARY KEY (ID) ); - DROP TABLE IF EXISTS DM_POLICY_CRITERIA; CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( ID INT NOT NULL AUTO_INCREMENT, @@ -315,6 +339,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( ON UPDATE NO ACTION ); +DROP TABLE IF EXISTS DM_POLICY_CRITERIA_PROPERTIES; CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( ID INT NOT NULL AUTO_INCREMENT, POLICY_CRITERION_ID INT NOT NULL, @@ -368,21 +393,6 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( ON UPDATE NO ACTION ); -DROP TABLE IF EXISTS DM_ENROLMENT; -CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER NOT NULL, - OWNER VARCHAR(50) NOT NULL, - OWNERSHIP VARCHAR(45) DEFAULT NULL, - STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, - DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, - TENANT_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - DROP TABLE IF EXISTS DM_APPLICATION; CREATE TABLE IF NOT EXISTS DM_APPLICATION ( ID INTEGER AUTO_INCREMENT NOT NULL, @@ -432,6 +442,7 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( ); -- NOTIFICATION TABLE END -- +DROP TABLE IF EXISTS DM_DEVICE_INFO; CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INT NULL, @@ -451,6 +462,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( ON UPDATE NO ACTION ); +DROP TABLE IF EXISTS DM_DEVICE_LOCATION; CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INT NULL, @@ -478,7 +490,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( ON UPDATE NO ACTION ); - +DROP TABLE IF EXISTS DM_DEVICE_DETAIL; CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, @@ -512,8 +524,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( ON UPDATE NO ACTION ); - - -- POLICY AND DEVICE GROUP MAPPING -- DROP TABLE IF EXISTS DM_DEVICE_GROUP_POLICY; CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( @@ -593,4 +603,4 @@ DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID ORDER BY TENANT_ID, DEVICE_ID; --- END OF DASHBOARD RELATED VIEWS -- +-- END OF DASHBOARD RELATED VIEWS -- \ No newline at end of file diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml index 7cb72faa84..671ac13d8d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml @@ -28,7 +28,6 @@ - diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml index d31c3dc610..25b064abd8 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/cdm-config.xml @@ -37,9 +37,9 @@ org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.XMPPBasedPushNotificationProvider - - false - + + false + https://localhost:9443 admin @@ -100,6 +100,11 @@ false + false + + DM_DB + ARCHIVAL_DB + org.wso2.carbon.device.mgt.core.task.impl.ArchivalTask 0 0 0 1/1 * ? * diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/mysql.sql index 85a9e38196..659e22d110 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/mysql.sql @@ -8,10 +8,10 @@ CREATE TABLE IF NOT EXISTS DM_OPERATION_ARCH ( INITIATED_BY VARCHAR(100) NULL, OPERATION_DETAILS BLOB DEFAULT NULL, ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - ARCHIVED_AT TIMESTAMP DEFAULT NOW(), - PRIMARY KEY (ID) + ARCHIVED_AT TIMESTAMP DEFAULT NOW() )ENGINE = InnoDB; +CREATE INDEX IDX_OPR_ARC ON DM_OPERATION_ARCH(ARCHIVED_AT); CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING_ARCH ( ID INTEGER NOT NULL, @@ -20,20 +20,31 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING_ARCH ( STATUS VARCHAR(50) NULL, CREATED_TIMESTAMP INTEGER NOT NULL, UPDATED_TIMESTAMP INTEGER NOT NULL, - ARCHIVED_AT TIMESTAMP DEFAULT NOW(), - PRIMARY KEY (ID) + ARCHIVED_AT TIMESTAMP DEFAULT NOW() )ENGINE = InnoDB; +CREATE INDEX IDX_EN_OP_MAP_ARCH ON DM_ENROLMENT_OP_MAPPING_ARCH(ARCHIVED_AT); + CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE_ARCH ( ID INT(11) NOT NULL, ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, - OPERATION_RESPONSE LONGBLOB DEFAULT NULL, + OPERATION_RESPONSE VARCHAR(4096) DEFAULT NULL, RECEIVED_TIMESTAMP TIMESTAMP NULL, ARCHIVED_AT TIMESTAMP DEFAULT NOW(), - PRIMARY KEY (ID) + IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE +)ENGINE = InnoDB; + +CREATE INDEX IDX_OPR_RES_ARCH ON DM_DEVICE_OPERATION_RESPONSE_ARCH(ARCHIVED_AT); + +CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE_ARCH ( + ID INT(11) NOT NULL, + OPERATION_RESPONSE LONGBLOB DEFAULT NULL, + ARCHIVED_AT TIMESTAMP DEFAULT NOW() )ENGINE = InnoDB; +CREATE INDEX IDX_OPR_RES_LRG_ARCH ON DM_DEVICE_OPERATION_RESPONSE_LARGE_ARCH(ARCHIVED_AT); + CREATE TABLE IF NOT EXISTS DM_NOTIFICATION_ARCH ( NOTIFICATION_ID INTEGER NOT NULL, DEVICE_ID INTEGER NOT NULL, @@ -41,6 +52,7 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION_ARCH ( TENANT_ID INTEGER NOT NULL, STATUS VARCHAR(10) NULL, DESCRIPTION VARCHAR(1000) NULL, - ARCHIVED_AT TIMESTAMP DEFAULT NOW(), - PRIMARY KEY (NOTIFICATION_ID) + ARCHIVED_AT TIMESTAMP DEFAULT NOW() )ENGINE = InnoDB; + +CREATE INDEX IDX_NOT_ARCH ON DM_NOTIFICATION_ARCH(ARCHIVED_AT); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/postgresql.sql new file mode 100644 index 0000000000..726f5b9a7c --- /dev/null +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/archival/postgresql.sql @@ -0,0 +1,57 @@ +CREATE TABLE IF NOT EXISTS DM_OPERATION_ARCH ( + ID INTEGER NOT NULL, + TYPE VARCHAR(20) NOT NULL, + CREATED_TIMESTAMP TIMESTAMP(0) NOT NULL, + RECEIVED_TIMESTAMP TIMESTAMP(0) NULL, + OPERATION_CODE VARCHAR(50) NOT NULL, + INITIATED_BY VARCHAR(100) NULL, + OPERATION_DETAILS BYTEA DEFAULT NULL, + ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + ARCHIVED_AT TIMESTAMP(0) DEFAULT NOW() +); + +CREATE INDEX IDX_OPR_ARC ON DM_OPERATION_ARCH(ARCHIVED_AT); + +CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING_ARCH ( + ID INTEGER NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + STATUS VARCHAR(50) NULL, + CREATED_TIMESTAMP INTEGER NOT NULL, + UPDATED_TIMESTAMP INTEGER NOT NULL, + ARCHIVED_AT TIMESTAMP(0) DEFAULT NOW() +); + +CREATE INDEX IDX_EN_OP_MAP_ARCH ON DM_ENROLMENT_OP_MAPPING_ARCH(ARCHIVED_AT); + +CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE_ARCH ( + ID INT NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + OPERATION_RESPONSE VARCHAR(4096) DEFAULT NULL, + RECEIVED_TIMESTAMP TIMESTAMP(0) NULL, + ARCHIVED_AT TIMESTAMP(0) DEFAULT NOW(), + IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE +); + +CREATE INDEX IDX_OPR_RES_ARCH ON DM_DEVICE_OPERATION_RESPONSE_ARCH(ARCHIVED_AT); + +CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE_ARCH ( + ID INT NOT NULL, + OPERATION_RESPONSE BYTEA DEFAULT NULL, + ARCHIVED_AT TIMESTAMP(0) DEFAULT NOW() +); + +CREATE INDEX IDX_OPR_RES_LRG_ARCH ON DM_DEVICE_OPERATION_RESPONSE_LARGE_ARCH(ARCHIVED_AT); + +CREATE TABLE IF NOT EXISTS DM_NOTIFICATION_ARCH ( + NOTIFICATION_ID INTEGER NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + STATUS VARCHAR(10) NULL, + DESCRIPTION VARCHAR(1000) NULL, + ARCHIVED_AT TIMESTAMP(0) DEFAULT NOW() +); + +CREATE INDEX IDX_NOT_ARCH ON DM_NOTIFICATION_ARCH(ARCHIVED_AT); \ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql index 53694c1147..de079f30a7 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -98,6 +98,7 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( OWNER VARCHAR(255) NOT NULL, OWNERSHIP VARCHAR(45) DEFAULT NULL, STATUS VARCHAR(50) NULL, + IS_TRANSFERRED BOOLEAN NOT NULL DEFAULT FALSE, DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, TENANT_ID INT NOT NULL, @@ -115,6 +116,13 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL, CREATED_TIMESTAMP INT NOT NULL, UPDATED_TIMESTAMP INT NOT NULL, + OPERATION_CODE VARCHAR(50) NOT NULL, + INITIATED_BY VARCHAR(100) NULL, + TYPE VARCHAR(20) NOT NULL, + DEVICE_ID INTEGER DEFAULT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, @@ -127,7 +135,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, EN_OP_MAP_ID INTEGER NOT NULL, - OPERATION_RESPONSE LONGBLOB DEFAULT NULL, + OPERATION_RESPONSE VARCHAR(1024) DEFAULT NULL , + IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE, RECEIVED_TIMESTAMP TIMESTAMP NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES @@ -138,6 +147,21 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); +CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE ( + ID INTEGER NOT NULL, + OPERATION_RESPONSE LONGBLOB DEFAULT NULL, + OPERATION_ID INTEGER NOT NULL, + EN_OP_MAP_ID INTEGER NOT NULL, + RECEIVED_TIMESTAMP TIMESTAMP NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + CONSTRAINT fk_dm_device_operation_response_large_mapping FOREIGN KEY (ID) + REFERENCES DM_DEVICE_OPERATION_RESPONSE (ID) + ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_en_op_map_response_large FOREIGN KEY (EN_OP_MAP_ID) + REFERENCES DM_ENROLMENT_OP_MAPPING (ID) + ON DELETE NO ACTION ON UPDATE NO ACTION +); + -- POLICY RELATED TABLES -- CREATE TABLE IF NOT EXISTS DM_PROFILE ( diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql index c1ac997d66..6ba14be3d2 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -114,47 +114,11 @@ CREATE TABLE DM_OPERATION ( RECEIVED_TIMESTAMP DATETIME2 NULL, OPERATION_CODE VARCHAR(50) NOT NULL, INITIATED_BY VARCHAR(100) NULL, - PRIMARY KEY (ID) -); - -IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_CONFIG_OPERATION]') AND TYPE IN (N'U')) -CREATE TABLE DM_CONFIG_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - OPERATION_CONFIG VARBINARY(MAX) DEFAULT NULL, - ENABLED BIT NOT NULL DEFAULT 0, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT FK_DM_OPERATION_CONFIG FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_COMMAND_OPERATION]') AND TYPE IN (N'U')) -CREATE TABLE DM_COMMAND_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED BIT NOT NULL DEFAULT 0, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT FK_DM_OPERATION_COMMAND FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_POLICY_OPERATION]') AND TYPE IN (N'U')) -CREATE TABLE DM_POLICY_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, OPERATION_DETAILS VARBINARY(MAX) DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT FK_DM_OPERATION_POLICY FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + ENABLED BIT NOT NULL DEFAULT 0, + PRIMARY KEY (ID) ); -IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_PROFILE_OPERATION]') AND TYPE IN (N'U')) -CREATE TABLE DM_PROFILE_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS VARBINARY(MAX) DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT FK_DM_OPERATION_PROFILE FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_ENROLMENT]') AND TYPE IN (N'U')) CREATE TABLE DM_ENROLMENT ( @@ -163,6 +127,7 @@ CREATE TABLE DM_ENROLMENT ( OWNER VARCHAR(255) NOT NULL, OWNERSHIP VARCHAR(45) DEFAULT NULL, STATUS VARCHAR(50) NULL, + IS_TRANSFERRED TINYINT NOT NULL DEFAULT 0, DATE_OF_ENROLMENT DATETIME2 DEFAULT NULL, DATE_OF_LAST_UPDATE DATETIME2 DEFAULT NULL, TENANT_ID INTEGER NOT NULL, @@ -205,7 +170,8 @@ CREATE TABLE DM_DEVICE_OPERATION_RESPONSE ( ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, EN_OP_MAP_ID INTEGER NOT NULL, - OPERATION_RESPONSE VARBINARY(MAX) DEFAULT NULL, + OPERATION_RESPONSE VARCHAR(1024) DEFAULT NULL, + IS_LARGE_RESPONSE BIT NOT NULL DEFAULT 0, RECEIVED_TIMESTAMP DATETIME2 DEFAULT NULL PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_OPERATION_RESP_ENROLMENT FOREIGN KEY (ENROLMENT_ID) REFERENCES @@ -222,6 +188,26 @@ CREATE INDEX IDX_ENID_OPID ON DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLME IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_DM_EN_OP_MAP_RES' AND OBJECT_ID = OBJECT_ID('DM_DEVICE_OPERATION_RESPONSE')) CREATE INDEX IDX_DM_EN_OP_MAP_RES ON DM_DEVICE_OPERATION_RESPONSE(EN_OP_MAP_ID); +IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_DEVICE_OPERATION_RESPONSE_LARGE]') AND TYPE IN (N'U')) +CREATE TABLE DM_DEVICE_OPERATION_RESPONSE_LARGE ( + ID INTEGER IDENTITY(1,1) NOT NULL, + OPERATION_ID INTEGER NOT NULL, + EN_OP_MAP_ID INTEGER NOT NULL, + OPERATION_RESPONSE VARBINARY(MAX) DEFAULT NULL, + RECEIVED_TIMESTAMP DATETIME2 DEFAULT NULL + PRIMARY KEY (ID), + CONSTRAINT FK_DM_DEVICE_OPERATION_RESP_LARGE_OPERATION FOREIGN KEY (OPERATION_ID) REFERENCES + DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT FK_DM_EN_OP_MAP_RESPONSE_LARGE FOREIGN KEY (EN_OP_MAP_ID) REFERENCES + DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_ENID_OPID_LARGE' AND OBJECT_ID = OBJECT_ID('DM_DEVICE_OPERATION_RESPONSE_LARGE')) +CREATE INDEX IDX_ENID_OPID_LARGE ON DM_DEVICE_OPERATION_RESPONSE_LARGE(OPERATION_ID); + +IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_DM_EN_OP_MAP_RES_LARGE' AND OBJECT_ID = OBJECT_ID('DM_DEVICE_OPERATION_RESPONSE_LARGE')) +CREATE INDEX IDX_DM_EN_OP_MAP_RES_LARGE ON DM_DEVICE_OPERATION_RESPONSE_LARGE(EN_OP_MAP_ID); + -- POLICY RELATED TABLES -- IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_PROFILE]') AND TYPE IN (N'U')) diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql index d20c9b571d..aa4b047c0b 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -113,6 +113,7 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( OWNER VARCHAR(255) NOT NULL, OWNERSHIP VARCHAR(45) DEFAULT NULL, STATUS VARCHAR(50) NULL, + IS_TRANSFERRED BOOLEAN NOT NULL DEFAULT FALSE, DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL, TENANT_ID INT NOT NULL, @@ -133,6 +134,13 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL, CREATED_TIMESTAMP INTEGER NOT NULL, UPDATED_TIMESTAMP INTEGER NOT NULL, + OPERATION_CODE VARCHAR(50) NOT NULL, + INITIATED_BY VARCHAR(100) NULL, + TYPE VARCHAR(20) NOT NULL, + DEVICE_ID INTEGER DEFAULT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0; PRIMARY KEY (ID), KEY `fk_dm_device_operation_mapping_operation` (`OPERATION_ID`), KEY `IDX_DM_ENROLMENT_OP_MAPPING` (`ENROLMENT_ID`,`OPERATION_ID`), @@ -148,25 +156,44 @@ CREATE INDEX IDX_EN_OP_MAPPING_EN_ID ON DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID); CREATE INDEX IDX_EN_OP_MAPPING_OP_ID ON DM_ENROLMENT_OP_MAPPING(OPERATION_ID); CREATE INDEX IDX_EN_OP_MAPPING_EN_ID_STATUS ON DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID, STATUS); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( - ID INT(11) NOT NULL AUTO_INCREMENT, - ENROLMENT_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, - EN_OP_MAP_ID INTEGER NOT NULL, - OPERATION_RESPONSE LONGBLOB DEFAULT NULL, - RECEIVED_TIMESTAMP TIMESTAMP NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES - DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_en_op_map_response FOREIGN KEY (EN_OP_MAP_ID) REFERENCES - DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -)ENGINE = InnoDB; - -CREATE INDEX IDX_ENID_OPID ON DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLMENT_ID); -CREATE INDEX IDX_DM_EN_OP_MAP_RES ON DM_DEVICE_OPERATION_RESPONSE(EN_OP_MAP_ID); +CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE +( + ID INT(11) NOT NULL AUTO_INCREMENT, + ENROLMENT_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + EN_OP_MAP_ID INTEGER NOT NULL, + OPERATION_RESPONSE VARCHAR(1024) DEFAULT NULL, + IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE, + RECEIVED_TIMESTAMP TIMESTAMP NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES + DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_en_op_map_response FOREIGN KEY (EN_OP_MAP_ID) REFERENCES + DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE = InnoDB; + +CREATE INDEX IDX_DM_RES_RT ON DM_DEVICE_OPERATION_RESPONSE(RECEIVED_TIMESTAMP); +CREATE INDEX IDX_ENID_OP_ID ON DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLMENT_ID); +CREATE INDEX IDX_DM_EN_OP_MAP_ID ON DM_DEVICE_OPERATION_RESPONSE(EN_OP_MAP_ID); + +CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE_LARGE +( + ID INT(11) NOT NULL, + OPERATION_RESPONSE LONGBLOB DEFAULT NULL, + OPERATION_ID INTEGER NOT NULL, + EN_OP_MAP_ID INTEGER NOT NULL, + RECEIVED_TIMESTAMP TIMESTAMP NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + CONSTRAINT fk_dm_device_operation_response_large FOREIGN KEY (ID) REFERENCES + DM_DEVICE_OPERATION_RESPONSE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_en_op_map_response_large FOREIGN KEY (EN_OP_MAP_ID) REFERENCES + DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE = InnoDB; + +CREATE INDEX IDX_DM_RES_LRG_RT ON DM_DEVICE_OPERATION_RESPONSE_LARGE(RECEIVED_TIMESTAMP); +CREATE INDEX IDX_DM_EN_OP_MAP_ID ON DM_DEVICE_OPERATION_RESPONSE_LARGE(EN_OP_MAP_ID); -- POLICY RELATED TABLES --- @@ -451,6 +478,8 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION )ENGINE = InnoDB; +CREATE INDEX IDX_NOTF_UT ON DM_NOTIFICATION(LAST_UPDATED_TIMESTAMP); + -- END NOTIFICATION TABLES -- CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql index 7631c201d0..c67591ebf2 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -176,6 +176,8 @@ CREATE TABLE DM_OPERATION ( RECEIVED_TIMESTAMP TIMESTAMP(0) NULL, OPERATION_CODE VARCHAR2(1000) NOT NULL, INITIATED_BY VARCHAR2(100) NULL, + ENABLED NUMBER(10) DEFAULT 0 NOT NULL, + OPERATION_DETAILS BLOB DEFAULT NULL, CONSTRAINT PK_DM_OPERATION PRIMARY KEY (ID) ) / @@ -193,47 +195,14 @@ WHEN (NEW.ID IS NULL) END; / -CREATE TABLE DM_CONFIG_OPERATION ( - OPERATION_ID NUMBER(10) NOT NULL, - OPERATION_CONFIG BLOB DEFAULT NULL, - ENABLED NUMBER(10) DEFAULT 0 NOT NULL, - CONSTRAINT PK_DM_CONFIG_OPERATION PRIMARY KEY (OPERATION_ID), - CONSTRAINT FK_DM_OPERATION_CONFIG FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) -) -/ -CREATE TABLE DM_COMMAND_OPERATION ( - OPERATION_ID NUMBER(10) NOT NULL, - ENABLED NUMBER(10) DEFAULT 0 NOT NULL, - CONSTRAINT PK_DM_COMMAND_OPERATION PRIMARY KEY (OPERATION_ID), - CONSTRAINT FK_DM_OPERATION_COMMAND FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) -) -/ -CREATE TABLE DM_POLICY_OPERATION ( - OPERATION_ID NUMBER(10) NOT NULL, - ENABLED NUMBER(10) DEFAULT 0 NOT NULL, - OPERATION_DETAILS BLOB DEFAULT NULL, - CONSTRAINT PK_DM_POLICY_OPERATION PRIMARY KEY (OPERATION_ID), - CONSTRAINT FK_DM_OPERATION_POLICY FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) -) -/ -CREATE TABLE DM_PROFILE_OPERATION ( - OPERATION_ID NUMBER(10) NOT NULL, - ENABLED NUMBER(10) DEFAULT 0 NOT NULL, - OPERATION_DETAILS BLOB DEFAULT NULL, - CONSTRAINT PK_DM_PROFILE_OPERATION PRIMARY KEY (OPERATION_ID), - CONSTRAINT FK_DM_OPERATION_PROFILE FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) -) -/ + CREATE TABLE DM_ENROLMENT ( ID NUMBER(10) NOT NULL, DEVICE_ID NUMBER(10) NOT NULL, OWNER VARCHAR2(255) NOT NULL, OWNERSHIP VARCHAR2(45) DEFAULT NULL, STATUS VARCHAR2(50) NULL, + IS_TRANSFERRED NUMBER(1) DEFAULT 0 NOT NULL, DATE_OF_ENROLMENT TIMESTAMP(0) DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP(0) DEFAULT NULL, TENANT_ID NUMBER(10) NOT NULL, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql index f12d0be98c..eeda27d3c4 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -1,610 +1,677 @@ -CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( - ID BIGSERIAL PRIMARY KEY, - NAME VARCHAR(300) DEFAULT NULL, - DEVICE_TYPE_META VARCHAR(20000) DEFAULT NULL, - LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, - PROVIDER_TENANT_ID INTEGER DEFAULT 0, - SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, - UNIQUE(NAME, PROVIDER_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, - CERTIFICATE BYTEA DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - USERNAME VARCHAR(500) DEFAULT NULL -); - -CREATE TABLE IF NOT EXISTS DM_GROUP ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - GROUP_NAME VARCHAR(100) DEFAULT NULL, - STATUS VARCHAR(50) DEFAULT NULL, - DESCRIPTION TEXT DEFAULT NULL, - OWNER VARCHAR(255) DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0 -); +CREATE SEQUENCE DM_DEVICE_TYPE_seq; -CREATE TABLE IF NOT EXISTS DM_ROLE_GROUP_MAP ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - GROUP_ID INTEGER DEFAULT NULL, - ROLE VARCHAR(45) DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - CONSTRAINT fk_DM_ROLE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) - REFERENCES DM_GROUP (ID) ON DELETE CASCADE ON UPDATE CASCADE +CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( + ID INTEGER DEFAULT NEXTVAL ('DM_DEVICE_TYPE_seq') NOT NULL, + NAME VARCHAR(300) DEFAULT NULL, + DEVICE_TYPE_META VARCHAR(20000) DEFAULT NULL, + LAST_UPDATED_TIMESTAMP TIMESTAMP(0) NOT NULL, + PROVIDER_TENANT_ID INTEGER DEFAULT 0, + SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (ID) ); CREATE INDEX IDX_DEVICE_TYPE ON DM_DEVICE_TYPE (NAME, PROVIDER_TENANT_ID); +CREATE INDEX IDX_DEVICE_NAME ON DM_DEVICE_TYPE (NAME); +CREATE INDEX IDX_DEVICE_TYPE_DEVICE_NAME ON DM_DEVICE_TYPE(ID, NAME); -CREATE TABLE IF NOT EXISTS DM_DEVICE ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DESCRIPTION TEXT DEFAULT NULL, - NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INTEGER DEFAULT NULL, - DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, - LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, - TENANT_ID INTEGER DEFAULT 0, - CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_PROPERTIES ( - DEVICE_TYPE_NAME VARCHAR(300) NOT NULL, - DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL, - PROPERTY_NAME VARCHAR(100) DEFAULT 0, - PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (DEVICE_TYPE_NAME, DEVICE_IDENTIFICATION, PROPERTY_NAME, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS GROUP_PROPERTIES ( - GROUP_ID INTEGER NOT NULL, - PROPERTY_NAME VARCHAR(100) DEFAULT 0, - PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (GROUP_ID, PROPERTY_NAME, TENANT_ID) -); - -CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID); +CREATE SEQUENCE DM_GROUP_seq; -CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_ID INTEGER DEFAULT NULL, - GROUP_ID INTEGER DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) - REFERENCES DM_GROUP (ID) ON DELETE CASCADE ON UPDATE CASCADE -); +CREATE TABLE IF NOT EXISTS DM_GROUP ( + ID INTEGER DEFAULT NEXTVAL ('DM_GROUP_seq') NOT NULL, + GROUP_NAME VARCHAR(100) DEFAULT NULL, + DESCRIPTION TEXT DEFAULT NULL, + OWNER VARCHAR(45) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +) +; -CREATE TABLE IF NOT EXISTS DM_OPERATION ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - TYPE VARCHAR(50) NOT NULL, - CREATED_TIMESTAMP TIMESTAMP NOT NULL, - RECEIVED_TIMESTAMP TIMESTAMP NULL, - OPERATION_CODE VARCHAR(1000) NOT NULL, - INITIATED_BY VARCHAR(50) NULL -); +CREATE SEQUENCE DM_ROLE_GROUP_MAP_seq; -CREATE TABLE IF NOT EXISTS DM_CONFIG_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - OPERATION_CONFIG BYTEA DEFAULT NULL, - ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_config FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +CREATE TABLE IF NOT EXISTS DM_ROLE_GROUP_MAP ( + ID INTEGER DEFAULT NEXTVAL ('DM_ROLE_GROUP_MAP_seq') NOT NULL, + GROUP_ID INTEGER DEFAULT NULL, + ROLE VARCHAR(45) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID), + CONSTRAINT DM_ROLE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) + REFERENCES DM_GROUP (ID) + ON DELETE CASCADE + ON UPDATE CASCADE +) +; + +CREATE SEQUENCE DM_DEVICE_seq; + +CREATE TABLE IF NOT EXISTS DM_DEVICE ( + ID INTEGER DEFAULT NEXTVAL ('DM_DEVICE_seq') NOT NULL, + DESCRIPTION TEXT DEFAULT NULL, + NAME VARCHAR(100) DEFAULT NULL, + DEVICE_TYPE_ID INTEGER DEFAULT NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + LAST_UPDATED_TIMESTAMP TIMESTAMP(0) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID), + CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID) + REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -CREATE TABLE IF NOT EXISTS DM_COMMAND_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_command FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID); +CREATE INDEX IDX_DM_DEVICE_TYPE_ID_DEVICE_IDENTIFICATION ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID,DEVICE_IDENTIFICATION); -CREATE TABLE IF NOT EXISTS DM_POLICY_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS BYTEA DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_policy FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +CREATE TABLE IF NOT EXISTS DM_DEVICE_PROPERTIES ( + DEVICE_TYPE_NAME VARCHAR(300) NOT NULL, + DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL, + PROPERTY_NAME VARCHAR(100) DEFAULT 0, + PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, + TENANT_ID VARCHAR(100), + PRIMARY KEY (DEVICE_TYPE_NAME, DEVICE_IDENTIFICATION, PROPERTY_NAME, TENANT_ID) ); -CREATE TABLE IF NOT EXISTS DM_PROFILE_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS BYTEA DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_profile FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +CREATE SEQUENCE DM_DEVICE_GROUP_MAP_seq; -CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_ID INTEGER NOT NULL, - OWNER VARCHAR(255) NOT NULL, - OWNERSHIP VARCHAR(45) DEFAULT NULL, - STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL, - DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL, - TENANT_ID INTEGER NOT NULL, - CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( + ID INTEGER DEFAULT NEXTVAL ('DM_DEVICE_GROUP_MAP_seq') NOT NULL, + DEVICE_ID INTEGER DEFAULT NULL, + GROUP_ID INTEGER DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID), + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE CASCADE + ON UPDATE CASCADE , + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) + REFERENCES DM_GROUP (ID) + ON DELETE CASCADE + ON UPDATE CASCADE +) +; + +CREATE SEQUENCE DM_OPERATION_seq; + +CREATE TABLE IF NOT EXISTS DM_OPERATION ( + ID INTEGER DEFAULT NEXTVAL ('DM_OPERATION_seq') NOT NULL, + TYPE VARCHAR(20) NOT NULL, + CREATED_TIMESTAMP TIMESTAMP(0) NOT NULL, + RECEIVED_TIMESTAMP TIMESTAMP(0) NULL, + OPERATION_CODE VARCHAR(50) NOT NULL, + INITIATED_BY VARCHAR(100) NULL, + OPERATION_DETAILS BYTEA DEFAULT NULL, + ENABLED BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (ID) +); + +CREATE SEQUENCE DM_ENROLMENT_seq; + +CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( + ID INTEGER DEFAULT NEXTVAL ('DM_ENROLMENT_seq') NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OWNER VARCHAR(50) NOT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, + STATUS VARCHAR(50) NULL, + IS_TRANSFERRED BOOLEAN NOT NULL DEFAULT FALSE, + DATE_OF_ENROLMENT TIMESTAMP(0) NULL DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP(0) NULL DEFAULT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); CREATE INDEX IDX_ENROLMENT_FK_DEVICE_ID ON DM_ENROLMENT(DEVICE_ID); CREATE INDEX IDX_ENROLMENT_DEVICE_ID_TENANT_ID ON DM_ENROLMENT(DEVICE_ID, TENANT_ID); - -CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - ENROLMENT_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, - STATUS VARCHAR(50) NULL, - PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL, - CREATED_TIMESTAMP INTEGER NOT NULL, - UPDATED_TIMESTAMP INTEGER NOT NULL, - CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES - DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_device_operation_mapping_operation FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +CREATE INDEX IDX_ENROLMENT_DEVICE_ID_TENANT_ID_STATUS ON DM_ENROLMENT(DEVICE_ID, TENANT_ID, STATUS); + +CREATE SEQUENCE DM_ENROLMENT_OP_MAPPING_seq; + +CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( + ID INTEGER DEFAULT NEXTVAL ('DM_ENROLMENT_OP_MAPPING_seq') NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + STATUS VARCHAR(50) NULL, + PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL, + CREATED_TIMESTAMP INTEGER NOT NULL, + UPDATED_TIMESTAMP INTEGER NOT NULL, + PRIMARY KEY (ID) + , + CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_device_operation_mapping_operation FOREIGN KEY (OPERATION_ID) REFERENCES + DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +CREATE INDEX fk_dm_device_operation_mapping_operation ON DM_ENROLMENT_OP_MAPPING (OPERATION_ID); +CREATE INDEX IDX_DM_ENROLMENT_OP_MAPPING ON DM_ENROLMENT_OP_MAPPING (ENROLMENT_ID,OPERATION_ID); +CREATE INDEX ID_DM_ENROLMENT_OP_MAPPING_UPDATED_TIMESTAMP ON DM_ENROLMENT_OP_MAPPING (UPDATED_TIMESTAMP); + +ALTER TABLE DM_ENROLMENT_OP_MAPPING + ADD OPERATION_CODE VARCHAR(50) NOT NULL, + ADD INITIATED_BY VARCHAR(100) NULL, + ADD TYPE VARCHAR(20) NOT NULL, + ADD DEVICE_ID INTEGER DEFAULT NULL, + ADD DEVICE_TYPE VARCHAR(300) NOT NULL, + ADD DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + ADD TENANT_ID INTEGER DEFAULT 0; CREATE INDEX IDX_ENROLMENT_OP_MAPPING ON DM_ENROLMENT_OP_MAPPING (UPDATED_TIMESTAMP); CREATE INDEX IDX_EN_OP_MAPPING_EN_ID ON DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID); CREATE INDEX IDX_EN_OP_MAPPING_OP_ID ON DM_ENROLMENT_OP_MAPPING(OPERATION_ID); +CREATE INDEX IDX_EN_OP_MAPPING_EN_ID_STATUS ON DM_ENROLMENT_OP_MAPPING(ENROLMENT_ID, STATUS); + +CREATE SEQUENCE DM_DEVICE_OPERATION_RESPONSE_seq; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE +( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_DEVICE_OPERATION_RESPONSE_seq'), + ENROLMENT_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + EN_OP_MAP_ID INTEGER NOT NULL, + OPERATION_RESPONSE VARCHAR(1024) DEFAULT NULL, + IS_LARGE_RESPONSE BOOLEAN NOT NULL DEFAULT FALSE, + RECEIVED_TIMESTAMP TIMESTAMP(0) NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES + DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_en_op_map_response FOREIGN KEY (EN_OP_MAP_ID) REFERENCES + DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +CREATE INDEX IDX_DM_RES_RT ON DM_DEVICE_OPERATION_RESPONSE(RECEIVED_TIMESTAMP); +CREATE INDEX IDX_ENID_OP_ID ON DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLMENT_ID); +CREATE INDEX IDX_DM_EN_OP_MAP_ID ON DM_DEVICE_OPERATION_RESPONSE(EN_OP_MAP_ID); + +CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE_LARGE +( + ID INTEGER NOT NULL, + OPERATION_RESPONSE BYTEA DEFAULT NULL, + OPERATION_ID INTEGER NOT NULL, + EN_OP_MAP_ID INTEGER NOT NULL, + RECEIVED_TIMESTAMP TIMESTAMP(0) NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, + CONSTRAINT fk_dm_device_operation_response_large FOREIGN KEY (ID) REFERENCES + DM_DEVICE_OPERATION_RESPONSE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_en_op_map_response_large FOREIGN KEY (EN_OP_MAP_ID) REFERENCES + DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +CREATE INDEX IDX_DM_RES_LRG_RT ON DM_DEVICE_OPERATION_RESPONSE_LARGE(RECEIVED_TIMESTAMP); +CREATE INDEX IDX_OP_RES_LARGE_EN_OP_MAP_ID ON DM_DEVICE_OPERATION_RESPONSE_LARGE(EN_OP_MAP_ID); -CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - ENROLMENT_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, - EN_OP_MAP_ID INTEGER NOT NULL, - OPERATION_RESPONSE BYTEA DEFAULT NULL, - RECEIVED_TIMESTAMP TIMESTAMP NULL, - CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES - DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_en_op_map_response FOREIGN KEY (EN_OP_MAP_ID) REFERENCES - DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -CREATE INDEX IDX_ENID_OPID ON DM_DEVICE_OPERATION_RESPONSE(OPERATION_ID, ENROLMENT_ID); -CREATE INDEX IDX_DM_EN_OP_MAP_RES ON DM_DEVICE_OPERATION_RESPONSE(EN_OP_MAP_ID); -- POLICY RELATED TABLES --- -CREATE TABLE IF NOT EXISTS DM_PROFILE ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - PROFILE_NAME VARCHAR(45) NOT NULL , - TENANT_ID INTEGER NOT NULL , - DEVICE_TYPE VARCHAR(300) NOT NULL , - CREATED_TIME TIMESTAMP NOT NULL , - UPDATED_TIME TIMESTAMP NOT NULL +CREATE SEQUENCE DM_PROFILE_seq; + +CREATE TABLE IF NOT EXISTS DM_PROFILE ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_PROFILE_seq') , + PROFILE_NAME VARCHAR(45) NOT NULL , + TENANT_ID INTEGER NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , + CREATED_TIME TIMESTAMP(0) NOT NULL , + UPDATED_TIME TIMESTAMP(0) NOT NULL , + PRIMARY KEY (ID) +); + + +CREATE SEQUENCE DM_POLICY_seq; + +CREATE TABLE IF NOT EXISTS DM_POLICY ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_POLICY_seq') , + NAME VARCHAR(45) DEFAULT NULL , + DESCRIPTION VARCHAR(1000) NULL, + TENANT_ID INTEGER NOT NULL , + PROFILE_ID INTEGER NOT NULL , + OWNERSHIP_TYPE VARCHAR(45) NULL, + COMPLIANCE VARCHAR(100) NULL, + PRIORITY INTEGER NOT NULL, + ACTIVE INTEGER NOT NULL, + UPDATED INTEGER NULL, + PRIMARY KEY (ID) , + CONSTRAINT FK_DM_PROFILE_DM_POLICY + FOREIGN KEY (PROFILE_ID ) + REFERENCES DM_PROFILE (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + +CREATE SEQUENCE DM_DEVICE_POLICY_seq; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_DEVICE_POLICY_seq') , + DEVICE_ID INTEGER NOT NULL , + ENROLMENT_ID INTEGER NOT NULL, + DEVICE BYTEA NOT NULL, + POLICY_ID INTEGER NOT NULL , + PRIMARY KEY (ID) , + CONSTRAINT FK_POLICY_DEVICE_POLICY + FOREIGN KEY (POLICY_ID ) + REFERENCES DM_POLICY (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_DEVICE_DEVICE_POLICY + FOREIGN KEY (DEVICE_ID ) + REFERENCES DM_DEVICE (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + +CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( + ID INTEGER NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , + POLICY_ID INTEGER NOT NULL , + PRIMARY KEY (ID) , + CONSTRAINT FK_DEVICE_TYPE_POLICY + FOREIGN KEY (POLICY_ID ) + REFERENCES DM_POLICY (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + +CREATE SEQUENCE DM_PROFILE_FEATURES_seq; + +CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_PROFILE_FEATURES_seq'), + PROFILE_ID INTEGER NOT NULL, + FEATURE_CODE VARCHAR(100) NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL , + TENANT_ID INTEGER NOT NULL , + CONTENT BYTEA NULL DEFAULT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES + FOREIGN KEY (PROFILE_ID) + REFERENCES DM_PROFILE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + +CREATE SEQUENCE DM_ROLE_POLICY_seq; + +CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_ROLE_POLICY_seq') , + ROLE_NAME VARCHAR(45) NOT NULL , + POLICY_ID INTEGER NOT NULL , + PRIMARY KEY (ID) , + CONSTRAINT FK_ROLE_POLICY_POLICY + FOREIGN KEY (POLICY_ID ) + REFERENCES DM_POLICY (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + +CREATE SEQUENCE DM_USER_POLICY_seq; + +CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_USER_POLICY_seq') , + POLICY_ID INTEGER NOT NULL , + USERNAME VARCHAR(45) NOT NULL , + PRIMARY KEY (ID) , + CONSTRAINT DM_POLICY_USER_POLICY + FOREIGN KEY (POLICY_ID ) + REFERENCES DM_POLICY (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + +CREATE SEQUENCE DM_DEVICE_POLICY_APPLIED_seq; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_DEVICE_POLICY_APPLIED_seq') , + DEVICE_ID INTEGER NOT NULL , + ENROLMENT_ID INTEGER NOT NULL, + POLICY_ID INTEGER NOT NULL , + POLICY_CONTENT BYTEA NULL , + TENANT_ID INTEGER NOT NULL, + APPLIED SMALLINT NULL , + CREATED_TIME TIMESTAMP(0) NULL , + UPDATED_TIME TIMESTAMP(0) NULL , + APPLIED_TIME TIMESTAMP(0) NULL , + PRIMARY KEY (ID) , + CONSTRAINT FK_DM_POLICY_DEVCIE_APPLIED + FOREIGN KEY (DEVICE_ID ) + REFERENCES DM_DEVICE (ID ) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); -CREATE TABLE IF NOT EXISTS DM_POLICY ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - NAME VARCHAR(45) DEFAULT NULL , - DESCRIPTION VARCHAR(1000) NULL, - TENANT_ID INTEGER NOT NULL , - PROFILE_ID INTEGER NOT NULL , - OWNERSHIP_TYPE VARCHAR(45) NULL, - COMPLIANCE VARCHAR(100) NULL, - PRIORITY INTEGER NOT NULL, - ACTIVE INTEGER NOT NULL, - UPDATED INTEGER NULL, - POLICY_TYPE VARCHAR(45) NULL, - CONSTRAINT FK_DM_PROFILE_DM_POLICY - FOREIGN KEY (PROFILE_ID ) - REFERENCES DM_PROFILE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); -CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - ACTION_TYPE VARCHAR(45) NOT NULL, - CORRECTIVE_POLICY_ID INTEGER DEFAULT NULL, - POLICY_ID INTEGER NOT NULL, - CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION - FOREIGN KEY (POLICY_ID) - REFERENCES DM_POLICY (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); +CREATE SEQUENCE DM_CRITERIA_seq; -CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_ID INTEGER NOT NULL , - ENROLMENT_ID INTEGER NOT NULL, - DEVICE BYTEA NOT NULL, - POLICY_ID INTEGER NOT NULL , - CONSTRAINT FK_POLICY_DEVICE_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT FK_DEVICE_DEVICE_POLICY - FOREIGN KEY (DEVICE_ID ) - REFERENCES DM_DEVICE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION +CREATE TABLE IF NOT EXISTS DM_CRITERIA ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_CRITERIA_seq'), + TENANT_ID INTEGER NOT NULL, + NAME VARCHAR(50) NULL, + PRIMARY KEY (ID) ); -CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( - ID INTEGER NOT NULL, - DEVICE_TYPE VARCHAR(300) NOT NULL , - POLICY_ID INTEGER NOT NULL , - PRIMARY KEY (ID) , - CONSTRAINT FK_DEVICE_TYPE_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); -CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - PROFILE_ID INTEGER NOT NULL, - FEATURE_CODE VARCHAR(100) NOT NULL, - DEVICE_TYPE VARCHAR(300) NOT NULL , - TENANT_ID INTEGER NOT NULL , - CONTENT BYTEA NULL DEFAULT NULL, - CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES - FOREIGN KEY (PROFILE_ID) - REFERENCES DM_PROFILE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); +CREATE SEQUENCE DM_POLICY_CRITERIA_seq; -CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - ROLE_NAME VARCHAR(45) NOT NULL , - POLICY_ID INTEGER NOT NULL, - CONSTRAINT FK_ROLE_POLICY_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION +CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_POLICY_CRITERIA_seq'), + CRITERIA_ID INTEGER NOT NULL, + POLICY_ID INTEGER NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_CRITERIA_POLICY_CRITERIA + FOREIGN KEY (CRITERIA_ID) + REFERENCES DM_CRITERIA (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_POLICY_POLICY_CRITERIA + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION ); -CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - POLICY_ID INT NOT NULL , - USERNAME VARCHAR(45) NOT NULL, - CONSTRAINT DM_POLICY_USER_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); -CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_ID INTEGER NOT NULL , - ENROLMENT_ID INTEGER NOT NULL, - POLICY_ID INTEGER NOT NULL , - POLICY_CONTENT BYTEA NULL , - TENANT_ID INTEGER NOT NULL, - APPLIED BOOLEAN NULL , - CREATED_TIME TIMESTAMP NULL , - UPDATED_TIME TIMESTAMP NULL , - APPLIED_TIME TIMESTAMP NULL , - CONSTRAINT FK_DM_POLICY_DEVICE_APPLIED - FOREIGN KEY (DEVICE_ID ) - REFERENCES DM_DEVICE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); +CREATE SEQUENCE DM_POLICY_CRITERIA_PROPERTIES_seq; -CREATE TABLE IF NOT EXISTS DM_CRITERIA ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - TENANT_ID INT NOT NULL, - NAME VARCHAR(50) NULL +CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_POLICY_CRITERIA_PROPERTIES_seq'), + POLICY_CRITERION_ID INTEGER NOT NULL, + PROP_KEY VARCHAR(45) NULL, + PROP_VALUE VARCHAR(100) NULL, + CONTENT BYTEA NULL , + PRIMARY KEY (ID), + CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES + FOREIGN KEY (POLICY_CRITERION_ID) + REFERENCES DM_POLICY_CRITERIA (ID) + ON DELETE CASCADE + ON UPDATE NO ACTION ); -CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - CRITERIA_ID INT NOT NULL, - POLICY_ID INT NOT NULL, - CONSTRAINT FK_CRITERIA_POLICY_CRITERIA - FOREIGN KEY (CRITERIA_ID) - REFERENCES DM_CRITERIA (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT FK_POLICY_POLICY_CRITERIA - FOREIGN KEY (POLICY_ID) - REFERENCES DM_POLICY (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); -CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - POLICY_CRITERION_ID INT NOT NULL, - PROP_KEY VARCHAR(45) NULL, - PROP_VALUE VARCHAR(100) NULL, - CONTENT BYTEA NULL, - CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES - FOREIGN KEY (POLICY_CRITERION_ID) - REFERENCES DM_POLICY_CRITERIA (ID) - ON DELETE CASCADE - ON UPDATE NO ACTION -); -COMMENT ON COLUMN DM_POLICY_CRITERIA_PROPERTIES.CONTENT IS 'This is used to '; - -CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_ID INTEGER NOT NULL, - ENROLMENT_ID INTEGER NOT NULL, - POLICY_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - STATUS INTEGER NULL, - LAST_SUCCESS_TIME TIMESTAMP NULL, - LAST_REQUESTED_TIME TIMESTAMP NULL, - LAST_FAILED_TIME TIMESTAMP NULL, - ATTEMPTS INTEGER NULL -); +CREATE SEQUENCE DM_POLICY_COMPLIANCE_STATUS_seq; -CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - POLICY_ID INTEGER NOT NULL, - DEVICE_TYPE VARCHAR(300) NOT NULL, - TENANT_ID INTEGER NOT NULL +CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_POLICY_COMPLIANCE_STATUS_seq'), + DEVICE_ID INTEGER NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + POLICY_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + STATUS INTEGER NULL, + LAST_SUCCESS_TIME TIMESTAMP(0) NULL, + LAST_REQUESTED_TIME TIMESTAMP(0) NULL, + LAST_FAILED_TIME TIMESTAMP(0) NULL, + ATTEMPTS INTEGER NULL, + PRIMARY KEY (ID) ); -CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - COMPLIANCE_STATUS_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - FEATURE_CODE VARCHAR(100) NOT NULL, - STATUS INTEGER NULL, - CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS - FOREIGN KEY (COMPLIANCE_STATUS_ID) - REFERENCES DM_POLICY_COMPLIANCE_STATUS (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + +CREATE SEQUENCE DM_POLICY_CHANGE_MGT_seq; + +CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_POLICY_CHANGE_MGT_seq'), + POLICY_ID INTEGER NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL , + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ID) ); -CREATE TABLE IF NOT EXISTS DM_APPLICATION ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - NAME VARCHAR(150) NOT NULL, - APP_IDENTIFIER VARCHAR(150) NOT NULL, - PLATFORM VARCHAR(50) DEFAULT NULL, - CATEGORY VARCHAR(50) NULL, - VERSION VARCHAR(50) NULL, - TYPE VARCHAR(50) NULL, - LOCATION_URL VARCHAR(100) DEFAULT NULL, - IMAGE_URL VARCHAR(100) DEFAULT NULL, - APP_PROPERTIES BYTEA NULL, - MEMORY_USAGE INTEGER NULL, - IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, - DEVICE_ID INTEGER NOT NULL, - ENROLMENT_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, + +CREATE SEQUENCE DM_POLICY_COMPLIANCE_FEATURES_seq; + +CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_POLICY_COMPLIANCE_FEATURES_seq'), + COMPLIANCE_STATUS_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + FEATURE_CODE VARCHAR(100) NOT NULL, + STATUS INTEGER NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS + FOREIGN KEY (COMPLIANCE_STATUS_ID) + REFERENCES DM_POLICY_COMPLIANCE_STATUS (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + +CREATE SEQUENCE DM_APPLICATION_seq; + +CREATE TABLE IF NOT EXISTS DM_APPLICATION ( + ID INTEGER DEFAULT NEXTVAL ('DM_APPLICATION_seq') NOT NULL, + NAME VARCHAR(150) NOT NULL, + APP_IDENTIFIER VARCHAR(150) NOT NULL, + PLATFORM VARCHAR(50) DEFAULT NULL, + CATEGORY VARCHAR(50) NULL, + VERSION VARCHAR(50) NULL, + TYPE VARCHAR(50) NULL, + LOCATION_URL VARCHAR(100) DEFAULT NULL, + IMAGE_URL VARCHAR(100) DEFAULT NULL, + APP_PROPERTIES BYTEA NULL, + MEMORY_USAGE INTEGER NULL, + IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, + DEVICE_ID INTEGER NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ID), CONSTRAINT fk_dm_device FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_enrollement FOREIGN KEY (ENROLMENT_ID) REFERENCES - DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT FK_DM_APP_MAP_DM_ENROL FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); --- POLICY RELATED TABLES FINISHED -- +-- END OF POLICY RELATED TABLES -- -- POLICY AND DEVICE GROUP MAPPING -- +CREATE SEQUENCE DM_DEVICE_GROUP_POLICY_seq; + CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_GROUP_ID INTEGER NOT NULL, - POLICY_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - CONSTRAINT FK_DM_DEVICE_GROUP_POLICY - FOREIGN KEY (DEVICE_GROUP_ID) - REFERENCES DM_GROUP (ID) - ON DELETE CASCADE - ON UPDATE CASCADE , - CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY - FOREIGN KEY (POLICY_ID) - REFERENCES DM_POLICY (ID) - ON DELETE CASCADE - ON UPDATE CASCADE + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_DEVICE_GROUP_POLICY_seq'), + DEVICE_GROUP_ID INTEGER NOT NULL, + POLICY_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_DEVICE_GROUP_POLICY + FOREIGN KEY (DEVICE_GROUP_ID) + REFERENCES DM_GROUP (ID) + ON DELETE CASCADE + ON UPDATE CASCADE , + CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE CASCADE + ON UPDATE CASCADE ); -- END OF POLICY AND DEVICE GROUP MAPPING -- --- NOTIFICATION TABLE -- -CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( - NOTIFICATION_ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NULL, - TENANT_ID INTEGER NOT NULL, - STATUS VARCHAR(10) NULL, - DESCRIPTION VARCHAR(1000) NULL, - LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, - CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +-- NOTIFICATION TABLES -- + +CREATE SEQUENCE DM_NOTIFICATION_seq; + +CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( + NOTIFICATION_ID INTEGER DEFAULT NEXTVAL ('DM_NOTIFICATION_seq') NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NULL, + TENANT_ID INTEGER NOT NULL, + STATUS VARCHAR(10) NULL, + DESCRIPTION VARCHAR(1000) NULL, + LAST_UPDATED_TIMESTAMP TIMESTAMP(0) NOT NULL, + PRIMARY KEY (NOTIFICATION_ID), + CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); --- NOTIFICATION TABLE END -- +CREATE INDEX IDX_NOTF_UT ON DM_NOTIFICATION(LAST_UPDATED_TIMESTAMP); --- Device Info and Search Table -- +-- END NOTIFICATION TABLES -- +CREATE SEQUENCE DM_DEVICE_INFO_seq; CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT NOT NULL, - KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(1000) NULL, - CONSTRAINT DM_DEVICE_INFO_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT DM_DEVICE_INFO_DEVICE_ENROLLMENT - FOREIGN KEY (ENROLMENT_ID) - REFERENCES DM_ENROLMENT (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - + ID INTEGER DEFAULT NEXTVAL ('DM_DEVICE_INFO_seq') NOT NULL, + DEVICE_ID INTEGER NULL, + ENROLMENT_ID INTEGER NOT NULL, + KEY_FIELD VARCHAR(45) NULL, + VALUE_FIELD VARCHAR(100) NULL, + PRIMARY KEY (ID) + , + CONSTRAINT DM_DEVICE_INFO_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT DM_DEVICE_INFO_DEVICE_ENROLLMENT + FOREIGN KEY (ENROLMENT_ID) + REFERENCES DM_ENROLMENT (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +) +; + +CREATE INDEX DM_DEVICE_INFO_DEVICE_idx ON DM_DEVICE_INFO (DEVICE_ID ASC); +CREATE INDEX DM_DEVICE_INFO_DEVICE_ENROLLMENT_idx ON DM_DEVICE_INFO (ENROLMENT_ID ASC); + +CREATE SEQUENCE DM_DEVICE_LOCATION_seq; CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT NOT NULL, - LATITUDE DOUBLE PRECISION NULL, - LONGITUDE DOUBLE PRECISION NULL, - STREET1 VARCHAR(255) NULL, - STREET2 VARCHAR(45) NULL, - CITY VARCHAR(45) NULL, - ZIP VARCHAR(10) NULL, - STATE VARCHAR(45) NULL, - COUNTRY VARCHAR(45) NULL, - GEO_HASH VARCHAR(45) NULL, - UPDATE_TIMESTAMP BIGINT NOT NULL, - ALTITUDE DOUBLE PRECISION NULL, - SPEED FLOAT NULL, - BEARING FLOAT NULL, - DISTANCE DOUBLE PRECISION NULL, - CONSTRAINT DM_DEVICE_LOCATION_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT DM_DEVICE_LOCATION_DM_ENROLLMENT - FOREIGN KEY (ENROLMENT_ID) - REFERENCES DM_ENROLMENT (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); -CREATE INDEX DM_DEVICE_LOCATION_GEO_hashx ON DM_DEVICE_LOCATION(GEO_HASH ASC); - - -CREATE TABLE IF NOT EXISTS DM_DEVICE_HISTORY_LAST_SEVEN_DAYS ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_ID INTEGER NOT NULL, - DEVICE_ID_NAME VARCHAR(255) NOT NULL, - TENANT_ID INTEGER NOT NULL, - DEVICE_TYPE_NAME VARCHAR(45) NOT NULL, + ID INTEGER DEFAULT NEXTVAL ('DM_DEVICE_LOCATION_seq') NOT NULL, + DEVICE_ID INT NULL, + ENROLMENT_ID INT NOT NULL, LATITUDE DOUBLE PRECISION NULL, LONGITUDE DOUBLE PRECISION NULL, - SPEED FLOAT NULL, - HEADING FLOAT NULL, - TIMESTAMP BIGINT NOT NULL, + STREET1 VARCHAR(255) NULL, + STREET2 VARCHAR(45) NULL, + CITY VARCHAR(45) NULL, + ZIP VARCHAR(10) NULL, + STATE VARCHAR(45) NULL, + COUNTRY VARCHAR(45) NULL, GEO_HASH VARCHAR(45) NULL, - DEVICE_OWNER VARCHAR(45) NULL, - DEVICE_ALTITUDE DOUBLE PRECISION NULL, - DISTANCE DOUBLE PRECISION NULL, - CONSTRAINT DM_DEVICE_HISTORY_LAST_SEVEN_DAYS - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); -CREATE INDEX DM_DEVICE_HISTORY_LAST_SEVEN_DAYS_GEO_hashx ON DM_DEVICE_HISTORY_LAST_SEVEN_DAYS(GEO_HASH ASC); + UPDATE_TIMESTAMP BIGINT NOT NULL, + PRIMARY KEY (ID) + , + CONSTRAINT DM_DEVICE_LOCATION_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT DM_DEVICE_LOCATION_DM_ENROLLMENT + FOREIGN KEY (ENROLMENT_ID) + REFERENCES DM_ENROLMENT (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +) +; + +CREATE INDEX DM_DEVICE_LOCATION_DEVICE_idx ON DM_DEVICE_LOCATION (DEVICE_ID ASC); +CREATE INDEX DM_DEVICE_LOCATION_GEO_hashx ON DM_DEVICE_LOCATION (GEO_HASH ASC); +CREATE INDEX DM_DEVICE_LOCATION_DM_ENROLLMENT_idx ON DM_DEVICE_LOCATION (ENROLMENT_ID ASC); + +CREATE SEQUENCE DM_DEVICE_DETAIL_seq; CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT NOT NULL, - DEVICE_MODEL VARCHAR(45) NULL, - VENDOR VARCHAR(45) NULL, - OS_VERSION VARCHAR(45) NULL, - OS_BUILD_DATE VARCHAR(100) NULL, - BATTERY_LEVEL DECIMAL(4) NULL, - INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, - INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, - EXTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, - EXTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, - CONNECTION_TYPE VARCHAR(50) NULL, - SSID VARCHAR(45) NULL, - CPU_USAGE DECIMAL(5) NULL, - TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, - AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, - PLUGGED_IN BOOLEAN NOT NULL DEFAULT FALSE, - UPDATE_TIMESTAMP BIGINT NOT NULL, - CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT FK_DM_ENROLMENT_DEVICE_DETAILS - FOREIGN KEY (ENROLMENT_ID) - REFERENCES DM_ENROLMENT (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_PLATFORM ( - ID BIGSERIAL NOT NULL PRIMARY KEY, - DEVICE_TYPE_ID INT DEFAULT 0, - VERSION_NAME VARCHAR(100) NULL, - VERSION_STATUS VARCHAR(100) DEFAULT 'ACTIVE', - CONSTRAINT FK_DM_DEVICE_TYPE_PLATFORM_MAPPING - FOREIGN KEY (DEVICE_TYPE_ID) - REFERENCES DM_DEVICE_TYPE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT device_type_version_uk - UNIQUE (DEVICE_TYPE_ID, VERSION_NAME) -); + ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_DEVICE_DETAIL_seq'), + DEVICE_ID INTEGER NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, + DEVICE_MODEL VARCHAR(45) NULL, + VENDOR VARCHAR(45) NULL, + OS_VERSION VARCHAR(45) NULL, + OS_BUILD_DATE VARCHAR(100) NULL, + BATTERY_LEVEL DECIMAL(4) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, + CONNECTION_TYPE VARCHAR(50) NULL, + SSID VARCHAR(45) NULL, + CPU_USAGE DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, + PLUGGED_IN Boolean NULL, + UPDATE_TIMESTAMP BIGINT NOT NULL, + PRIMARY KEY (ID) + , + CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_DM_ENROLMENT_DEVICE_DETAILS + FOREIGN KEY (ENROLMENT_ID) + REFERENCES DM_ENROLMENT (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +) +; + +CREATE INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx ON DM_DEVICE_DETAIL (DEVICE_ID ASC); +CREATE INDEX FK_DM_ENROLMENT_DEVICE_DETAILS_idx ON DM_DEVICE_DETAIL (ENROLMENT_ID ASC); -- DASHBOARD RELATED VIEWS -- +CREATE VIEW DEVICE_INFO_VIEW AS +SELECT + DM_DEVICE.ID AS DEVICE_ID, + DM_DEVICE.DEVICE_IDENTIFICATION, + DM_DEVICE_TYPE.NAME AS PLATFORM, + DM_ENROLMENT.OWNERSHIP, + DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS, + DM_DEVICE.TENANT_ID +FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT +WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID; + +CREATE VIEW DEVICE_WITH_POLICY_INFO_VIEW AS +SELECT + DEVICE_ID, + POLICY_ID, + STATUS AS IS_COMPLIANT +FROM DM_POLICY_COMPLIANCE_STATUS; + CREATE VIEW POLICY_COMPLIANCE_INFO AS SELECT -DEVICE_INFO.DEVICE_ID, -DEVICE_INFO.DEVICE_IDENTIFICATION, -DEVICE_INFO.PLATFORM, -DEVICE_INFO.OWNERSHIP, -DEVICE_INFO.CONNECTIVITY_STATUS, -COALESCE(DEVICE_WITH_POLICY_INFO.POLICY_ID, -1) AS POLICY_ID, -COALESCE(DEVICE_WITH_POLICY_INFO.IS_COMPLIANT, -1) AS IS_COMPLIANT, -DEVICE_INFO.TENANT_ID + DEVICE_INFO_VIEW.DEVICE_ID, + DEVICE_INFO_VIEW.DEVICE_IDENTIFICATION, + DEVICE_INFO_VIEW.PLATFORM, + DEVICE_INFO_VIEW.OWNERSHIP, + DEVICE_INFO_VIEW.CONNECTIVITY_STATUS, + COALESCE(DEVICE_WITH_POLICY_INFO_VIEW.POLICY_ID, -1) AS POLICY_ID, + COALESCE(DEVICE_WITH_POLICY_INFO_VIEW.IS_COMPLIANT, -1) AS IS_COMPLIANT, + DEVICE_INFO_VIEW.TENANT_ID FROM -(SELECT -DM_DEVICE.ID AS DEVICE_ID, -DM_DEVICE.DEVICE_IDENTIFICATION, -DM_DEVICE_TYPE.NAME AS PLATFORM, -DM_ENROLMENT.OWNERSHIP, -DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS, -DM_DEVICE.TENANT_ID -FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT -WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO -LEFT JOIN -(SELECT -DEVICE_ID, -POLICY_ID, -STATUS AS IS_COMPLIANT -FROM DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO -ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID -ORDER BY DEVICE_INFO.DEVICE_ID; + DEVICE_INFO_VIEW + LEFT JOIN + DEVICE_WITH_POLICY_INFO_VIEW + ON DEVICE_INFO_VIEW.DEVICE_ID = DEVICE_WITH_POLICY_INFO_VIEW.DEVICE_ID +ORDER BY DEVICE_INFO_VIEW.DEVICE_ID; CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS SELECT -DM_DEVICE.ID AS DEVICE_ID, -DM_DEVICE.DEVICE_IDENTIFICATION, -DM_DEVICE_DETAIL.DEVICE_MODEL, -DM_DEVICE_DETAIL.VENDOR, -DM_DEVICE_DETAIL.OS_VERSION, -DM_ENROLMENT.OWNERSHIP, -DM_ENROLMENT.OWNER, -DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS, -DM_POLICY_COMPLIANCE_STATUS.POLICY_ID, -DM_DEVICE_TYPE.NAME AS PLATFORM, -DM_POLICY_COMPLIANCE_FEATURES.FEATURE_CODE, -DM_POLICY_COMPLIANCE_FEATURES.STATUS AS IS_COMPLAINT, -DM_DEVICE.TENANT_ID + DM_DEVICE.ID AS DEVICE_ID, + DM_DEVICE.DEVICE_IDENTIFICATION, + DM_DEVICE_DETAIL.DEVICE_MODEL, + DM_DEVICE_DETAIL.VENDOR, + DM_DEVICE_DETAIL.OS_VERSION, + DM_ENROLMENT.OWNERSHIP, + DM_ENROLMENT.OWNER, + DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS, + DM_POLICY_COMPLIANCE_STATUS.POLICY_ID, + DM_DEVICE_TYPE.NAME AS PLATFORM, + DM_POLICY_COMPLIANCE_FEATURES.FEATURE_CODE, + DM_POLICY_COMPLIANCE_FEATURES.STATUS AS IS_COMPLAINT, + DM_DEVICE.TENANT_ID FROM -DM_POLICY_COMPLIANCE_FEATURES, DM_POLICY_COMPLIANCE_STATUS, DM_ENROLMENT, DM_DEVICE, DM_DEVICE_TYPE, DM_DEVICE_DETAIL + DM_POLICY_COMPLIANCE_FEATURES, DM_POLICY_COMPLIANCE_STATUS, DM_ENROLMENT, DM_DEVICE, DM_DEVICE_TYPE, DM_DEVICE_DETAIL WHERE -DM_POLICY_COMPLIANCE_FEATURES.COMPLIANCE_STATUS_ID = DM_POLICY_COMPLIANCE_STATUS.ID AND -DM_POLICY_COMPLIANCE_STATUS.ENROLMENT_ID = DM_ENROLMENT.ID AND -DM_POLICY_COMPLIANCE_STATUS.DEVICE_ID = DM_DEVICE.ID AND -DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND -DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID + DM_POLICY_COMPLIANCE_FEATURES.COMPLIANCE_STATUS_ID = DM_POLICY_COMPLIANCE_STATUS.ID AND + DM_POLICY_COMPLIANCE_STATUS.ENROLMENT_ID = DM_ENROLMENT.ID AND + DM_POLICY_COMPLIANCE_STATUS.DEVICE_ID = DM_DEVICE.ID AND + DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND + DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID ORDER BY TENANT_ID, DEVICE_ID; -- END OF DASHBOARD RELATED VIEWS -- + +-- TEMP TABLE REQUIRED FOR DATA ARCHIVAL JOB +CREATE TABLE IF NOT EXISTS DM_ARCHIVED_OPERATIONS ( + ID INTEGER NOT NULL, + CREATED_TIMESTAMP TIMESTAMP(0) NOT NULL, + PRIMARY KEY (ID) +); \ No newline at end of file