Updated group sharing model

revert-70aa11f8
charitha 8 years ago
parent 023b554e0f
commit c07d77b85d

@ -19,26 +19,38 @@
package org.wso2.carbon.device.mgt.jaxrs.service.api; package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Info;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Extension;
import io.swagger.annotations.Tag;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.AuthorizationScope;
import io.swagger.annotations.Authorization;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Authorization;
import io.swagger.annotations.AuthorizationScope;
import io.swagger.annotations.Extension;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Info;
import io.swagger.annotations.ResponseHeader; import io.swagger.annotations.ResponseHeader;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import org.apache.axis2.transport.http.HTTPConstants; import org.apache.axis2.transport.http.HTTPConstants;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
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.jaxrs.beans.*; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupList;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupShare;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupUsersList;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import javax.validation.Valid; import javax.validation.Valid;
import javax.ws.rs.*; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List; import java.util.List;
@ -475,126 +487,6 @@ public interface GroupManagementService {
required = true) required = true)
@Valid DeviceGroupShare deviceGroupShare); @Valid DeviceGroupShare deviceGroupShare);
@Path("/id/{groupId}/users")
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HTTPConstants.HEADER_GET,
value = "View list of users of a device group.",
notes = "Returns details of users which particular group has been shared with.",
tags = "Device Group Management",
authorizations = {
@Authorization(
value="permission",
scopes = { @AuthorizationScope(scope = "/device-mgt/groups/users/view",
description = "View users") }
)
}
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the users.",
response = DeviceGroupUsersList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of " +
"the requested resource."),
@ApiResponse(
code = 404,
message = "No groups found.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the users.",
response = ErrorResponse.class)
})
Response getUsersOfGroup(@ApiParam(
name = "groupId",
value = "ID of the group.",
required = true)
@PathParam("groupId") int groupId);
@Path("id/{groupId}/roles/create")
@POST
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HTTPConstants.HEADER_GET,
value = "Create a group sharing role to a device group.",
notes = "Group sharing is done through a group sharing role.",
tags = "Device Group Management",
authorizations = {
@Authorization(
value="permission",
scopes = { @AuthorizationScope(scope = "/device-mgt/groups/roles/create",
description = "Create roles") }
)
}
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. \n Successfully created the role.",
response = DeviceGroupUsersList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of " +
"the requested resource."),
@ApiResponse(
code = 404,
message = "No groups found.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while creating the role.",
response = ErrorResponse.class)
})
Response createGroupSharingRole(
@ApiParam(
name = "groupId",
value = "ID of the group.",
required = true)
@PathParam("groupId") int groupId,
@ApiParam(
name = "userName",
value = "User name of the current user.",
required = false)
@QueryParam("userName") String userName,
@ApiParam(
name = "roleInfo",
value = "Group role information with permissions and users",
required = true)
@Valid RoleInfo roleInfo);
@Path("/id/{groupId}/roles") @Path("/id/{groupId}/roles")
@GET @GET
@ApiOperation( @ApiOperation(
@ -647,12 +539,7 @@ public interface GroupManagementService {
name = "groupId", name = "groupId",
value = "ID of the group.", value = "ID of the group.",
required = true) required = true)
@PathParam("groupId") int groupId, @PathParam("groupId") int groupId);
@ApiParam(
name = "userName",
value = "User name of the current user.",
required = false)
@QueryParam("userName") String userName);
@Path("/id/{groupId}/devices") @Path("/id/{groupId}/devices")
@GET @GET

