Merge pull request #205 from charithag/master

Refactor group management
revert-70aa11f8
Prabath Abeysekara 9 years ago
commit 30e5666750

@ -1,20 +1,19 @@
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package org.wso2.carbon.device.mgt.common.group.mgt; package org.wso2.carbon.device.mgt.common.group.mgt;
@ -29,7 +28,6 @@ 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;
@ -38,15 +36,6 @@ 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;

@ -0,0 +1,60 @@
/*
* 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.common.group.mgt;
/**
* This class represents a custom exception specified for group management
*/
public class GroupAlreadyEixistException extends Exception {
private static final long serialVersionUID = -312678379574816874L;
private String errorMessage;
public GroupAlreadyEixistException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public GroupAlreadyEixistException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public GroupAlreadyEixistException(String msg) {
super(msg);
setErrorMessage(msg);
}
public GroupAlreadyEixistException() {
super();
}
public GroupAlreadyEixistException(Throwable cause) {
super(cause);
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -28,13 +28,14 @@ import java.util.List;
*/ */
public class DeviceGroupBuilder extends DeviceGroup { public class DeviceGroupBuilder extends DeviceGroup {
private int groupId;
/** /**
* Set device group to be decorated with the builder * Set device group to be decorated with the builder
* *
* @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());
@ -44,11 +45,6 @@ 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);
@ -64,4 +60,11 @@ public class DeviceGroupBuilder extends DeviceGroup {
return super.getGroup(); return super.getGroup();
} }
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
} }

@ -19,7 +19,6 @@
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.PaginationRequest;
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;
@ -42,37 +41,57 @@ public interface GroupDAO {
/** /**
* Update an existing Device Group. * Update an existing Device Group.
* *
* @param deviceGroup group to update. * @param deviceGroup group to update.
* @param oldGroupName of the group.
* @param oldOwner of the group.
* @param tenantId of the group.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
void updateGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException; void updateGroup(DeviceGroup deviceGroup, String oldGroupName, String oldOwner, int tenantId)
throws GroupManagementDAOException;
/** /**
* Delete an existing Device Group. * Delete an existing Device Group.
* *
* @param groupId to be deleted. * @param groupName to be deleted.
* @param owner of the group.
* @param tenantId of the group.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
void deleteGroup(int groupId, int tenantId) throws GroupManagementDAOException; void deleteGroup(String groupName, String owner, int tenantId) throws GroupManagementDAOException;
/** /**
* Get device group by id. * Get device group by id.
* *
* @param groupId of Device Group. * @param groupId of Device Group.
* @param tenantId of the group.
* @return Device Group in tenant with specified name. * @return Device Group in tenant with specified name.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException; DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException;
/**
* Get device group by name.
*
* @param groupName of Device Group.
* @param owner of the group.
* @param tenantId of the group.
* @return Device Group in tenant with specified name.
* @throws GroupManagementDAOException
*/
DeviceGroupBuilder getGroup(String groupName, String owner, int tenantId) throws GroupManagementDAOException;
/** /**
* Get the list of Device Groups in tenant. * Get the list of Device Groups in tenant.
* *
* @param request for pagination. * @param startIndex for pagination.
* @param rowCount for pagination.
* @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
*/ */
List<DeviceGroupBuilder> getGroups(PaginationRequest request, int tenantId) throws GroupManagementDAOException; List<DeviceGroupBuilder> getGroups(int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException;
/** /**
@ -98,70 +117,81 @@ public interface GroupDAO {
* Check group already existed with given name. * Check group already existed with given name.
* *
* @param groupName of the Device Group. * @param groupName of the Device Group.
* @param owner of the Device Group.
* @param tenantId of user's tenant. * @param tenantId of user's tenant.
* @return existence of group with name * @return existence of group with name
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException; boolean isGroupExist(String groupName, String owner, int tenantId) throws GroupManagementDAOException;
/** /**
* Add device to a given Device Group. * Add device to a given Device Group.
* *
* @param groupId of the Device Group. * @param groupName of the Device Group.
* @param owner of the Device Group.
* @param deviceId of the device. * @param deviceId of the device.
* @param tenantId of user's tenant. * @param tenantId of user's tenant.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
void addDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException; void addDevice(String groupName, String owner, int deviceId, int tenantId) throws GroupManagementDAOException;
/** /**
* Remove device from the Device Group. * Remove device from the Device Group.
* *
* @param groupId of the Device Group. * @param groupName of the Device Group.
* @param owner of the Device Group.
* @param deviceId of the device. * @param deviceId of the device.
* @param tenantId of user's tenant. * @param tenantId of user's tenant.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
void removeDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException; void removeDevice(String groupName, String owner, int deviceId, int tenantId) throws GroupManagementDAOException;
/** /**
* Check device is belonging to a Device Group. * Check device is belonging to a Device Group.
* *
* @param groupId of the Device Group. * @param groupName of the Device Group.
* @param owner of the Device Group.
* @param deviceId of the device. * @param deviceId of the device.
* @param tenantId of user's tenant. * @param tenantId of user's tenant.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
boolean isDeviceMappedToGroup(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException; boolean isDeviceMappedToGroup(String groupName, String owner, int deviceId, int tenantId)
throws GroupManagementDAOException;
/** /**
* Get count of devices in a Device Group. * Get count of devices in a Device Group.
* *
* @param groupId of the Device Group. * @param groupName of the Device Group.
* @param owner of the Device Group.
* @param tenantId of user's tenant. * @param tenantId of user's tenant.
* @return device count. * @return device count.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
int getDeviceCount(int groupId, int tenantId) throws GroupManagementDAOException; int getDeviceCount(String groupName, String owner, int tenantId) throws GroupManagementDAOException;
/** /**
* Get all devices of a given tenant and device group. * Get all devices of a given tenant and device group.
* *
* @param groupId of the group. * @param groupName of the group.
* @param owner of the Device Group.
* @param tenantId of user's tenant. * @param tenantId of user's tenant.
* @return list of device in group * @return list of device in group
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
List<Device> getDevices(int groupId, int tenantId) throws GroupManagementDAOException; List<Device> getDevices(String groupName, String owner, int tenantId) throws GroupManagementDAOException;
/** /**
* Get all devices of a given tenant and device group. * Get paginated result of devices of a given tenant and device group.
* *
* @param groupId of the group. * @param groupName of the group.
* @param request for pagination. * @param owner of the Device Group.
* @param startIndex for pagination.
* @param rowCount for pagination.
* @param tenantId of user's tenant. * @param tenantId of user's tenant.
* @return list of device in group * @return list of device in group
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
List<Device> getDevices(int groupId, PaginationRequest request, int tenantId) throws GroupManagementDAOException; List<Device> getDevices(String groupName, String owner, int startIndex, int rowCount, int tenantId)
throws GroupManagementDAOException;
} }

@ -19,7 +19,6 @@
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.PaginationRequest;
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.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
@ -68,19 +67,21 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public void updateGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException { public void updateGroup(DeviceGroup deviceGroup, String oldGroupName, String oldOwner, int tenantId)
throws GroupManagementDAOException {
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 = ?, DATE_OF_LAST_UPDATE = ?, OWNER = ? "
+ "WHERE ID = ? AND TENANT_ID = ?"; + "WHERE GROUP_NAME = ? AND OWNER = ? 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.setInt(5, deviceGroup.getId()); stmt.setString(5, oldGroupName);
stmt.setInt(6, tenantId); stmt.setString(6, oldOwner);
stmt.setInt(7, 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 '" +
@ -91,31 +92,35 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public void deleteGroup(int groupId, int tenantId) throws GroupManagementDAOException { public void deleteGroup(String groupName, String owner, 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_DEVICE_GROUP_MAP WHERE GROUP_ID = ? AND TENANT_ID = ?"; String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = (SELECT ID AS GROUP_ID FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId); stmt.setString(1, groupName);
stmt.setInt(2, tenantId); stmt.setString(2, owner);
stmt.setInt(3, tenantId);
stmt.setInt(4, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while removing mappings for group '" + groupId + "'", e); throw new GroupManagementDAOException("Error occurred while removing mappings for group '" + groupName +
"'", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, null); GroupManagementDAOUtil.cleanupResources(stmt, null);
} }
try { try {
conn = GroupManagementDAOFactory.getConnection(); conn = GroupManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_GROUP WHERE ID = ? AND TENANT_ID = ?"; String sql = "DELETE FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId); stmt.setString(1, groupName);
stmt.setInt(2, tenantId); stmt.setString(2, owner);
stmt.setInt(3, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while deleting group '" + groupId + "'", e); throw new GroupManagementDAOException("Error occurred while deleting group '" + groupName + "'", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, null); GroupManagementDAOUtil.cleanupResources(stmt, null);
} }
@ -140,14 +145,41 @@ 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 '" +
groupId + "'", e); groupId + "'", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet); GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
} }
} }
@Override @Override
public List<DeviceGroupBuilder> getGroups(PaginationRequest request, int tenantId) public DeviceGroupBuilder getGroup(String groupName, String owner, int tenantId)
throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER "
+ "FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, groupName);
stmt.setString(2, owner);
stmt.setInt(3, tenantId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
return GroupManagementDAOUtil.loadGroup(resultSet);
} else {
return null;
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while obtaining information of Device Group '" +
groupName + "'", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
}
@Override
public List<DeviceGroupBuilder> getGroups(int startIndex, int rowCount, int tenantId)
throws GroupManagementDAOException { throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
@ -159,9 +191,9 @@ public class GroupDAOImpl implements GroupDAO {
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
//noinspection JpaQueryApiInspection //noinspection JpaQueryApiInspection
stmt.setInt(2, request.getStartIndex()); stmt.setInt(2, startIndex);
//noinspection JpaQueryApiInspection //noinspection JpaQueryApiInspection
stmt.setInt(3, request.getRowCount()); stmt.setInt(3, rowCount);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
deviceGroupList = new ArrayList<>(); deviceGroupList = new ArrayList<>();
while (resultSet.next()) { while (resultSet.next()) {
@ -181,12 +213,12 @@ public class GroupDAOImpl implements GroupDAO {
ResultSet resultSet = null; ResultSet resultSet = null;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT COUNT(ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP WHERE TENANT_ID = ?"; String sql = "SELECT COUNT(ID) AS GROUP_COUNT 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();
if (resultSet.next()) { if (resultSet.next()) {
return resultSet.getInt("DEVICE_COUNT"); return resultSet.getInt("GROUP_COUNT");
} else { } else {
return 0; return 0;
} }
@ -205,7 +237,7 @@ public class GroupDAOImpl implements GroupDAO {
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_CREATE, DATE_OF_LAST_UPDATE, OWNER " String sql = "SELECT 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 + "%");
@ -224,15 +256,16 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException { public boolean isGroupExist(String groupName, String owner, 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 FROM DM_GROUP WHERE GROUP_NAME = ? AND TENANT_ID = ?"; String sql = "SELECT GROUP_NAME FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, groupName); stmt.setString(1, groupName);
stmt.setInt(2, tenantId); stmt.setString(2, owner);
stmt.setInt(3, tenantId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
return resultSet.next(); return resultSet.next();
} catch (SQLException e) { } catch (SQLException e) {
@ -244,77 +277,93 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public void addDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException { public void addDevice(String groupName, String owner, int deviceId, int tenantId)
throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_DEVICE_GROUP_MAP(DEVICE_ID, GROUP_ID, TENANT_ID) VALUES (?, ?, ?)"; String sql = "INSERT INTO DM_DEVICE_GROUP_MAP(DEVICE_ID, GROUP_ID, TENANT_ID) " +
"VALUES (?, (SELECT ID as GROUP_ID FROM DM_GROUP " +
"WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?), ?)";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
stmt.setInt(2, groupId); stmt.setString(2, groupName);
stmt.setInt(3, tenantId); stmt.setString(3, owner);
stmt.setInt(4, tenantId);
stmt.setInt(5, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
stmt.getGeneratedKeys(); stmt.getGeneratedKeys();
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while adding device to Group '" + groupId + "'", e); throw new GroupManagementDAOException("Error occurred while adding device to Group '" + groupName + "'", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, null); GroupManagementDAOUtil.cleanupResources(stmt, null);
} }
} }
@Override @Override
public void removeDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException { public void removeDevice(String groupName, String owner, int deviceId, int tenantId)
throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ? AND GROUP_ID = ? AND TENANT_ID = ?"; String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ? AND GROUP_ID = (SELECT ID as GROUP_ID " +
"FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
stmt.setInt(2, groupId); stmt.setString(2, groupName);
stmt.setInt(3, tenantId); stmt.setString(3, owner);
stmt.setInt(4, tenantId);
stmt.setInt(5, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
stmt.getGeneratedKeys(); stmt.getGeneratedKeys();
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while removing device from Group '" + throw new GroupManagementDAOException("Error occurred while removing device from Group '" +
groupId + "'", e); groupName + "'", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, null); GroupManagementDAOUtil.cleanupResources(stmt, null);
} }
} }
@Override @Override
public boolean isDeviceMappedToGroup(int groupId, int deviceId, int tenantId) public boolean isDeviceMappedToGroup(String groupName, String owner, int deviceId, int tenantId)
throws GroupManagementDAOException { 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 FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ? AND GROUP_ID = ? AND TENANT_ID = ?"; String sql = "SELECT dm.ID FROM DM_DEVICE_GROUP_MAP dm, (SELECT ID as GROUP_ID FROM DM_GROUP " +
"WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) dg " +
"WHERE dm.GROUP_ID = dg.GROUP_ID AND dm.ID = ? AND dm.TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId); stmt.setString(1, groupName);
stmt.setInt(2, groupId); stmt.setString(2, owner);
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
stmt.setInt(4, deviceId);
stmt.setInt(5, tenantId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
return resultSet.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 '" +
groupId + "'", e); groupName + "'", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet); GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
} }
} }
@Override @Override
public int getDeviceCount(int groupId, int tenantId) throws GroupManagementDAOException { public int getDeviceCount(String groupName, String owner, 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 COUNT(ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? " + String sql = "SELECT COUNT(gm.ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP gm, (SELECT ID as GROUP_ID " +
"AND TENANT_ID = ?"; "FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) dg " +
"WHERE dm.GROUP_ID = dg.GROUP_ID AND dm.TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId); stmt.setString(1, groupName);
stmt.setInt(2, tenantId); stmt.setString(2, owner);
stmt.setInt(3, tenantId);
stmt.setInt(4, tenantId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
return resultSet.getInt("DEVICE_COUNT"); return resultSet.getInt("DEVICE_COUNT");
@ -323,14 +372,14 @@ public class GroupDAOImpl implements GroupDAO {
} }
} 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 '" +
groupId + "'", e); groupName + "'", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet); GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
} }
} }
@Override @Override
public List<Device> getDevices(int groupId, int tenantId) throws GroupManagementDAOException { public List<Device> getDevices(String groupName, String owner, int tenantId) throws GroupManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -339,16 +388,20 @@ public class GroupDAOImpl implements GroupDAO {
conn = GroupManagementDAOFactory.getConnection(); conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT gd.DEVICE_ID, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " +
"gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, " +
"FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, " + "t.NAME AS DEVICE_TYPE FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, " +
"d.DEVICE_TYPE_ID FROM DM_DEVICE d, DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ? " + "d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID " +
"AND d.ID = dgm.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " + "FROM DM_DEVICE_GROUP_MAP dgm, DM_GROUP dg WHERE dgm.GROUP_ID = dg.ID AND dg.GROUP_NAME = ? " +
"WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; "AND dg.OWNER = ? AND dg.TENANT_ID = ?) dgm1 WHERE d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t WHERE gd.DEVICE_TYPE_ID = t.ID) d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId); stmt.setString(1, groupName);
stmt.setInt(2, tenantId); stmt.setString(2, owner);
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
stmt.setInt(4, tenantId);
stmt.setInt(5, tenantId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
@ -364,9 +417,8 @@ public class GroupDAOImpl implements GroupDAO {
return devices; return devices;
} }
@SuppressWarnings("JpaQueryApiInspection")
@Override @Override
public List<Device> getDevices(int groupId, PaginationRequest request, int tenantId) public List<Device> getDevices(String groupName, String owner, int startIndex, int rowCount, int tenantId)
throws GroupManagementDAOException { throws GroupManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -376,22 +428,25 @@ public class GroupDAOImpl implements GroupDAO {
conn = GroupManagementDAOFactory.getConnection(); conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT gd.DEVICE_ID, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " +
"gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, " +
"FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, " + "t.NAME AS DEVICE_TYPE FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, " +
"d.DEVICE_TYPE_ID FROM DM_DEVICE d, DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ? " + "d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID " +
"AND d.ID = dgm.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " + "FROM DM_DEVICE_GROUP_MAP dgm, DM_GROUP dg WHERE dgm.GROUP_ID = dg.ID AND dg.GROUP_NAME = ? " +
"WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? " + "AND dg.OWNER = ? AND dg.TENANT_ID = ?) dgm1 WHERE d.ID = dgm1.DEVICE_ID " +
"LIMIT ?, ?"; "AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t WHERE gd.DEVICE_TYPE_ID = t.ID) d1 " +
"WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?, ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId); stmt.setString(1, groupName);
stmt.setInt(2, tenantId); stmt.setString(2, owner);
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
stmt.setInt(4, tenantId);
stmt.setInt(5, tenantId);
//noinspection JpaQueryApiInspection //noinspection JpaQueryApiInspection
stmt.setInt(4, request.getStartIndex()); stmt.setInt(6, startIndex);
//noinspection JpaQueryApiInspection //noinspection JpaQueryApiInspection
stmt.setInt(5, request.getRowCount()); stmt.setInt(7, rowCount);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {

@ -82,7 +82,6 @@ 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_CREATE")); group.setDateOfCreation(resultSet.getLong("DATE_OF_CREATE"));

@ -20,8 +20,9 @@ package org.wso2.carbon.device.mgt.core.service;
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.common.group.mgt.GroupAlreadyEixistException;
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;
@ -33,41 +34,44 @@ import java.util.List;
public interface GroupManagementProviderService { 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.
* *
* @param deviceGroup to add * @param deviceGroup to add
* @param defaultRole of the deviceGroup * @param defaultRole of the deviceGroup
* @param defaultPermissions of the default role * @param defaultPermissions of the default role
* @return id of the new group
* @throws GroupManagementException * @throws GroupManagementException
*/ */
int createGroup(DeviceGroup deviceGroup, String defaultRole, void createGroup(DeviceGroup deviceGroup, String defaultRole,
String[] defaultPermissions) throws GroupManagementException; String[] defaultPermissions) throws GroupManagementException, GroupAlreadyEixistException;
/** /**
* Update existing device group * Update existing device group.
* *
* @param deviceGroup to update * @param deviceGroup to update.
* @param oldGroupName of the group.
* @param oldOwner of the group.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
void updateGroup(DeviceGroup deviceGroup) throws GroupManagementException; void updateGroup(DeviceGroup deviceGroup, String oldGroupName, String oldOwner) throws GroupManagementException;
/** /**
* Delete existing device group * Delete existing device group.
* *
* @param groupId of the group to delete * @param groupName to be deleted.
* @param owner of the group.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean deleteGroup(int groupId) throws GroupManagementException; boolean deleteGroup(String groupName, String owner) throws GroupManagementException;
/** /**
* Get device group specified by groupId * Get device group specified by group name.
* *
* @param groupId of the group of the group * @param groupName of the group.
* @param owner of the group.
* @return group * @return group
* @throws GroupManagementException * @throws GroupManagementException
*/ */
DeviceGroup getGroup(int groupId) throws GroupManagementException; DeviceGroup getGroup(String groupName, String owner) throws GroupManagementException;
/** /**
* Get list of device groups matched with %groupName% * Get list of device groups matched with %groupName%
@ -80,12 +84,14 @@ public interface GroupManagementProviderService {
List<DeviceGroup> findInGroups(String groupName, String username) throws GroupManagementException; List<DeviceGroup> findInGroups(String groupName, String username) throws GroupManagementException;
/** /**
* Get all device groups in tenant * Get paginated device groups in tenant
* *
* @return list of groups * @param startIndex for pagination.
* @param rowCount for pagination.
* @return paginated list of groups
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<DeviceGroup> getGroups(PaginationRequest request) throws GroupManagementException; PaginationResult getGroups(int startIndex, int rowCount) throws GroupManagementException;
/** /**
* Get all device group count in tenant * Get all device group count in tenant
@ -117,154 +123,158 @@ public interface GroupManagementProviderService {
* 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 groupId of the group of the group * @param groupName of the group
* @param owner 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, int groupId, String sharingRole) boolean shareGroup(String username, String groupName, String owner, 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 groupId of the group of the group * @param groupName of the group
* @param owner 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, int groupId, String sharingRole) boolean unshareGroup(String userName, String groupName, String owner, 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 groupId of the group * @param groupName of the group
* @param owner 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, int groupId, String roleName, String[] permissions) boolean addGroupSharingRole(String userName, String groupName, String owner, String roleName, String[] permissions)
throws GroupManagementException; throws GroupManagementException;
/** /**
* Remove existing sharing role for device group * Remove existing sharing role for device group
* *
* @param groupId of the group * @param groupName of the group
* @param roleName to remove * @param owner of the group
* @param roleName to remove
* @return is role removed * @return is role removed
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean removeGroupSharingRole(int groupId, String roleName) throws GroupManagementException; boolean removeGroupSharingRole(String groupName, String owner, String roleName) throws GroupManagementException;
/** /**
* Get all sharing roles for device group * Get all sharing roles for device group
* *
* @param groupId of the group * @param groupName of the group
* @param owner of the group
* @return list of roles * @return list of roles
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<String> getRoles(int groupId) throws GroupManagementException; List<String> getRoles(String groupName, String owner) 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 groupId of the group * @param groupName of the group
* @param owner of the group
* @return list of roles * @return list of roles
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<String> getRoles(String userName, int groupId) throws GroupManagementException; List<String> getRoles(String userName, String groupName, String owner) throws GroupManagementException;
/** /**
* Get device group users * Get device group users
* *
* @param groupId of the group * @param groupName of the group
* @param owner of the group
* @return list of group users * @return list of group users
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<GroupUser> getUsers(int groupId) throws GroupManagementException; List<GroupUser> getUsers(String groupName, String owner) throws GroupManagementException;
/** /**
* Get all devices in device group * Get all devices in device group.
* *
* @param groupId of the group * @param groupName of the group.
* @return list of group devices * @param owner of the group.
* @return list of group devices.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<Device> getDevices(int groupId) throws GroupManagementException; List<Device> getDevices(String groupName, String owner) throws GroupManagementException;
/** /**
* Get all devices in device group * Get all devices in device group as paginated result.
* *
* @param groupId of the group * @param groupName of the group.
* @param request PaginationRequest object holding the data for pagination * @param owner of the group.
* @return list of group devices * @param startIndex for pagination.
* @param rowCount for pagination.
* @return Paginated list of devices.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<Device> getDevices(int groupId, PaginationRequest request) throws GroupManagementException; PaginationResult getDevices(String groupName, String owner, int startIndex, int rowCount)
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 groupId Name of the group * @param groupName of the group.
* @param owner of the group.
* @return returns the device count. * @return returns the device count.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
int getDeviceCount(int groupId) throws GroupManagementException; int getDeviceCount(String groupName, String owner) throws GroupManagementException;
/** /**
* Add device to device group * Add device to device group.
* *
* @param deviceId of the device * @param deviceId of the device.
* @param groupId of the group * @param groupName of the group.
* @return is device added * @param owner of the group.
* @return is device added.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean addDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException; boolean addDevice(DeviceIdentifier deviceId, String groupName, String owner) throws GroupManagementException;
/** /**
* Remove device from device group * Remove device from device group.
* *
* @param deviceId of the device * @param deviceId of the device.
* @param groupId of the group * @param groupName of the group.
* @return is device removed * @param owner of the group.
* @return is device removed.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean removeDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException; boolean removeDevice(DeviceIdentifier deviceId, String groupName, String owner) 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 groupId of the group * @param groupName of the group.
* @return array of permissions * @param owner of the group.
* @return array of permissions.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
String[] getPermissions(String username, int groupId) throws GroupManagementException; String[] getPermissions(String username, String groupName, String owner) throws GroupManagementException;
/** /**
* Get device groups of user with permission * Get device groups of user with permission.
* *
* @param username of the user * @param username of the user.
* @param permission to filter * @param permission to filter.
* @return group list with specified permissions * @return group list with specified permissions.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<DeviceGroup> getGroups(String username, String permission) throws GroupManagementException; List<DeviceGroup> getGroups(String username, String permission) throws GroupManagementException;
/**
* Check user is authorized for specific permission of device group
*
* @param username of the user
* @param groupId to authorize
* @param permission to authorize
* @return is user authorized for permission
* @throws GroupManagementException
*/
boolean isAuthorized(String username, int groupId, String permission) throws GroupManagementException;
} }

@ -25,9 +25,10 @@ import org.wso2.carbon.context.CarbonContext;
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.DeviceManagementException; 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.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.GroupAlreadyEixistException;
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;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
@ -43,6 +44,7 @@ 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;
@ -64,8 +66,8 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public int createGroup(DeviceGroup deviceGroup, String defaultRole, String[] defaultPermissions) public void createGroup(DeviceGroup deviceGroup, String defaultRole, String[] defaultPermissions)
throws GroupManagementException { throws GroupManagementException, GroupAlreadyEixistException {
if (deviceGroup == null) { if (deviceGroup == null) {
throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException()); throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException());
} }
@ -74,16 +76,12 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
int groupId = -1; int groupId = -1;
try { try {
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
boolean nameIsExists = this.groupDAO.isGroupExist(deviceGroup.getName(), tenantId); boolean nameIsExists = this.groupDAO.isGroupExist(deviceGroup.getName(), deviceGroup.getOwner(), tenantId);
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; throw new GroupAlreadyEixistException("Group exist with name " + deviceGroup.getName());
} }
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction(); GroupManagementDAOFactory.rollbackTransaction();
@ -99,20 +97,22 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("DeviceGroup added: " + groupBroker.getName()); log.debug("DeviceGroup added: " + groupBroker.getName());
} }
return groupId;
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public void updateGroup(DeviceGroup deviceGroup) throws GroupManagementException { public void updateGroup(DeviceGroup deviceGroup, String oldGroupName, String oldOwner)
throws GroupManagementException {
if (deviceGroup == null) { if (deviceGroup == null) {
throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException()); throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException());
} }
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
this.groupDAO.updateGroup(deviceGroup, CarbonContext.getThreadLocalCarbonContext().getTenantId()); deviceGroup.setDateOfLastUpdate(new Date().getTime());
this.groupDAO.updateGroup(deviceGroup, oldGroupName, oldOwner, tenantId);
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction(); GroupManagementDAOFactory.rollbackTransaction();
@ -129,22 +129,22 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean deleteGroup(int groupId) throws GroupManagementException { public boolean deleteGroup(String groupName, String owner) throws GroupManagementException {
String roleName; String roleName;
DeviceGroup deviceGroup = getGroup(groupId); DeviceGroupBuilder deviceGroup = getGroupBuilder(groupName, owner);
if (deviceGroup == null) { if (deviceGroup == null) {
return false; return false;
} }
List<String> groupRoles = getRoles(groupId); List<String> groupRoles = getRoles(groupName, owner);
for (String role : groupRoles) { for (String role : groupRoles) {
if (role != null) { if (role != null) {
roleName = role.replace("Internal/group-" + groupId + "-", ""); roleName = role.replace("Internal/group-" + deviceGroup.getGroupId() + "-", "");
removeGroupSharingRole(groupId, roleName); removeGroupSharingRole(deviceGroup.getGroupId(), roleName);
} }
} }
try { try {
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
this.groupDAO.deleteGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId()); this.groupDAO.deleteGroup(groupName, owner, 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.");
@ -153,7 +153,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} 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 " +
"'" + groupId + "' data.", e); "'" + groupName + "' 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 {
@ -165,25 +165,49 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public DeviceGroup getGroup(int groupId) throws GroupManagementException { public DeviceGroup getGroup(String groupName, String owner) throws GroupManagementException {
return getGroupBuilder(groupName, owner).getGroup();
}
@SuppressWarnings("Duplicates")
private DeviceGroupBuilder getGroupBuilder(String groupName, String owner) throws GroupManagementException {
DeviceGroupBuilder deviceGroupBuilder;
try {
GroupManagementDAOFactory.openConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
deviceGroupBuilder = this.groupDAO.getGroup(groupName, owner, tenantId);
} catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while obtaining group '" + groupName + "'", e);
} catch (SQLException e) {
throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
if (deviceGroupBuilder != null) {
deviceGroupBuilder.setUsers(this.getUsers(deviceGroupBuilder.getGroupId()));
deviceGroupBuilder.setRoles(this.getRoles(deviceGroupBuilder.getGroupId()));
}
return deviceGroupBuilder;
}
@SuppressWarnings("Duplicates")
private DeviceGroupBuilder getGroupBuilder(int groupId) throws GroupManagementException {
DeviceGroupBuilder groupBroker; DeviceGroupBuilder groupBroker;
try { try {
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
groupBroker = this.groupDAO.getGroup(groupId, 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 " + groupId, 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(groupId)); groupBroker.setUsers(this.getUsers(groupBroker.getGroupId()));
groupBroker.setRoles(this.getRoles(groupId)); groupBroker.setRoles(this.getRoles(groupBroker.getGroupId()));
return groupBroker.getGroup();
} else {
return null;
} }
return groupBroker;
} }
/** /**
@ -205,20 +229,20 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} }
List<DeviceGroup> groupsWithData = new ArrayList<>(); List<DeviceGroup> groupsWithData = new ArrayList<>();
for (DeviceGroupBuilder groupBroker : deviceGroups) { for (DeviceGroupBuilder groupBroker : deviceGroups) {
groupBroker.setUsers(this.getUsers(groupBroker.getId())); groupBroker.setUsers(this.getUsers(groupBroker.getGroupId()));
groupBroker.setRoles(this.getRoles(groupBroker.getId())); groupBroker.setRoles(this.getRoles(groupBroker.getGroupId()));
groupsWithData.add(groupBroker.getGroup()); groupsWithData.add(groupBroker.getGroup());
} }
return groupsWithData; return groupsWithData;
} }
@Override @Override
public List<DeviceGroup> getGroups(PaginationRequest request) throws GroupManagementException { public PaginationResult getGroups(int startIndex, int rowCount) 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(request, tenantId); deviceGroups = this.groupDAO.getGroups(startIndex, rowCount, tenantId);
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e); throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e);
} catch (SQLException e) { } catch (SQLException e) {
@ -228,21 +252,23 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} }
List<DeviceGroup> groupsWithData = new ArrayList<>(); List<DeviceGroup> groupsWithData = new ArrayList<>();
for (DeviceGroupBuilder groupBroker : deviceGroups) { for (DeviceGroupBuilder groupBroker : deviceGroups) {
groupBroker.setUsers(this.getUsers(groupBroker.getId())); groupBroker.setUsers(this.getUsers(groupBroker.getGroupId()));
groupBroker.setRoles(this.getRoles(groupBroker.getId())); groupBroker.setRoles(this.getRoles(groupBroker.getGroupId()));
groupsWithData.add(groupBroker.getGroup()); groupsWithData.add(groupBroker.getGroup());
} }
return groupsWithData; PaginationResult paginationResult = new PaginationResult();
paginationResult.setRecordsTotal(getGroupCount());
paginationResult.setData(groupsWithData);
paginationResult.setRecordsFiltered(groupsWithData.size());
return paginationResult;
} }
@Override @Override
public int getGroupCount() throws GroupManagementException { public int getGroupCount() throws GroupManagementException {
try { try {
int count;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
count = groupDAO.getGroupCount(tenantId); return groupDAO.getGroupCount(tenantId);
return count;
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e); throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e);
} catch (SQLException e) { } catch (SQLException e) {
@ -266,9 +292,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
Map<Integer, 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-")) {
DeviceGroup deviceGroup = extractNewGroupFromRole(groups, role); DeviceGroupBuilder deviceGroupBuilder = extractNewGroupFromRole(groups, role);
if (deviceGroup != null) { if (deviceGroupBuilder != null) {
groups.put(deviceGroup.getId(), deviceGroup); groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder.getGroup());
} }
} }
} }
@ -283,15 +309,36 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
*/ */
@Override @Override
public int getGroupCount(String username) throws GroupManagementException { public int getGroupCount(String username) throws GroupManagementException {
return this.getGroups(username).size(); UserStoreManager userStoreManager;
int count = 0;
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager();
String[] roleList = userStoreManager.getRoleListOfUser(username);
List<Integer> groupIds = new ArrayList<>();
for (String role : roleList) {
if (role != null && role.contains("Internal/group-")) {
int groupId = Integer.parseInt(role.split("-")[1]);
if (!groupIds.contains(groupId)) {
groupIds.add(groupId);
count++;
}
}
}
return count;
} catch (UserStoreException e) {
throw new GroupManagementException("Error occurred while getting user store manager.", e);
}
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean shareGroup(String username, int groupId, String sharingRole) public boolean shareGroup(String username, String groupName, String owner, String sharingRole)
throws GroupManagementException { throws GroupManagementException {
int groupId = getGroupId(groupName, owner);
return modifyGroupShare(username, groupId, sharingRole, true); return modifyGroupShare(username, groupId, sharingRole, true);
} }
@ -299,26 +346,66 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean unshareGroup(String username, int groupId, String sharingRole) public boolean unshareGroup(String username, String groupName, String owner, String sharingRole)
throws GroupManagementException { throws GroupManagementException {
int groupId = getGroupId(groupName, owner);
return modifyGroupShare(username, groupId, sharingRole, false); return modifyGroupShare(username, groupId, sharingRole, false);
} }
private boolean modifyGroupShare(String username, int groupId, String sharingRole,
boolean isAddNew)
throws GroupManagementException {
if (groupId == -1) {
return false;
}
UserStoreManager userStoreManager;
String[] roles = new String[1];
try {
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 int getGroupId(String groupName, String owner) throws GroupManagementException {
DeviceGroupBuilder deviceGroupBuilder = getGroupBuilder(groupName, owner);
if (deviceGroupBuilder == null) {
return -1;
}
return deviceGroupBuilder.getGroupId();
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean addGroupSharingRole(String username, int groupId, String roleName, public boolean addGroupSharingRole(String userName, String groupName, String owner, String roleName,
String[] permissions) throws GroupManagementException {
int groupId = getGroupId(groupName, owner);
return addGroupSharingRole(userName, groupId, roleName, permissions);
}
private boolean addGroupSharingRole(String username, int groupId, String roleName,
String[] permissions) String[] permissions)
throws GroupManagementException { throws GroupManagementException {
if (groupId == -1) {
return false;
}
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
String role; String role;
String[] userNames = new String[1]; String[] userNames = new String[1];
try { try {
DeviceGroup deviceGroup = getGroup(groupId);
if (deviceGroup == null) {
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();
@ -340,15 +427,20 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean removeGroupSharingRole(int groupId, String roleName) public boolean removeGroupSharingRole(String groupName, String owner, String roleName)
throws GroupManagementException {
int groupId = getGroupId(groupName, owner);
return removeGroupSharingRole(groupId, roleName);
}
private boolean removeGroupSharingRole(int groupId, String roleName)
throws GroupManagementException { throws GroupManagementException {
if (groupId == -1) {
return false;
}
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
String role; String role;
try { try {
DeviceGroup deviceGroup = getGroup(groupId);
if (deviceGroup == null) {
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();
@ -366,7 +458,12 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<String> getRoles(int groupId) throws GroupManagementException { public List<String> getRoles(String groupName, String owner) throws GroupManagementException {
int groupId = getGroupId(groupName, owner);
return getRoles(groupId);
}
private List<String> getRoles(int groupId) throws GroupManagementException {
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
String[] roles; String[] roles;
List<String> groupRoles; List<String> groupRoles;
@ -393,7 +490,12 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<String> getRoles(String username, int groupId) throws GroupManagementException { public List<String> getRoles(String username, String groupName, String owner) throws GroupManagementException {
int groupId = getGroupId(groupName, owner);
return getRoles(username, groupId);
}
private 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 {
@ -417,6 +519,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<GroupUser> getUsers(String groupName, String owner) throws GroupManagementException {
int groupId = getGroupId(groupName, owner);
return getUsers(groupId);
}
public List<GroupUser> getUsers(int groupId) 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<>();
@ -453,11 +560,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<Device> getDevices(int groupId) throws GroupManagementException { public List<Device> getDevices(String groupName, String owner) throws GroupManagementException {
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.getConnection(); GroupManagementDAOFactory.getConnection();
return this.groupDAO.getDevices(groupId, tenantId); return this.groupDAO.getDevices(groupName, owner, tenantId);
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while getting devices in group.", e); throw new GroupManagementException("Error occurred while getting devices in group.", e);
} catch (SQLException e) { } catch (SQLException e) {
@ -471,12 +578,13 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<Device> getDevices(int groupId, PaginationRequest request) public PaginationResult getDevices(String groupName, String owner, int startIndex, int rowCount)
throws GroupManagementException { throws GroupManagementException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
List<Device> devices;
try { try {
GroupManagementDAOFactory.getConnection(); GroupManagementDAOFactory.getConnection();
return this.groupDAO.getDevices(groupId, request, tenantId); devices = this.groupDAO.getDevices(groupName, owner, startIndex, rowCount, tenantId);
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while getting devices in group.", e); throw new GroupManagementException("Error occurred while getting devices in group.", e);
} catch (SQLException e) { } catch (SQLException e) {
@ -484,17 +592,22 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
PaginationResult paginationResult = new PaginationResult();
paginationResult.setRecordsTotal(getDeviceCount(groupName, owner));
paginationResult.setData(devices);
paginationResult.setRecordsFiltered(devices.size());
return paginationResult;
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public int getDeviceCount(int groupId) throws GroupManagementException { public int getDeviceCount(String groupName, String owner) throws GroupManagementException {
try { try {
int count; int count;
GroupManagementDAOFactory.getConnection(); GroupManagementDAOFactory.getConnection();
count = groupDAO.getDeviceCount(groupId, count = groupDAO.getDeviceCount(groupName, owner,
CarbonContext.getThreadLocalCarbonContext().getTenantId()); CarbonContext.getThreadLocalCarbonContext().getTenantId());
return count; return count;
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
@ -510,25 +623,23 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean addDevice(DeviceIdentifier deviceIdentifier, int groupId) public boolean addDevice(DeviceIdentifier deviceIdentifier, String groupName, String owner)
throws GroupManagementException { throws GroupManagementException {
Device device; Device device;
DeviceGroup deviceGroup;
try { try {
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier); device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier);
deviceGroup = this.getGroup(groupId); if (device == null) {
if (device == null || deviceGroup == null) {
return false; return false;
} }
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
this.groupDAO.addDevice(groupId, device.getId(), tenantId); this.groupDAO.addDevice(groupName, owner, device.getId(), tenantId);
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
throw new GroupManagementException("Error occurred while retrieving device.", e); throw new GroupManagementException("Error occurred while retrieving device.", e);
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction(); GroupManagementDAOFactory.rollbackTransaction();
throw new GroupManagementException("Error occurred while adding device to group '" + groupId + "'.", e); throw new GroupManagementException("Error occurred while adding device to group '" + groupName + "'.", 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 {
@ -541,19 +652,17 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean removeDevice(DeviceIdentifier deviceIdentifier, int groupId) public boolean removeDevice(DeviceIdentifier deviceIdentifier, String groupName, String owner)
throws GroupManagementException { throws GroupManagementException {
Device device; Device device;
DeviceGroup deviceGroup;
try { try {
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier); device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier);
deviceGroup = this.getGroup(groupId); if (device == null) {
if (device == null || deviceGroup == null) {
return false; return false;
} }
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
this.groupDAO.removeDevice(groupId, device.getId(), tenantId); this.groupDAO.removeDevice(groupName, owner, device.getId(), tenantId);
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
throw new GroupManagementException("Error occurred while retrieving device.", e); throw new GroupManagementException("Error occurred while retrieving device.", e);
@ -561,7 +670,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
throw new GroupManagementException("Error occurred while initiating transaction.", e); throw new GroupManagementException("Error occurred while initiating transaction.", e);
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction(); GroupManagementDAOFactory.rollbackTransaction();
throw new GroupManagementException("Error occurred while adding device to group '" + groupId + "'.", e); throw new GroupManagementException("Error occurred while adding device to group '" + groupName + "'.", e);
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
@ -572,8 +681,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public String[] getPermissions(String username, int groupId) throws GroupManagementException { public String[] getPermissions(String username, String groupName, String owner) throws GroupManagementException {
UserRealm userRealm; UserRealm userRealm;
int groupId = getGroupId(groupName, owner);
List<String> roles = getRoles(username, groupId); List<String> roles = getRoles(username, groupId);
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try { try {
@ -613,9 +723,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
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)) {
DeviceGroup deviceGroup = extractNewGroupFromRole(groups, role); DeviceGroupBuilder deviceGroupBuilder = extractNewGroupFromRole(groups, role);
if (deviceGroup != null) { if (deviceGroupBuilder != null) {
groups.put(deviceGroup.getId(), deviceGroup); groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder.getGroup());
} }
} }
} }
@ -625,63 +735,12 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} }
} }
/** private DeviceGroupBuilder extractNewGroupFromRole(Map<Integer, DeviceGroup> groups, String role)
* {@inheritDoc}
*/
@Override
public boolean isAuthorized(String username, int groupId, String permission)
throws GroupManagementException {
UserRealm userRealm;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
List<String> roles = this.getRoles(username, groupId);
for (String role : roles) {
if (userRealm.getAuthorizationManager()
.isRoleAuthorized("Internal/group-" + groupId + "-" + role, permission,
CarbonConstants.UI_PERMISSION_ACTION)) {
return true;
}
}
return false;
} catch (UserStoreException e) {
throw new GroupManagementException("Error occurred while getting user realm.", e);
}
}
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 { throws GroupManagementException {
try { try {
int groupId = Integer.parseInt(role.split("-")[1]); int groupId = Integer.parseInt(role.split("-")[1]);
if (!groups.containsKey(groupId)) { if (!groups.containsKey(groupId)) {
return getGroup(groupId); return getGroupBuilder(groupId);
} }
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
log.error("Unable to extract groupId from role " + role, e); log.error("Unable to extract groupId from role " + role, e);

@ -24,7 +24,6 @@ import org.testng.Assert;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.TransactionManagementException; 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.core.common.BaseDeviceManagementTest; import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
@ -77,59 +76,6 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
log.debug("Group name: " + group.getName()); 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"}) @Test(dependsOnMethods = {"testAddGroupTest"})
public void findGroupTest() { public void findGroupTest() {
try { try {
@ -155,8 +101,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
public void getGroupTest() { public void getGroupTest() {
try { try {
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
PaginationRequest paginationRequest = new PaginationRequest(0, 1000); List<DeviceGroupBuilder> groups = groupDAO.getGroups(0, 100, TestDataHolder.SUPER_TENANT_ID);
List<DeviceGroupBuilder> groups = groupDAO.getGroups(paginationRequest, TestDataHolder.SUPER_TENANT_ID);
Assert.assertNotEquals(groups.size(), 0, "No groups found"); Assert.assertNotEquals(groups.size(), 0, "No groups found");
Assert.assertNotNull(groups.get(0), "Group is null"); Assert.assertNotNull(groups.get(0), "Group is null");
log.debug("No of Groups found: " + groups.size()); log.debug("No of Groups found: " + groups.size());
@ -173,12 +118,14 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
} }
} }
@Test(dependsOnMethods = {"updateGroupTest"}) @Test(dependsOnMethods = {"testAddGroupTest"})
public void addDeviceToGroupTest() { public void addDeviceToGroupTest() {
Device initialTestDevice = TestDataHolder.initialTestDevice; Device initialTestDevice = TestDataHolder.initialTestDevice;
DeviceGroup deviceGroup = getGroupById(groupId);
try { try {
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
groupDAO.addDevice(groupId, initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID); groupDAO.addDevice(deviceGroup.getName(), deviceGroup.getOwner(), initialTestDevice.getId(),
TestDataHolder.SUPER_TENANT_ID);
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
log.debug("Device added to group."); log.debug("Device added to group.");
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
@ -196,7 +143,8 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
try { try {
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
List<Device> groupedDevices = groupDAO.getDevices(groupId, TestDataHolder.SUPER_TENANT_ID); List<Device> groupedDevices = groupDAO.getDevices(deviceGroup.getName(), deviceGroup.getOwner(),
TestDataHolder.SUPER_TENANT_ID);
Assert.assertNotEquals(groupedDevices.size(), 0, "No device found"); Assert.assertNotEquals(groupedDevices.size(), 0, "No device found");
Assert.assertNotNull(groupedDevices.get(0), "Device is null"); Assert.assertNotNull(groupedDevices.get(0), "Device is null");
Assert.assertEquals(groupedDevices.get(0).getId(), initialTestDevice.getId(), "Device ids not matched"); Assert.assertEquals(groupedDevices.get(0).getId(), initialTestDevice.getId(), "Device ids not matched");
@ -216,14 +164,15 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
@Test(dependsOnMethods = {"addDeviceToGroupTest"}) @Test(dependsOnMethods = {"addDeviceToGroupTest"})
public void removeDeviceFromGroupTest() { public void removeDeviceFromGroupTest() {
Device initialTestDevice = TestDataHolder.initialTestDevice; Device initialTestDevice = TestDataHolder.initialTestDevice;
DeviceGroup deviceGroup = getGroupById(groupId);
try { try {
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
groupDAO.removeDevice(groupId, initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID); groupDAO.removeDevice(deviceGroup.getName(), deviceGroup.getOwner(), initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID);
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
log.debug("Group added to database."); log.debug("Device added to group.");
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction(); GroupManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while adding device '" + initialTestDevice.getName() + "'."; String msg = "Error occurred while adding device '" + initialTestDevice.getDeviceIdentifier() + "'.";
log.error(msg, e); log.error(msg, e);
Assert.fail(msg, e); Assert.fail(msg, e);
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
@ -236,14 +185,48 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
} }
@Test(dependsOnMethods = {"removeDeviceFromGroupTest"}) @Test(dependsOnMethods = {"removeDeviceFromGroupTest"})
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.generateDummyGroupData().getName(),
TestDataHolder.generateDummyGroupData().getOwner(), 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(groupId);
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 = {"updateGroupTest"})
public void deleteGroupTest() { public void deleteGroupTest() {
DeviceGroup group = getGroupById(groupId); DeviceGroup group = getGroupById(groupId);
int groupId = 0;
try { try {
Assert.assertNotNull(group, "Group is null"); Assert.assertNotNull(group, "Group is null");
groupId = group.getId();
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
groupDAO.deleteGroup(groupId, TestDataHolder.SUPER_TENANT_ID); groupDAO.deleteGroup(group.getName(), group.getOwner(), TestDataHolder.SUPER_TENANT_ID);
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
log.debug("Group deleted"); log.debug("Group deleted");
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
@ -259,7 +242,24 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
group = getGroupById(groupId); group = getGroupById(groupId);
Assert.assertNull(group, "Group not deleted"); Assert.assertNull(group, "Group is not deleted");
} }
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;
}
} }

Loading…
Cancel
Save