Fix merge conflicts

apim420
tcdlpds 6 months ago
commit ae8a170421

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

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

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

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

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

@ -301,10 +301,10 @@
</systemPropertyVariables>
<suiteXmlFiles>
<file>src/test/resources/testng.xml</file>
<file>src/test/resources/mysql-testng.xml</file>
<file>src/test/resources/mssql-testng.xml</file>
<file>src/test/resources/oracle-testng.xml</file>
<file>src/test/resources/postgre-testng.xml</file>
<!-- <file>src/test/resources/mysql-testng.xml</file>-->
<!-- <file>src/test/resources/mssql-testng.xml</file>-->
<!-- <file>src/test/resources/oracle-testng.xml</file>-->
<!-- <file>src/test/resources/postgre-testng.xml</file>-->
</suiteXmlFiles>
</configuration>
</plugin>

@ -89,6 +89,7 @@ public final class DeviceManagementConstants {
public static final String POLICY_OPERATION_CODE = PolicyOperation.POLICY_OPERATION_CODE;
public static final String POLICY_REVOKE_OPERATION_CODE = OperationMgtConstants.OperationCodes.POLICY_REVOKE;
public static final String EVENT_CONFIG_OPERATION_CODE = OperationMgtConstants.OperationCodes.EVENT_CONFIG;
public static final String EVENT_UPDATE_OPERATION_CODE = OperationMgtConstants.OperationCodes.EVENT_UPDATE;
public static final String EVENT_REVOKE_OPERATION_CODE = OperationMgtConstants.OperationCodes.EVENT_REVOKE;
}

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