@ -31,19 +31,17 @@ 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.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
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.RoleDoesNotExistException; import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.*; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupList;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupShare;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList;
import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.Date;
import java.util.List; import java.util.List;
public class GroupManagementServiceImpl implements GroupManagementService { public class GroupManagementServiceImpl implements GroupManagementService {
@ -100,8 +98,6 @@ public class GroupManagementServiceImpl implements GroupManagementService {
return Response.status(Response.Status.BAD_REQUEST).build(); return Response.status(Response.Status.BAD_REQUEST).build();
} }
group.setOwner(owner); group.setOwner(owner);
group.setDateOfCreation(new Date().getTime());
group.setDateOfLastUpdate(new Date().getTime());
try { try {
DeviceMgtAPIUtils.getGroupManagementProviderService().createGroup(group, DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS); DeviceMgtAPIUtils.getGroupManagementProviderService().createGroup(group, DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS);
return Response.status(Response.Status.CREATED).build(); return Response.status(Response.Status.CREATED).build();
@ -171,66 +167,21 @@ public class GroupManagementServiceImpl implements GroupManagementService {
public Response manageGroupSharing(int groupId, DeviceGroupShare deviceGroupShare) { public Response manageGroupSharing(int groupId, DeviceGroupShare deviceGroupShare) {
try { try {
DeviceMgtAPIUtils.getGroupManagementProviderService() DeviceMgtAPIUtils.getGroupManagementProviderService()
.manageGroupSharing(groupId, deviceGroupShare.getUsername(), deviceGroupShare.getGroupRoles()); .manageGroupSharing(groupId, deviceGroupShare.getGroupRoles());
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) { } catch (GroupManagementException e) {
String msg = "Error occurred while managing group share."; String msg = "Error occurred while managing group share.";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (RoleDoesNotExistException | UserDoesNotExistException e) { } catch (RoleDoesNotExistException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} }
} }
@Override @Override
public Response getUsersOfGroup(int groupId) { public Response getRolesOfGroup(int groupId) {
try { try {
List<GroupUser> groupUsers = DeviceMgtAPIUtils.getGroupManagementProviderService().getUsers(groupId); List<String> groupRoles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupId);
if (groupUsers != null && groupUsers.size() > 0) {
DeviceGroupUsersList deviceGroupUsersList = new DeviceGroupUsersList();
deviceGroupUsersList.setList(groupUsers);
deviceGroupUsersList.setCount(groupUsers.size());
return Response.status(Response.Status.OK).entity(deviceGroupUsersList).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
String msg = "Error occurred while getting users of the group.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
public Response createGroupSharingRole(int groupId, String userName, RoleInfo roleInfo) {
try {
DeviceMgtAPIUtils.getGroupManagementProviderService()
.addGroupSharingRole(userName, groupId, roleInfo.getRoleName(), roleInfo.getPermissions());
return Response.status(Response.Status.CREATED).build();
} catch (GroupManagementException e) {
String msg = "Error occurred while creating group sharing role.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
public Response getRolesOfGroup(int groupId, String userName) {
try {
List<String> groupRoles;
if(userName != null) {
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
if (!userStoreManager.isExistingUser(userName)) {
// returning response with bad request state
return Response.status(Response.Status.CONFLICT).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " +
userName + " doesn't exists. Therefore, request made to get user " +
"was refused.").build()).build();
}
groupRoles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(userName, groupId);
} else {
groupRoles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupId);
}
if(groupRoles != null && groupRoles.size() > 0) { if(groupRoles != null && groupRoles.size() > 0) {
RoleList deviceGroupRolesList = new RoleList(); RoleList deviceGroupRolesList = new RoleList();
@ -244,10 +195,6 @@ public class GroupManagementServiceImpl implements GroupManagementService {
String msg = "Error occurred while getting roles of the group."; String msg = "Error occurred while getting roles of the group.";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (UserStoreException e) {
String msg = "Error while retrieving the user.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }

@ -20,10 +20,7 @@ package org.wso2.carbon.device.mgt.common.group.mgt;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable; import java.io.Serializable;
import java.util.List;
/** /**
* Holds Device Group details and expose to external access * Holds Device Group details and expose to external access
@ -44,8 +41,6 @@ public class DeviceGroup implements Serializable {
required = true) required = true)
private String name; private String name;
private Long dateOfCreation;
private Long dateOfLastUpdate;
private String owner; private String owner;
public int getGroupId() { public int getGroupId() {
@ -72,22 +67,6 @@ public class DeviceGroup implements Serializable {
this.name = name; this.name = name;
} }
public Long getDateOfCreation() {
return dateOfCreation;
}
public void setDateOfCreation(Long dateOfCreation) {
this.dateOfCreation = dateOfCreation;
}
public Long getDateOfLastUpdate() {
return dateOfLastUpdate;
}
public void setDateOfLastUpdate(Long dateOfLastUpdate) {
this.dateOfLastUpdate = dateOfLastUpdate;
}
public String getOwner() { public String getOwner() {
return owner; return owner;
} }

@ -86,6 +86,18 @@ public interface GroupDAO {
*/ */
List<DeviceGroup> getGroups(GroupPaginationRequest paginationRequest, int tenantId) throws GroupManagementDAOException; List<DeviceGroup> getGroups(GroupPaginationRequest paginationRequest, int tenantId) throws GroupManagementDAOException;
/**
* Get paginated list of Device Groups in tenant with specified device group ids.
*
* @param paginationRequest to filter results.
* @param deviceGroupIds of groups required.
* @param tenantId of user's tenant.
* @return List of all Device Groups in tenant.
* @throws GroupManagementDAOException
*/
List<DeviceGroup> getGroups(GroupPaginationRequest paginationRequest, List<Integer> deviceGroupIds,
int tenantId) throws GroupManagementDAOException;
/** /**
* Get the list of Device Groups in tenant. * Get the list of Device Groups in tenant.
* *
@ -178,4 +190,94 @@ public interface GroupDAO {
List<Device> getDevices(int groupId, int startIndex, int rowCount, int tenantId) List<Device> getDevices(int groupId, int startIndex, int rowCount, int tenantId)
throws GroupManagementDAOException; throws GroupManagementDAOException;
/**
* Get all user roles for device group.
*
* @param groupId of the group
* @param tenantId of user's tenant.
* @return list of roles
* @throws GroupManagementDAOException
*/
List<String> getRoles(int groupId, int tenantId) throws GroupManagementDAOException;
/**
* Add user role for device group.
*
* @param groupId of the group.
* @param role to be added.
* @param tenantId of user's tenant.
* @throws GroupManagementDAOException
*/
void addRole(int groupId, String role, int tenantId) throws GroupManagementDAOException;
/**
* Add user role for device group.
*
* @param groupId of the group.
* @param role to be removed.
* @param tenantId of user's tenant.
* @throws GroupManagementDAOException
*/
void removeRole(int groupId, String role, int tenantId) throws GroupManagementDAOException;
/**
* Get all device groups which shared with a user role.
*
* @param roles of the group.
* @param tenantId of user's tenant.
* @return list of device groups.
* @throws GroupManagementDAOException
*/
List<DeviceGroup> getGroups(String[] roles, int tenantId) throws GroupManagementDAOException;
/**
* Get all device group ids which shared with a user role.
*
* @param roles of the group.
* @param tenantId of user's tenant.
* @return list of device group ids.
* @throws GroupManagementDAOException
*/
List<Integer> getGroupIds(String[] roles, int tenantId) throws GroupManagementDAOException;
/**
* Get count of all device groups which shared with a user role.
*
* @param roles of the group.
* @param tenantId of user's tenant.
* @return count of device groups.
* @throws GroupManagementDAOException
*/
int getGroupsCount(String[] roles, int tenantId) throws GroupManagementDAOException;
/**
* Get all device groups which owned by user.
*
* @param username of the owner.
* @param tenantId of user's tenant.
* @return list of device groups.
* @throws GroupManagementDAOException
*/
List<DeviceGroup> getOwnGroups(String username, int tenantId) throws GroupManagementDAOException;
/**
* Get all device group ids which owned by user.
*
* @param username of the owner.
* @param tenantId of user's tenant.
* @return list of device group ids.
* @throws GroupManagementDAOException
*/
List<Integer> getOwnGroupIds(String username, int tenantId) throws GroupManagementDAOException;
/**
* Get count of device groups which owned by user.
*
* @param username of the owner.
* @param tenantId of user's tenant.
* @return count of device groups.
* @throws GroupManagementDAOException
*/
int getOwnGroupsCount(String username, int tenantId) throws GroupManagementDAOException;
} }

@ -22,9 +22,9 @@ import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
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.GroupDAO; import org.wso2.carbon.device.mgt.core.dao.GroupDAO;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.dao.util.GroupManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.GroupManagementDAOUtil;
import java.sql.Connection; import java.sql.Connection;
@ -32,7 +32,6 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
/** /**
@ -47,15 +46,12 @@ 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_CREATE, DATE_OF_LAST_UPDATE, " String sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, 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.setString(3, deviceGroup.getOwner());
stmt.setLong(4, new Date().getTime()); stmt.setInt(4, tenantId);
stmt.setString(5, deviceGroup.getOwner());
stmt.setInt(6, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
rs = stmt.getGeneratedKeys(); rs = stmt.getGeneratedKeys();
if (rs.next()) { if (rs.next()) {
@ -76,15 +72,13 @@ public class GroupDAOImpl implements GroupDAO {
PreparedStatement stmt = null; PreparedStatement stmt = null;
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 = ?, OWNER = ? WHERE ID = ? 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.setString(3, deviceGroup.getOwner());
stmt.setString(4, deviceGroup.getOwner()); stmt.setInt(4, groupId);
stmt.setInt(5, groupId); stmt.setInt(5, tenantId);
stmt.setInt(6, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while updating deviceGroup '" + throw new GroupManagementDAOException("Error occurred while updating deviceGroup '" +
@ -100,7 +94,12 @@ public class GroupDAOImpl implements GroupDAO {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = GroupManagementDAOFactory.getConnection(); conn = GroupManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? AND TENANT_ID = ?"; String sql = "DELETE FROM DM_ROLE_GROUP_MAP WHERE GROUP_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId); stmt.setInt(1, groupId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
@ -131,8 +130,7 @@ public class GroupDAOImpl implements GroupDAO {
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_CREATE, DATE_OF_LAST_UPDATE, OWNER " String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE ID = ? AND TENANT_ID = ?";
+ "FROM DM_GROUP WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId); stmt.setInt(1, groupId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
@ -157,9 +155,9 @@ public class GroupDAOImpl implements GroupDAO {
List<DeviceGroup> deviceGroupBuilders = new ArrayList<>(); List<DeviceGroup> deviceGroupBuilders = new ArrayList<>();
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT G.ID, G.GROUP_NAME, G.DESCRIPTION, G.DATE_OF_CREATE, G.DATE_OF_LAST_UPDATE, \n" + String sql = "SELECT G.ID, G.GROUP_NAME, G.DESCRIPTION, G.OWNER FROM DM_GROUP G " +
"G.OWNER FROM DM_GROUP G INNER JOIN DM_DEVICE_GROUP_MAP GM ON G.ID = GM.GROUP_ID " + "INNER JOIN DM_DEVICE_GROUP_MAP GM ON G.ID = GM.GROUP_ID " +
"WHERE GM.DEVICE_ID = ? AND GM.TENANT_ID = ?"; "WHERE GM.DEVICE_ID = ? AND GM.TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
@ -190,8 +188,7 @@ public class GroupDAOImpl implements GroupDAO {
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?";
+ "FROM DM_GROUP WHERE TENANT_ID = ?";
if (groupName != null && !groupName.isEmpty()) { if (groupName != null && !groupName.isEmpty()) {
sql += " AND GROUP_NAME LIKE ?"; sql += " AND GROUP_NAME LIKE ?";
hasGroupName = true; hasGroupName = true;
@ -230,6 +227,71 @@ public class GroupDAOImpl implements GroupDAO {
return deviceGroupList; return deviceGroupList;
} }
@Override
public List<DeviceGroup> getGroups(GroupPaginationRequest request, List<Integer> deviceGroupIds,
int tenantId) throws GroupManagementDAOException {
if (deviceGroupIds.size() == 0) {
return new ArrayList<>();
}
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<DeviceGroup> deviceGroupList = null;
String groupName = request.getGroupName();
boolean hasGroupName = false;
String owner = request.getOwner();
boolean hasOwner = false;
boolean hasLimit = request.getRowCount() != 0;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE TENANT_ID = ?";
if (groupName != null && !groupName.isEmpty()) {
sql += " AND GROUP_NAME LIKE ?";
hasGroupName = true;
}
if (owner != null && !owner.isEmpty()) {
sql += " AND OWNER LIKE ?";
hasOwner = true;
}
sql += " AND ID IN (";
for (int i = 0; i < deviceGroupIds.size() - 1; i++) {
sql += "?,";
}
sql += "?)";
if (hasLimit) {
sql += " LIMIT ?, ?";
}
int paramIndex = 1;
stmt = conn.prepareStatement(sql);
stmt.setInt(paramIndex++, tenantId);
if (hasGroupName) {
stmt.setString(paramIndex++, groupName + "%");
}
if (hasOwner) {
stmt.setString(paramIndex++, owner + "%");
}
for (Integer deviceGroupId : deviceGroupIds) {
stmt.setInt(paramIndex++, deviceGroupId);
}
if (hasLimit) {
stmt.setInt(paramIndex++, request.getStartIndex());
stmt.setInt(paramIndex, request.getRowCount());
}
resultSet = stmt.executeQuery();
deviceGroupList = new ArrayList<>();
while (resultSet.next()) {
deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet));
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return deviceGroupList;
}
@Override @Override
public List<DeviceGroup> getGroups(int tenantId) throws GroupManagementDAOException { public List<DeviceGroup> getGroups(int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -237,8 +299,7 @@ public class GroupDAOImpl implements GroupDAO {
List<DeviceGroup> deviceGroupList = null; List<DeviceGroup> deviceGroupList = null;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, 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);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
@ -327,8 +388,7 @@ public class GroupDAOImpl implements GroupDAO {
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_CREATE, DATE_OF_LAST_UPDATE, OWNER " + String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE GROUP_NAME = ? AND TENANT_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);
@ -356,7 +416,6 @@ public class GroupDAOImpl implements GroupDAO {
stmt.setInt(2, groupId); stmt.setInt(2, groupId);
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
stmt.getGeneratedKeys();
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while adding device to Group.", e); throw new GroupManagementDAOException("Error occurred while adding device to Group.", e);
} finally { } finally {
@ -376,7 +435,6 @@ public class GroupDAOImpl implements GroupDAO {
stmt.setInt(2, groupId); stmt.setInt(2, groupId);
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
stmt.getGeneratedKeys();
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while removing device from Group.", e); throw new GroupManagementDAOException("Error occurred while removing device from Group.", e);
} finally { } finally {
@ -428,7 +486,6 @@ public class GroupDAOImpl implements GroupDAO {
} }
} }
//TODO: Move this to device mgt
@Override @Override
public List<Device> getDevices(int groupId, int startIndex, int rowCount, int tenantId) public List<Device> getDevices(int groupId, int startIndex, int rowCount, int tenantId)
throws GroupManagementDAOException { throws GroupManagementDAOException {
@ -470,4 +527,249 @@ public class GroupDAOImpl implements GroupDAO {
return devices; return devices;
} }
@Override
public List<String> getRoles(int groupId, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<String> userRoles;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ROLE FROM DM_ROLE_GROUP_MAP WHERE GROUP_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery();
userRoles = new ArrayList<>();
while (resultSet.next()) {
userRoles.add(resultSet.getString("ROLE"));
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return userRoles;
}
@Override
public void addRole(int groupId, String role, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_ROLE_GROUP_MAP(GROUP_ID, ROLE, TENANT_ID) VALUES (?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);
stmt.setString(2, role);
stmt.setInt(3, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while adding new user role to Group.", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public void removeRole(int groupId, String role, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_ROLE_GROUP_MAP WHERE GROUP_ID = ? AND ROLE = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);
stmt.setString(2, role);
stmt.setInt(3, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while removing device from Group.", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public List<DeviceGroup> getGroups(String[] roles, int tenantId) throws GroupManagementDAOException {
if (roles.length == 0) {
return new ArrayList<>();
}
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<DeviceGroup> deviceGroupList = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP g, " +
"(SELECT GROUP_ID FROM DM_ROLE_GROUP_MAP WHERE ROLE IN (";
int index = 1;
while (index++ <= roles.length) {
sql += "?";
}
sql += ")) gr WHERE g.ID = gr.GROUP_ID AND TENANT_ID = ? GROUP BY g.ID";
stmt = conn.prepareStatement(sql);
index = 1;
while (index++ <= roles.length) {
stmt.setString(index, roles[index++]);
}
stmt.setInt(index, tenantId);
resultSet = stmt.executeQuery();
deviceGroupList = new ArrayList<>();
while (resultSet.next()) {
deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet));
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return deviceGroupList;
}
@Override
public List<Integer> getGroupIds(String[] roles, int tenantId) throws GroupManagementDAOException {
if (roles.length == 0) {
return new ArrayList<>();
}
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<Integer> deviceGroupIdList = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID FROM DM_GROUP g, (SELECT GROUP_ID FROM DM_ROLE_GROUP_MAP WHERE ROLE IN (";
for (int i = 0; i < roles.length - 1; i++) {
sql += "?,";
}
sql += "?)) gr WHERE g.ID = gr.GROUP_ID AND TENANT_ID = ? GROUP BY g.ID";
stmt = conn.prepareStatement(sql);
int index = 1;
while (index++ <= roles.length) {
stmt.setString(index, roles[index++]);
}
stmt.setInt(index, tenantId);
resultSet = stmt.executeQuery();
deviceGroupIdList = new ArrayList<>();
while (resultSet.next()) {
deviceGroupIdList.add(resultSet.getInt("ID"));
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return deviceGroupIdList;
}
@Override
public int getGroupsCount(String[] roles, int tenantId) throws GroupManagementDAOException {
if (roles.length == 0) {
return 0;
}
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT COUNT(ID) AS GROUP_COUNT FROM DM_GROUP g, " +
"(SELECT GROUP_ID FROM DM_ROLE_GROUP_MAP WHERE ROLE IN (";
int index = 1;
while (index++ <= roles.length) {
sql += "?";
}
sql += ")) gr WHERE g.ID = gr.GROUP_ID AND TENANT_ID = ? GROUP BY g.ID";
stmt = conn.prepareStatement(sql);
index = 1;
while (index++ <= roles.length) {
stmt.setString(index, roles[index++]);
}
stmt.setInt(index, tenantId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
return resultSet.getInt("GROUP_COUNT");
} else {
return 0;
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while getting permitted groups count.", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
}
@Override
public List<DeviceGroup> getOwnGroups(String username, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<DeviceGroup> deviceGroupList = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, OWNER FROM DM_GROUP WHERE OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery();
deviceGroupList = new ArrayList<>();
while (resultSet.next()) {
deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet));
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while getting own groups of user '"
+ username + "'", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return deviceGroupList;
}
@Override
public List<Integer> getOwnGroupIds(String username, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<Integer> deviceGroupIdList = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID FROM DM_GROUP WHERE OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery();
deviceGroupIdList = new ArrayList<>();
while (resultSet.next()) {
deviceGroupIdList.add(resultSet.getInt("ID"));
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while getting own groups of user '"
+ username + "'", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return deviceGroupIdList;
}
@Override
public int getOwnGroupsCount(String username, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT COUNT(ID) AS GROUP_COUNT FROM DM_GROUP WHERE OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
return resultSet.getInt("GROUP_COUNT");
} else {
return 0;
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while getting own groups count of user '"
+ username + "'", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
}
} }

@ -84,8 +84,6 @@ public final class GroupManagementDAOUtil {
group.setGroupId(resultSet.getInt("ID")); group.setGroupId(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_CREATE"));
group.setDateOfLastUpdate(resultSet.getLong("DATE_OF_LAST_UPDATE"));
group.setOwner(resultSet.getString("OWNER")); group.setOwner(resultSet.getString("OWNER"));
return group; return group;
} }

@ -22,14 +22,11 @@ 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.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; 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.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
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.RoleDoesNotExistException; import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException;
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
import java.util.List; import java.util.List;
@ -132,36 +129,12 @@ public interface GroupManagementProviderService {
/** /**
* Manage device group sharing with user with list of roles. * Manage device group sharing with user with list of roles.
* *
* @param username of the user
* @param groupId of the group * @param groupId of the group
* @param newRoles to be shared * @param newRoles to be shared
* @throws GroupManagementException UserDoesNotExistException * @throws GroupManagementException UserDoesNotExistException
*/ */
void manageGroupSharing(int groupId, String username, List<String> newRoles) void manageGroupSharing(int groupId, List<String> newRoles)
throws GroupManagementException, UserDoesNotExistException, RoleDoesNotExistException; throws GroupManagementException, RoleDoesNotExistException;
/**
* Add new sharing role for device group
*
* @param userName of the user
* @param groupId of the group
* @param roleName to add
* @param permissions to bind with role
* @return is role added
* @throws GroupManagementException
*/
boolean addGroupSharingRole(String userName, int groupId, String roleName, String[] permissions)
throws GroupManagementException;
/**
* Remove existing sharing role for device group
*
* @param groupId of the group
* @param roleName to remove
* @return is role removed
* @throws GroupManagementException
*/
boolean removeGroupSharingRole(int groupId, String roleName) throws GroupManagementException;
/** /**
* Get all sharing roles for device group * Get all sharing roles for device group
@ -172,25 +145,6 @@ public interface GroupManagementProviderService {
*/ */
List<String> getRoles(int groupId) throws GroupManagementException; List<String> getRoles(int groupId) throws GroupManagementException;
/**
* Get specific device group sharing roles for user
*
* @param userName of the user
* @param groupId of the group
* @return list of roles
* @throws GroupManagementException UserDoesNotExistException
*/
List<String> getRoles(String userName, int groupId) throws GroupManagementException, UserDoesNotExistException;
/**
* Get device group users
*
* @param groupId of the group
* @return list of group users
* @throws GroupManagementException
*/
List<GroupUser> getUsers(int groupId) throws GroupManagementException;
/** /**
* Get all devices in device group as paginated result. * Get all devices in device group as paginated result.
* *
@ -230,17 +184,6 @@ public interface GroupManagementProviderService {
*/ */
void removeDevice(int groupId, List<DeviceIdentifier> deviceIdentifiers) throws GroupManagementException, void removeDevice(int groupId, List<DeviceIdentifier> deviceIdentifiers) throws GroupManagementException,
DeviceNotFoundException; DeviceNotFoundException;
/**
* Get device group permissions of user.
*
* @param username of the user.
* @param groupId of the group
* @return array of permissions.
* @throws GroupManagementException UserDoesNotExistException
*/
String[] getPermissions(String username, int groupId) throws GroupManagementException, UserDoesNotExistException;
/** /**
* Get device groups of user with permission. * Get device groups of user with permission.
* *
@ -252,10 +195,10 @@ public interface GroupManagementProviderService {
List<DeviceGroup> getGroups(String username, String permission) throws GroupManagementException; List<DeviceGroup> getGroups(String username, String permission) throws GroupManagementException;
/** /**
* Get the group of device. * Get groups which contains particular device.
* *
* @param deviceIdentifier * @param deviceIdentifier of the device.
* @return * @return groups contain the device.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<DeviceGroup> getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException; List<DeviceGroup> getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException;

@ -33,23 +33,18 @@ 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.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
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.RoleDoesNotExistException; import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException;
import org.wso2.carbon.device.mgt.core.dao.GroupDAO; import org.wso2.carbon.device.mgt.core.dao.GroupDAO;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.user.api.Permission;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
import org.wso2.carbon.user.core.util.UserCoreUtil;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -77,12 +72,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException()); throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException());
} }
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
int groupId = -1;
try { try {
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
DeviceGroup existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId); DeviceGroup existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId);
if (existingGroup == null) { if (existingGroup == null) {
groupId = this.groupDAO.addGroup(deviceGroup, tenantId); this.groupDAO.addGroup(deviceGroup, tenantId);
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
} else { } else {
throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName()); throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName());
@ -97,7 +91,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
addGroupSharingRole(deviceGroup.getOwner(), groupId, defaultRole, defaultPermissions);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("DeviceGroup added: " + deviceGroup.getName()); log.debug("DeviceGroup added: " + deviceGroup.getName());
} }
@ -117,7 +110,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
DeviceGroup existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId); DeviceGroup existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId);
if (existingGroup == null || existingGroup.getGroupId() == groupId) { if (existingGroup == null || existingGroup.getGroupId() == groupId) {
deviceGroup.setDateOfLastUpdate(new Date().getTime());
this.groupDAO.updateGroup(deviceGroup, groupId, tenantId); this.groupDAO.updateGroup(deviceGroup, groupId, tenantId);
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
} else { } else {
@ -139,18 +131,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
*/ */
@Override @Override
public boolean deleteGroup(int groupId) throws GroupManagementException { public boolean deleteGroup(int groupId) throws GroupManagementException {
String roleName;
DeviceGroup deviceGroup = getGroup(groupId); DeviceGroup deviceGroup = getGroup(groupId);
if (deviceGroup == null) { if (deviceGroup == null) {
return false; return false;
} }
List<String> groupRoles = getRoles(groupId);
for (String role : groupRoles) {
if (role != null) {
roleName = role.replace("Internal/group-" + deviceGroup.getGroupId() + "-", "");
removeGroupSharingRole(deviceGroup.getGroupId(), roleName);
}
}
try { try {
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
this.groupDAO.deleteGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId()); this.groupDAO.deleteGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId());
@ -208,14 +192,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
@Override @Override
public PaginationResult getGroups(GroupPaginationRequest request) throws GroupManagementException { public PaginationResult getGroups(GroupPaginationRequest request) throws GroupManagementException {
request = DeviceManagerUtil.validateGroupListPageSize(request); request = DeviceManagerUtil.validateGroupListPageSize(request);
List<DeviceGroup> deviceGroups = getPlainDeviceGroups(request);
PaginationResult groupResult = new PaginationResult();
groupResult.setData(deviceGroups);
groupResult.setRecordsTotal(getGroupCount(request));
return groupResult;
}
private List<DeviceGroup> getPlainDeviceGroups(GroupPaginationRequest request) throws GroupManagementException {
List<DeviceGroup> deviceGroups = new ArrayList<>(); List<DeviceGroup> deviceGroups = new ArrayList<>();
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
@ -228,7 +204,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
return deviceGroups; PaginationResult groupResult = new PaginationResult();
groupResult.setData(deviceGroups);
groupResult.setRecordsTotal(getGroupCount(request));
return groupResult;
} }
@Override @Override
@ -240,57 +219,70 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager(); .getUserStoreManager();
String[] roleList = userStoreManager.getRoleListOfUser(username); String[] roleList = userStoreManager.getRoleListOfUser(username);
for (String role : roleList) { GroupManagementDAOFactory.openConnection();
if (role != null && role.contains("Internal/group-")) { List<DeviceGroup> deviceGroups = this.groupDAO.getOwnGroups(username, tenantId);
DeviceGroup deviceGroup = checkAndExtractNonExistingGroup(groups, role); for (DeviceGroup deviceGroup : deviceGroups) {
if (deviceGroup != null) { groups.put(deviceGroup.getGroupId(), deviceGroup);
groups.put(deviceGroup.getGroupId(), deviceGroup); }
} deviceGroups = this.groupDAO.getGroups(roleList, tenantId);
} for (DeviceGroup deviceGroup : deviceGroups) {
groups.put(deviceGroup.getGroupId(), deviceGroup);
} }
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new GroupManagementException("Error occurred while getting user store manager.", e); throw new GroupManagementException("Error occurred while getting user store manager.", e);
} catch (SQLException e) {
throw new GroupManagementException("Error occurred while retrieving all groups accessible to user.", e);
} catch (GroupManagementDAOException e) {
throw new GroupManagementException(e);
} finally {
GroupManagementDAOFactory.closeConnection();
} }
return new ArrayList<>(groups.values()); return new ArrayList<>(groups.values());
} }
public PaginationResult getGroups(String currentUser, GroupPaginationRequest request) throws GroupManagementException { private List<Integer> getGroupIds(String username) throws GroupManagementException {
request = DeviceManagerUtil.validateGroupListPageSize(request); UserStoreManager userStoreManager;
int startIndex = request.getStartIndex(); List<Integer> deviceGroupIds = new ArrayList<>();
int count = request.getRowCount();
int index = 0;
request.setRowCount(0);
List<DeviceGroup> allMatchingGroups = this.getPlainDeviceGroups(request);
List<DeviceGroup> deviceGroups = new ArrayList<>();
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
UserStoreManager userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager(); .getUserStoreManager();
String[] roleList = userStoreManager.getRoleListOfUser(currentUser); String[] roleList = userStoreManager.getRoleListOfUser(username);
List<Integer> groupIds = new ArrayList<>(); GroupManagementDAOFactory.openConnection();
for (String role : roleList) { deviceGroupIds = this.groupDAO.getOwnGroupIds(username, tenantId);
if (role != null && role.contains("Internal/group-")) { deviceGroupIds.addAll(this.groupDAO.getGroupIds(roleList, tenantId));
int groupId = Integer.parseInt(role.split("-")[1]);
if (!groupIds.contains(groupId)) {
groupIds.add(groupId);
}
}
}
for (DeviceGroup group : allMatchingGroups) {
int groupId = group.getGroupId();
if (groupIds.contains(groupId)) {
if (startIndex <= index && index < count) {
deviceGroups.add(group);
}
index++;
}
}
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new GroupManagementException("Error occurred while getting user store manager.", e); throw new GroupManagementException("Error occurred while getting user store manager.", e);
} catch (SQLException e) {
throw new GroupManagementException("Error occurred while retrieving all groups accessible to user.", e);
} catch (GroupManagementDAOException e) {
throw new GroupManagementException(e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
return deviceGroupIds;
}
@Override
public PaginationResult getGroups(String currentUser, GroupPaginationRequest request)
throws GroupManagementException {
request = DeviceManagerUtil.validateGroupListPageSize(request);
List<Integer> allDeviceGroupIdsOfUser = getGroupIds(currentUser);
List<DeviceGroup> allMatchingGroups = new ArrayList<>();
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection();
allMatchingGroups = this.groupDAO.getGroups(request, allDeviceGroupIdsOfUser, tenantId);
} catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e);
} catch (SQLException e) {
throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
} finally {
GroupManagementDAOFactory.closeConnection();
} }
PaginationResult groupResult = new PaginationResult(); PaginationResult groupResult = new PaginationResult();
groupResult.setData(deviceGroups); groupResult.setData(allMatchingGroups);
groupResult.setRecordsTotal(index); groupResult.setRecordsTotal(getGroupCount(currentUser));
return groupResult; return groupResult;
} }
@ -329,25 +321,24 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
@Override @Override
public int getGroupCount(String username) throws GroupManagementException { public int getGroupCount(String username) throws GroupManagementException {
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
int count = 0; int count;
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();
String[] roleList = userStoreManager.getRoleListOfUser(username); String[] roleList = userStoreManager.getRoleListOfUser(username);
List<Integer> groupIds = new ArrayList<>(); GroupManagementDAOFactory.openConnection();
for (String role : roleList) { count = groupDAO.getOwnGroupsCount(username, tenantId);
if (role != null && role.contains("Internal/group-")) { count += groupDAO.getGroupsCount(roleList, tenantId);
int groupId = Integer.parseInt(role.split("-")[1]);
if (!groupIds.contains(groupId)) {
groupIds.add(groupId);
count++;
}
}
}
return count; return count;
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new GroupManagementException("Error occurred while getting user store manager.", e); throw new GroupManagementException("Error occurred while getting user store manager.", e);
} catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while retrieving group count of user '" + username + "'", e);
} catch (SQLException e) {
throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
} finally {
GroupManagementDAOFactory.closeConnection();
} }
} }
@ -355,103 +346,41 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
@SuppressWarnings("Duplicates") public void manageGroupSharing(int groupId, List<String> newRoles)
public void manageGroupSharing(int groupId, String username, List<String> newRoles) throws GroupManagementException, RoleDoesNotExistException {
throws GroupManagementException, UserDoesNotExistException, RoleDoesNotExistException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
try { try {
userStoreManager = userStoreManager =
DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
tenantId).getUserStoreManager(); tenantId).getUserStoreManager();
if (!userStoreManager.isExistingUser(username)) { List<String> currentUserRoles = getRoles(groupId);
throw new UserDoesNotExistException("User not exists with name " + username); GroupManagementDAOFactory.beginTransaction();
}
List<String> currentGroupRoles = getRoles(groupId);
List<String> currentUserRoles = getRoles(username, groupId);
List<String> rolesToAdd = new ArrayList<>();
List<String> rolesToRemove = new ArrayList<>();
String roleNamePrefix = "Internal/group-" + groupId + "-";
for (String role : newRoles) { for (String role : newRoles) {
if (currentGroupRoles.contains(role)) { if (!userStoreManager.isExistingRole(role)) {
if (!currentUserRoles.contains(role)) { throw new RoleDoesNotExistException("Role '" + role + "' does not exists in the user store.");
rolesToAdd.add(roleNamePrefix + role); }
} // Removing role from current user roles of the group will return true if role exist.
} else { // So we don't need to add it to the db again.
throw new RoleDoesNotExistException("Role '" + role + "' is not exists in requested group."); if (!currentUserRoles.remove(role)) {
// If group doesn't have the role, it is adding to the db.
groupDAO.addRole(groupId, role, tenantId);
} }
} }
for (String role : currentUserRoles) { for (String role : currentUserRoles) {
if (currentGroupRoles.contains(role)) { // Removing old roles from db which are not available in the new roles list.
if (!newRoles.contains(role)) { groupDAO.removeRole(groupId, role, tenantId);
rolesToRemove.add(roleNamePrefix + role);
}
} else {
throw new RoleDoesNotExistException("Role '" + role + "' is not exists in requested group.");
}
} }
userStoreManager.updateRoleListOfUser(username, GroupManagementDAOFactory.commitTransaction();
rolesToRemove.toArray(new String[rolesToRemove.size()]), } catch (GroupManagementDAOException e) {
rolesToAdd.toArray(new String[rolesToAdd.size()])); GroupManagementDAOFactory.rollbackTransaction();
throw new GroupManagementException(e);
} catch (UserStoreException e) { } catch (UserStoreException e) {
if (e instanceof UserDoesNotExistException) {
throw (UserDoesNotExistException) e;
}
throw new GroupManagementException("User store error in updating sharing roles.", e); throw new GroupManagementException("User store error in updating sharing roles.", e);
} } catch (TransactionManagementException e) {
} throw new GroupManagementException(e);
} finally {
/** GroupManagementDAOFactory.closeConnection();
* {@inheritDoc}
*/
@Override
public boolean addGroupSharingRole(String username, int groupId, String roleName, String[] permissions)
throws GroupManagementException {
if (groupId == -1) {
return false;
}
UserStoreManager userStoreManager;
String role;
String[] userNames = new String[1];
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager();
role = "Internal/group-" + groupId + "-" + roleName;
userNames[0] = username;
Permission[] carbonPermissions = new Permission[permissions.length];
for (int i = 0; i < permissions.length; i++) {
carbonPermissions[i] = new Permission(permissions[i], CarbonConstants.UI_PERMISSION_ACTION);
}
userStoreManager.addRole(role, userNames, carbonPermissions);
return true;
} catch (UserStoreException e) {
String errorMsg = "User store error in adding role to group id:" + groupId;
throw new GroupManagementException(errorMsg, e);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeGroupSharingRole(int groupId, String roleName) throws GroupManagementException {
if (groupId == -1) {
return false;
}
UserStoreManager userStoreManager;
String role;
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager();
role = "Internal/group-" + groupId + "-" + roleName;
userStoreManager.deleteRole(role);
return true;
} catch (UserStoreException userStoreEx) {
String errorMsg = "User store error in adding role to group id:" + groupId;
log.error(errorMsg, userStoreEx);
throw new GroupManagementException(errorMsg, userStoreEx);
} }
} }
@ -460,92 +389,16 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
*/ */
@Override @Override
public List<String> getRoles(int groupId) throws GroupManagementException { public List<String> getRoles(int groupId) throws GroupManagementException {
UserStoreManager userStoreManager;
String[] roles;
List<String> groupRoles;
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager();
roles = userStoreManager.getRoleNames();
groupRoles = new ArrayList<>();
for (String r : roles) {
if (r != null && r.contains("Internal/group-" + groupId + "-")) {
groupRoles.add(r.replace("Internal/group-" + groupId + "-", ""));
}
}
return groupRoles;
} catch (UserStoreException userStoreEx) {
String errorMsg = "User store error in adding role to group id:" + groupId;
log.error(errorMsg, userStoreEx);
throw new GroupManagementException(errorMsg, userStoreEx);
}
}
/**
* {@inheritDoc}
*/
@Override
public List<String> getRoles(String username, int groupId)
throws GroupManagementException, UserDoesNotExistException {
UserStoreManager userStoreManager;
List<String> groupRoleList = new ArrayList<>();
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) GroupManagementDAOFactory.openConnection();
.getUserStoreManager(); return groupDAO.getRoles(groupId, tenantId);
if (!userStoreManager.isExistingUser(username)) { } catch (GroupManagementDAOException e) {
throw new UserDoesNotExistException("User not exists with name " + username); throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e);
} } catch (SQLException e) {
String[] roleList = userStoreManager.getRoleListOfUser(username); throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
for (String role : roleList) { } finally {
if (role != null && role.contains("Internal/group-" + groupId)) { GroupManagementDAOFactory.closeConnection();
String roleName = role.replace("Internal/group-" + groupId + "-", "");
groupRoleList.add(roleName);
}
}
return groupRoleList;
} catch (UserStoreException e) {
if (e instanceof UserDoesNotExistException) {
throw (UserDoesNotExistException) e;
}
throw new GroupManagementException("Error occurred while getting user store manager.", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public List<GroupUser> getUsers(int groupId) throws GroupManagementException {
UserStoreManager userStoreManager;
Map<String, GroupUser> groupUserHashMap = new HashMap<>();
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager();
List<String> rolesForGroup = this.getRoles(groupId);
for (String role : rolesForGroup) {
String[] users = userStoreManager.getUserListOfRole("Internal/group-" + groupId + "-" + role);
for (String user : users) {
GroupUser groupUser;
if (groupUserHashMap.containsKey(user)) {
groupUser = groupUserHashMap.get(user);
groupUser.getGroupRoles().add(role);
} else {
groupUser = new GroupUser();
groupUser.setUsername(user);
groupUser.setGroupRoles(new ArrayList<String>());
groupUser.getGroupRoles().add(role);
groupUserHashMap.put(user, groupUser);
}
}
}
return new ArrayList<>(groupUserHashMap.values());
} catch (UserStoreException e) {
String errorMsg = "User store error in fetching user list for group id:" + groupId;
log.error(errorMsg, e);
throw new GroupManagementException(errorMsg, e);
} }
} }
@ -653,58 +506,26 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public String[] getPermissions(String username, int groupId) public List<DeviceGroup> getGroups(String username, String permission) throws GroupManagementException {
throws GroupManagementException, UserDoesNotExistException { List<DeviceGroup> deviceGroups = getGroups(username);
Map<Integer, DeviceGroup> permittedDeviceGroups = new HashMap<>();
UserRealm userRealm; UserRealm userRealm;
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);
List<String> lstPermissions = new ArrayList<>(); for (DeviceGroup deviceGroup : deviceGroups) {
String[] resourceIds = userRealm.getAuthorizationManager().getAllowedUIResourcesForUser(username, "/"); List<String> roles = getRoles(deviceGroup.getGroupId());
if (resourceIds != null) { for (String roleName : roles) {
for (String resourceId : resourceIds) { if (userRealm.getAuthorizationManager().
for (String roleName : roles) { isRoleAuthorized(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION)) {
if (userRealm.getAuthorizationManager(). permittedDeviceGroups.put(deviceGroup.getGroupId(), deviceGroup);
isRoleAuthorized("Internal/group-" + groupId + "-" + roleName, resourceId,
CarbonConstants.UI_PERMISSION_ACTION)) {
lstPermissions.add(resourceId);
}
} }
} }
} }
String[] permissions = lstPermissions.toArray(new String[lstPermissions.size()]);
return UserCoreUtil.optimizePermissions(permissions);
} catch (UserStoreException e) {
throw new GroupManagementException("Error occurred while getting user realm.", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public List<DeviceGroup> getGroups(String username, String permission)
throws GroupManagementException {
UserRealm userRealm;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<Integer, DeviceGroup> groups = new HashMap<>();
try {
userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
String[] roles = userRealm.getUserStoreManager().getRoleListOfUser(username);
for (String role : roles) {
if (role != null && role.contains("Internal/group-") && userRealm.getAuthorizationManager()
.isRoleAuthorized(role, permission, CarbonConstants.UI_PERMISSION_ACTION)) {
DeviceGroup group = checkAndExtractNonExistingGroup(groups, role);
if (group != null) {
groups.put(group.getGroupId(), group);
}
}
}
return new ArrayList<>(groups.values());
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new GroupManagementException("Error occurred while getting user realm.", e); throw new GroupManagementException("Error occurred while getting user realm.", e);
} }
return new ArrayList<>(permittedDeviceGroups.values());
} }
@Override @Override
@ -725,26 +546,4 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
} }
/**
* This method returns group belongs to particular role, if it is not existed in groups map.
*
* @param groups existing groups map.
* @param role group related role which needs to evaluate.
* @return device group if it is not existing in the groups map.
* @throws GroupManagementException
*/
private DeviceGroup checkAndExtractNonExistingGroup(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;
}
} }

