Add missing parts in group management

revert-70aa11f8
charithag 9 years ago
parent 062a843ca2
commit fa2f61f48a

@ -29,6 +29,7 @@ import java.util.List;
@XmlRootElement @XmlRootElement
public class DeviceGroup implements Serializable { public class DeviceGroup implements Serializable {
private int id;
private String description; private String description;
private String name; private String name;
private Long dateOfCreation; private Long dateOfCreation;
@ -37,6 +38,15 @@ public class DeviceGroup implements Serializable {
private List<GroupUser> users; private List<GroupUser> users;
private List<String> roles; private List<String> roles;
@XmlElement
public int getId() {
return id;
}
protected void setId(int id) {
this.id = id;
}
@XmlElement @XmlElement
public String getDescription() { public String getDescription() {
return description; return description;

@ -34,6 +34,7 @@ public class DeviceGroupBuilder extends DeviceGroup {
* @param deviceGroup to decorate * @param deviceGroup to decorate
*/ */
public DeviceGroupBuilder(DeviceGroup deviceGroup) { public DeviceGroupBuilder(DeviceGroup deviceGroup) {
this.setId(deviceGroup.getId());
this.setDescription(deviceGroup.getDescription()); this.setDescription(deviceGroup.getDescription());
this.setName(deviceGroup.getName()); this.setName(deviceGroup.getName());
this.setDateOfCreation(deviceGroup.getDateOfCreation()); this.setDateOfCreation(deviceGroup.getDateOfCreation());
@ -43,6 +44,11 @@ public class DeviceGroupBuilder extends DeviceGroup {
this.setRoles(deviceGroup.getRoles()); this.setRoles(deviceGroup.getRoles());
} }
@Override
public void setId(int id) {
super.setId(id);
}
@Override @Override
public void setUsers(List<GroupUser> users) { public void setUsers(List<GroupUser> users) {
super.setUsers(users); super.setUsers(users);

@ -20,7 +20,10 @@ package org.wso2.carbon.device.mgt.core.group.mgt.dao;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
import java.util.List; import java.util.List;
@ -31,44 +34,44 @@ import java.util.Set;
*/ */
public interface GroupDAO { public interface GroupDAO {
/** /**
* Add new Device Group * Add new Device Group.
* *
* @param deviceGroup to be added * @param deviceGroup to be added.
* @param tenantId of the group * @param tenantId of the group.
* @return sql execution result * @return sql execution result.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
int addGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException; int addGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException;
/** /**
* Update an existing Device Group * Update an existing Device Group.
* *
* @param deviceGroup group to update * @param deviceGroup group to update.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
void updateGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException; void updateGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException;
/** /**
* Delete an existing Device Group * Delete an existing Device Group.
* *
* @param groupName group Id to delete * @param groupId to be deleted.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
void deleteGroup(String groupName, int tenantId) throws GroupManagementDAOException; void deleteGroup(int groupId, int tenantId) throws GroupManagementDAOException;
/** /**
* Get device group by Id * Get device group by id.
* *
* @param groupName id of Device Group * @param groupId of Device Group.
* @return Device Group * @return Device Group in tenant with specified name.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
DeviceGroupBuilder getGroup(String groupName, int tenantId) throws GroupManagementDAOException; DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException;
/** /**
* Get the list of Device Groups in tenant. * Get the list of Device Groups in tenant.
* *
* @param tenantId of user's tenant * @param tenantId of user's tenant.
* @return List of all Device Groups in tenant. * @return List of all Device Groups in tenant.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
@ -77,25 +80,81 @@ public interface GroupDAO {
/** /**
* Get the list of Groups that matches with the given DeviceGroup name. * Get the list of Groups that matches with the given DeviceGroup name.
* *
* @param groupName name of the Device Group. * @param groupName of the Device Group.
* @param tenantId of user's tenant * @param tenantId of user's tenant.
* @return List of DeviceGroup that matches with the given DeviceGroup name. * @return List of DeviceGroup that matches with the given DeviceGroup name.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
List<DeviceGroupBuilder> getGroups(String groupName, int tenantId) throws GroupManagementDAOException; List<DeviceGroupBuilder> findInGroups(String groupName, int tenantId) throws GroupManagementDAOException;
/**
* Check group already existed with given name.
*
* @param groupName of the Device Group.
* @param tenantId of user's tenant.
* @return existence of group with name
* @throws GroupManagementDAOException
*/
boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException; boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException;
void addDeviceToGroup(String groupName, Device device, int tenantId) throws GroupManagementDAOException; /**
* Add device to a given Device Group.
*
* @param groupId of the Device Group.
* @param deviceId of the device.
* @param tenantId of user's tenant.
* @throws GroupManagementDAOException
*/
void addDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException;
void addDevicesToGroup(String groupName, Set<Device> devices, int tenantId) throws GroupManagementDAOException; /**
* Remove device from the Device Group.
*
* @param groupId of the Device Group.
* @param deviceId of the device.
* @param tenantId of user's tenant.
* @throws GroupManagementDAOException
*/
void removeDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException;
void removeDeviceFromGroup(String groupName, DeviceIdentifier id, /**
int tenantId) throws GroupManagementDAOException; * Check device is belonging to a Device Group.
*
* @param groupId of the Device Group.
* @param deviceId of the device.
* @param tenantId of user's tenant.
* @throws GroupManagementDAOException
*/
boolean isDeviceMappedToGroup(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException;
boolean isDeviceMappedToGroup(String groupName, DeviceIdentifier id, /**
int tenantId) throws GroupManagementDAOException; * Get count of devices in a Device Group.
*
* @param groupId of the Device Group.
* @param tenantId of user's tenant.
* @return device count.
* @throws GroupManagementDAOException
*/
int getDeviceCount(int groupId, int tenantId) throws GroupManagementDAOException;
int getDeviceCount(String groupName, int tenantId) throws GroupManagementDAOException; /**
* Get all devices of a given tenant and device group.
*
* @param groupId of the group.
* @param tenantId of user's tenant.
* @return list of device in group
* @throws GroupManagementDAOException
*/
List<Device> getDevices(int groupId, int tenantId) throws GroupManagementDAOException;
/**
* Get all devices of a given tenant and device group.
*
* @param groupId of the group.
* @param tenantId of user's tenant.
* @param request for pagination.
* @return list of device in group
* @throws GroupManagementDAOException
*/
PaginationResult getDevices(int groupId, PaginationRequest request, int tenantId) throws GroupManagementDAOException;
} }

@ -19,7 +19,8 @@
package org.wso2.carbon.device.mgt.core.group.mgt.dao; package org.wso2.carbon.device.mgt.core.group.mgt.dao;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
@ -30,7 +31,6 @@ import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Set;
/** /**
* This class represents implementation of GroupDAO * This class represents implementation of GroupDAO
@ -44,9 +44,9 @@ public class GroupDAOImpl implements GroupDAO {
int groupId = -1; int groupId = -1;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, " String sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, "
+ "OWNER, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?)"; + "OWNER, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, new String[]{"id"}); stmt = conn.prepareStatement(sql, new String[]{"ID"});
stmt.setString(1, deviceGroup.getDescription()); stmt.setString(1, deviceGroup.getDescription());
stmt.setString(2, deviceGroup.getName()); stmt.setString(2, deviceGroup.getName());
stmt.setLong(3, new Date().getTime()); stmt.setLong(3, new Date().getTime());
@ -73,13 +73,13 @@ public class GroupDAOImpl implements GroupDAO {
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "UPDATE DM_GROUP SET DESCRIPTION = ?, GROUP_NAME = ?, DATE_OF_LAST_UPDATE = ?, OWNER = ? " String sql = "UPDATE DM_GROUP SET DESCRIPTION = ?, GROUP_NAME = ?, DATE_OF_LAST_UPDATE = ?, OWNER = ? "
+ "WHERE NAME = ? AND TENANT_ID = ?"; + "WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceGroup.getDescription()); stmt.setString(1, deviceGroup.getDescription());
stmt.setString(2, deviceGroup.getName()); stmt.setString(2, deviceGroup.getName());
stmt.setLong(3, deviceGroup.getDateOfLastUpdate()); stmt.setLong(3, deviceGroup.getDateOfLastUpdate());
stmt.setString(4, deviceGroup.getOwner()); stmt.setString(4, deviceGroup.getOwner());
stmt.setString(5, deviceGroup.getName()); stmt.setInt(5, deviceGroup.getId());
stmt.setInt(6, tenantId); stmt.setInt(6, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
@ -91,33 +91,46 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public void deleteGroup(String groupName, int tenantId) throws GroupManagementDAOException { public void deleteGroup(int groupId, int tenantId) throws GroupManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = GroupManagementDAOFactory.getConnection(); conn = GroupManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_GROUP WHERE NAME = ? AND TENANT_ID = ?"; String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, groupName); stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while removing mappings for group '" + groupId + "'", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, null);
}
try {
conn = GroupManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_GROUP WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while deleting group '" + groupName + "'", e); throw new GroupManagementDAOException("Error occurred while deleting group '" + groupId + "'", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, null); GroupManagementDAOUtil.cleanupResources(stmt, null);
} }
} }
@Override @Override
public DeviceGroupBuilder getGroup(String groupName, int tenantId) throws GroupManagementDAOException { public DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, OWNER " String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER "
+ "FROM DM_GROUP WHERE NAME = ? AND TENANT_ID = ?"; + "FROM DM_GROUP WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, groupName); stmt.setInt(1, groupId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
@ -127,7 +140,7 @@ public class GroupDAOImpl implements GroupDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while obtaining information of Device Group '" + throw new GroupManagementDAOException("Error occurred while obtaining information of Device Group '" +
groupName + "'", e); groupId + "'", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet); GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
} }
@ -140,7 +153,7 @@ public class GroupDAOImpl implements GroupDAO {
List<DeviceGroupBuilder> deviceGroupList = null; List<DeviceGroupBuilder> deviceGroupList = null;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, OWNER " String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER "
+ "FROM DM_GROUP WHERE TENANT_ID = ?"; + "FROM DM_GROUP WHERE TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
@ -158,14 +171,14 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public List<DeviceGroupBuilder> getGroups(String groupName, int tenantId) public List<DeviceGroupBuilder> findInGroups(String groupName, int tenantId)
throws GroupManagementDAOException { throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<DeviceGroupBuilder> deviceGroups = new ArrayList<>(); List<DeviceGroupBuilder> deviceGroups = new ArrayList<>();
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, OWNER " String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER "
+ "FROM DM_GROUP WHERE GROUP_NAME LIKE ? AND TENANT_ID = ?"; + "FROM DM_GROUP WHERE GROUP_NAME LIKE ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, "%" + groupName + "%"); stmt.setString(1, "%" + groupName + "%");
@ -186,49 +199,118 @@ public class GroupDAOImpl implements GroupDAO {
@Override @Override
public boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException { public boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rst = null; ResultSet resultSet = null;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID FROM DM_GROUP WHERE GROUP_NAME = ? AND TENANT_ID = ?"; String sql = "SELECT ID FROM DM_GROUP WHERE GROUP_NAME = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, groupName); stmt.setString(1, groupName);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
rst = stmt.executeQuery(); resultSet = stmt.executeQuery();
return rst.next(); return resultSet.next();
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" + throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" +
groupName + "'", e); groupName + "'", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, rst); GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
} }
} }
@Override @Override
public void addDeviceToGroup(String group, Device device, int tenantId) throws GroupManagementDAOException { public void addDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_DEVICE_GROUP_MAP(DEVICE_ID, GROUP_ID, TENANT_ID) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, groupId);
stmt.setInt(3, tenantId);
stmt.executeUpdate();
stmt.getGeneratedKeys();
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while adding device to Group '" + groupId + "'", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, null);
}
} }
@Override @Override
public void addDevicesToGroup(String group, Set<Device> devices, public void removeDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException {
int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ? AND GROUP_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, groupId);
stmt.setInt(3, tenantId);
stmt.executeUpdate();
stmt.getGeneratedKeys();
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while removing device from Group '" +
groupId + "'", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, null);
}
} }
@Override @Override
public void removeDeviceFromGroup(String group, DeviceIdentifier id, public boolean isDeviceMappedToGroup(int groupId, int deviceId, int tenantId)
int tenantId) throws GroupManagementDAOException { throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ? AND GROUP_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, groupId);
stmt.setInt(3, tenantId);
resultSet = stmt.executeQuery();
return resultSet.next();
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" +
groupId + "'", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
}
@Override
public int getDeviceCount(int groupId, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT COUNT(ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? " +
"AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
return resultSet.getInt("DEVICE_COUNT");
} else {
return 0;
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" +
groupId + "'", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
} }
@Override @Override
public boolean isDeviceMappedToGroup(String group, DeviceIdentifier id, public List<Device> getDevices(int groupId, int tenantId) throws GroupManagementDAOException {
int tenantId) throws GroupManagementDAOException { return null;
return false;
} }
@Override @Override
public int getDeviceCount(String groupName, int tenantId) throws GroupManagementDAOException { public PaginationResult getDevices(int groupId, PaginationRequest request, int tenantId)
return 0; throws GroupManagementDAOException {
return null;
} }
} }

@ -82,9 +82,10 @@ public final class GroupManagementDAOUtil {
public static DeviceGroupBuilder loadGroup(ResultSet resultSet) throws SQLException { public static DeviceGroupBuilder loadGroup(ResultSet resultSet) throws SQLException {
DeviceGroupBuilder group = new DeviceGroupBuilder(new DeviceGroup()); DeviceGroupBuilder group = new DeviceGroupBuilder(new DeviceGroup());
group.setId(resultSet.getInt("ID"));
group.setDescription(resultSet.getString("DESCRIPTION")); group.setDescription(resultSet.getString("DESCRIPTION"));
group.setName(resultSet.getString("GROUP_NAME")); group.setName(resultSet.getString("GROUP_NAME"));
group.setDateOfCreation(resultSet.getLong("DATE_OF_ENROLLMENT")); group.setDateOfCreation(resultSet.getLong("DATE_OF_CREATE"));
group.setDateOfLastUpdate(resultSet.getLong("DATE_OF_LAST_UPDATE")); group.setDateOfLastUpdate(resultSet.getLong("DATE_OF_LAST_UPDATE"));
group.setOwner(resultSet.getString("OWNER")); group.setOwner(resultSet.getString("OWNER"));
return group; return group;

@ -50,6 +50,8 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOF
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer; import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer;
import org.wso2.carbon.email.sender.core.service.EmailSenderService; import org.wso2.carbon.email.sender.core.service.EmailSenderService;
import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.ndatasource.core.DataSourceService;
@ -181,6 +183,10 @@ public class DeviceManagementServiceComponent {
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProvider); DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProvider);
bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null); bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null);
/* Registering Group Management Service */
GroupManagementProviderService groupManagementProvider = new GroupManagementProviderServiceImpl();
bundleContext.registerService(GroupManagementProviderService.class.getName(), groupManagementProvider, null);
/* Registering Tenant Configuration Management Service */ /* Registering Tenant Configuration Management Service */
TenantConfigurationManagementService TenantConfigurationManagementService
tenantConfiguration = new TenantConfigurationManagementServiceImpl(); tenantConfiguration = new TenantConfigurationManagementServiceImpl();

@ -31,7 +31,7 @@ import java.util.List;
/** /**
* Interface for Group Management Services * Interface for Group Management Services
*/ */
public interface GroupManagementServiceProvider { public interface GroupManagementProviderService {
/** /**
* Add new device group and create default role with default permissions * Add new device group and create default role with default permissions
@ -56,19 +56,19 @@ public interface GroupManagementServiceProvider {
/** /**
* Delete existing device group * Delete existing device group
* *
* @param groupName of the group to delete * @param groupId of the group to delete
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean deleteGroup(String groupName) throws GroupManagementException; boolean deleteGroup(int groupId) throws GroupManagementException;
/** /**
* Get device group specified by groupId * Get device group specified by groupId
* *
* @param groupName of the group of the group * @param groupId of the group of the group
* @return group * @return group
* @throws GroupManagementException * @throws GroupManagementException
*/ */
DeviceGroup getGroup(String groupName) throws GroupManagementException; DeviceGroup getGroup(int groupId) throws GroupManagementException;
/** /**
* Get list of device groups matched with %groupName% * Get list of device groups matched with %groupName%
@ -78,7 +78,7 @@ public interface GroupManagementServiceProvider {
* @return List of Groups that matches with the given DeviceGroup name. * @return List of Groups that matches with the given DeviceGroup name.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<DeviceGroup> findGroups(String groupName, String username) throws GroupManagementException; List<DeviceGroup> findInGroups(String groupName, String username) throws GroupManagementException;
/** /**
* Get device groups of user * Get device groups of user
@ -102,134 +102,134 @@ public interface GroupManagementServiceProvider {
* Share device group with user specified by role * Share device group with user specified by role
* *
* @param username of the user * @param username of the user
* @param groupName of the group of the group * @param groupId of the group of the group
* @param sharingRole to be shared * @param sharingRole to be shared
* @return is group shared * @return is group shared
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean shareGroup(String username, String groupName, String sharingRole) boolean shareGroup(String username, int groupId, String sharingRole)
throws GroupManagementException; throws GroupManagementException;
/** /**
* Un share existing group sharing with user specified by role * Un share existing group sharing with user specified by role
* *
* @param userName of the user * @param userName of the user
* @param groupName of the group of the group * @param groupId of the group of the group
* @param sharingRole to be un shared * @param sharingRole to be un shared
* @return is group un shared * @return is group un shared
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean unshareGroup(String userName, String groupName, String sharingRole) boolean unshareGroup(String userName, int groupId, String sharingRole)
throws GroupManagementException; throws GroupManagementException;
/** /**
* Add new sharing role for device group * Add new sharing role for device group
* *
* @param userName of the user * @param userName of the user
* @param groupName of the group * @param groupId of the group
* @param roleName to add * @param roleName to add
* @param permissions to bind with role * @param permissions to bind with role
* @return is role added * @return is role added
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean addGroupSharingRole(String userName, String groupName, String roleName, String[] permissions) boolean addGroupSharingRole(String userName, int groupId, String roleName, String[] permissions)
throws GroupManagementException; throws GroupManagementException;
/** /**
* Remove existing sharing role for device group * Remove existing sharing role for device group
* *
* @param groupName of the group * @param groupId of the group
* @param roleName to remove * @param roleName to remove
* @return is role removed * @return is role removed
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean removeGroupSharingRole(String groupName, String roleName) throws GroupManagementException; boolean removeGroupSharingRole(int groupId, String roleName) throws GroupManagementException;
/** /**
* Get all sharing roles for device group * Get all sharing roles for device group
* *
* @param groupName of the group * @param groupId of the group
* @return list of roles * @return list of roles
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<String> getRoles(String groupName) throws GroupManagementException; List<String> getRoles(int groupId) throws GroupManagementException;
/** /**
* Get specific device group sharing roles for user * Get specific device group sharing roles for user
* *
* @param userName of the user * @param userName of the user
* @param groupName of the group * @param groupId of the group
* @return list of roles * @return list of roles
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<String> getRoles(String userName, String groupName) throws GroupManagementException; List<String> getRoles(String userName, int groupId) throws GroupManagementException;
/** /**
* Get device group users * Get device group users
* *
* @param groupName of the group * @param groupId of the group
* @return list of group users * @return list of group users
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<GroupUser> getUsers(String groupName) throws GroupManagementException; List<GroupUser> getUsers(int groupId) throws GroupManagementException;
/** /**
* Get all devices in device group * Get all devices in device group
* *
* @param groupName of the group * @param groupId of the group
* @return list of group devices * @return list of group devices
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<Device> getDevices(String groupName) throws GroupManagementException; List<Device> getDevices(int groupId) throws GroupManagementException;
/** /**
* Get all devices in device group * Get all devices in device group
* *
* @param groupName of the group * @param groupId of the group
* @param request PaginationRequest object holding the data for pagination * @param request PaginationRequest object holding the data for pagination
* @return list of group devices * @return list of group devices
* @throws GroupManagementException * @throws GroupManagementException
*/ */
PaginationResult getDevices(String groupName, PaginationRequest request) throws GroupManagementException; PaginationResult getDevices(int groupId, PaginationRequest request) throws GroupManagementException;
/** /**
* This method is used to retrieve the device count of a given group. * This method is used to retrieve the device count of a given group.
* *
* @param groupName Name of the group * @param groupId Name of the group
* @return returns the device count. * @return returns the device count.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
int getDeviceCount(String groupName) throws GroupManagementException; int getDeviceCount(int groupId) throws GroupManagementException;
/** /**
* Add device to device group * Add device to device group
* *
* @param deviceId of the device * @param deviceId of the device
* @param groupName of the group * @param groupId of the group
* @return is device added * @return is device added
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean addDevice(DeviceIdentifier deviceId, String groupName) throws GroupManagementException; boolean addDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException;
/** /**
* Remove device from device group * Remove device from device group
* *
* @param deviceId of the device * @param deviceId of the device
* @param groupName of the group * @param groupId of the group
* @return is device removed * @return is device removed
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean removeDevice(DeviceIdentifier deviceId, String groupName) throws GroupManagementException; boolean removeDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException;
/** /**
* Get device group permissions of user * Get device group permissions of user
* *
* @param username of the user * @param username of the user
* @param groupName of the group * @param groupId of the group
* @return array of permissions * @return array of permissions
* @throws GroupManagementException * @throws GroupManagementException
*/ */
String[] getPermissions(String username, String groupName) throws GroupManagementException; String[] getPermissions(String username, int groupId) throws GroupManagementException;
/** /**
* Get device groups of user with permission * Get device groups of user with permission
@ -245,11 +245,11 @@ public interface GroupManagementServiceProvider {
* Check user is authorized for specific permission of device group * Check user is authorized for specific permission of device group
* *
* @param username of the user * @param username of the user
* @param groupName to authorize * @param groupId to authorize
* @param permission to authorize * @param permission to authorize
* @return is user authorized for permission * @return is user authorized for permission
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean isAuthorized(String username, String groupName, String permission) throws GroupManagementException; boolean isAuthorized(String username, int groupId, String permission) throws GroupManagementException;
} }

@ -22,7 +22,12 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
@ -38,18 +43,21 @@ import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.carbon.user.core.util.UserCoreUtil;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GroupManagementServiceProviderImpl implements GroupManagementServiceProvider { public class GroupManagementProviderServiceImpl implements GroupManagementProviderService {
private static Log log = LogFactory.getLog(GroupManagementServiceProviderImpl.class); private static Log log = LogFactory.getLog(GroupManagementProviderServiceImpl.class);
private GroupDAO groupDAO; private GroupDAO groupDAO;
/** /**
* Set groupDAO from GroupManagementDAOFactory when class instantiate. * Set groupDAO from GroupManagementDAOFactory when class instantiate.
*/ */
public GroupManagementServiceProviderImpl() { public GroupManagementProviderServiceImpl() {
this.groupDAO = GroupManagementDAOFactory.getGroupDAO(); this.groupDAO = GroupManagementDAOFactory.getGroupDAO();
} }
@ -71,6 +79,10 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
if (!nameIsExists) { if (!nameIsExists) {
groupId = this.groupDAO.addGroup(groupBroker, tenantId); groupId = this.groupDAO.addGroup(groupBroker, tenantId);
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
if (groupId < 0) {
return -1;
}
groupBroker.setId(groupId);
} else { } else {
return -2; return -2;
} }
@ -83,10 +95,8 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
if (groupId == -1) {
return -1; addGroupSharingRole(groupBroker.getOwner(), groupId, defaultRole, defaultPermissions);
}
addGroupSharingRole(groupBroker.getOwner(), deviceGroup.getName(), defaultRole, defaultPermissions);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("DeviceGroup added: " + groupBroker.getName()); log.debug("DeviceGroup added: " + groupBroker.getName());
} }
@ -120,30 +130,22 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean deleteGroup(String groupName) throws GroupManagementException { public boolean deleteGroup(int groupId) throws GroupManagementException {
String roleName; String roleName;
DeviceGroup deviceGroup = getGroup(groupName); DeviceGroup deviceGroup = getGroup(groupId);
if (deviceGroup == null) { if (deviceGroup == null) {
return false; return false;
} }
List<String> groupRoles = getRoles(groupName); List<String> groupRoles = getRoles(groupId);
for (String role : groupRoles) { for (String role : groupRoles) {
if (role != null) { if (role != null) {
roleName = role.replace("Internal/group-" + groupName + "-", ""); roleName = role.replace("Internal/group-" + groupId + "-", "");
removeGroupSharingRole(groupName, roleName); removeGroupSharingRole(groupId, roleName);
} }
} }
List<Device> groupDevices = getDevices(groupName);
try {
for (Device device : groupDevices) {
DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device);
}
} catch (DeviceManagementException e) {
throw new GroupManagementException("Error occurred while removing device from group.", e);
}
try { try {
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
this.groupDAO.deleteGroup(groupName, CarbonContext.getThreadLocalCarbonContext().getTenantId()); this.groupDAO.deleteGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId());
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("DeviceGroup " + deviceGroup.getName() + " removed."); log.debug("DeviceGroup " + deviceGroup.getName() + " removed.");
@ -152,7 +154,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction(); GroupManagementDAOFactory.rollbackTransaction();
throw new GroupManagementException("Error occurred while removing group " + throw new GroupManagementException("Error occurred while removing group " +
"'" + groupName + "' data.", e); "'" + groupId + "' data.", e);
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
throw new GroupManagementException("Error occurred while initiating transaction.", e); throw new GroupManagementException("Error occurred while initiating transaction.", e);
} finally { } finally {
@ -164,21 +166,21 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public DeviceGroup getGroup(String groupName) throws GroupManagementException { public DeviceGroup getGroup(int groupId) throws GroupManagementException {
DeviceGroupBuilder groupBroker; DeviceGroupBuilder groupBroker;
try { try {
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
groupBroker = this.groupDAO.getGroup(groupName, CarbonContext.getThreadLocalCarbonContext().getTenantId()); groupBroker = this.groupDAO.getGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId());
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while obtaining group " + groupName, e); throw new GroupManagementException("Error occurred while obtaining group " + groupId, e);
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementException("Error occurred while opening a connection to the data source.", e); throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
if (groupBroker != null) { if (groupBroker != null) {
groupBroker.setUsers(this.getUsers(groupName)); groupBroker.setUsers(this.getUsers(groupId));
groupBroker.setRoles(this.getRoles(groupName)); groupBroker.setRoles(this.getRoles(groupId));
return groupBroker.getGroup(); return groupBroker.getGroup();
} else { } else {
return null; return null;
@ -189,12 +191,12 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<DeviceGroup> findGroups(String groupName, String owner) throws GroupManagementException { public List<DeviceGroup> findInGroups(String groupName, String owner) throws GroupManagementException {
List<DeviceGroupBuilder> deviceGroups = new ArrayList<>(); List<DeviceGroupBuilder> deviceGroups = new ArrayList<>();
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
deviceGroups = this.groupDAO.getGroups(groupName, tenantId); deviceGroups = this.groupDAO.findInGroups(groupName, tenantId);
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while finding group " + groupName, e); throw new GroupManagementException("Error occurred while finding group " + groupName, e);
} catch (SQLException e) { } catch (SQLException e) {
@ -204,8 +206,8 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
} }
List<DeviceGroup> groupsWithData = new ArrayList<>(); List<DeviceGroup> groupsWithData = new ArrayList<>();
for (DeviceGroupBuilder groupBroker : deviceGroups) { for (DeviceGroupBuilder groupBroker : deviceGroups) {
groupBroker.setUsers(this.getUsers(groupBroker.getName())); groupBroker.setUsers(this.getUsers(groupBroker.getId()));
groupBroker.setRoles(this.getRoles(groupBroker.getName())); groupBroker.setRoles(this.getRoles(groupBroker.getId()));
groupsWithData.add(groupBroker.getGroup()); groupsWithData.add(groupBroker.getGroup());
} }
return groupsWithData; return groupsWithData;
@ -222,13 +224,12 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager(); .getUserStoreManager();
String[] roleList = userStoreManager.getRoleListOfUser(username); String[] roleList = userStoreManager.getRoleListOfUser(username);
Map<String, DeviceGroup> groups = new HashMap<>(); Map<Integer, DeviceGroup> groups = new HashMap<>();
for (String role : roleList) { for (String role : roleList) {
if (role != null && role.contains("Internal/group-")) { if (role != null && role.contains("Internal/group-")) {
String groupName = role.split("-")[1]; DeviceGroup deviceGroup = extractNewGroupFromRole(groups, role);
if (!groups.containsKey(groupName)) { if (deviceGroup != null) {
DeviceGroup deviceGroup = getGroup(groupName); groups.put(deviceGroup.getId(), deviceGroup);
groups.put(groupName, deviceGroup);
} }
} }
} }
@ -250,66 +251,39 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean shareGroup(String username, String groupName, String sharingRole) public boolean shareGroup(String username, int groupId, String sharingRole)
throws GroupManagementException { throws GroupManagementException {
return modifyGroupShare(username, groupName, sharingRole, true); return modifyGroupShare(username, groupId, sharingRole, true);
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean unshareGroup(String username, String groupName, String sharingRole) public boolean unshareGroup(String username, int groupId, String sharingRole)
throws GroupManagementException { throws GroupManagementException {
return modifyGroupShare(username, groupName, sharingRole, false); return modifyGroupShare(username, groupId, sharingRole, false);
}
private boolean modifyGroupShare(String username, String groupName, String sharingRole,
boolean isAddNew)
throws GroupManagementException {
UserStoreManager userStoreManager;
String[] roles = new String[1];
try {
DeviceGroup deviceGroup = getGroup(groupName);
if (deviceGroup == null) {
return false;
}
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager =
DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
tenantId).getUserStoreManager();
roles[0] = "Internal/group-" + groupName + "-" + sharingRole;
if (isAddNew) {
userStoreManager.updateRoleListOfUser(username, null, roles);
} else {
userStoreManager.updateRoleListOfUser(username, roles, null);
}
return true;
} catch (UserStoreException e) {
throw new GroupManagementException("User store error in adding user " + username + " to group name:" +
groupName, e);
}
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean addGroupSharingRole(String username, String groupName, String roleName, public boolean addGroupSharingRole(String username, int groupId, String roleName,
String[] permissions) String[] permissions)
throws GroupManagementException { throws GroupManagementException {
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
String role; String role;
String[] userNames = new String[1]; String[] userNames = new String[1];
try { try {
DeviceGroup deviceGroup = getGroup(groupName); DeviceGroup deviceGroup = getGroup(groupId);
if (deviceGroup == null) { if (deviceGroup == null) {
return false; return false;
} }
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager(); .getUserStoreManager();
role = "Internal/group-" + groupName + "-" + roleName; role = "Internal/group-" + groupId + "-" + roleName;
userNames[0] = username; userNames[0] = username;
Permission[] carbonPermissions = new Permission[permissions.length]; Permission[] carbonPermissions = new Permission[permissions.length];
for (int i = 0; i < permissions.length; i++) { for (int i = 0; i < permissions.length; i++) {
@ -318,8 +292,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
userStoreManager.addRole(role, userNames, carbonPermissions); userStoreManager.addRole(role, userNames, carbonPermissions);
return true; return true;
} catch (UserStoreException e) { } catch (UserStoreException e) {
String errorMsg = "User store error in adding role to group id:" + groupName; String errorMsg = "User store error in adding role to group id:" + groupId;
log.error(errorMsg, e);
throw new GroupManagementException(errorMsg, e); throw new GroupManagementException(errorMsg, e);
} }
} }
@ -328,23 +301,23 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean removeGroupSharingRole(String groupName, String roleName) public boolean removeGroupSharingRole(int groupId, String roleName)
throws GroupManagementException { throws GroupManagementException {
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
String role; String role;
try { try {
DeviceGroup deviceGroup = getGroup(groupName); DeviceGroup deviceGroup = getGroup(groupId);
if (deviceGroup == null) { if (deviceGroup == null) {
return false; return false;
} }
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager(); .getUserStoreManager();
role = "Internal/group-" + groupName + "-" + roleName; role = "Internal/group-" + groupId + "-" + roleName;
userStoreManager.deleteRole(role); userStoreManager.deleteRole(role);
return true; return true;
} catch (UserStoreException userStoreEx) { } catch (UserStoreException userStoreEx) {
String errorMsg = "User store error in adding role to group id:" + groupName; String errorMsg = "User store error in adding role to group id:" + groupId;
log.error(errorMsg, userStoreEx); log.error(errorMsg, userStoreEx);
throw new GroupManagementException(errorMsg, userStoreEx); throw new GroupManagementException(errorMsg, userStoreEx);
} }
@ -354,7 +327,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<String> getRoles(String groupName) throws GroupManagementException { public List<String> getRoles(int groupId) throws GroupManagementException {
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
String[] roles; String[] roles;
List<String> groupRoles; List<String> groupRoles;
@ -365,13 +338,13 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
roles = userStoreManager.getRoleNames(); roles = userStoreManager.getRoleNames();
groupRoles = new ArrayList<>(); groupRoles = new ArrayList<>();
for (String r : roles) { for (String r : roles) {
if (r != null && r.contains("Internal/group-" + groupName + "-")) { if (r != null && r.contains("Internal/group-" + groupId + "-")) {
groupRoles.add(r.replace("Internal/group-" + groupName + "-", "")); groupRoles.add(r.replace("Internal/group-" + groupId + "-", ""));
} }
} }
return groupRoles; return groupRoles;
} catch (UserStoreException userStoreEx) { } catch (UserStoreException userStoreEx) {
String errorMsg = "User store error in adding role to group id:" + groupName; String errorMsg = "User store error in adding role to group id:" + groupId;
log.error(errorMsg, userStoreEx); log.error(errorMsg, userStoreEx);
throw new GroupManagementException(errorMsg, userStoreEx); throw new GroupManagementException(errorMsg, userStoreEx);
} }
@ -381,7 +354,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<String> getRoles(String username, String groupName) throws GroupManagementException { public List<String> getRoles(String username, int groupId) throws GroupManagementException {
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
List<String> groupRoleList = new ArrayList<>(); List<String> groupRoleList = new ArrayList<>();
try { try {
@ -390,8 +363,8 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
.getUserStoreManager(); .getUserStoreManager();
String[] roleList = userStoreManager.getRoleListOfUser(username); String[] roleList = userStoreManager.getRoleListOfUser(username);
for (String role : roleList) { for (String role : roleList) {
if (role != null && role.contains("Internal/group-" + groupName)) { if (role != null && role.contains("Internal/group-" + groupId)) {
String roleName = role.replace("Internal/group-" + groupName + "-", ""); String roleName = role.replace("Internal/group-" + groupId + "-", "");
groupRoleList.add(roleName); groupRoleList.add(roleName);
} }
} }
@ -405,16 +378,16 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<GroupUser> getUsers(String groupName) throws GroupManagementException { public List<GroupUser> getUsers(int groupId) throws GroupManagementException {
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
Map<String, GroupUser> groupUserHashMap = new HashMap<>(); Map<String, GroupUser> groupUserHashMap = new HashMap<>();
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager(); .getUserStoreManager();
List<String> rolesForGroup = this.getRoles(groupName); List<String> rolesForGroup = this.getRoles(groupId);
for (String role : rolesForGroup) { for (String role : rolesForGroup) {
String[] users = userStoreManager.getUserListOfRole("Internal/group-" + groupName + "-" + role); String[] users = userStoreManager.getUserListOfRole("Internal/group-" + groupId + "-" + role);
for (String user : users) { for (String user : users) {
GroupUser groupUser; GroupUser groupUser;
if (groupUserHashMap.containsKey(user)) { if (groupUserHashMap.containsKey(user)) {
@ -431,7 +404,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
} }
return new ArrayList<>(groupUserHashMap.values()); return new ArrayList<>(groupUserHashMap.values());
} catch (UserStoreException e) { } catch (UserStoreException e) {
String errorMsg = "User store error in fetching user list for group id:" + groupName; String errorMsg = "User store error in fetching user list for group id:" + groupId;
log.error(errorMsg, e); log.error(errorMsg, e);
throw new GroupManagementException(errorMsg, e); throw new GroupManagementException(errorMsg, e);
} }
@ -441,53 +414,45 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<Device> getDevices(String groupName) throws GroupManagementException { public List<Device> getDevices(int groupId) throws GroupManagementException {
return Collections.emptyList(); try {
//TODO: Add a method that returns a collection of devices in a particular group to GroupDAO int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
// try { return this.groupDAO.getDevices(groupId, tenantId);
// return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevices(groupName); } catch (GroupManagementDAOException e) {
// } catch (DeviceManagementException e) { throw new GroupManagementException("Error occurred while getting devices in group.", e);
// throw new GroupManagementException("Error occurred while getting devices in group.", e); }
// }
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public PaginationResult getDevices(String groupName, PaginationRequest request) public PaginationResult getDevices(int groupId, PaginationRequest request)
throws GroupManagementException { throws GroupManagementException {
return null; int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
//TODO: Add a method that returns a collection of devices in a particular group to GroupDAO try {
// try { return this.groupDAO.getDevices(groupId, request, tenantId);
// return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevices(groupName); } catch (GroupManagementDAOException e) {
// } catch (DeviceManagementException e) { throw new GroupManagementException("Error occurred while getting devices in group.", e);
// throw new GroupManagementException("Error occurred while getting devices in group.", e); }
// }
// try {
// return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevices(groupName,
// request);
// } catch (DeviceManagementException e) {
// throw new GroupManagementException("Error occurred while getting devices in group.", e);
// }
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public int getDeviceCount(String groupName) throws GroupManagementException { public int getDeviceCount(int groupId) throws GroupManagementException {
try { try {
int count; int count;
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
count = groupDAO.getDeviceCount(groupName, count = groupDAO.getDeviceCount(groupId,
CarbonContext.getThreadLocalCarbonContext().getTenantId()); CarbonContext.getThreadLocalCarbonContext().getTenantId());
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
return count; return count;
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction(); GroupManagementDAOFactory.rollbackTransaction();
throw new GroupManagementException("Error occurred while retrieving device count of group " + throw new GroupManagementException("Error occurred while retrieving device count of group " +
"'" + groupName + "'.", e); "'" + groupId + "'.", e);
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
throw new GroupManagementException("Error occurred while initiating transaction.", e); throw new GroupManagementException("Error occurred while initiating transaction.", e);
} finally { } finally {
@ -499,19 +464,22 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean addDevice(DeviceIdentifier deviceId, String groupName) public boolean addDevice(DeviceIdentifier deviceIdentifier, int groupId)
throws GroupManagementException { throws GroupManagementException {
Device device; Device device;
DeviceGroup deviceGroup; DeviceGroup deviceGroup;
try { try {
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId); device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier);
deviceGroup = this.getGroup(groupName); deviceGroup = this.getGroup(groupId);
if (device == null || deviceGroup == null) { if (device == null || deviceGroup == null) {
return false; return false;
} }
DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
this.groupDAO.addDevice(groupId, device.getId(), tenantId);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
throw new GroupManagementException("Error occurred while adding device in to deviceGroup.", e); throw new GroupManagementException("Error occurred while retrieving device.", e);
} catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while adding device to group '" + groupId + "'.", e);
} }
return true; return true;
} }
@ -520,19 +488,22 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean removeDevice(DeviceIdentifier deviceId, String groupName) public boolean removeDevice(DeviceIdentifier deviceIdentifier, int groupId)
throws GroupManagementException { throws GroupManagementException {
Device device; Device device;
DeviceGroup deviceGroup; DeviceGroup deviceGroup;
try { try {
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId); device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier);
deviceGroup = this.getGroup(groupName); deviceGroup = this.getGroup(groupId);
if (device == null || deviceGroup == null) { if (device == null || deviceGroup == null) {
return false; return false;
} }
DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
this.groupDAO.removeDevice(groupId, device.getId(), tenantId);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
throw new GroupManagementException("Error occurred while removing device from deviceGroup.", e); throw new GroupManagementException("Error occurred while retrieving device.", e);
} catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while adding device to group '" + groupId + "'.", e);
} }
return true; return true;
} }
@ -541,9 +512,9 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public String[] getPermissions(String username, String groupName) throws GroupManagementException { public String[] getPermissions(String username, int groupId) throws GroupManagementException {
UserRealm userRealm; UserRealm userRealm;
List<String> roles = getRoles(username, groupName); List<String> roles = getRoles(username, groupId);
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try { try {
userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
@ -553,7 +524,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
for (String resourceId : resourceIds) { for (String resourceId : resourceIds) {
for (String roleName : roles) { for (String roleName : roles) {
if (userRealm.getAuthorizationManager(). if (userRealm.getAuthorizationManager().
isRoleAuthorized("Internal/group-" + groupName + "-" + roleName, resourceId, isRoleAuthorized("Internal/group-" + groupId + "-" + roleName, resourceId,
CarbonConstants.UI_PERMISSION_ACTION)) { CarbonConstants.UI_PERMISSION_ACTION)) {
lstPermissions.add(resourceId); lstPermissions.add(resourceId);
} }
@ -575,17 +546,16 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
throws GroupManagementException { throws GroupManagementException {
UserRealm userRealm; UserRealm userRealm;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, DeviceGroup> groups = new HashMap<>(); Map<Integer, DeviceGroup> groups = new HashMap<>();
try { try {
userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
String[] roles = userRealm.getUserStoreManager().getRoleListOfUser(username); String[] roles = userRealm.getUserStoreManager().getRoleListOfUser(username);
for (String role : roles) { for (String role : roles) {
if (role != null && role.contains("Internal/group-") && userRealm.getAuthorizationManager() if (role != null && role.contains("Internal/group-") && userRealm.getAuthorizationManager()
.isRoleAuthorized(role, permission, CarbonConstants.UI_PERMISSION_ACTION)) { .isRoleAuthorized(role, permission, CarbonConstants.UI_PERMISSION_ACTION)) {
String groupName = role.split("-")[1]; DeviceGroup deviceGroup = extractNewGroupFromRole(groups, role);
if (!groups.containsKey(groupName)) { if (deviceGroup != null) {
DeviceGroup deviceGroup = getGroup(groupName); groups.put(deviceGroup.getId(), deviceGroup);
groups.put(groupName, deviceGroup);
} }
} }
} }
@ -599,16 +569,16 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean isAuthorized(String username, String groupName, String permission) public boolean isAuthorized(String username, int groupId, String permission)
throws GroupManagementException { throws GroupManagementException {
UserRealm userRealm; UserRealm userRealm;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try { try {
userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
List<String> roles = this.getRoles(username, groupName); List<String> roles = this.getRoles(username, groupId);
for (String role : roles) { for (String role : roles) {
if (userRealm.getAuthorizationManager() if (userRealm.getAuthorizationManager()
.isRoleAuthorized("Internal/group-" + groupName + "-" + role, permission, .isRoleAuthorized("Internal/group-" + groupId + "-" + role, permission,
CarbonConstants.UI_PERMISSION_ACTION)) { CarbonConstants.UI_PERMISSION_ACTION)) {
return true; return true;
} }
@ -619,4 +589,44 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
} }
} }
private boolean modifyGroupShare(String username, int groupId, String sharingRole,
boolean isAddNew)
throws GroupManagementException {
UserStoreManager userStoreManager;
String[] roles = new String[1];
try {
DeviceGroup deviceGroup = getGroup(groupId);
if (deviceGroup == null) {
return false;
}
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager =
DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
tenantId).getUserStoreManager();
roles[0] = "Internal/group-" + groupId + "-" + sharingRole;
if (isAddNew) {
userStoreManager.updateRoleListOfUser(username, null, roles);
} else {
userStoreManager.updateRoleListOfUser(username, roles, null);
}
return true;
} catch (UserStoreException e) {
throw new GroupManagementException("User store error in adding user " + username + " to group name:" +
groupId, e);
}
}
private DeviceGroup extractNewGroupFromRole(Map<Integer, DeviceGroup> groups, String role)
throws GroupManagementException {
try {
int groupId = Integer.parseInt(role.split("-")[1]);
if (!groups.containsKey(groupId)) {
return getGroup(groupId);
}
} catch (NumberFormatException e) {
log.error("Unable to extract groupId from role " + role, e);
}
return null;
}
} }

@ -31,6 +31,7 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.TestUtils; import org.wso2.carbon.device.mgt.core.TestUtils;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import javax.sql.DataSource; import javax.sql.DataSource;
@ -58,6 +59,7 @@ public abstract class BaseDeviceManagementTest {
public void initDataSource() throws Exception { public void initDataSource() throws Exception {
this.dataSource = this.getDataSource(this.readDataSourceConfig()); this.dataSource = this.getDataSource(this.readDataSourceConfig());
DeviceManagementDAOFactory.init(dataSource); DeviceManagementDAOFactory.init(dataSource);
GroupManagementDAOFactory.init(dataSource);
} }
@BeforeClass @BeforeClass
@ -135,6 +137,7 @@ public abstract class BaseDeviceManagementTest {
// this.cleanApplicationData(conn); // this.cleanApplicationData(conn);
// this.cleanupDeviceData(conn); // this.cleanupDeviceData(conn);
// this.cleanupDeviceTypeData(conn); // this.cleanupDeviceTypeData(conn);
this.cleanupGroupData(conn);
conn.commit(); conn.commit();
} catch (SQLException e) { } catch (SQLException e) {
@ -190,6 +193,12 @@ public abstract class BaseDeviceManagementTest {
} }
} }
private void cleanupGroupData(Connection conn) throws SQLException {
try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_GROUP")) {
stmt.execute();
}
}
public DataSource getDataSource() { public DataSource getDataSource() {
return dataSource; return dataSource;
} }

@ -18,7 +18,9 @@ package org.wso2.carbon.device.mgt.core.common;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
import java.util.Date; import java.util.Date;
import java.util.Properties; import java.util.Properties;
@ -30,6 +32,7 @@ public class TestDataHolder {
public static String TEST_DEVICE_TYPE = "Test"; public static String TEST_DEVICE_TYPE = "Test";
public static Integer SUPER_TENANT_ID = -1234; public static Integer SUPER_TENANT_ID = -1234;
public static String initialDeviceIdentifier = "12345"; public static String initialDeviceIdentifier = "12345";
public static String OWNER = "admin";
public static Device generateDummyDeviceData(String deviceType){ public static Device generateDummyDeviceData(String deviceType){
@ -37,12 +40,12 @@ public class TestDataHolder {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime()); enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setOwner("admin"); enrolmentInfo.setOwner(OWNER);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED); enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED);
device.setEnrolmentInfo(enrolmentInfo); device.setEnrolmentInfo(enrolmentInfo);
device.setDescription("Test Description"); device.setDescription("Test Description");
device.setDeviceIdentifier("12345"); device.setDeviceIdentifier(initialDeviceIdentifier);
device.setType(deviceType); device.setType(deviceType);
return device; return device;
} }
@ -70,4 +73,15 @@ public class TestDataHolder {
return application; return application;
} }
public static DeviceGroup generateDummyGroupData() {
DeviceGroup deviceGroup = new DeviceGroup();
deviceGroup.setName("Test device group");
deviceGroup.setDescription("Test description");
deviceGroup.setDateOfCreation(new Date().getTime());
deviceGroup.setDateOfLastUpdate(new Date().getTime());
deviceGroup.setOwner(OWNER);
DeviceGroupBuilder broker = new DeviceGroupBuilder(deviceGroup);
return broker.getGroup();
}
} }

@ -0,0 +1,204 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupDAO;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOException;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
public class GroupPersistTests extends BaseDeviceManagementTest {
private static final Log log = LogFactory.getLog(GroupPersistTests.class);
GroupDAO groupDAO = GroupManagementDAOFactory.getGroupDAO();
int groupId = -1;
@BeforeClass
@Override
public void init() {
try {
initDataSource();
} catch (Exception e) {
String msg = "Error occurred while initializing data source.";
log.error(msg, e);
Assert.fail(msg, e);
}
}
@Test
public void testAddGroupTest() {
DeviceGroup deviceGroup = TestDataHolder.generateDummyGroupData();
try {
GroupManagementDAOFactory.beginTransaction();
groupId = groupDAO.addGroup(deviceGroup, TestDataHolder.SUPER_TENANT_ID);
GroupManagementDAOFactory.commitTransaction();
log.debug("Group added to database.");
} catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while adding device type '" + deviceGroup.getName() + "'.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (TransactionManagementException e) {
String msg = "Error occurred while initiating transaction.";
log.error(msg, e);
Assert.fail(msg, e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
DeviceGroup group = getGroupById(groupId);
Assert.assertNotNull(group, "Group is null");
log.debug("Group name: " + group.getName());
}
public DeviceGroup getGroupById(int groupId) {
try {
GroupManagementDAOFactory.openConnection();
return groupDAO.getGroup(groupId, TestDataHolder.SUPER_TENANT_ID);
} catch (GroupManagementDAOException e) {
String msg = "Error occurred while retrieving group details.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source.";
log.error(msg, e);
Assert.fail(msg, e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
return null;
}
@Test(dependsOnMethods = {"testAddGroupTest"})
public void updateGroupTest() {
long time = new Date().getTime();
String name = "Test Updated";
String desc = "Desc updated";
DeviceGroup group = getGroupById(groupId);
Assert.assertNotNull(group, "Group is null");
group.setDateOfLastUpdate(time);
group.setName(name);
group.setDescription(desc);
try {
GroupManagementDAOFactory.beginTransaction();
groupDAO.updateGroup(group, TestDataHolder.SUPER_TENANT_ID);
GroupManagementDAOFactory.commitTransaction();
log.debug("Group updated");
} catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while updating group details.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (TransactionManagementException e) {
String msg = "Error occurred while initiating transaction.";
log.error(msg, e);
Assert.fail(msg, e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
group = getGroupById(group.getId());
Assert.assertNotNull(group, "Group is null");
Assert.assertEquals(group.getName(), name, "Group name");
Assert.assertEquals(group.getDescription(), desc, "Group description");
Assert.assertEquals((long) group.getDateOfLastUpdate(), time, "Update time");
}
@Test(dependsOnMethods = {"testAddGroupTest"})
public void findGroupTest() {
try {
GroupManagementDAOFactory.openConnection();
List<DeviceGroupBuilder> groups = groupDAO.findInGroups("Test", TestDataHolder.SUPER_TENANT_ID);
Assert.assertNotEquals(groups.size(), 0, "No groups found");
Assert.assertNotNull(groups.get(0), "Group is null");
log.debug("Group found: " + groups.get(0).getName());
} catch (GroupManagementDAOException e) {
String msg = "Error occurred while find group by name.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source.";
log.error(msg, e);
Assert.fail(msg, e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
}
@Test(dependsOnMethods = {"testAddGroupTest"})
public void getGroupTest() {
try {
GroupManagementDAOFactory.openConnection();
List<DeviceGroupBuilder> groups = groupDAO.getGroups(TestDataHolder.SUPER_TENANT_ID);
Assert.assertNotEquals(groups.size(), 0, "No groups found");
Assert.assertNotNull(groups.get(0), "Group is null");
log.debug("No of Groups found: " + groups.size());
} catch (GroupManagementDAOException e) {
String msg = "Error occurred while find group by name.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source.";
log.error(msg, e);
Assert.fail(msg, e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
}
@Test(dependsOnMethods = {"updateGroupTest"})
public void deleteGroupTest() {
DeviceGroup group = getGroupById(groupId);
int groupId = 0;
try {
Assert.assertNotNull(group, "Group is null");
groupId = group.getId();
GroupManagementDAOFactory.beginTransaction();
groupDAO.deleteGroup(groupId, TestDataHolder.SUPER_TENANT_ID);
GroupManagementDAOFactory.commitTransaction();
log.debug("Group deleted");
} catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while updating group details.";
log.error(msg, e);
Assert.fail(msg, e);
} catch (TransactionManagementException e) {
String msg = "Error occurred while initiating transaction.";
log.error(msg, e);
Assert.fail(msg, e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
group = getGroupById(groupId);
Assert.assertNull(group, "Group not deleted");
}
}

@ -1,28 +1,52 @@
CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE (
ID INT auto_increment NOT NULL, ID INT AUTO_INCREMENT NOT NULL,
NAME VARCHAR(300) DEFAULT NULL, NAME VARCHAR(300) DEFAULT NULL,
PRIMARY KEY (ID) PRIMARY KEY (ID)
); );
CREATE TABLE IF NOT EXISTS DM_GROUP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_NAME VARCHAR(100) DEFAULT NULL,
DESCRIPTION TEXT DEFAULT NULL,
DATE_OF_CREATE BIGINT DEFAULT NULL,
DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL,
OWNER VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID INTEGER auto_increment NOT NULL, ID INTEGER AUTO_INCREMENT NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL, CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID) PRIMARY KEY (ID)
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE ( CREATE TABLE IF NOT EXISTS DM_DEVICE (
ID INTEGER auto_increment NOT NULL, ID INTEGER AUTO_INCREMENT NOT NULL,
DESCRIPTION TEXT DEFAULT NULL, DESCRIPTION TEXT DEFAULT NULL,
NAME VARCHAR(100) DEFAULT NULL, NAME VARCHAR(100) DEFAULT NULL,
DEVICE_TYPE_ID INT(11) DEFAULT NULL, DEVICE_TYPE_ID INT(11) DEFAULT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0, TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID)
REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER DEFAULT NULL,
GROUP_ID INTEGER DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_OPERATION ( CREATE TABLE IF NOT EXISTS DM_OPERATION (
ID INTEGER AUTO_INCREMENT NOT NULL, ID INTEGER AUTO_INCREMENT NOT NULL,
TYPE VARCHAR(50) NOT NULL, TYPE VARCHAR(50) NOT NULL,
@ -107,95 +131,81 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
-- POLICY RELATED TABLES -- -- POLICY RELATED TABLES --
CREATE TABLE IF NOT EXISTS DM_PROFILE ( CREATE TABLE IF NOT EXISTS DM_PROFILE (
ID INT NOT NULL AUTO_INCREMENT , ID INT NOT NULL AUTO_INCREMENT,
PROFILE_NAME VARCHAR(45) NOT NULL , PROFILE_NAME VARCHAR(45) NOT NULL,
TENANT_ID INT NOT NULL , TENANT_ID INT NOT NULL,
DEVICE_TYPE_ID INT NOT NULL , DEVICE_TYPE_ID INT NOT NULL,
CREATED_TIME DATETIME NOT NULL , CREATED_TIME DATETIME NOT NULL,
UPDATED_TIME DATETIME NOT NULL , UPDATED_TIME DATETIME NOT NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT DM_PROFILE_DEVICE_TYPE CONSTRAINT DM_PROFILE_DEVICE_TYPE
FOREIGN KEY (DEVICE_TYPE_ID ) FOREIGN KEY (DEVICE_TYPE_ID)
REFERENCES DM_DEVICE_TYPE (ID ) REFERENCES DM_DEVICE_TYPE (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_POLICY ( CREATE TABLE IF NOT EXISTS DM_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT , ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(45) DEFAULT NULL , NAME VARCHAR(45) DEFAULT NULL,
DESCRIPTION VARCHAR(1000) NULL, DESCRIPTION VARCHAR(1000) NULL,
TENANT_ID INT(11) NOT NULL , TENANT_ID INT(11) NOT NULL,
PROFILE_ID INT(11) NOT NULL , PROFILE_ID INT(11) NOT NULL,
OWNERSHIP_TYPE VARCHAR(45) NULL, OWNERSHIP_TYPE VARCHAR(45) NULL,
COMPLIANCE VARCHAR(100) NULL, COMPLIANCE VARCHAR(100) NULL,
PRIORITY INT NOT NULL, PRIORITY INT NOT NULL,
ACTIVE INT(2) NOT NULL, ACTIVE INT(2) NOT NULL,
UPDATED INT(1) NULL, UPDATED INT(1) NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT FK_DM_PROFILE_DM_POLICY CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID ) FOREIGN KEY (PROFILE_ID)
REFERENCES DM_PROFILE (ID ) REFERENCES DM_PROFILE (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT , ID INT(11) NOT NULL AUTO_INCREMENT,
DEVICE_ID INT(11) NOT NULL , DEVICE_ID INT(11) NOT NULL,
ENROLMENT_ID INT(11) NOT NULL, ENROLMENT_ID INT(11) NOT NULL,
DEVICE BLOB NOT NULL, DEVICE BLOB NOT NULL,
POLICY_ID INT(11) NOT NULL , POLICY_ID INT(11) NOT NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT FK_POLICY_DEVICE_POLICY CONSTRAINT FK_POLICY_DEVICE_POLICY
FOREIGN KEY (POLICY_ID ) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID ) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION, ON UPDATE NO ACTION,
CONSTRAINT FK_DEVICE_DEVICE_POLICY CONSTRAINT FK_DEVICE_DEVICE_POLICY
FOREIGN KEY (DEVICE_ID ) FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID ) REFERENCES DM_DEVICE (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY (
ID INT(11) NOT NULL , ID INT(11) NOT NULL,
DEVICE_TYPE_ID INT(11) NOT NULL , DEVICE_TYPE_ID INT(11) NOT NULL,
POLICY_ID INT(11) NOT NULL , POLICY_ID INT(11) NOT NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT FK_DEVICE_TYPE_POLICY CONSTRAINT FK_DEVICE_TYPE_POLICY
FOREIGN KEY (POLICY_ID ) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID ) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION, ON UPDATE NO ACTION,
CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE
FOREIGN KEY (DEVICE_TYPE_ID ) FOREIGN KEY (DEVICE_TYPE_ID)
REFERENCES DM_DEVICE_TYPE (ID ) REFERENCES DM_DEVICE_TYPE (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES (
ID INT(11) NOT NULL AUTO_INCREMENT, ID INT(11) NOT NULL AUTO_INCREMENT,
PROFILE_ID INT(11) NOT NULL, PROFILE_ID INT(11) NOT NULL,
FEATURE_CODE VARCHAR(30) NOT NULL, FEATURE_CODE VARCHAR(30) NOT NULL,
DEVICE_TYPE_ID INT NOT NULL, DEVICE_TYPE_ID INT NOT NULL,
TENANT_ID INT(11) NOT NULL , TENANT_ID INT(11) NOT NULL,
CONTENT BLOB NULL DEFAULT NULL, CONTENT BLOB NULL DEFAULT NULL,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES
@ -205,58 +215,49 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES (
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT , ID INT(11) NOT NULL AUTO_INCREMENT,
ROLE_NAME VARCHAR(45) NOT NULL , ROLE_NAME VARCHAR(45) NOT NULL,
POLICY_ID INT(11) NOT NULL , POLICY_ID INT(11) NOT NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT FK_ROLE_POLICY_POLICY CONSTRAINT FK_ROLE_POLICY_POLICY
FOREIGN KEY (POLICY_ID ) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID ) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( CREATE TABLE IF NOT EXISTS DM_USER_POLICY (
ID INT NOT NULL AUTO_INCREMENT , ID INT NOT NULL AUTO_INCREMENT,
POLICY_ID INT NOT NULL , POLICY_ID INT NOT NULL,
USERNAME VARCHAR(45) NOT NULL , USERNAME VARCHAR(45) NOT NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT DM_POLICY_USER_POLICY CONSTRAINT DM_POLICY_USER_POLICY
FOREIGN KEY (POLICY_ID ) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID ) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED (
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( ID INT NOT NULL AUTO_INCREMENT,
ID INT NOT NULL AUTO_INCREMENT , DEVICE_ID INT NOT NULL,
DEVICE_ID INT NOT NULL ,
ENROLMENT_ID INT(11) NOT NULL, ENROLMENT_ID INT(11) NOT NULL,
POLICY_ID INT NOT NULL , POLICY_ID INT NOT NULL,
POLICY_CONTENT BLOB NULL , POLICY_CONTENT BLOB NULL,
TENANT_ID INT NOT NULL, TENANT_ID INT NOT NULL,
APPLIED TINYINT(1) NULL , APPLIED BOOLEAN NULL,
CREATED_TIME TIMESTAMP NULL , CREATED_TIME TIMESTAMP NULL,
UPDATED_TIME TIMESTAMP NULL , UPDATED_TIME TIMESTAMP NULL,
APPLIED_TIME TIMESTAMP NULL , APPLIED_TIME TIMESTAMP NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT FK_DM_POLICY_DEVCIE_APPLIED CONSTRAINT FK_DM_POLICY_DEVICE_APPLIED
FOREIGN KEY (DEVICE_ID ) FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID ) REFERENCES DM_DEVICE (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_CRITERIA ( CREATE TABLE IF NOT EXISTS DM_CRITERIA (
ID INT NOT NULL AUTO_INCREMENT, ID INT NOT NULL AUTO_INCREMENT,
TENANT_ID INT NOT NULL, TENANT_ID INT NOT NULL,
@ -264,8 +265,6 @@ CREATE TABLE IF NOT EXISTS DM_CRITERIA (
PRIMARY KEY (ID) PRIMARY KEY (ID)
); );
CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA (
ID INT NOT NULL AUTO_INCREMENT, ID INT NOT NULL AUTO_INCREMENT,
CRITERIA_ID INT NOT NULL, CRITERIA_ID INT NOT NULL,
@ -288,7 +287,8 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES (
POLICY_CRITERION_ID INT NOT NULL, POLICY_CRITERION_ID INT NOT NULL,
PROP_KEY VARCHAR(45) NULL, PROP_KEY VARCHAR(45) NULL,
PROP_VALUE VARCHAR(100) NULL, PROP_VALUE VARCHAR(100) NULL,
CONTENT BLOB NULL COMMENT 'This is used to ', CONTENT BLOB NULL
COMMENT 'This is used to ',
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES
FOREIGN KEY (POLICY_CRITERION_ID) FOREIGN KEY (POLICY_CRITERION_ID)
@ -409,8 +409,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
DROP TABLE IF EXISTS DM_DEVICE_LOCATION; DROP TABLE IF EXISTS DM_DEVICE_LOCATION;
CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
@ -432,7 +430,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
ID INT NOT NULL AUTO_INCREMENT, ID INT NOT NULL AUTO_INCREMENT,
DEVICE_ID INT NOT NULL, DEVICE_ID INT NOT NULL,

@ -33,6 +33,7 @@
<class name="org.wso2.carbon.device.mgt.core.dao.ApplicationPersistenceTests"/> <class name="org.wso2.carbon.device.mgt.core.dao.ApplicationPersistenceTests"/>
<class name="org.wso2.carbon.device.mgt.core.search.DeviceDetails"/> <class name="org.wso2.carbon.device.mgt.core.search.DeviceDetails"/>
<class name="org.wso2.carbon.device.mgt.core.search.SearchDevice"/> <class name="org.wso2.carbon.device.mgt.core.search.SearchDevice"/>
<class name="org.wso2.carbon.device.mgt.core.dao.GroupPersistTests"/>
</classes> </classes>
</test> </test>
<test name="Service Unit Tests" preserve-order="true"> <test name="Service Unit Tests" preserve-order="true">

@ -1,11 +1,22 @@
CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE (
ID INT auto_increment NOT NULL, ID INT AUTO_INCREMENT NOT NULL,
NAME VARCHAR(300) DEFAULT NULL, NAME VARCHAR(300) DEFAULT NULL,
PRIMARY KEY (ID) PRIMARY KEY (ID)
); );
CREATE TABLE IF NOT EXISTS DM_GROUP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_NAME VARCHAR(100) DEFAULT NULL,
DESCRIPTION TEXT DEFAULT NULL,
DATE_OF_CREATE BIGINT DEFAULT NULL,
DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL,
OWNER VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID INTEGER auto_increment NOT NULL, ID INTEGER AUTO_INCREMENT NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
CERTIFICATE BLOB DEFAULT NULL, CERTIFICATE BLOB DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0, TENANT_ID INTEGER DEFAULT 0,
@ -13,17 +24,29 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE ( CREATE TABLE IF NOT EXISTS DM_DEVICE (
ID INTEGER auto_increment NOT NULL, ID INTEGER AUTO_INCREMENT NOT NULL,
DESCRIPTION TEXT DEFAULT NULL, DESCRIPTION TEXT DEFAULT NULL,
NAME VARCHAR(100) DEFAULT NULL, NAME VARCHAR(100) DEFAULT NULL,
DEVICE_TYPE_ID INT(11) DEFAULT NULL, DEVICE_TYPE_ID INT(11) DEFAULT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0, TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID)
REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP (
ID INTEGER AUTO_INCREMENT NOT NULL,
DEVICE_ID INTEGER DEFAULT NULL,
GROUP_ID INTEGER DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE IF NOT EXISTS DM_OPERATION ( CREATE TABLE IF NOT EXISTS DM_OPERATION (
ID INTEGER AUTO_INCREMENT NOT NULL, ID INTEGER AUTO_INCREMENT NOT NULL,
TYPE VARCHAR(50) NOT NULL, TYPE VARCHAR(50) NOT NULL,
@ -108,95 +131,81 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE (
-- POLICY RELATED TABLES -- -- POLICY RELATED TABLES --
CREATE TABLE IF NOT EXISTS DM_PROFILE ( CREATE TABLE IF NOT EXISTS DM_PROFILE (
ID INT NOT NULL AUTO_INCREMENT , ID INT NOT NULL AUTO_INCREMENT,
PROFILE_NAME VARCHAR(45) NOT NULL , PROFILE_NAME VARCHAR(45) NOT NULL,
TENANT_ID INT NOT NULL , TENANT_ID INT NOT NULL,
DEVICE_TYPE_ID INT NOT NULL , DEVICE_TYPE_ID INT NOT NULL,
CREATED_TIME DATETIME NOT NULL , CREATED_TIME DATETIME NOT NULL,
UPDATED_TIME DATETIME NOT NULL , UPDATED_TIME DATETIME NOT NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT DM_PROFILE_DEVICE_TYPE CONSTRAINT DM_PROFILE_DEVICE_TYPE
FOREIGN KEY (DEVICE_TYPE_ID ) FOREIGN KEY (DEVICE_TYPE_ID)
REFERENCES DM_DEVICE_TYPE (ID ) REFERENCES DM_DEVICE_TYPE (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_POLICY ( CREATE TABLE IF NOT EXISTS DM_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT , ID INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(45) DEFAULT NULL , NAME VARCHAR(45) DEFAULT NULL,
DESCRIPTION VARCHAR(1000) NULL, DESCRIPTION VARCHAR(1000) NULL,
TENANT_ID INT(11) NOT NULL , TENANT_ID INT(11) NOT NULL,
PROFILE_ID INT(11) NOT NULL , PROFILE_ID INT(11) NOT NULL,
OWNERSHIP_TYPE VARCHAR(45) NULL, OWNERSHIP_TYPE VARCHAR(45) NULL,
COMPLIANCE VARCHAR(100) NULL, COMPLIANCE VARCHAR(100) NULL,
PRIORITY INT NOT NULL, PRIORITY INT NOT NULL,
ACTIVE INT(2) NOT NULL, ACTIVE INT(2) NOT NULL,
UPDATED INT(1) NULL, UPDATED INT(1) NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT FK_DM_PROFILE_DM_POLICY CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID ) FOREIGN KEY (PROFILE_ID)
REFERENCES DM_PROFILE (ID ) REFERENCES DM_PROFILE (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT , ID INT(11) NOT NULL AUTO_INCREMENT,
DEVICE_ID INT(11) NOT NULL , DEVICE_ID INT(11) NOT NULL,
ENROLMENT_ID INT(11) NOT NULL, ENROLMENT_ID INT(11) NOT NULL,
DEVICE BLOB NOT NULL, DEVICE BLOB NOT NULL,
POLICY_ID INT(11) NOT NULL , POLICY_ID INT(11) NOT NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT FK_POLICY_DEVICE_POLICY CONSTRAINT FK_POLICY_DEVICE_POLICY
FOREIGN KEY (POLICY_ID ) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID ) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION, ON UPDATE NO ACTION,
CONSTRAINT FK_DEVICE_DEVICE_POLICY CONSTRAINT FK_DEVICE_DEVICE_POLICY
FOREIGN KEY (DEVICE_ID ) FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID ) REFERENCES DM_DEVICE (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY (
ID INT(11) NOT NULL , ID INT(11) NOT NULL,
DEVICE_TYPE_ID INT(11) NOT NULL , DEVICE_TYPE_ID INT(11) NOT NULL,
POLICY_ID INT(11) NOT NULL , POLICY_ID INT(11) NOT NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT FK_DEVICE_TYPE_POLICY CONSTRAINT FK_DEVICE_TYPE_POLICY
FOREIGN KEY (POLICY_ID ) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID ) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION, ON UPDATE NO ACTION,
CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE
FOREIGN KEY (DEVICE_TYPE_ID ) FOREIGN KEY (DEVICE_TYPE_ID)
REFERENCES DM_DEVICE_TYPE (ID ) REFERENCES DM_DEVICE_TYPE (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES (
ID INT(11) NOT NULL AUTO_INCREMENT, ID INT(11) NOT NULL AUTO_INCREMENT,
PROFILE_ID INT(11) NOT NULL, PROFILE_ID INT(11) NOT NULL,
FEATURE_CODE VARCHAR(30) NOT NULL, FEATURE_CODE VARCHAR(30) NOT NULL,
DEVICE_TYPE_ID INT NOT NULL, DEVICE_TYPE_ID INT NOT NULL,
TENANT_ID INT(11) NOT NULL , TENANT_ID INT(11) NOT NULL,
CONTENT BLOB NULL DEFAULT NULL, CONTENT BLOB NULL DEFAULT NULL,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES
@ -206,58 +215,49 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES (
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT , ID INT(11) NOT NULL AUTO_INCREMENT,
ROLE_NAME VARCHAR(45) NOT NULL , ROLE_NAME VARCHAR(45) NOT NULL,
POLICY_ID INT(11) NOT NULL , POLICY_ID INT(11) NOT NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT FK_ROLE_POLICY_POLICY CONSTRAINT FK_ROLE_POLICY_POLICY
FOREIGN KEY (POLICY_ID ) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID ) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( CREATE TABLE IF NOT EXISTS DM_USER_POLICY (
ID INT NOT NULL AUTO_INCREMENT , ID INT NOT NULL AUTO_INCREMENT,
POLICY_ID INT NOT NULL , POLICY_ID INT NOT NULL,
USERNAME VARCHAR(45) NOT NULL , USERNAME VARCHAR(45) NOT NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT DM_POLICY_USER_POLICY CONSTRAINT DM_POLICY_USER_POLICY
FOREIGN KEY (POLICY_ID ) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID ) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED (
CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( ID INT NOT NULL AUTO_INCREMENT,
ID INT NOT NULL AUTO_INCREMENT , DEVICE_ID INT NOT NULL,
DEVICE_ID INT NOT NULL ,
ENROLMENT_ID INT(11) NOT NULL, ENROLMENT_ID INT(11) NOT NULL,
POLICY_ID INT NOT NULL , POLICY_ID INT NOT NULL,
POLICY_CONTENT BLOB NULL , POLICY_CONTENT BLOB NULL,
TENANT_ID INT NOT NULL, TENANT_ID INT NOT NULL,
APPLIED TINYINT(1) NULL , APPLIED BOOLEAN NULL,
CREATED_TIME TIMESTAMP NULL , CREATED_TIME TIMESTAMP NULL,
UPDATED_TIME TIMESTAMP NULL , UPDATED_TIME TIMESTAMP NULL,
APPLIED_TIME TIMESTAMP NULL , APPLIED_TIME TIMESTAMP NULL,
PRIMARY KEY (ID) , PRIMARY KEY (ID),
CONSTRAINT FK_DM_POLICY_DEVCIE_APPLIED CONSTRAINT FK_DM_POLICY_DEVICE_APPLIED
FOREIGN KEY (DEVICE_ID ) FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID ) REFERENCES DM_DEVICE (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_CRITERIA ( CREATE TABLE IF NOT EXISTS DM_CRITERIA (
ID INT NOT NULL AUTO_INCREMENT, ID INT NOT NULL AUTO_INCREMENT,
TENANT_ID INT NOT NULL, TENANT_ID INT NOT NULL,
@ -265,8 +265,6 @@ CREATE TABLE IF NOT EXISTS DM_CRITERIA (
PRIMARY KEY (ID) PRIMARY KEY (ID)
); );
CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA (
ID INT NOT NULL AUTO_INCREMENT, ID INT NOT NULL AUTO_INCREMENT,
CRITERIA_ID INT NOT NULL, CRITERIA_ID INT NOT NULL,
@ -289,7 +287,8 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES (
POLICY_CRITERION_ID INT NOT NULL, POLICY_CRITERION_ID INT NOT NULL,
PROP_KEY VARCHAR(45) NULL, PROP_KEY VARCHAR(45) NULL,
PROP_VALUE VARCHAR(100) NULL, PROP_VALUE VARCHAR(100) NULL,
CONTENT BLOB NULL COMMENT 'This is used to ', CONTENT BLOB NULL
COMMENT 'This is used to ',
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES
FOREIGN KEY (POLICY_CRITERION_ID) FOREIGN KEY (POLICY_CRITERION_ID)
@ -410,8 +409,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
DROP TABLE IF EXISTS DM_DEVICE_LOCATION; DROP TABLE IF EXISTS DM_DEVICE_LOCATION;
CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
@ -433,7 +430,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
ID INT NOT NULL AUTO_INCREMENT, ID INT NOT NULL AUTO_INCREMENT,
DEVICE_ID INT NOT NULL, DEVICE_ID INT NOT NULL,

Loading…
Cancel
Save