@ -122,6 +122,9 @@ public interface DeviceDAO {
*/
boolean updateDevice(Device device, int tenantId) throws DeviceManagementDAOException;
boolean recordDeviceUpdate(DeviceIdentifier deviceIdentifier, int tenantId)
throws DeviceManagementDAOException;
Device getDevice(DeviceData deviceData, int tenantId) throws DeviceManagementDAOException;
@ -477,6 +480,7 @@ public interface DeviceDAO {
* @return returns list of device types.
* @throws DeviceManagementDAOException
*/
@Deprecated
List<DeviceType> getDeviceTypes() throws DeviceManagementDAOException;
/**

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.device.mgt.core.dao;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo.Status;
@ -25,7 +26,8 @@ import java.util.List;
public interface EnrollmentDAO {
EnrolmentInfo addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException;
EnrolmentInfo addEnrollment(int deviceId, DeviceIdentifier deviceIdentifier,
EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException;
int updateEnrollment(EnrolmentInfo enrolmentInfo, int tenantId) throws DeviceManagementDAOException;

@ -17,6 +17,8 @@
*/
package io.entgra.device.mgt.core.device.mgt.core.dao.impl;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
@ -34,24 +36,29 @@ import java.util.List;
public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
@Override
public EnrolmentInfo addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo,
public EnrolmentInfo addEnrollment(int deviceId, DeviceIdentifier deviceIdentifier, EnrolmentInfo enrolmentInfo,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
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(?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, new String[] {"id"});
String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, DEVICE_TYPE, DEVICE_IDENTIFICATION, OWNER, OWNERSHIP, " +
"STATUS, IS_TRANSFERRED, DATE_OF_ENROLMENT, DATE_OF_LAST_UPDATE, TENANT_ID) " +
"VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
Timestamp enrollmentTime = new Timestamp(new Date().getTime());
stmt = conn.prepareStatement(sql, new String[]{"id"});
stmt.setInt(1, deviceId);
stmt.setString(2, enrolmentInfo.getOwner());
stmt.setString(3, enrolmentInfo.getOwnership().toString());
stmt.setString(4, enrolmentInfo.getStatus().toString());
stmt.setTimestamp(5, enrollmentTime);
stmt.setTimestamp(6, enrollmentTime);
stmt.setInt(7, tenantId);
stmt.setString(2, deviceIdentifier.getType());
stmt.setString(3, deviceIdentifier.getId());
stmt.setString(4, enrolmentInfo.getOwner());
stmt.setString(5, enrolmentInfo.getOwnership().toString());
stmt.setString(6, enrolmentInfo.getStatus().toString());
stmt.setBoolean(7, enrolmentInfo.isTransferred());
stmt.setTimestamp(8, enrollmentTime);
stmt.setTimestamp(9, enrollmentTime);
stmt.setInt(10, tenantId);
stmt.execute();
rs = stmt.getGeneratedKeys();
@ -65,7 +72,6 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
}
return null;
} catch (SQLException e) {
e.printStackTrace();
throw new DeviceManagementDAOException("Error occurred while adding enrolment configuration", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
@ -76,7 +82,6 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
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 = ? " +
@ -87,12 +92,11 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
stmt.setTimestamp(3, new Timestamp(new Date().getTime()));
stmt.setInt(4, enrolmentInfo.getId());
stmt.setInt(5, tenantId);
int updatedCount = stmt.executeUpdate();
return updatedCount;
return stmt.executeUpdate();
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
}
@ -100,7 +104,6 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
public boolean updateEnrollmentStatus(List<EnrolmentInfo> enrolmentInfos) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
boolean status = false;
int updateStatus = -1;
try {
@ -127,7 +130,7 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment status of given device-list.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@ -142,7 +145,7 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
try {
conn = this.getConnection();
String sql = "DELETE FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql, new String[] {"id"});
stmt = conn.prepareStatement(sql, new String[]{"id"});
stmt.setInt(1, deviceId);
stmt.setString(2, currentOwner);
stmt.setInt(3, tenantId);
@ -172,12 +175,12 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
stmt.setString(1, owner);
stmt.setInt(2, tenantID);
rs = stmt.executeQuery();
if(rs.next()){
if (rs.next()) {
count = rs.getInt("COUNT");
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while trying to get device " +
"count of Owner : "+owner, e);
"count of Owner : " + owner, e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
@ -192,11 +195,11 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
@Override
public boolean setStatusAllDevices(String currentOwner, EnrolmentInfo.Status status, int tenantId)
throws DeviceManagementDAOException{
throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
Timestamp updateTime = new Timestamp(new Date().getTime());
if(getCountOfDevicesOfOwner(currentOwner, tenantId) > 0){
if (getCountOfDevicesOfOwner(currentOwner, tenantId) > 0) {
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE OWNER = ? AND TENANT_ID = ?";
@ -231,8 +234,8 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
stmt.setInt(3, enrolmentID);
stmt.setInt(4, tenantId);
int updatedRowCount = stmt.executeUpdate();
if (updatedRowCount != 1){
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment: "+
if (updatedRowCount != 1) {
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment: " +
updatedRowCount + " rows were updated instead of one row!!!");
}
// save the device status history
@ -249,10 +252,11 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
return addDeviceStatus(config.getId(), config.getStatus());
}
public boolean addDeviceStatus(String currentOwner, EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException {
public boolean addDeviceStatus(String currentOwner, EnrolmentInfo.Status status, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
String changedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (changedBy == null){
if (changedBy == null) {
changedBy = DeviceManagementConstants.MaintenanceProperties.MAINTENANCE_USER;
}
PreparedStatement stmt = null;
@ -276,7 +280,7 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
sql = "INSERT INTO DM_DEVICE_STATUS (ENROLMENT_ID, DEVICE_ID, STATUS, UPDATE_TIME, CHANGED_BY) VALUES(?, ?, ?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
if (conn.getMetaData().supportsBatchUpdates()) {
for(int[] info: enrolmentInfoList){
for (int[] info : enrolmentInfoList) {
ps.setInt(1, info[0]);
ps.setInt(2, info[1]);
ps.setString(3, status.toString());
@ -291,7 +295,7 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
}
}
} else {
for(int[] info: enrolmentInfoList){
for (int[] info : enrolmentInfoList) {
ps.setInt(1, info[0]);
ps.setInt(2, info[1]);
ps.setString(3, status.toString());
@ -315,14 +319,15 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
public boolean addDeviceStatus(int enrolmentId, EnrolmentInfo.Status status) throws DeviceManagementDAOException {
Connection conn;
String changedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (changedBy == null){
if (changedBy == null) {
changedBy = DeviceManagementConstants.MaintenanceProperties.MAINTENANCE_USER;
}
PreparedStatement stmt = null;
try {
conn = this.getConnection();
// get the device id and last udpated status from the device status table
String sql = "SELECT DEVICE_ID, STATUS FROM DM_DEVICE_STATUS WHERE ENROLMENT_ID = ? ORDER BY UPDATE_TIME DESC LIMIT 1";
// get the device id and last updated status from the device status table
String sql = "SELECT DEVICE_ID, STATUS FROM DM_DEVICE_STATUS " +
"WHERE ENROLMENT_ID = ? ORDER BY UPDATE_TIME DESC LIMIT 1";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, enrolmentId);
ResultSet rs = stmt.executeQuery();
@ -348,12 +353,14 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
} else {
// if there were no records corresponding to the enrolment id this is a problem. i.e. enrolment
// id is invalid
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment: no record for enrolment id " + enrolmentId);
throw new DeviceManagementDAOException("Error occurred while setting the status of " +
"device enrolment: no record for enrolment id " + enrolmentId);
}
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
sql = "INSERT INTO DM_DEVICE_STATUS (ENROLMENT_ID, DEVICE_ID, STATUS, UPDATE_TIME, CHANGED_BY) VALUES(?, ?, ?, ?, ?)";
sql = "INSERT INTO DM_DEVICE_STATUS (ENROLMENT_ID, DEVICE_ID, STATUS, UPDATE_TIME, CHANGED_BY) " +
"VALUES(?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
Timestamp updateTime = new Timestamp(new Date().getTime());
stmt.setInt(1, enrolmentId);
@ -372,6 +379,7 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
}
return true;
}
@Override
public EnrolmentInfo.Status getStatus(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
@ -529,11 +537,11 @@ public abstract class AbstractEnrollmentDAOImpl implements EnrollmentDAO {
}
}
private Connection getConnection() throws SQLException {
protected Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}
private EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException {
protected EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setOwner(rs.getString("OWNER"));
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP")));

@ -1282,9 +1282,10 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
StringJoiner joiner = new StringJoiner(",","SELECT "
+ "d1.DEVICE_ID, "
+ "d1.DESCRIPTION, "
+ "d1.NAME AS DEVICE_NAME, "
+ "e.DEVICE_NAME, "
+ "d1.DEVICE_TYPE, "
+ "d1.DEVICE_IDENTIFICATION, "
+ "d1.LAST_UPDATED_TIMESTAMP, "
+ "e.OWNER, "
+ "e.OWNERSHIP, "
+ "e.STATUS, "
@ -1294,15 +1295,14 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
+ "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 "
+ "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, gd.LAST_UPDATED_TIMESTAMP "
+ "FROM "
+ "(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID "
+ "(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.LAST_UPDATED_TIMESTAMP "
+ "FROM DM_DEVICE d, "
+ "(SELECT dgm.DEVICE_ID "
+ "FROM DM_DEVICE_GROUP_MAP dgm "
+ "WHERE dgm.GROUP_ID = (SELECT ID FROM DM_GROUP WHERE GROUP_NAME = ? AND TENANT_ID = ?)) dgm1 "
+ "WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t "
+ "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 "
+ "WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd) d1 "
+ "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? AND e.STATUS IN (",
")");
@ -1343,9 +1343,10 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
String sql = "SELECT "
+ "d1.DEVICE_ID, "
+ "d1.DESCRIPTION, "
+ "d1.NAME AS DEVICE_NAME, "
+ "e.DEVICE_NAME, "
+ "d1.DEVICE_TYPE, "
+ "d1.DEVICE_IDENTIFICATION, "
+ "d1.LAST_UPDATED_TIMESTAMP, "
+ "e.OWNER, "
+ "e.OWNERSHIP, "
+ "e.STATUS, "
@ -1355,15 +1356,14 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
+ "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 "
+ "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, gd.LAST_UPDATED_TIMESTAMP "
+ "FROM "
+ "(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID "
+ "(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.LAST_UPDATED_TIMESTAMP "
+ "FROM DM_DEVICE d, "
+ "(SELECT dgm.DEVICE_ID "
+ "FROM DM_DEVICE_GROUP_MAP dgm "
+ "WHERE dgm.GROUP_ID = (SELECT ID FROM DM_GROUP WHERE GROUP_NAME = ? AND TENANT_ID = ?)) dgm1 "
+ "WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t "
+ "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 "
+ "WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd) d1 "
+ "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
@ -1396,9 +1396,10 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
StringJoiner sql = new StringJoiner(",",
"SELECT DEVICE.ID AS DEVICE_ID, " +
"DEVICE.NAME AS DEVICE_NAME, " +
"DEVICE_TYPE.NAME AS DEVICE_TYPE, " +
"ENROLMENT.DEVICE_TYPE, " +
"DEVICE.DESCRIPTION, " +
"DEVICE.DEVICE_IDENTIFICATION, " +
"DEVICE.LAST_UPDATED_TIMESTAMP, " +
"ENROLMENT.ID AS ENROLMENT_ID, " +
"ENROLMENT.OWNER, " +
"ENROLMENT.OWNERSHIP, " +
@ -1406,9 +1407,9 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
"ENROLMENT.DATE_OF_LAST_UPDATE, " +
"ENROLMENT.STATUS, " +
"ENROLMENT.IS_TRANSFERRED " +
"FROM DM_DEVICE AS DEVICE, DM_DEVICE_TYPE AS DEVICE_TYPE, DM_ENROLMENT " +
"FROM DM_DEVICE AS DEVICE, DM_ENROLMENT " +
"AS ENROLMENT " +
"WHERE DEVICE_TYPE.NAME = ? AND DEVICE.ID " +
"WHERE ENROLMENT.DEVICE_TYPE = ? AND DEVICE.ID " +
"NOT IN " +
"(SELECT DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP " +

@ -18,17 +18,25 @@
package io.entgra.device.mgt.core.device.mgt.core.dao.impl.device;
import io.entgra.device.mgt.core.device.mgt.common.*;
import io.entgra.device.mgt.core.device.mgt.common.Count;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory;
import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractDeviceDAOImpl;
import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.*;
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;
@ -63,14 +71,14 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
String serial = request.getSerialNumber();
boolean isSerialProvided = false;
try {
Connection conn = getConnection();
String sql = "SELECT d1.ID AS DEVICE_ID, " +
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"e.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"d1.LAST_UPDATED_TIMESTAMP, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
@ -82,15 +90,13 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"(SELECT d.ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE ";
"d.LAST_UPDATED_TIMESTAMP, " +
"d.DEVICE_IDENTIFICATION ";
//Filter by serial number or any Custom Property in DM_DEVICE_INFO
if ((serial != null) || (request.getCustomProperty() != null && !request.getCustomProperty().isEmpty())) {
sql = sql +
"FROM DM_DEVICE d " +
"INNER JOIN DM_DEVICE_TYPE t ON d.DEVICE_TYPE_ID = t.ID " +
"WHERE ";
"FROM DM_DEVICE d WHERE ";
if (serial != null) {
sql += "EXISTS (" +
"SELECT VALUE_FIELD " +
@ -120,24 +126,24 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
sql += "AND d.TENANT_ID = ? ";
} else {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ";
sql = sql + "FROM DM_DEVICE d WHERE d.TENANT_ID = ? ";
}
//Add query for last updated timestamp
if (since != null) {
sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?";
isSinceProvided = true;
}
//Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?";
isDeviceTypeProvided = true;
}
//Add the query for device-name
if (deviceName != null && !deviceName.isEmpty()) {
sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true;
}
sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?";
//Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND e.DEVICE_TYPE = ?";
isDeviceTypeProvided = true;
}
//Add the query for ownership
if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?";
@ -155,7 +161,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql += buildStatusQuery(statusList);
isStatusProvided = true;
}
sql = sql + " LIMIT ?,?";
sql = sql + " LIMIT ? OFFSET ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
@ -171,13 +177,13 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (isSinceProvided) {
stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime()));
}
if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType);
}
if (isDeviceNameProvided) {
stmt.setString(paramIdx++, "%" + deviceName + "%");
}
stmt.setInt(paramIdx++, tenantId);
if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType);
}
if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership);
}
@ -191,8 +197,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(paramIdx++, status);
}
}
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount());
stmt.setInt(paramIdx++, request.getRowCount());
stmt.setInt(paramIdx, request.getStartIndex());
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>();
@ -222,6 +228,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"DESCRIPTION, " +
"NAME, " +
"DATE_OF_ENROLMENT, " +
"LAST_UPDATED_TIMESTAMP, " +
"STATUS, " +
"DATE_OF_LAST_UPDATE, " +
"TIMESTAMPDIFF(DAY, ?, DATE_OF_ENROLMENT) as DAYS_SINCE_ENROLLED " +
@ -263,6 +270,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"NAME, " +
"DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, " +
"d1.LAST_UPDATED_TIMESTAMP, " +
"STATUS, " +
"TIMESTAMPDIFF(DAY, DATE_OF_LAST_UPDATE, DATE_OF_ENROLMENT) AS DAYS_USED " +
"from DM_DEVICE d, DM_ENROLMENT e " +
@ -306,6 +314,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"DESCRIPTION, " +
"NAME, " +
"DATE_OF_ENROLMENT, " +
"LAST_UPDATED_TIMESTAMP, " +
"STATUS, " +
"DATE_OF_LAST_UPDATE, " +
"TIMESTAMPDIFF(DAY, ?, ?) as DAYS_SINCE_ENROLLED " +
@ -347,6 +356,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"NAME, " +
"DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, " +
"LAST_UPDATED_TIMESTAMP, " +
"STATUS, " +
"TIMESTAMPDIFF(DAY, DATE_OF_LAST_UPDATE, ?) AS DAYS_USED " +
"from DM_DEVICE d, DM_ENROLMENT e " +
@ -391,8 +401,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"DM_DEVICE.ID AS DEVICE_ID, " +
"DEVICE_IDENTIFICATION, " +
"DESCRIPTION, " +
"LAST_UPDATED_TIMESTAMP, " +
"DM_DEVICE.NAME AS DEVICE_NAME, " +
"DM_DEVICE_TYPE.NAME AS DEVICE_TYPE, " +
"DEVICE_TYPE, " +
"DM_ENROLMENT.ID AS ENROLMENT_ID, " +
"DATE_OF_ENROLMENT, " +
"OWNER, " +
@ -404,7 +415,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"FROM " +
"DM_DEVICE " +
"JOIN DM_ENROLMENT ON (DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) " +
"JOIN DM_DEVICE_TYPE ON (DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID) " +
"WHERE " +
"DM_ENROLMENT.TENANT_ID = ? ";
stmt = conn.prepareStatement(sql);
@ -440,6 +450,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
String sql = "SELECT " +
"d1.ID AS DEVICE_ID, " +
"d1.DEVICE_IDENTIFICATION, " +
"d1.LAST_UPDATED_TIMESTAMP, " +
"e.STATUS, " +
"e.OWNER, " +
"e.IS_TRANSFERRED, " +
@ -523,8 +534,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
String sql = "SELECT d1.ID AS DEVICE_ID, " +
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"e.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"d1.LAST_UPDATED_TIMESTAMP, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
@ -537,29 +549,29 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t ";
"d.LAST_UPDATED_TIMESTAMP " +
"FROM DM_DEVICE d ";
//Add the query to filter active devices on timestamp
if (since != null) {
sql = sql + ", DM_DEVICE_DETAIL dt";
isSinceProvided = true;
}
sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
sql = sql + " WHERE d.TENANT_ID = ?";
//Add query for last updated timestamp
if (isSinceProvided) {
sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?";
}
//Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?";
isDeviceTypeProvided = true;
}
//Add the query for device-name
if (deviceName != null && !deviceName.isEmpty()) {
sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true;
}
sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?";
//Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND e.DEVICE_TYPE = ?";
isDeviceTypeProvided = true;
}
//Add the query for ownership
if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?";
@ -581,7 +593,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND MOD(d1.ID, ?) = ?";
isPartitionedTask = true;
}
sql = sql + " LIMIT ?,?";
sql = sql + " LIMIT ? OFFSET ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
@ -589,13 +601,13 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (isSinceProvided) {
stmt.setLong(paramIdx++, since.getTime());
}
if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType);
}
if (isDeviceNameProvided) {
stmt.setString(paramIdx++, deviceName + "%");
}
stmt.setInt(paramIdx++, tenantId);
if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType);
}
if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership);
}
@ -613,8 +625,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setInt(paramIdx++, activeServerCount);
stmt.setInt(paramIdx++, serverIndex);
}
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount());
stmt.setInt(paramIdx++, request.getRowCount());
stmt.setInt(paramIdx, request.getStartIndex());
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>();
@ -660,8 +672,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
String sql = "SELECT d1.DEVICE_ID, " +
"d1.DESCRIPTION, " +
"d1.NAME AS DEVICE_NAME, " +
"d1.DEVICE_TYPE, " +
"e.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, " +
"d1.LAST_UPDATED_TIMESTAMP, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
@ -674,13 +687,12 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"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 " +
"d.LAST_UPDATED_TIMESTAMP " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
@ -692,19 +704,19 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true;
}
sql = sql + ") gd, DM_DEVICE_TYPE t";
sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID";
sql = sql + ") gd";
sql = sql + " WHERE 1 = 1";
//Add query for last updated timestamp
if (since != null) {
sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?";
isSinceProvided = true;
}
sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ";
//Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?";
sql = sql + " AND e.DEVICE_TYPE = ?";
isDeviceTypeProvided = true;
}
sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ";
//Add the query for ownership
if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?";
@ -744,7 +756,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
}
sql = sql + " LIMIT ?,?";
sql = sql + " LIMIT ? OFFSET ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
@ -756,10 +768,10 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (isSinceProvided) {
stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime()));
}
stmt.setInt(paramIdx++, tenantId);
if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType);
}
stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership);
}
@ -781,8 +793,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(paramIdx++, "%" + entry.getValue() + "%");
}
}
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount());
stmt.setInt(paramIdx++, request.getRowCount());
stmt.setInt(paramIdx, request.getStartIndex());
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>();
@ -809,17 +821,17 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
List<Device> devices = new ArrayList<>();
try {
conn = this.getConnection();
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, " +
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.IS_TRANSFERRED, " +
"e1.DATE_OF_LAST_UPDATE, d.LAST_UPDATED_TIMESTAMP, " +
"e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, " +
"e1.DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, e.DEVICE_TYPE, " +
"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 ?,?";
"e.TENANT_ID = ? AND e.OWNER = ?) e1 WHERE d.ID = e1.DEVICE_ID LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, request.getOwner());
stmt.setInt(3, request.getStartIndex());
stmt.setInt(4, request.getRowCount());
stmt.setInt(3, request.getRowCount());
stmt.setInt(4, request.getStartIndex());
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
@ -843,18 +855,19 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
List<Device> devices = new ArrayList<>();
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.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, e.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, d1.LAST_UPDATED_TIMESTAMP, 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 ?,?";
"d.DESCRIPTION, d.LAST_UPDATED_TIMESTAMP, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d " +
"WHERE 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);
stmt.setInt(3, tenantId);
stmt.setInt(4, request.getStartIndex());
stmt.setInt(5, request.getRowCount());
stmt.setInt(4, request.getRowCount());
stmt.setInt(5, request.getStartIndex());
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
@ -878,18 +891,20 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
List<Device> devices = new ArrayList<>();
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.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, " +
String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, e.DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, d.LAST_UPDATED_TIMESTAMP, 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.DEVICE_TYPE, " +
"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 ?,?";
"WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d " +
"WHERE DEVICE_ID = e.DEVICE_ID AND d.TENANT_ID = ? LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, request.getOwnership());
stmt.setInt(3, tenantId);
stmt.setInt(4, request.getStartIndex());
stmt.setInt(5, request.getRowCount());
stmt.setInt(4, request.getRowCount());
stmt.setInt(5, request.getStartIndex());
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
@ -916,8 +931,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
String sql = "SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"e.DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"d.LAST_UPDATED_TIMESTAMP, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
@ -934,6 +950,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"e.IS_TRANSFERRED, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DEVICE_TYPE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
@ -945,12 +962,10 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
sql += buildStatusQuery(statusList);
sql += ") e, " +
"DM_DEVICE d, " +
"DM_DEVICE_TYPE t " +
"DM_DEVICE d " +
"WHERE DEVICE_ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID " +
"AND d.TENANT_ID = ? " +
"LIMIT ?,?";
"LIMIT ? OFFSET ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
@ -959,8 +974,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(paramIdx++, status);
}
stmt.setInt(paramIdx++, tenantId);
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount());
stmt.setInt(paramIdx++, request.getRowCount());
stmt.setInt(paramIdx, request.getStartIndex());
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
@ -990,8 +1005,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
String sql = "SELECT " +
"d.ID AS DEVICE_ID, " +
"d.DESCRIPTION,d.NAME AS DEVICE_NAME, " +
"t.NAME AS DEVICE_TYPE, " +
"d.DEVICE_IDENTIFICATION, " +
"d.LAST_UPDATED_TIMESTAMP, " +
"e.DEVICE_TYPE, " +
"e.DEVICE_IDENTIFICATION, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
@ -999,9 +1015,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"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 " +
"FROM DM_DEVICE AS d, DM_ENROLMENT AS e " +
"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()) {
@ -1011,7 +1026,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (ownership != null) {
sql = sql + " AND e.OWNERSHIP = ?";
}
sql = sql + " LIMIT ?,?";
sql = sql + " LIMIT ? OFFSET ?";
try (Connection conn = this.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
@ -1027,8 +1042,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (ownership != null) {
stmt.setString(paramIdx++, ownership);
}
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount());
stmt.setInt(paramIdx++, request.getRowCount());
stmt.setInt(paramIdx, request.getStartIndex());
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>();
@ -1055,11 +1070,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
String sql = "SELECT " +
"COUNT(d.ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE AS d , " +
"DM_ENROLMENT AS e , " +
"DM_DEVICE_TYPE AS t " +
"FROM DM_DEVICE AS d, " +
"DM_ENROLMENT AS e " +
"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()) {
@ -1113,7 +1126,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"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 ? ";
@ -1128,7 +1140,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND e.OWNERSHIP = ?";
}
sql = sql + " GROUP BY SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) LIMIT ? OFFSET ?";
sql = sql + " GROUP BY SUBSTRING(e.DATE_OF_ENROLMENT, 1, 10) LIMIT ?, ?";
try {
Connection conn = this.getConnection();
@ -1179,27 +1191,27 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
public List<Device> getDevicesByNameAndType(String deviceName, String type, int tenantId, int offset, int limit)
throws DeviceManagementDAOException {
String filteringString = "";
if (deviceName != null && !deviceName.isEmpty()) {
filteringString = filteringString + " AND d.NAME LIKE ?";
}
if (type != null && !type.isEmpty()) {
filteringString = filteringString + " AND t.NAME = ?";
}
Connection conn;
PreparedStatement stmt = null;
List<Device> devices = new ArrayList<>();
ResultSet rs = null;
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.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, e.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, d1.LAST_UPDATED_TIMESTAMP, 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 LIMIT ?, ?";
"d.DESCRIPTION, d.DEVICE_IDENTIFICATION, d.LAST_UPDATED_TIMESTAMP FROM DM_DEVICE d " +
"WHERE d.TENANT_ID = ?";
if (deviceName != null && !deviceName.isEmpty()) {
sql += " AND d.NAME LIKE ? ";
}
sql += ") d1 WHERE d1.ID = e.DEVICE_ID";
if (type != null && !type.isEmpty()) {
sql += " AND e.DEVICE_TYPE = ?";
}
sql+=" LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
@ -1214,8 +1226,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(++i, type);
}
stmt.setInt(++i, offset);
stmt.setInt(++i, limit);
stmt.setInt(++i, offset);
rs = stmt.executeQuery();
@ -1264,7 +1276,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
+ "DM_DEVICE.ID AS DEVICE_ID, "
+ "DM_DEVICE.NAME AS DEVICE_NAME, "
+ "DM_DEVICE.DESCRIPTION AS DESCRIPTION, "
+ "DM_DEVICE.DEVICE_TYPE_ID, "
+ "DM_DEVICE.LAST_UPDATED_TIMESTAMP, "
+ "DM_DEVICE.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION, "
+ "e.ID AS ENROLMENT_ID, "
+ "e.OWNER, "
@ -1272,14 +1284,12 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
+ "e.DATE_OF_ENROLMENT, "
+ "e.DATE_OF_LAST_UPDATE, "
+ "e.STATUS, "
+ "e.IS_TRANSFERRED, "
+ "device_types.NAME AS DEVICE_TYPE "
+ "e.DEVICE_TYPE, "
+ "e.IS_TRANSFERRED "
+ "FROM DM_DEVICE "
+ "INNER JOIN DM_ENROLMENT e ON "
+ "DM_DEVICE.ID = e.DEVICE_ID AND "
+ "DM_DEVICE.TENANT_ID = e.TENANT_ID "
+ "INNER JOIN (SELECT ID, NAME FROM DM_DEVICE_TYPE) AS device_types ON "
+ "device_types.ID = DM_DEVICE.DEVICE_TYPE_ID ";
+ "DM_DEVICE.TENANT_ID = e.TENANT_ID ";
if (null != serial && !serial.isEmpty()) { // Only if serial is provided, join with device info table
query = query.concat("INNER JOIN DM_DEVICE_INFO i ON "
@ -1289,7 +1299,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
query = query.concat("WHERE DM_DEVICE.ID IN (");
StringJoiner joiner = new StringJoiner(",", query ,
") AND DM_DEVICE.TENANT_ID = ? AND e.STATUS != ?");
") AND DM_DEVICE.TENANT_ID = ? AND e.STATUS != ? AND e.STATUS != ?");
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
query = joiner.toString();
@ -1324,7 +1334,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
query = query + " LIMIT ?,?";
query = query + " LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
@ -1333,6 +1343,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
ps.setInt(index++, tenantId);
ps.setString(index++, EnrolmentInfo.Status.REMOVED.toString());
ps.setString(index++, EnrolmentInfo.Status.DELETED.toString());
if (isDeviceNameProvided) {
ps.setString(index++, name + "%");
}
@ -1356,8 +1367,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
ps.setString(index++, "%" + entry.getValue() + "%");
}
}
ps.setInt(index++, offsetValue);
ps.setInt(index, limitValue);
ps.setInt(index++, limitValue);
ps.setInt(index, offsetValue);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
@ -1435,11 +1446,12 @@ 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 " +
"d1.DEVICE_TYPE, " +
"e.DEVICE_TYPE, " +
"d1.DEVICE_ID, " +
"d1.DEVICE_NAME, " +
"d1.DESCRIPTION, " +
"d1.DEVICE_IDENTIFICATION, " +
"d1.LAST_UPDATED_TIMESTAMP, " +
"ddd.OS_VERSION, " +
"e.ID AS ENROLMENT_ID, " +
"e.OWNER, " +
@ -1449,20 +1461,10 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"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 " +
"DM_DEVICE_DETAIL ddd, DM_ENROLMENT e, DM_DEVICE d1 " +
"WHERE e.DEVICE_TYPE = ? " +
"AND e.TENANT_ID = ? " +
"AND d1.DEVICE_ID = e.DEVICE_ID " +
"AND d1.DEVICE_ID = ddi.DEVICE_ID " +
"AND d1.DEVICE_ID = ddd.DEVICE_ID " +
"AND ddi.KEY_FIELD = ? ";
@ -1478,8 +1480,8 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
ps.setInt(2, tenantId);
ps.setString(3, Constants.OS_VALUE);
ps.setLong(4, osValue);
ps.setInt(5, request.getRowCount());
ps.setInt(6, request.getStartIndex());
ps.setInt(5, request.getStartIndex());
ps.setInt(6, request.getRowCount());
try (ResultSet rs = ps.executeQuery()) {
List<Device> devices = new ArrayList<>();
@ -1548,7 +1550,143 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
@Override
public List<Device> getGroupedDevicesDetails(PaginationRequest request, List<Integer> deviceIds, String groupName,
int tenantId) throws DeviceManagementDAOException {
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
List<String> status = request.getStatusList();
String name = request.getDeviceName();
String user = request.getOwner();
String ownership = request.getOwnership();
try {
List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) {
return devices;
}
Connection conn = this.getConnection();
int index = 1;
StringJoiner joiner = new StringJoiner(",",
"SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, "
+ "DM_DEVICE.NAME AS DEVICE_NAME, "
+ "DM_DEVICE.DESCRIPTION AS DESCRIPTION, "
+ "DM_DEVICE.LAST_UPDATED_TIMESTAMP, "
+ "e.DEVICE_TYPE, "
+ "e.DEVICE_IDENTIFICATION AS DEVICE_IDENTIFICATION, "
+ "e.ID AS ENROLMENT_ID, "
+ "e.OWNER, "
+ "e.OWNERSHIP, "
+ "e.DATE_OF_ENROLMENT, "
+ "e.DATE_OF_LAST_UPDATE, "
+ "e.STATUS, "
+ "e.IS_TRANSFERRED "
+ "FROM DM_DEVICE_GROUP_MAP "
+ "INNER JOIN DM_DEVICE ON "
+ "DM_DEVICE_GROUP_MAP.DEVICE_ID = DM_DEVICE.ID "
+ "INNER JOIN DM_GROUP ON "
+ "DM_DEVICE_GROUP_MAP.GROUP_ID = DM_GROUP.ID "
+ "INNER JOIN DM_ENROLMENT e ON "
+ "DM_DEVICE.ID = e.DEVICE_ID AND "
+ "DM_DEVICE.TENANT_ID = e.TENANT_ID "
+ "WHERE DM_DEVICE.ID IN (",
") AND DM_DEVICE.TENANT_ID = ?");
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
if (StringUtils.isNotBlank(groupName)) {
query += " AND DM_GROUP.GROUP_NAME = ?";
}
if (StringUtils.isNotBlank(name)) {
query += " AND DM_DEVICE.NAME LIKE ?";
}
if (StringUtils.isNotBlank(user)) {
query += " AND e.OWNER = ?";
}
if (StringUtils.isNotBlank(ownership)) {
query += " AND e.OWNERSHIP = ?";
}
if (status != null && !status.isEmpty()) {
query += buildStatusQuery(status);
}
query += "LIMIT ? OFFSET ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
for (Integer deviceId : deviceIds) {
ps.setInt(index++, deviceId);
}
ps.setInt(index++, tenantId);
if (StringUtils.isNotBlank(groupName)) {
ps.setString(index++, groupName);
}
if (StringUtils.isNotBlank(name)) {
ps.setString(index++, name);
}
if (StringUtils.isNotBlank(user)) {
ps.setString(index++, user);
}
if (StringUtils.isNotBlank(ownership)) {
ps.setString(index++, ownership);
}
if (status != null && !status.isEmpty()) {
for (String deviceStatus : status) {
ps.setString(index++, deviceStatus);
}
}
ps.setInt(index++, limitValue);
ps.setInt(index, offsetValue);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
devices.add(DeviceManagementDAOUtil.loadDevice(rs));
}
return devices;
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all registered devices " +
"according to device ids and the limit area.";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
/***
* This method updates the status of a given list of devices to DELETED state in the DM_DEVICE_STATUS table
* @param conn Connection object
* @param validDevices list of devices
* @throws DeviceManagementDAOException if updating fails
*/
public void refactorDeviceStatus(Connection conn, List<Device> validDevices) throws DeviceManagementDAOException {
String updateQuery = "UPDATE DM_DEVICE_STATUS SET STATUS = ? WHERE ID = ?";
String selectLastMatchingRecordQuery = "SELECT ID FROM DM_DEVICE_STATUS WHERE ENROLMENT_ID = ? " +
"AND DEVICE_ID = ? ORDER BY ID DESC LIMIT 1";
try (PreparedStatement selectStatement = conn.prepareStatement(selectLastMatchingRecordQuery);
PreparedStatement updateStatement = conn.prepareStatement(updateQuery)) {
for (Device device : validDevices) {
selectStatement.setInt(1, device.getEnrolmentInfo().getId());
selectStatement.setInt(2, device.getId());
ResultSet resultSet = selectStatement.executeQuery();
int lastRecordId = 0;
if (resultSet.next()) {
lastRecordId = resultSet.getInt("ID");
}
updateStatement.setString(1, String.valueOf(EnrolmentInfo.Status.DELETED));
updateStatement.setInt(2, lastRecordId);
updateStatement.execute();
}
} catch (SQLException e) {
String msg = "SQL error occurred while updating device status properties.";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
}

@ -21,10 +21,9 @@ package io.entgra.device.mgt.core.device.mgt.core.dao.impl.device;
import io.entgra.device.mgt.core.device.mgt.common.Count;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory;
import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractDeviceDAOImpl;
import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants;
import org.apache.commons.logging.Log;
@ -40,7 +39,7 @@ import java.util.Map;
/**
* This class holds the generic implementation of DeviceDAO which can be used to support ANSI db syntax.
*/
public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
public class PostgreSQLDeviceDAOImpl extends GenericDeviceDAOImpl {
private static final Log log = LogFactory.getLog(PostgreSQLDeviceDAOImpl.class);
@ -1051,7 +1050,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
+ "INNER JOIN (SELECT ID, NAME FROM DM_DEVICE_TYPE) AS device_types ON "
+ "device_types.ID = DM_DEVICE.DEVICE_TYPE_ID "
+ "WHERE DM_DEVICE.ID IN (",
") AND DM_DEVICE.TENANT_ID = ?");
") AND DM_DEVICE.TENANT_ID = ? AND e.STATUS NOT IN (?, ?)");
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
@ -1093,6 +1092,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
ps.setInt(index++, tenantId);
ps.setString(index++, EnrolmentInfo.Status.REMOVED.toString());
ps.setString(index++, EnrolmentInfo.Status.DELETED.toString());
if (isDeviceNameProvided) {
ps.setString(index++, name + "%");
}
@ -1291,7 +1292,4 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}
}