@ -78,8 +78,6 @@ public class TestDataHolder {
DeviceGroup deviceGroup = new DeviceGroup(); DeviceGroup deviceGroup = new DeviceGroup();
deviceGroup.setName("Test device group"); deviceGroup.setName("Test device group");
deviceGroup.setDescription("Test description"); deviceGroup.setDescription("Test description");
deviceGroup.setDateOfCreation(new Date().getTime());
deviceGroup.setDateOfLastUpdate(new Date().getTime());
deviceGroup.setOwner(OWNER); deviceGroup.setOwner(OWNER);
return deviceGroup; return deviceGroup;
} }

@ -31,7 +31,6 @@ 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.common.TestDataHolder;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Date;
import java.util.List; import java.util.List;
public class GroupPersistTests extends BaseDeviceManagementTest { public class GroupPersistTests extends BaseDeviceManagementTest {
@ -165,12 +164,10 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
@Test(dependsOnMethods = {"removeDeviceFromGroupTest"}) @Test(dependsOnMethods = {"removeDeviceFromGroupTest"})
public void updateGroupTest() { public void updateGroupTest() {
long time = new Date().getTime();
String name = "Test Updated"; String name = "Test Updated";
String desc = "Desc updated"; String desc = "Desc updated";
DeviceGroup group = getGroupById(groupId); DeviceGroup group = getGroupById(groupId);
Assert.assertNotNull(group, "Group is null"); Assert.assertNotNull(group, "Group is null");
group.setDateOfLastUpdate(time);
group.setName(name); group.setName(name);
group.setDescription(desc); group.setDescription(desc);
try { try {
@ -195,7 +192,6 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
Assert.assertNotNull(group, "Group is null"); Assert.assertNotNull(group, "Group is null");
Assert.assertEquals(group.getName(), name, "Group name"); Assert.assertEquals(group.getName(), name, "Group name");
Assert.assertEquals(group.getDescription(), desc, "Group description"); Assert.assertEquals(group.getDescription(), desc, "Group description");
Assert.assertEquals((long) group.getDateOfLastUpdate(), time, "Update time");
} }
@Test(dependsOnMethods = {"updateGroupTest"}) @Test(dependsOnMethods = {"updateGroupTest"})

@ -10,13 +10,21 @@ CREATE TABLE IF NOT EXISTS DM_GROUP (
ID INTEGER AUTO_INCREMENT NOT NULL, ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_NAME VARCHAR(100) DEFAULT NULL, GROUP_NAME VARCHAR(100) DEFAULT NULL,
DESCRIPTION TEXT DEFAULT NULL, DESCRIPTION TEXT DEFAULT NULL,
DATE_OF_CREATE BIGINT DEFAULT NULL,
DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL,
OWNER VARCHAR(45) DEFAULT NULL, OWNER VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0, TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID) PRIMARY KEY (ID)
); );
CREATE TABLE IF NOT EXISTS DM_ROLE_GROUP_MAP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_ID INTEGER DEFAULT NULL,
ROLE VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_ROLE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
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,

@ -10,13 +10,21 @@ CREATE TABLE IF NOT EXISTS DM_GROUP (
ID INTEGER AUTO_INCREMENT NOT NULL, ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_NAME VARCHAR(100) DEFAULT NULL, GROUP_NAME VARCHAR(100) DEFAULT NULL,
DESCRIPTION TEXT DEFAULT NULL, DESCRIPTION TEXT DEFAULT NULL,
DATE_OF_CREATE BIGINT DEFAULT NULL,
DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL,
OWNER VARCHAR(45) DEFAULT NULL, OWNER VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0, TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID) PRIMARY KEY (ID)
); );
CREATE TABLE IF NOT EXISTS DM_ROLE_GROUP_MAP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_ID INTEGER DEFAULT NULL,
ROLE VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_ROLE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
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,

@ -11,6 +11,33 @@ CREATE TABLE DM_DEVICE_TYPE (
IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_DEVICE_TYPE' AND OBJECT_ID = OBJECT_ID('DM_DEVICE_TYPE')) IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_DEVICE_TYPE' AND OBJECT_ID = OBJECT_ID('DM_DEVICE_TYPE'))
CREATE INDEX IDX_DEVICE_TYPE ON DM_DEVICE_TYPE (NAME); CREATE INDEX IDX_DEVICE_TYPE ON DM_DEVICE_TYPE (NAME);
IF NOT EXISTS(SELECT *
FROM SYS.OBJECTS
WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_GROUP]') AND TYPE IN (N'U'))
CREATE TABLE DM_GROUP (
ID INTEGER IDENTITY (1, 1) NOT NULL,
GROUP_NAME VARCHAR(100) DEFAULT NULL,
DESCRIPTION VARCHAR(MAX) DEFAULT NULL,
OWNER VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID)
);
IF NOT EXISTS(SELECT *
FROM SYS.OBJECTS
WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_ROLE_GROUP_MAP]') AND TYPE IN (N'U'))
CREATE TABLE DM_ROLE_GROUP_MAP (
ID INTEGER IDENTITY (1, 1) NOT NULL,
GROUP_ID INTEGER DEFAULT NULL,
ROLE VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT FK_DM_ROLE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
REFERENCES DM_GROUP (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_DEVICE]') AND TYPE IN (N'U')) IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_DEVICE]') AND TYPE IN (N'U'))
CREATE TABLE DM_DEVICE ( CREATE TABLE DM_DEVICE (
ID INTEGER IDENTITY(1,1) NOT NULL, ID INTEGER IDENTITY(1,1) NOT NULL,
@ -25,6 +52,25 @@ CREATE TABLE DM_DEVICE (
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
); );
IF NOT EXISTS(SELECT *
FROM SYS.OBJECTS
WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_DEVICE_GROUP_MAP]') AND TYPE IN (N'U'))
CREATE TABLE DM_DEVICE_GROUP_MAP (
ID INTEGER IDENTITY (1, 1) 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
);
IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_DM_DEVICE' AND OBJECT_ID = OBJECT_ID('DM_DEVICE')) IF NOT EXISTS (SELECT * FROM SYS.INDEXES WHERE NAME = 'IDX_DM_DEVICE' AND OBJECT_ID = OBJECT_ID('DM_DEVICE'))
CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID); CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID);