@ -24,8 +24,6 @@ import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.device.details.DeviceInfo;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory;
import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractDeviceDAOImpl;
import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import io.entgra.device.mgt.core.device.mgt.core.report.mgt.Constants;
import org.apache.commons.lang.StringUtils;
@ -46,7 +44,7 @@ import java.util.Map;
/**
* This class holds the generic implementation of DeviceDAO which can be used to support ANSI db syntax.
*/
public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
public class SQLServerDeviceDAOImpl extends GenericDeviceDAOImpl {
private static final Log log = LogFactory.getLog(SQLServerDeviceDAOImpl.class);
@ -924,7 +922,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
+ "INNER JOIN (SELECT ID, NAME FROM DM_DEVICE_TYPE) AS device_types ON "
+ "device_types.ID = DM_DEVICE.DEVICE_TYPE_ID "
+ "WHERE DM_DEVICE.ID IN (",
") AND DM_DEVICE.TENANT_ID = ?");
") AND DM_DEVICE.TENANT_ID = ? AND e.STATUS != ? AND e.STATUS != ?");
deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString();
@ -966,6 +964,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
ps.setInt(index++, tenantId);
ps.setString(index++, EnrolmentInfo.Status.REMOVED.toString());
ps.setString(index++, EnrolmentInfo.Status.DELETED.toString());
if (isDeviceNameProvided) {
ps.setString(index++, name + "%");
}
@ -1113,10 +1113,6 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}
@Override
public List<Device> getDevicesByDuration(PaginationRequest request, int tenantId,
String fromDate, String toDate)

@ -17,532 +17,8 @@
*/
package io.entgra.device.mgt.core.device.mgt.core.dao.impl.enrolment;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory;
import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractEnrollmentDAOImpl;
import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class GenericEnrollmentDAOImpl extends AbstractEnrollmentDAOImpl {
@Override
public EnrolmentInfo addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
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(?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, new String[] {"id"});
Timestamp enrollmentTime = new Timestamp(new Date().getTime());
stmt.setInt(1, deviceId);
stmt.setString(2, enrolmentInfo.getOwner());
stmt.setString(3, enrolmentInfo.getOwnership().toString());
stmt.setString(4, enrolmentInfo.getStatus().toString());
stmt.setTimestamp(5, enrollmentTime);
stmt.setTimestamp(6, enrollmentTime);
stmt.setInt(7, tenantId);
stmt.execute();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
int enrolmentId = rs.getInt(1);
enrolmentInfo.setId(enrolmentId);
enrolmentInfo.setDateOfEnrolment(enrollmentTime.getTime());
enrolmentInfo.setDateOfLastUpdate(enrollmentTime.getTime());
addDeviceStatus(enrolmentId, enrolmentInfo.getStatus());
return enrolmentInfo;
}
return null;
} catch (SQLException e) {
e.printStackTrace();
throw new DeviceManagementDAOException("Error occurred while adding enrolment configuration", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
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 = ? 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());
stmt.setInt(5, tenantId);
int updatedCount = stmt.executeUpdate();
return updatedCount;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public boolean updateEnrollmentStatus(List<EnrolmentInfo> enrolmentInfos) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
boolean status = false;
int updateStatus = -1;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE ID = ?";
stmt = conn.prepareStatement(sql);
if (conn.getMetaData().supportsBatchUpdates()) {
for (EnrolmentInfo enrolmentInfo : enrolmentInfos) {
stmt.setString(1, enrolmentInfo.getStatus().toString());
stmt.setInt(2, enrolmentInfo.getId());
stmt.addBatch();
}
updateStatus = stmt.executeBatch().length;
} else {
for (EnrolmentInfo enrolmentInfo : enrolmentInfos) {
stmt.setString(1, enrolmentInfo.getStatus().toString());
stmt.setInt(2, enrolmentInfo.getId());
updateStatus = stmt.executeUpdate();
}
}
if (updateStatus > 0) {
status = true;
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment status of given device-list.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return status;
}
@Override
public int removeEnrollment(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int status = -1;
try {
conn = this.getConnection();
String sql = "DELETE FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql, new String[] {"id"});
stmt.setInt(1, deviceId);
stmt.setString(2, currentOwner);
stmt.setInt(3, tenantId);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
status = 1;
}
return status;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while removing device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
private int getCountOfDevicesOfOwner(String owner, int tenantID) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int count = 0;
try {
conn = this.getConnection();
String checkQuery = "SELECT COUNT(ID) AS COUNT FROM DM_ENROLMENT WHERE OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(checkQuery);
stmt.setString(1, owner);
stmt.setInt(2, tenantID);
rs = stmt.executeQuery();
if(rs.next()){
count = rs.getInt("COUNT");
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while trying to get device " +
"count of Owner : "+owner, e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return count;
}
@Override
public boolean setStatus(String currentOwner, EnrolmentInfo.Status status,
int tenantId) throws DeviceManagementDAOException {
return setStatusAllDevices(currentOwner, status, tenantId);
}
@Override
public boolean setStatusAllDevices(String currentOwner, EnrolmentInfo.Status status, int tenantId)
throws DeviceManagementDAOException{
Connection conn;
PreparedStatement stmt = null;
Timestamp updateTime = new Timestamp(new Date().getTime());
if(getCountOfDevicesOfOwner(currentOwner, tenantId) > 0){
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, status.toString());
stmt.setTimestamp(2, updateTime);
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 addDeviceStatus(currentOwner, status, tenantId);
} else {
return false;
}
}
@Override
public boolean setStatus(int enrolmentID, EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
Timestamp updateTime = new Timestamp(new Date().getTime());
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, status.toString());
stmt.setTimestamp(2, updateTime);
stmt.setInt(3, enrolmentID);
stmt.setInt(4, tenantId);
int updatedRowCount = stmt.executeUpdate();
if (updatedRowCount != 1){
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment: "+
updatedRowCount + " rows were updated instead of one row!!!");
}
// save the device status history
addDeviceStatus(enrolmentID, status);
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return true;
}
public boolean addDeviceStatus(EnrolmentInfo config) throws DeviceManagementDAOException {
return addDeviceStatus(config.getId(), config.getStatus());
}
public boolean addDeviceStatus(String currentOwner, EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException {
Connection conn;
String changedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (changedBy == null){
changedBy = DeviceManagementConstants.MaintenanceProperties.MAINTENANCE_USER;
}
PreparedStatement stmt = null;
ResultSet rs = null;
List<int[]> enrolmentInfoList = new ArrayList<>();
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 OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, currentOwner);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
while (rs.next()) {
int enrolmentId = rs.getInt("ID");
int deviceId = rs.getInt("DEVICE_ID");
enrolmentInfoList.add(new int[]{enrolmentId, deviceId});
}
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
Timestamp updateTime = new Timestamp(new Date().getTime());
sql = "INSERT INTO DM_DEVICE_STATUS (ENROLMENT_ID, DEVICE_ID, STATUS, UPDATE_TIME, CHANGED_BY) VALUES(?, ?, ?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
if (conn.getMetaData().supportsBatchUpdates()) {
for(int[] info: enrolmentInfoList){
ps.setInt(1, info[0]);
ps.setInt(2, info[1]);
ps.setString(3, status.toString());
ps.setTimestamp(4, updateTime);
ps.setString(5, changedBy);
ps.addBatch();
}
int[] batchResult = ps.executeBatch();
for (int i : batchResult) {
if (i == 0 || i == Statement.SUCCESS_NO_INFO || i == Statement.EXECUTE_FAILED) {
return false;
}
}
} else {
for(int[] info: enrolmentInfoList){
ps.setInt(1, info[0]);
ps.setInt(2, info[1]);
ps.setString(3, status.toString());
ps.setTimestamp(4, updateTime);
ps.setString(5, changedBy);
ps.execute();
}
}
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the enrolments " +
"information of owner '" + currentOwner + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return true;
}
public boolean addDeviceStatus(int enrolmentId, EnrolmentInfo.Status status) throws DeviceManagementDAOException {
Connection conn;
String changedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (changedBy == null){
changedBy = DeviceManagementConstants.MaintenanceProperties.MAINTENANCE_USER;
}
PreparedStatement stmt = null;
try {
conn = this.getConnection();
// get the device id and last udpated status from the device status table
String sql = "SELECT DEVICE_ID, STATUS FROM DM_DEVICE_STATUS WHERE ENROLMENT_ID = ? ORDER BY UPDATE_TIME DESC LIMIT 1";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, enrolmentId);
ResultSet rs = stmt.executeQuery();
int deviceId = -1;
EnrolmentInfo.Status previousStatus = null;
if (rs.next()) {
// if there is a record corresponding to the enrolment we save the status and the device id
previousStatus = EnrolmentInfo.Status.valueOf(rs.getString("STATUS"));
deviceId = rs.getInt("DEVICE_ID");
}
DeviceManagementDAOUtil.cleanupResources(stmt, null);
// if there was no record for the enrolment or the previous status is not the same as the current status
// we'll add a record
if (previousStatus == null || previousStatus != status){
if (deviceId == -1) {
// we need the device id in order to add a new record, therefore we get it from the enrolment table
sql = "SELECT DEVICE_ID FROM DM_ENROLMENT WHERE ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, enrolmentId);
rs = stmt.executeQuery();
if (rs.next()) {
deviceId = rs.getInt("DEVICE_ID");
} else {
// if there were no records corresponding to the enrolment id this is a problem. i.e. enrolment
// id is invalid
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment: no record for enrolment id " + enrolmentId);
}
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
sql = "INSERT INTO DM_DEVICE_STATUS (ENROLMENT_ID, DEVICE_ID, STATUS, UPDATE_TIME, CHANGED_BY) VALUES(?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
Timestamp updateTime = new Timestamp(new Date().getTime());
stmt.setInt(1, enrolmentId);
stmt.setInt(2, deviceId);
stmt.setString(3, status.toString());
stmt.setTimestamp(4, updateTime);
stmt.setString(5, changedBy);
stmt.execute();
} else {
// no need to update status since the last recorded status is the same as the current status
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while setting the status of device", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return true;
}
@Override
public EnrolmentInfo.Status getStatus(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
EnrolmentInfo.Status status = null;
try {
conn = this.getConnection();
String sql = "SELECT STATUS FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setString(2, currentOwner);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
status = EnrolmentInfo.Status.valueOf(rs.getString("STATUS"));
}
return status;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public EnrolmentInfo getEnrollment(int deviceId, String currentOwner,
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 OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setString(2, currentOwner);
stmt.setInt(3, 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 user '" + currentOwner + "' upon device '" + deviceId + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@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<EnrolmentInfo> getEnrollmentsOfUser(int deviceId, String user, int tenantId)
throws DeviceManagementDAOException {
List<EnrolmentInfo> enrolmentInfos = new ArrayList<>();
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 OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setString(2, user);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
while (rs.next()) {
enrolmentInfo = this.loadEnrolment(rs);
enrolmentInfos.add(enrolmentInfo);
}
return enrolmentInfos;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the enrolments " +
"information of user '" + user + "' upon device '" + deviceId + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public boolean updateOwnerOfEnrollment(List<Device> devices, String owner, int tenantId)
throws DeviceManagementDAOException {
try {
Connection conn = this.getConnection();
boolean updateStatus = true;
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.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();
}
int[] batchResult = ps.executeBatch();
for (int i : batchResult) {
if (i == 0 || i == Statement.SUCCESS_NO_INFO || i == Statement.EXECUTE_FAILED) {
updateStatus = false;
break;
}
}
} else {
for (Device device : devices) {
ps.setString(1, owner);
ps.setBoolean(2, device.getEnrolmentInfo().isTransferred());
ps.setInt(3, device.getId());
ps.setInt(4, tenantId);
if (ps.executeUpdate() == 0) {
updateStatus = false;
break;
}
}
}
}
return updateStatus;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while obtaining the DB connection to update the "
+ "owner of the device enrollment.", e);
}
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}
private EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException {
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")));
enrolmentInfo.setId(rs.getInt("ID"));
return enrolmentInfo;
}
}

@ -17,301 +17,22 @@
*/
package io.entgra.device.mgt.core.device.mgt.core.dao.impl.enrolment;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory;
import io.entgra.device.mgt.core.device.mgt.core.dao.impl.AbstractEnrollmentDAOImpl;
import io.entgra.device.mgt.core.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import java.sql.*;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
public class SQLServerEnrollmentDAOImpl extends AbstractEnrollmentDAOImpl {
@Override
public EnrolmentInfo addEnrollment(int deviceId, EnrolmentInfo enrolmentInfo,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
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(?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, new String[] {"id"});
Timestamp enrollmentTime = new Timestamp(new Date().getTime());
stmt.setInt(1, deviceId);
stmt.setString(2, enrolmentInfo.getOwner());
stmt.setString(3, enrolmentInfo.getOwnership().toString());
stmt.setString(4, enrolmentInfo.getStatus().toString());
stmt.setTimestamp(5, enrollmentTime);
stmt.setTimestamp(6, enrollmentTime);
stmt.setInt(7, tenantId);
stmt.execute();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
int enrolmentId = rs.getInt(1);
enrolmentInfo.setId(enrolmentId);
enrolmentInfo.setDateOfEnrolment(enrollmentTime.getTime());
enrolmentInfo.setDateOfLastUpdate(enrollmentTime.getTime());
addDeviceStatus(enrolmentId, enrolmentInfo.getStatus());
return enrolmentInfo;
}
return null;
} catch (SQLException e) {
e.printStackTrace();
throw new DeviceManagementDAOException("Error occurred while adding enrolment configuration", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
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 = ? 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());
stmt.setInt(5, tenantId);
int updatedCount = stmt.executeUpdate();
return updatedCount;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment configuration", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public boolean updateEnrollmentStatus(List<EnrolmentInfo> enrolmentInfos) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
boolean status = false;
int updateStatus = -1;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET STATUS = ? WHERE ID = ?";
stmt = conn.prepareStatement(sql);
if (conn.getMetaData().supportsBatchUpdates()) {
for (EnrolmentInfo enrolmentInfo : enrolmentInfos) {
stmt.setString(1, enrolmentInfo.getStatus().toString());
stmt.setInt(2, enrolmentInfo.getId());
stmt.addBatch();
}
updateStatus = stmt.executeBatch().length;
} else {
for (EnrolmentInfo enrolmentInfo : enrolmentInfos) {
stmt.setString(1, enrolmentInfo.getStatus().toString());
stmt.setInt(2, enrolmentInfo.getId());
updateStatus = stmt.executeUpdate();
}
}
if (updateStatus > 0) {
status = true;
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment status of given device-list.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return status;
}
@Override
public int removeEnrollment(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int status = -1;
try {
conn = this.getConnection();
String sql = "DELETE FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql, new String[] {"id"});
stmt.setInt(1, deviceId);
stmt.setString(2, currentOwner);
stmt.setInt(3, tenantId);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
status = 1;
}
return status;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while removing device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
private int getCountOfDevicesOfOwner(String owner, int tenantID) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
int count = 0;
try {
conn = this.getConnection();
String checkQuery = "SELECT COUNT(ID) AS COUNT FROM DM_ENROLMENT WHERE OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(checkQuery);
stmt.setString(1, owner);
stmt.setInt(2, tenantID);
rs = stmt.executeQuery();
if(rs.next()){
count = rs.getInt("COUNT");
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while trying to get device " +
"count of Owner : "+owner, e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return count;
}
@Override
public boolean setStatus(String currentOwner, EnrolmentInfo.Status status,
int tenantId) throws DeviceManagementDAOException {
return setStatusAllDevices(currentOwner, status, tenantId);
}
@Override
public boolean setStatusAllDevices(String currentOwner, EnrolmentInfo.Status status, int tenantId)
throws DeviceManagementDAOException{
Connection conn;
PreparedStatement stmt = null;
Timestamp updateTime = new Timestamp(new Date().getTime());
if(getCountOfDevicesOfOwner(currentOwner, tenantId) > 0){
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, status.toString());
stmt.setTimestamp(2, updateTime);
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 addDeviceStatus(currentOwner, status, tenantId);
} else {
return false;
}
}
@Override
public boolean setStatus(int enrolmentID, EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
Timestamp updateTime = new Timestamp(new Date().getTime());
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, status.toString());
stmt.setTimestamp(2, updateTime);
stmt.setInt(3, enrolmentID);
stmt.setInt(4, tenantId);
int updatedRowCount = stmt.executeUpdate();
if (updatedRowCount != 1){
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment: "+
updatedRowCount + " rows were updated instead of one row!!!");
}
// save the device status history
addDeviceStatus(enrolmentID, status);
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return true;
}
public boolean addDeviceStatus(EnrolmentInfo config) throws DeviceManagementDAOException {
return addDeviceStatus(config.getId(), config.getStatus());
}
public boolean addDeviceStatus(String currentOwner, EnrolmentInfo.Status status, int tenantId) throws DeviceManagementDAOException {
Connection conn;
String changedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (changedBy == null){
changedBy = DeviceManagementConstants.MaintenanceProperties.MAINTENANCE_USER;
}
PreparedStatement stmt = null;
ResultSet rs = null;
List<int[]> enrolmentInfoList = new ArrayList<>();
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 OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, currentOwner);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
while (rs.next()) {
int enrolmentId = rs.getInt("ID");
int deviceId = rs.getInt("DEVICE_ID");
enrolmentInfoList.add(new int[]{enrolmentId, deviceId});
}
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
Timestamp updateTime = new Timestamp(new Date().getTime());
sql = "INSERT INTO DM_DEVICE_STATUS (ENROLMENT_ID, DEVICE_ID, STATUS, UPDATE_TIME, CHANGED_BY) VALUES(?, ?, ?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
if (conn.getMetaData().supportsBatchUpdates()) {
for(int[] info: enrolmentInfoList){
ps.setInt(1, info[0]);
ps.setInt(2, info[1]);
ps.setString(3, status.toString());
ps.setTimestamp(4, updateTime);
ps.setString(5, changedBy);
ps.addBatch();
}
int[] batchResult = ps.executeBatch();
for (int i : batchResult) {
if (i == 0 || i == Statement.SUCCESS_NO_INFO || i == Statement.EXECUTE_FAILED) {
return false;
}
}
} else {
for(int[] info: enrolmentInfoList){
ps.setInt(1, info[0]);
ps.setInt(2, info[1]);
ps.setString(3, status.toString());
ps.setTimestamp(4, updateTime);
ps.setString(5, changedBy);
ps.execute();
}
}
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the enrolments " +
"information of owner '" + currentOwner + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return true;
}
public boolean addDeviceStatus(int enrolmentId, EnrolmentInfo.Status status) throws DeviceManagementDAOException {
Connection conn;
String changedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
@ -320,8 +41,8 @@ public class SQLServerEnrollmentDAOImpl extends AbstractEnrollmentDAOImpl {
}
PreparedStatement stmt = null;
try {
conn = this.getConnection();
// get the device id and last udpated status from the device status table
conn = getConnection();
// get the device id and last updated status from the device status table
String sql = "SELECT TOP 1 DEVICE_ID, STATUS FROM DM_DEVICE_STATUS WHERE ENROLMENT_ID = ? ORDER BY UPDATE_TIME DESC";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, enrolmentId);
@ -372,177 +93,5 @@ public class SQLServerEnrollmentDAOImpl extends AbstractEnrollmentDAOImpl {
}
return true;
}
@Override
public EnrolmentInfo.Status getStatus(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
EnrolmentInfo.Status status = null;
try {
conn = this.getConnection();
String sql = "SELECT STATUS FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setString(2, currentOwner);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
status = EnrolmentInfo.Status.valueOf(rs.getString("STATUS"));
}
return status;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while setting the status of device enrolment", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public EnrolmentInfo getEnrollment(int deviceId, String currentOwner,
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 OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setString(2, currentOwner);
stmt.setInt(3, 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 user '" + currentOwner + "' upon device '" + deviceId + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@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<EnrolmentInfo> getEnrollmentsOfUser(int deviceId, String user, int tenantId)
throws DeviceManagementDAOException {
List<EnrolmentInfo> enrolmentInfos = new ArrayList<>();
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 OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setString(2, user);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
while (rs.next()) {
enrolmentInfo = this.loadEnrolment(rs);
enrolmentInfos.add(enrolmentInfo);
}
return enrolmentInfos;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the enrolments " +
"information of user '" + user + "' upon device '" + deviceId + "'", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public boolean updateOwnerOfEnrollment(List<Device> devices, String owner, int tenantId)
throws DeviceManagementDAOException {
try {
Connection conn = this.getConnection();
boolean updateStatus = true;
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.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();
}
int[] batchResult = ps.executeBatch();
for (int i : batchResult) {
if (i == 0 || i == Statement.SUCCESS_NO_INFO || i == Statement.EXECUTE_FAILED) {
updateStatus = false;
break;
}
}
} else {
for (Device device : devices) {
ps.setString(1, owner);
ps.setBoolean(2, device.getEnrolmentInfo().isTransferred());
ps.setInt(3, device.getId());
ps.setInt(4, tenantId);
if (ps.executeUpdate() == 0) {
updateStatus = false;
break;
}
}
}
}
return updateStatus;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while obtaining the DB connection to update the "
+ "owner of the device enrollment.", e);
}
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}
private EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException {
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")));
enrolmentInfo.setId(rs.getInt("ID"));
return enrolmentInfo;
}
}