@ -8,6 +8,29 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE (
CREATE INDEX IDX_DEVICE_TYPE ON DM_DEVICE_TYPE (NAME); CREATE INDEX IDX_DEVICE_TYPE ON DM_DEVICE_TYPE (NAME);
CREATE TABLE IF NOT EXISTS DM_GROUP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_NAME VARCHAR(100) DEFAULT NULL,
DESCRIPTION TEXT DEFAULT NULL,
OWNER VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID)
)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS DM_ROLE_GROUP_MAP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_ID INTEGER DEFAULT NULL,
ROLE VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT DM_ROLE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
REFERENCES DM_GROUP (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = InnoDB;
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,
@ -23,6 +46,23 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE (
CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID); CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID);
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
)
ENGINE = InnoDB;
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(20) NOT NULL, TYPE VARCHAR(20) NOT NULL,

@ -25,8 +25,6 @@ CREATE TABLE DM_GROUP (
ID NUMBER(10) NOT NULL, ID NUMBER(10) NOT NULL,
DESCRIPTION CLOB DEFAULT NULL, DESCRIPTION CLOB DEFAULT NULL,
GROUP_NAME VARCHAR2(100) DEFAULT NULL, GROUP_NAME VARCHAR2(100) DEFAULT NULL,
DATE_OF_CREATE TIMESTAMP(0) DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP(0) DEFAULT NULL,
OWNER VARCHAR2(45) DEFAULT NULL, OWNER VARCHAR2(45) DEFAULT NULL,
TENANT_ID NUMBER(10) DEFAULT 0, TENANT_ID NUMBER(10) DEFAULT 0,
CONSTRAINT PK_DM_GROUP PRIMARY KEY (ID) CONSTRAINT PK_DM_GROUP PRIMARY KEY (ID)
@ -46,6 +44,32 @@ WHEN (NEW.ID IS NULL)
END; END;
/ /
CREATE TABLE DM_ROLE_GROUP_MAP (
ID NUMBER(10) NOT NULL,
GROUP_ID NUMBER(10) DEFAULT NULL,
ROLE VARCHAR2(45) DEFAULT NULL,
TENANT_ID NUMBER(10) DEFAULT 0,
CONSTRAINT PK_DM_GROUP PRIMARY KEY (ID),
CONSTRAINT fk_DM_ROLE_GROUP_MAP_GROUP2 FOREIGN KEY (GROUP_ID)
REFERENCES DM_GROUP (ID)
)
/
-- Generate ID using sequence and trigger
CREATE SEQUENCE DM_ROLE_GROUP_MAP_seq START WITH 1 INCREMENT BY 1 NOCACHE
/
CREATE OR REPLACE TRIGGER DM_ROLE_GROUP_MAP_seq_tr
BEFORE INSERT
ON DM_ROLE_GROUP_MAP
REFERENCING NEW AS NEW
FOR EACH ROW
WHEN (NEW.ID IS NULL)
BEGIN
SELECT DM_ROLE_GROUP_MAP_seq.NEXTVAL
INTO :NEW.ID
FROM DUAL;
END;
/
CREATE TABLE DM_DEVICE ( CREATE TABLE DM_DEVICE (
ID NUMBER(10) NOT NULL, ID NUMBER(10) NOT NULL,
DESCRIPTION CLOB DEFAULT NULL, DESCRIPTION CLOB DEFAULT NULL,

@ -8,6 +8,24 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE (
CREATE INDEX IDX_DEVICE_TYPE ON DM_DEVICE_TYPE (NAME); CREATE INDEX IDX_DEVICE_TYPE ON DM_DEVICE_TYPE (NAME);
CREATE TABLE IF NOT EXISTS DM_GROUP (
ID BIGSERIAL NOT NULL PRIMARY KEY,
DESCRIPTION TEXT DEFAULT NULL,
NAME VARCHAR(100) DEFAULT NULL,
OWNER VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS DM_ROLE_GROUP_MAP (
ID BIGSERIAL NOT NULL PRIMARY KEY,
GROUP_ID INTEGER DEFAULT NULL,
ROLE VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_DM_ROLE_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_DEVICE ( CREATE TABLE IF NOT EXISTS DM_DEVICE (
ID BIGSERIAL NOT NULL PRIMARY KEY, ID BIGSERIAL NOT NULL PRIMARY KEY,
DESCRIPTION TEXT DEFAULT NULL, DESCRIPTION TEXT DEFAULT NULL,
@ -22,6 +40,18 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE (
CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID); CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID);
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP (
ID BIGSERIAL NOT NULL PRIMARY KEY,
DEVICE_ID INTEGER DEFAULT NULL,
GROUP_ID INTEGER DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,
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 BIGSERIAL NOT NULL PRIMARY KEY, ID BIGSERIAL NOT NULL PRIMARY KEY,
TYPE VARCHAR(50) NOT NULL, TYPE VARCHAR(50) NOT NULL,

Loading…
Cancel
Save