@ -625,6 +625,9 @@ public class GenericGeofenceDAOImpl extends AbstractGeofenceDAOImpl {
geofenceData.setGroupData(groupMap);
}
}
if (geofenceData != null) {
geofenceData.setGroupIds(new ArrayList<>(groupMap.keySet()));
}
return geofenceData;
}
} catch (SQLException e) {

@ -157,6 +157,9 @@ public class SQLServerGeofenceDAOImpl extends AbstractGeofenceDAOImpl {
geofenceData.setFenceShape(rst.getString("FENCE_SHAPE"));
geofenceData.setGroupData(groupMap);
}
if (geofenceData != null) {
geofenceData.setGroupIds(new ArrayList<>(groupMap.keySet()));
}
return geofenceData;
}
}

@ -45,25 +45,26 @@ public class GenericGroupDAOImpl extends AbstractGroupDAOImpl {
List<Device> devices = null;
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.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, e.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, d1.LAST_UPDATED_TIMESTAMP, 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 " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, gd.LAST_UPDATED_TIMESTAMP " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM" +
"(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.LAST_UPDATED_TIMESTAMP 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 = ?) gd, DM_DEVICE_TYPE t " +
"WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? , ?";
"WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd) d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
stmt.setInt(3, tenantId);
//noinspection JpaQueryApiInspection
stmt.setInt(4, startIndex);
stmt.setInt(4, rowCount);
//noinspection JpaQueryApiInspection
stmt.setInt(5, rowCount);
stmt.setInt(5, startIndex);
rs = stmt.executeQuery();
devices = new ArrayList<>();
while (rs.next()) {

@ -192,16 +192,17 @@ public class OracleGroupDAOImpl extends AbstractGroupDAOImpl {
List<Device> devices = null;
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.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, e.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, d1.LAST_UPDATED_TIMESTAMP, 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 " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, gd.LAST_UPDATED_TIMESTAMP " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM" +
"(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.LAST_UPDATED_TIMESTAMP 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 = ?) gd, DM_DEVICE_TYPE t " +
"WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
"WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd) d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);
@ -219,7 +220,7 @@ public class OracleGroupDAOImpl extends AbstractGroupDAOImpl {
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while retrieving information of all " +
"registered devices", e);
"registered devices", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}

@ -133,16 +133,17 @@ public class PostgreSQLGroupDAOImpl extends AbstractGroupDAOImpl {
List<Device> devices = null;
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.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, e.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, d1.LAST_UPDATED_TIMESTAMP, 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 " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, gd.LAST_UPDATED_TIMESTAMP " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM" +
"(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.LAST_UPDATED_TIMESTAMP 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 = ?) gd, DM_DEVICE_TYPE t " +
"WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?";
"WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd) d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);
@ -160,7 +161,7 @@ public class PostgreSQLGroupDAOImpl extends AbstractGroupDAOImpl {
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while retrieving information of all " +
"registered devices", e);
"registered devices", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}

@ -192,16 +192,17 @@ public class SQLServerGroupDAOImpl extends AbstractGroupDAOImpl {
List<Device> devices = null;
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.IS_TRANSFERRED, e.DATE_OF_LAST_UPDATE, " +
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, e.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, d1.LAST_UPDATED_TIMESTAMP, 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 " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, gd.LAST_UPDATED_TIMESTAMP " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM" +
"(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.LAST_UPDATED_TIMESTAMP 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 = ?) gd, DM_DEVICE_TYPE t " +
"WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY d1.DEVICE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
"WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd) d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY d1.DEVICE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);

@ -228,6 +228,7 @@ public final class DeviceManagementDAOUtil {
device.setDescription(rs.getString("DESCRIPTION"));
device.setType(rs.getString("DEVICE_TYPE"));
device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));
device.setLastUpdatedTimeStamp(rs.getTimestamp("LAST_UPDATED_TIMESTAMP").getTime());
device.setEnrolmentInfo(loadEnrolment(rs));
return device;
}

@ -142,9 +142,12 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
log.info("Device identifier " + device.getDeviceIdentifier() + ", Device name " +
"changed by user from " + device.getName() + " to " + name);
device.setName(name);
deviceDAO.updateDevice(device, CarbonContext.getThreadLocalCarbonContext().getTenantId());
} else {
deviceDAO.recordDeviceUpdate(
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()),
CarbonContext.getThreadLocalCarbonContext().getTenantId());
}
deviceDAO.updateDevice(device, CarbonContext.getThreadLocalCarbonContext().getTenantId());
DeviceManagementDAOFactory.commitTransaction();
//TODO :: This has to be fixed by adding the enrollment ID.

@ -76,6 +76,16 @@ public class EventOperationExecutor implements Runnable {
} //extend with another cases to handle other types of events
}
/**
* Build operation to create EVENT_UPDATE operation.
* @param operation Operation object to build
*/
private void buildEventUpdateOperation(ProfileOperation operation) {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
createGeoFenceUpdateOperation(operation);
} //extend with another cases to handle other types of events
}
/**
* Build operation to create EVENT_CONFIG operation.
* @param operation Operation object to build
@ -120,6 +130,18 @@ public class EventOperationExecutor implements Runnable {
* @param operation operation object to set the payload
*/
private void createGeoFenceRevokeOperation(ProfileOperation operation) {
changeGeoFenceOperation(operation);
}
/**
* Create EVENT_UPDATE operation object and attach payload to configure geo fence events
* @param operation operation object to set the payload
*/
private void createGeoFenceUpdateOperation(ProfileOperation operation) {
changeGeoFenceOperation(operation);
}
private void changeGeoFenceOperation(ProfileOperation operation) {
GeoFenceEventMeta geoFenceMeta = (GeoFenceEventMeta) eventMetaData;
EventRevokeOperation eventRevokeOperation = new EventRevokeOperation();
eventRevokeOperation.setEventSource(eventSource);
@ -180,6 +202,9 @@ public class EventOperationExecutor implements Runnable {
if (operationCode.equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_CONFIG)) {
operation.setCode(OperationMgtConstants.OperationCodes.EVENT_CONFIG);
buildEventConfigOperation(operation);
} else if (operationCode.equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_UPDATE)){
operation.setCode(OperationMgtConstants.OperationCodes.EVENT_UPDATE);
buildEventUpdateOperation(operation);
} else if (operationCode.equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_REVOKE)){
operation.setCode(OperationMgtConstants.OperationCodes.EVENT_REVOKE);
buildEventRevokeOperation(operation);

@ -106,6 +106,8 @@ public class GroupAssignmentEventOperationExecutor implements Runnable {
operation.setType(Operation.Type.PROFILE);
if (operationCode.equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_CONFIG)) {
buildEventConfigOperationObject(operation);
} else if (operationCode.equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_UPDATE)) {
buildEventUpdateOperation(operation);
} else if (operationCode.equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_REVOKE)) {
buildEventRevokeOperation(operation);
}
@ -162,6 +164,19 @@ public class GroupAssignmentEventOperationExecutor implements Runnable {
}
}
/**
* Build EVENT_UPDATE operation attaching event payload
* @param operation operation object to build
* @throws EventConfigurationException if not events found for the specific group
*/
private void buildEventUpdateOperation(ProfileOperation operation) throws EventConfigurationException {
for (String eventSource : this.eventSources) {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
setGeoFenceUpdateOperationContent(operation);
} //add other cases to handle other types of events
}
}
/**
* Build EVENT_CONFIG operation attaching event payload
* @param operation operation object to build
@ -217,6 +232,18 @@ public class GroupAssignmentEventOperationExecutor implements Runnable {
* @param operation operation object to attach payload
*/
private void setGeoFenceRevokeOperationContent(ProfileOperation operation){
changeGeoFenceOperation(operation);
}
/**
* Set operation payload GeoFence for EVENT_UPDATE operation
* @param operation operation object to attach payload
*/
private void setGeoFenceUpdateOperationContent(ProfileOperation operation){
changeGeoFenceOperation(operation);
}
private void changeGeoFenceOperation(ProfileOperation operation) {
List<EventRevokeOperation> revokeOperationList = new ArrayList<>();
for (GeofenceData geofenceData : this.geoFencesOfGroup) {
EventRevokeOperation eventRevokeOperation = new EventRevokeOperation();

@ -1307,7 +1307,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
DeviceManagementConstants.EventServices.GEOFENCE, new GeoFenceEventMeta(geofenceData),
tenantId, geofenceData.getGroupIds());
} catch (EventConfigurationException e) {
String msg = "Failed while creating EVENT_REVOKE operation creation task entry while updating geo fence "
String msg = "Failed while creating EVENT_CONFIG operation creation task entry while updating geo fence "
+ geofenceData.getFenceName() + " of the tenant " + tenantId;
log.error(msg, e);
throw new GeoLocationBasedServiceException(msg, e);
@ -1634,11 +1634,11 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
log.debug("Update geofence event completed.");
}
try {
eventConfigService.createEventOperationTask(OperationMgtConstants.OperationCodes.EVENT_REVOKE,
eventConfigService.createEventOperationTask(OperationMgtConstants.OperationCodes.EVENT_UPDATE,
DeviceManagementConstants.EventServices.GEOFENCE,
new GeoFenceEventMeta(geofenceData), tenantId, geofenceData.getGroupIds());
} catch (EventConfigurationException e) {
String msg = "Failed while creating EVENT_REVOKE operation creation task entry while updating geo fence "
String msg = "Failed while creating EVENT_UPDATE operation creation task entry while updating geo fence "
+ geofenceData.getFenceName() + " of the tenant " + tenantId;
log.error(msg, e);
throw new GeoLocationBasedServiceException(msg, e);

@ -206,6 +206,7 @@ public class OperationManagerImpl implements OperationManager {
String initiatedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (initiatedBy == null && (isScheduledOperation
|| operation.getCode().equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_CONFIG)
|| operation.getCode().equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_UPDATE)
|| operation.getCode().equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_REVOKE))) {
operation.setInitiatedBy(SYSTEM);
} else if (StringUtils.isEmpty(operation.getInitiatedBy())) {
@ -1460,6 +1461,7 @@ public class OperationManagerImpl implements OperationManager {
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.POLICY_OPERATION_CODE:
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.EVENT_CONFIG_OPERATION_CODE:
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.EVENT_REVOKE_OPERATION_CODE:
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.EVENT_UPDATE_OPERATION_CODE:
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.POLICY_REVOKE_OPERATION_CODE:
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.MONITOR_OPERATION_CODE:
status = true;

@ -26,6 +26,7 @@ public class OperationMgtConstants {
public static final String POLICY_REVOKE = "POLICY_REVOKE";
public static final String EVENT_CONFIG = "EVENT_CONFIG";
public static final String EVENT_UPDATE = "EVENT_UPDATE";
public static final String EVENT_REVOKE = "EVENT_REVOKE";
}
}

@ -17,7 +17,6 @@
*/
package io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.impl;
import io.entgra.device.mgt.core.device.mgt.common.MDMAppConstants;
import io.entgra.device.mgt.core.device.mgt.core.dto.operation.mgt.ProfileOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -44,8 +43,6 @@ import io.entgra.device.mgt.core.device.mgt.core.operation.mgt.dao.util.Operatio
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -59,7 +56,6 @@ import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@ -575,14 +571,12 @@ public class GenericOperationDAOImpl implements OperationDAO {
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, de.DEVICE_ID, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID, "
+ "dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, "
+ "dor.ID AS OP_RES_ID, de.DEVICE_ID, de.DEVICE_IDENTIFICATION, de.DEVICE_TYPE, "
+ "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, 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 "
+ "INNER JOIN DM_DEVICE_TYPE dt ON dt.ID=d.DEVICE_TYPE_ID "
+ "ON op.ID=eom.OPERATION_ID INNER JOIN DM_ENROLMENT de ON de.ID=eom.ENROLMENT_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 = ?";
@ -617,7 +611,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
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);
@ -655,7 +649,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
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")));
@ -715,8 +709,8 @@ public class GenericOperationDAOImpl implements OperationDAO {
+ "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, "
+ "de.DEVICE_IDENTIFICATION, "
+ "de.DEVICE_TYPE, "
+ "eom.STATUS, eom.CREATED_TIMESTAMP, "
+ "eom.UPDATED_TIMESTAMP, "
+ "op.OPERATION_CODE, "
@ -727,11 +721,9 @@ public class GenericOperationDAOImpl implements OperationDAO {
+ "op.INITIATED_BY FROM DM_ENROLMENT_OP_MAPPING AS eom "
+ "INNER JOIN DM_OPERATION AS op ON op.ID=eom.OPERATION_ID "
+ "INNER JOIN DM_ENROLMENT AS de ON de.ID=eom.ENROLMENT_ID "
+ "INNER JOIN DM_DEVICE AS d ON d.ID=de.DEVICE_ID "
+ "INNER JOIN DM_DEVICE_TYPE AS dt ON dt.ID=d.DEVICE_TYPE_ID "
+ "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE AS dor ON dor.ENROLMENT_ID=de.id "
+ "AND dor.OPERATION_ID = eom.OPERATION_ID "
+ "WHERE eom.OPERATION_ID = ? AND de.device_id = ? AND de.TENANT_ID = ?";
+ "WHERE eom.OPERATION_ID = ? AND de.DEVICE_ID = ? AND de.TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, operationId);
@ -756,7 +748,7 @@ public class GenericOperationDAOImpl implements OperationDAO {
if (enrolmentId != rs.getInt("ENROLMENT_ID")) {
activityStatus = new ActivityStatus();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"),
rs.getString("DEVICE_TYPE_NAME"));
rs.getString("DEVICE_TYPE"));
activityStatus.setDeviceIdentifier(deviceIdentifier);
activityStatus.setStatus(ActivityStatus.Status.valueOf(rs.getString("STATUS")));
@ -850,15 +842,13 @@ public class GenericOperationDAOImpl implements OperationDAO {
" op.TYPE AS OPERATION_TYPE, " +
" opm.STATUS, " +
" en.DEVICE_ID, " +
" de.DEVICE_IDENTIFICATION, " +
" dt.NAME AS DEVICE_TYPE, " +
" en.DEVICE_IDENTIFICATION, " +
" en.DEVICE_TYPE, " +
" de.TENANT_ID " +
" FROM" +
" DM_ENROLMENT_OP_MAPPING opm " +
" 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 " +
" op.OPERATION_CODE = ? " +
" AND de.TENANT_ID = ? " +

@ -661,6 +661,8 @@ public interface DeviceManagementProviderService {
void addLicense(String deviceType, License license) throws DeviceManagementException;
boolean recordDeviceUpdate(DeviceIdentifier deviceIdentifier) throws DeviceManagementException;
boolean modifyEnrollment(Device device) throws DeviceManagementException;
boolean enrollDevice(Device device) throws DeviceManagementException;

@ -38,7 +38,6 @@ import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.device.mgt.core.device.mgt.common.ActivityPaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.Billing;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.DeviceEnrollmentInfoNotification;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
@ -58,7 +57,6 @@ import io.entgra.device.mgt.core.device.mgt.common.StartupOperationConfig;
import io.entgra.device.mgt.core.device.mgt.common.BillingResponse;
import io.entgra.device.mgt.core.device.mgt.common.app.mgt.Application;
import io.entgra.device.mgt.core.device.mgt.common.app.mgt.ApplicationManagementException;
import io.entgra.device.mgt.core.device.mgt.common.app.mgt.MobileAppTypes;
import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.AmbiguousConfigurationException;
import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry;
import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException;
@ -329,7 +327,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
if ((updateStatus > 0) || EnrolmentInfo.Status.REMOVED.
equals(existingEnrolmentInfo.getStatus())) {
enrollment = enrollmentDAO
.addEnrollment(existingDevice.getId(), newEnrolmentInfo, tenantId);
.addEnrollment(existingDevice.getId(), deviceIdentifier,
newEnrolmentInfo, tenantId);
if (enrollment == null) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException(
@ -383,7 +382,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
if (type != null) {
int deviceId = deviceDAO.addDevice(type.getId(), device, tenantId);
device.setId(deviceId);
enrollment = enrollmentDAO.addEnrollment(deviceId, device.getEnrolmentInfo(), tenantId);
enrollment = enrollmentDAO.addEnrollment(deviceId, deviceIdentifier, device.getEnrolmentInfo(), tenantId);
if (enrollment == null) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException(
@ -459,6 +458,31 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return status;
}
@Override
public boolean recordDeviceUpdate(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
int tenantId = this.getTenantId();
boolean isUpdated;
try {
DeviceManagementDAOFactory.beginTransaction();
isUpdated = deviceDAO.recordDeviceUpdate(deviceIdentifier, tenantId);
DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while setting updated " +
"timestamp of device: " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (TransactionManagementException e) {
String msg = "Error occurred while initiating transaction to set updated " +
"timestamp of device: " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
return isUpdated;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
if (device == null) {
@ -497,10 +521,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
if (device.getName() == null) {
device.setName(currentDevice.getName());
}
deviceDAO.updateDevice(device, tenantId);
int updatedRows = enrollmentDAO.updateEnrollment(device.getEnrolmentInfo(), tenantId);
boolean isEnableDeviceStatusCheck = deviceStatusManagementService.getDeviceStatusCheck(tenantId);
boolean isValidState = deviceStatusManagementService.isDeviceStatusValid(device.getType(),device.getEnrolmentInfo().getStatus().name(),tenantId);
boolean isValidState = deviceStatusManagementService.isDeviceStatusValid(device.getType(),
device.getEnrolmentInfo().getStatus().name(),tenantId);
if (updatedRows == 1 && !deviceStatusManagementService.getDeviceStatusCheck(tenantId)){
enrollmentDAO.addDeviceStatus(device.getEnrolmentInfo().getId(), device.getEnrolmentInfo().getStatus());
} else if (updatedRows ==1 && isEnableDeviceStatusCheck && isValidState ) {
@ -508,7 +533,15 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
DeviceManagementDAOFactory.commitTransaction();
log.info("Device enrolled successfully", deviceEnrolmentLogContextBuilder.setDeviceId(String.valueOf(currentDevice.getId())).setDeviceType(String.valueOf(currentDevice.getType())).setOwner(currentDevice.getEnrolmentInfo().getOwner()).setOwnership(String.valueOf(currentDevice.getEnrolmentInfo().getOwnership())).setTenantID(String.valueOf(tenantId)).setTenantDomain(tenantDomain).setUserName(userName).build());
log.info("Device enrollment modified successfully",
deviceEnrolmentLogContextBuilder.setDeviceId(String.valueOf(currentDevice.getId()))
.setDeviceType(String.valueOf(currentDevice.getType()))
.setOwner(currentDevice.getEnrolmentInfo().getOwner())
.setOwnership(String.valueOf(currentDevice.getEnrolmentInfo().getOwnership()))
.setTenantID(String.valueOf(tenantId))
.setTenantDomain(tenantDomain)
.setUserName(userName).build());
this.removeDeviceFromCache(deviceIdentifier);
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
@ -623,20 +656,27 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} else if (updatedRows ==1 && isEnableDeviceStatusCheck && isValidState ) {
enrollmentDAO.addDeviceStatus(device.getEnrolmentInfo().getId(), device.getEnrolmentInfo().getStatus());
}
deviceDAO.updateDevice(device, tenantId);
DeviceManagementDAOFactory.commitTransaction();
this.removeDeviceFromCache(deviceId);
//procees to dis-enroll a device from traccar starts
//process to dis-enroll a device from traccar starts
if (HttpReportingUtil.isTrackerEnabled()) {
DeviceManagementDataHolder.getInstance().getTraccarManagementService().unLinkTraccarDevice(device.getEnrolmentInfo().getId());
DeviceManagementDataHolder.getInstance().getTraccarManagementService()
.unLinkTraccarDevice(device.getEnrolmentInfo().getId());
} else {
if (log.isDebugEnabled()) {
log.debug("Traccar is disabled");
}
}
//procees to dis-enroll a device from traccar ends
log.info("Device disenrolled successfully", deviceEnrolmentLogContextBuilder.setDeviceId(String.valueOf(device.getId())).setDeviceType(String.valueOf(device.getType())).setOwner(device.getEnrolmentInfo().getOwner()).setOwnership(String.valueOf(device.getEnrolmentInfo().getOwnership())).setTenantID(String.valueOf(tenantId)).setTenantDomain(tenantDomain).setUserName(userName).build());
//process to dis-enroll a device from traccar ends
log.info("Device disenrolled successfully",
deviceEnrolmentLogContextBuilder.setDeviceId(String.valueOf(device.getId()))
.setDeviceType(String.valueOf(device.getType()))
.setOwner(device.getEnrolmentInfo().getOwner())
.setOwnership(String.valueOf(device.getEnrolmentInfo().getOwnership()))
.setTenantID(String.valueOf(tenantId))
.setTenantDomain(tenantDomain)
.setUserName(userName).build());
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while dis-enrolling '" + deviceId.getType() +
@ -1115,7 +1155,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
List<DeviceStatus> deviceStatus;
for (Device device : allDevices) {
long dateDiff = 0;
deviceStatus = getDeviceStatusHistory(device, null, endDate, true);
deviceStatus = getDeviceStatusHistoryInsideTransaction(device, null, endDate, true);
if (device.getEnrolmentInfo().getDateOfEnrolment() < startDate.getTime()) {
if (!deviceStatus.isEmpty() && (String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED")
|| String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) {
@ -2170,23 +2210,52 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
}
@Override
public List<DeviceStatus> getDeviceStatusHistory(Device device, Date fromDate, Date toDate, boolean billingStatus) throws DeviceManagementException {
/*
This is just to avoid breaking the billing functionality as it required to call getDeviceStatusHistory method
without transaction handling.
*/
private List<DeviceStatus> getDeviceStatusHistoryInsideTransaction(
Device device, Date fromDate, Date toDate, boolean billingStatus)
throws DeviceManagementException {
if (log.isDebugEnabled()) {
log.debug("get status history of device: " + device.getDeviceIdentifier());
}
try {
DeviceManagementDAOFactory.getConnection();
int tenantId = this.getTenantId();
return deviceStatusDAO.getStatus(device.getId(), tenantId, fromDate, toDate, billingStatus);
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while retrieving status history";
String msg = "Error occurred in retrieving status history for device :" + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (Exception e) {
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source";
log.info(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public List<DeviceStatus> getDeviceStatusHistory(Device device, Date fromDate, Date toDate, boolean billingStatus) throws DeviceManagementException {
if (log.isDebugEnabled()) {
log.debug("get status history of device: " + device.getDeviceIdentifier());
}
try {
DeviceManagementDAOFactory.openConnection();
int tenantId = this.getTenantId();
return deviceStatusDAO.getStatus(device.getId(), tenantId, fromDate, toDate, billingStatus);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred in retrieving status history for device :" + device.getDeviceIdentifier();
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.info(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
@ -4463,15 +4532,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} catch (MetadataManagementException e) {
throw new RuntimeException(e);
}
try {
deviceDAO.updateDevice(device, tenantId);
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while updating device: " +
device.getName();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
}
}
DeviceManagementDAOFactory.commitTransaction();

@ -22,6 +22,7 @@ import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo.Status;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.TransactionManagementException;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.core.TestUtils;
import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest;
import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder;
@ -36,6 +37,8 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
public class DevicePersistTests extends BaseDeviceManagementTest {
@ -227,4 +230,60 @@ public class DevicePersistTests extends BaseDeviceManagementTest {
DeviceManagementDAOFactory.closeConnection();
}
}
@Test(dependsOnMethods = "testAddDeviceTest")
public void getDevicesByIdentifiersTest() throws DeviceManagementDAOException, TransactionManagementException {
Device device = TestDataHolder.initialTestDevice;
try {
DeviceManagementDAOFactory.openConnection();
DeviceIdentifier deviceId = new DeviceIdentifier(device.getDeviceIdentifier(), device.getType());
List<Device> retrieved = deviceDAO.getDevicesByIdentifiers(
Collections.singletonList(deviceId.getId()), TestDataHolder.SUPER_TENANT_ID);
Assert.assertEquals(1, retrieved.size(), "Device count is not matched to expected.");
} catch (DeviceManagementDAOException | SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the current status of the " +
"enrolment", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
@Test(dependsOnMethods = "testAddDeviceTest")
public void recordDeviceUpdateTest() throws DeviceManagementDAOException, TransactionManagementException {
Device device = TestDataHolder.initialTestDevice;
try {
DeviceManagementDAOFactory.beginTransaction();
device = deviceDAO.getDevice(device.getDeviceIdentifier(), TestDataHolder.SUPER_TENANT_ID);
log.info("Device before update: " + device);
DeviceIdentifier deviceId = new DeviceIdentifier(device.getDeviceIdentifier(), device.getType());
boolean updated = deviceDAO.recordDeviceUpdate(deviceId, TestDataHolder.SUPER_TENANT_ID);
Assert.assertTrue(updated, "Device timestamp is not updated.");
Device updatedDevice = deviceDAO.getDevice(device.getDeviceIdentifier(), TestDataHolder.SUPER_TENANT_ID);
log.info("Device after update: " + updatedDevice);
Assert.assertTrue(device.getLastUpdatedTimeStamp() < updatedDevice.getLastUpdatedTimeStamp(),
"Last updated timestamp is way older.");
} catch (DeviceManagementDAOException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the current status of the " +
"enrolment", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
@Test(dependsOnMethods = "testAddDeviceTest")
public void getDeviceByStatusTest() throws DeviceManagementDAOException, TransactionManagementException {
try {
DeviceManagementDAOFactory.beginTransaction();
PaginationRequest pr = new PaginationRequest(0, 10);
pr.setStatusList(Collections.singletonList(Status.ACTIVE.name()));
List<Device> results = deviceDAO.getDevicesByStatus(pr, TestDataHolder.SUPER_TENANT_ID);
Assert.assertEquals(1, results.size(), "No device returned");
} catch (DeviceManagementDAOException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the current status of the " +
"enrolment", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
}

@ -21,6 +21,7 @@ import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.common.type.mgt.DeviceStatus;
import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -29,7 +30,12 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.sql.SQLException;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Stream;
import static io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo.Status.*;
@ -214,7 +220,8 @@ public class DeviceStatusPersistenceTests extends BaseDeviceManagementTest {
EnrolmentInfo source = new EnrolmentInfo(owner, EnrolmentInfo.OwnerShip.BYOD, initialStatus);
try {
DeviceManagementDAOFactory.openConnection();
EnrolmentInfo config = enrollmentDAO.addEnrollment(deviceId, source, tenantId);
EnrolmentInfo config = enrollmentDAO.addEnrollment(deviceId,
new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()), source, tenantId);
device.setEnrolmentInfo(config);
return config.getId();
} catch (DeviceManagementDAOException | SQLException e) {

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.device.mgt.core.dao;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.DeviceIdentifier;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest;
import io.entgra.device.mgt.core.device.mgt.core.common.TestDataHolder;
@ -58,7 +59,8 @@ public class EnrolmentPersistenceTests extends BaseDeviceManagementTest {
DeviceDAO deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
deviceId = deviceDAO.addDevice(TestDataHolder.initialTestDeviceType.getId(), device, TestDataHolder.SUPER_TENANT_ID);
device.setId(deviceId);
enrollmentDAO.addEnrollment(deviceId, source, TestDataHolder.SUPER_TENANT_ID);
enrollmentDAO.addEnrollment(deviceId, new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()),
source, TestDataHolder.SUPER_TENANT_ID);
} catch (DeviceManagementDAOException | SQLException e) {
log.error("Error occurred while adding enrollment", e);
} finally {

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

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

@ -40,7 +40,7 @@ public class HeartBeatBeaconDAOFactory {
private static final Log log = LogFactory.getLog(HeartBeatBeaconDAOFactory.class);
private static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
private static final ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
/**
* Get instance of GroupDAO
@ -62,7 +62,6 @@ public class HeartBeatBeaconDAOFactory {
/**
* Begin transaction with datasource for write data
*
* @throws TransactionManagementException
*/
public static void beginTransaction() throws TransactionManagementException {
Connection conn = currentConnection.get();
@ -83,7 +82,6 @@ public class HeartBeatBeaconDAOFactory {
/**
* Open connection to the datasource for read data
*
* @throws SQLException
*/
public static void openConnection() throws SQLException {
Connection conn = currentConnection.get();
@ -100,7 +98,6 @@ public class HeartBeatBeaconDAOFactory {
* Get current connection to datasource
*
* @return current connection
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
Connection conn = currentConnection.get();
@ -187,7 +184,7 @@ public class HeartBeatBeaconDAOFactory {
List<JNDILookupDefinition.JNDIProperty> jndiPropertyList =
jndiConfig.getJndiProperties();
if (jndiPropertyList != null) {
Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>();
Hashtable<Object, Object> jndiProperties = new Hashtable<>();
for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) {
jndiProperties.put(prop.getName(), prop.getValue());
}

@ -59,9 +59,8 @@ public class OperationTemplateCacheLoader extends CacheLoader<String, OperationT
String deviceType = operationTemplateCacheKey.getDeviceType();
if (log.isTraceEnabled()) {
log.trace(
"Loading operation template for subtype Id : " + subTypeId + " & deviceType : " + deviceType + " operation code : "
+ operationCode);
log.trace("Loading operation template for subtype Id : " + subTypeId
+ " & deviceType : " + deviceType + " operation code : " + operationCode);
}
try {
ConnectionManagerUtils.openDBConnection();

@ -47,4 +47,23 @@ public class OperationTemplateCacheKey {
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
return subTypeId + "|" + deviceType + "|" + operationCode;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof OperationTemplateCacheKey) {
return (this.hashCode() == obj.hashCode());
}
return false;
}
}

@ -102,7 +102,8 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
DeviceManagementDAOFactory.beginTransaction();
for (Device device : devices) {
int id = deviceDAO.addDevice(type.getId(), device, -1234);
enrollmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -1234);
enrollmentDAO.addEnrollment(id, new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()),
device.getEnrolmentInfo(), -1234);
}
} catch (TransactionManagementException e) {
log.error("Error occurred while adding device enrolment", e);

@ -61,23 +61,35 @@ DROP TABLE IF EXISTS DM_GROUP;
CREATE TABLE IF NOT EXISTS DM_GROUP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_NAME VARCHAR(100) DEFAULT NULL,
STATUS VARCHAR(50) DEFAULT NULL,
DESCRIPTION TEXT DEFAULT NULL,
STATUS VARCHAR(50) DEFAULT NULL,
DATE_OF_CREATE BIGINT DEFAULT NULL,
DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL,
OWNER VARCHAR(255) DEFAULT NULL,
PARENT_PATH VARCHAR(255) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PARENT_GROUP_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID)
);
DROP TABLE IF EXISTS DM_ROLE_GROUP_MAP;
CREATE TABLE IF NOT EXISTS DM_ROLE_GROUP_MAP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_ID INTEGER DEFAULT NULL,
ROLE VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_ROLE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
REFERENCES DM_GROUP (ID) ON DELETE CASCADE ON UPDATE CASCADE
DROP TABLE IF EXISTS DM_ROLE_GROUP_MAP;
CREATE TABLE IF NOT EXISTS DM_ROLE_GROUP_MAP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_ID INTEGER DEFAULT NULL,
ROLE VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_ROLE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
REFERENCES DM_GROUP (ID) ON DELETE CASCADE ON UPDATE CASCADE
);
DROP TABLE IF EXISTS DM_DEVICE_CERTIFICATE;
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID INTEGER auto_increment NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
USERNAME VARCHAR(500) DEFAULT NULL,
PRIMARY KEY (ID)
);
DROP TABLE IF EXISTS DM_DEVICE;
@ -146,6 +158,8 @@ DROP TABLE IF EXISTS DM_ENROLMENT;
CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
DEVICE_TYPE VARCHAR(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL,
OWNER VARCHAR(255) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,
@ -246,8 +260,8 @@ DROP TABLE IF EXISTS DM_POLICY;
CREATE TABLE IF NOT EXISTS DM_POLICY (
ID INT NOT NULL AUTO_INCREMENT ,
NAME VARCHAR(45) DEFAULT NULL ,
PAYLOAD_VERSION VARCHAR (45) DEFAULT NULL,
DESCRIPTION VARCHAR(1000) NULL,
PAYLOAD_VERSION VARCHAR (45) NULL,
TENANT_ID INT NOT NULL ,
PROFILE_ID INT NOT NULL ,
OWNERSHIP_TYPE VARCHAR(45) NULL,
@ -263,6 +277,24 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_POLICY_CORRECTIVE_ACTION;
CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION (
ID INT NOT NULL AUTO_INCREMENT,
ACTION_TYPE VARCHAR(45) NOT NULL,
CORRECTIVE_POLICY_ID INT DEFAULT NULL,
POLICY_ID INT NOT NULL,
FEATURE_ID INT DEFAULT NULL,
IS_REACTIVE BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (ID),
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION
FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_DEVICE_POLICY;
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY (
ID INT NOT NULL AUTO_INCREMENT ,
@ -312,21 +344,6 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES (
ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION (
ID INT NOT NULL AUTO_INCREMENT,
ACTION_TYPE VARCHAR(45) NOT NULL,
CORRECTIVE_POLICY_ID INT DEFAULT NULL,
POLICY_ID INT NOT NULL,
FEATURE_ID INT DEFAULT NULL,
IS_REACTIVE BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (ID),
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION
FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
DROP TABLE IF EXISTS DM_ROLE_POLICY;
CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY (
ID INT NOT NULL AUTO_INCREMENT ,
@ -405,7 +422,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES (
POLICY_CRITERION_ID INT NOT NULL,
PROP_KEY VARCHAR(45) NULL,
PROP_VALUE VARCHAR(100) NULL,
CONTENT BLOB NULL,
CONTENT BLOB NULL COMMENT 'This is used to ',
PRIMARY KEY (ID),
CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES
FOREIGN KEY (POLICY_CRITERION_ID)
@ -433,7 +450,7 @@ DROP TABLE IF EXISTS DM_POLICY_CHANGE_MGT;
CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT (
ID INT NOT NULL AUTO_INCREMENT,
POLICY_ID INT NOT NULL,
DEVICE_TYPE VARCHAR(300) NOT NULL ,
DEVICE_TYPE VARCHAR(300) NOT NULL,
TENANT_ID INT NOT NULL,
PRIMARY KEY (ID)
);
@ -490,7 +507,7 @@ DROP TABLE IF EXISTS DM_NOTIFICATION;
CREATE TABLE IF NOT EXISTS DM_NOTIFICATION (
NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
OPERATION_ID INTEGER NULL,
OPERATION_ID INTEGER NOT NULL,
TENANT_ID INTEGER NOT NULL,
STATUS VARCHAR(10) NULL,
DESCRIPTION VARCHAR(1000) NULL,
@ -667,4 +684,22 @@ DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND
DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID
ORDER BY TENANT_ID, DEVICE_ID;
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
-- END OF DASHBOARD RELATED VIEWS --

@ -58,4 +58,12 @@ public class DeviceSubTypeCacheKey {
return tenantId + "|" + subTypeId + "|" + deviceType;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof DeviceSubTypeCacheKey) {
return (this.hashCode() == obj.hashCode());
}
return false;
}
}

@ -42,7 +42,9 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class DeviceSubTypeServiceImpl implements DeviceSubTypeService {
private static final Log log = LogFactory.getLog(DeviceSubTypeServiceImpl.class);
private static final LoadingCache<DeviceSubTypeCacheKey, DeviceSubType> deviceSubTypeCache
= CacheBuilder.newBuilder()
.expireAfterWrite(15, TimeUnit.MINUTES)
@ -143,7 +145,7 @@ public class DeviceSubTypeServiceImpl implements DeviceSubTypeService {
}
@Override
public DeviceSubType getDeviceSubType(String subTypeId, int tenantId, String deviceType)
public synchronized DeviceSubType getDeviceSubType(String subTypeId, int tenantId, String deviceType)
throws SubTypeMgtPluginException {
try {
DeviceSubTypeCacheKey key = DeviceSubTypeMgtUtil.getDeviceSubTypeCacheKey(tenantId, subTypeId, deviceType);

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

@ -295,6 +295,14 @@
<DefaultRoles>Internal/devicemgt-user</DefaultRoles>
</MappedScopeDetails>
</DefaultPermission>
<DefaultPermission>
<Name>/permission/admin/device-mgt/devices/any-group/permitted-actions-under-owning-group</Name>
<MappedScopeDetails>
<Name>Apply permitted actions on any group</Name>
<Key>dm:group:any:permitted</Key>
<DefaultRoles>Internal/devicemgt-user</DefaultRoles>
</MappedScopeDetails>
</DefaultPermission>
</DefaultPermissions>
</DeviceMgtConfiguration>

@ -469,6 +469,14 @@
<DefaultRoles>Internal/devicemgt-user</DefaultRoles>
</MappedScopeDetails>
</DefaultPermission>
<DefaultPermission>
<Name>/permission/admin/device-mgt/devices/any-group/permitted-actions-under-owning-group</Name>
<MappedScopeDetails>
<Name>Apply permitted actions on any group</Name>
<Key>dm:group:any:permitted</Key>
<DefaultRoles>Internal/devicemgt-user</DefaultRoles>
</MappedScopeDetails>
</DefaultPermission>
</DefaultPermissions>
</DeviceMgtConfiguration>

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

@ -142,6 +142,8 @@ IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[D
CREATE TABLE DM_ENROLMENT (
ID INTEGER IDENTITY(1,1) NOT NULL,
DEVICE_ID INTEGER NOT NULL,
DEVICE_TYPE VARCHAR(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL,
OWNER VARCHAR(255) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,

@ -52,8 +52,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE (
ID INTEGER AUTO_INCREMENT NOT NULL,
DESCRIPTION TEXT DEFAULT NULL,
NAME VARCHAR(100) DEFAULT NULL,
DEVICE_TYPE_ID INT(11) DEFAULT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
DEVICE_TYPE_ID INT(11) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL,
LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
@ -63,6 +63,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE (
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 INDEX IDX_DM_DEVICE_DEVICE_IDENTIFICATION ON DM_DEVICE(DEVICE_IDENTIFICATION);
CREATE INDEX IDX_DM_DEVICE_LAST_UPDATED_TIMESTAMP ON DM_DEVICE(LAST_UPDATED_TIMESTAMP);
CREATE TABLE IF NOT EXISTS DM_DEVICE_PROPERTIES (
DEVICE_TYPE_NAME VARCHAR(300) NOT NULL,
@ -119,6 +121,8 @@ CREATE INDEX IDX_OP_INITIATED_BY ON DM_OPERATION (INITIATED_BY ASC);
CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER NOT NULL,
DEVICE_TYPE VARCHAR(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL,
OWNER VARCHAR(255) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,
@ -130,6 +134,14 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
)ENGINE = InnoDB;
CREATE INDEX IDX_ENROLMENT_DATE_OF_LAST_UPDATE ON DM_ENROLMENT(DATE_OF_LAST_UPDATE);
CREATE INDEX IDX_ENROLMENT_DEVICE_IDENTIFICATION ON DM_ENROLMENT(DEVICE_IDENTIFICATION);
CREATE INDEX IDX_ENROLMENT_DEVICE_TYPE ON DM_ENROLMENT(DEVICE_TYPE);
CREATE INDEX IDX_ENROLMENT_FK_DEVICE_ID ON DM_ENROLMENT(DEVICE_ID);
CREATE INDEX IDX_ENROLMENT_STATUS ON DM_ENROLMENT(STATUS);
CREATE INDEX IDX_ENROLMENT_TENANT_ID ON DM_ENROLMENT(TENANT_ID);
CREATE TABLE IF NOT EXISTS DM_DEVICE_STATUS (
ID INTEGER AUTO_INCREMENT NOT NULL,
ENROLMENT_ID INTEGER NOT NULL,
@ -143,9 +155,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_STATUS (
CONSTRAINT FK_DM_DEVICE_STATUS_ENROLMENT FOREIGN KEY (ENROLMENT_ID) REFERENCES
DM_ENROLMENT (ID) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE = InnoDB;
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 INDEX IDX_ENROLMENT_DEVICE_ID_TENANT_ID_STATUS ON DM_ENROLMENT(DEVICE_ID, TENANT_ID, STATUS);
CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING (
ID INTEGER AUTO_INCREMENT NOT NULL,

@ -205,6 +205,8 @@ WHEN (NEW.ID IS NULL)
CREATE TABLE DM_ENROLMENT (
ID NUMBER(10) NOT NULL,
DEVICE_ID NUMBER(10) NOT NULL,
DEVICE_TYPE VARCHAR2(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR2(300) NOT NULL,
OWNER VARCHAR2(255) NOT NULL,
OWNERSHIP VARCHAR2(45) DEFAULT NULL,
STATUS VARCHAR2(50) NULL,

@ -114,6 +114,8 @@ 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,
DEVICE_TYPE VARCHAR(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL,
OWNER VARCHAR(50) NOT NULL,
OWNERSHIP VARCHAR(45) DEFAULT NULL,
STATUS VARCHAR(50) NULL,

Loading…
Cancel
Save