Add device filter changes

pull/271/head
osh 1 year ago
parent 8f78a27158
commit 9df0939ca0

@ -2749,7 +2749,15 @@ public interface DeviceManagementService {
message = "Error occurred while getting the version data.",
response = ErrorResponse.class)
})
Response getDeviceFilters();
Response getDeviceFilters(
@ApiParam(
name = "isGroups",
value = "Check if group data is needed", required = false)
@QueryParam("isGroups") boolean isGroups,
@ApiParam(
name = "isConfig",
value = "Check if config data is needed", required = false)
@QueryParam("isConfig") boolean isConfig);
@GET
@Produces(MediaType.APPLICATION_JSON)

@ -26,6 +26,10 @@ import io.entgra.device.mgt.core.application.mgt.common.exception.SubscriptionMa
import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager;
import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager;
import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil;
import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry;
import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupFilter;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
@ -101,13 +105,14 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.Map;
import java.util.Arrays;
@Path("/devices")
public class DeviceManagementServiceImpl implements DeviceManagementService {
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
private static final String DEFAULT_ADMIN_ROLE = "admin";
private static final Log log = LogFactory.getLog(DeviceManagementServiceImpl.class);
@GET
@ -1612,8 +1617,39 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@GET
@Path("/filters")
@Override
public Response getDeviceFilters() {
public Response getDeviceFilters( @QueryParam("isGroups") boolean isGroups, @QueryParam("isConfig") boolean isConfig) {
try {
String currentUser = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
List<String> permissions = DeviceMgtAPIUtils
.getUserManagementService().getPermissions(currentUser);
List<GroupFilter> groupFilters = new ArrayList<>();
List<ConfigurationEntry> configList = new ArrayList<>();
if (isGroups) {
List<String> roles = DeviceMgtAPIUtils
.getUserManagementService().getRoles(currentUser);
boolean isAdmin = DEFAULT_ADMIN_ROLE.equals(currentUser);
boolean hasAdminRole = Arrays.asList(roles).contains(DEFAULT_ADMIN_ROLE);
if (permissions.contains("/permission/admin/device-mgt/admin/groups/view")) {
if (StringUtils.isBlank(currentUser) || isAdmin || hasAdminRole) {
groupFilters = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupFilterValues(null, null);
} else {
groupFilters = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupFilterValues(currentUser, null);
}
} else {
if (hasAdminRole) {
groupFilters = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupFilterValues(null, null);
} else {
groupFilters = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupFilterValues(currentUser, null);
}
}
}
if (isConfig) {
if (permissions.contains("/permission/admin/device-mgt/platform-configurations/view")) {
PlatformConfiguration config = DeviceMgtAPIUtils.getPlatformConfigurationManagementService().
getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
configList = config.getConfiguration();
}
}
List<String> deviceTypeNames = new ArrayList<>();
List<String> ownershipNames = new ArrayList<>();
List<String> statusNames = new ArrayList<>();
@ -1633,11 +1669,25 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
deviceFilters.setDeviceTypes(deviceTypeNames);
deviceFilters.setOwnerships(ownershipNames);
deviceFilters.setStatuses(statusNames);
deviceFilters.setConfigs(configList);
deviceFilters.setGroups(groupFilters);
return Response.status(Response.Status.OK).entity(deviceFilters).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred white retrieving device types to be used in device filters.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (UserManagementException e) {
String msg = "Error occurred while retrieving permission details to be used in device filters.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (GroupManagementException e) {
String msg = "Error occurred while retrieving group data for device filters values.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ConfigurationManagementException e) {
String msg = "Error occurred while retrieving config data for device filter values.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}

@ -18,6 +18,8 @@
package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl;
import io.entgra.device.mgt.core.device.mgt.common.*;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.UserManagementException;
import io.entgra.device.mgt.core.device.mgt.core.service.UserManagementProviderService;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
@ -40,12 +42,10 @@ import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService;
import io.entgra.device.mgt.core.device.mgt.core.otp.mgt.service.OTPManagementServiceImpl;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderService;
import io.entgra.device.mgt.core.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import io.entgra.device.mgt.core.device.mgt.common.BasicUserInfo;
import io.entgra.device.mgt.core.device.mgt.common.EnrollmentInvitation;
import io.entgra.device.mgt.core.device.mgt.common.UserInfo;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.UserManagementService;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.user.api.RealmConfiguration;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
@ -88,9 +88,10 @@ public class UserManagementServiceImplTest {
}
@BeforeClass
public void setup() throws UserStoreException {
public void init() throws UserStoreException {
initMocks(this);
userManagementService = new UserManagementServiceImpl();
userManagementProviderService = Mockito.mock(UserManagementProviderService.class);
userStoreManager = Mockito.mock(UserStoreManager.class, Mockito.RETURNS_MOCKS);
deviceManagementProviderService = Mockito
.mock(DeviceManagementProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS);
@ -114,6 +115,8 @@ public class UserManagementServiceImplTest {
public void testAddUser() throws UserStoreException, ConfigurationManagementException, DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager"))
.toReturn(this.userStoreManager);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserManagementService"))
.toReturn(userManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.doReturn(true).when(userStoreManager).isExistingUser("admin");
@ -152,11 +155,27 @@ public class UserManagementServiceImplTest {
@Test(description = "This method tests the getUser method of UserManagementService", dependsOnMethods =
"testAddUser")
public void testGetUser() throws UserStoreException {
public void testGetUser() throws UserStoreException, UserManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager"))
.toReturn(this.userStoreManager);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserManagementService"))
.toReturn(userManagementProviderService);
BasicUserInfo basicUserInfo = new BasicUserInfo();
Mockito.doReturn(basicUserInfo).when(userManagementProviderService)
.getUser(Mockito.anyString());
Response response = userManagementService.getUser(TEST_USERNAME, null, null);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "User retrieval failed");
Mockito.reset(userManagementProviderService);
basicUserInfo.setUsername(TEST_USERNAME);
basicUserInfo.setFirstname(TEST_USERNAME);
basicUserInfo.setLastname(TEST_USERNAME);
basicUserInfo.setEmailAddress("test@gmail.com");
Mockito.doReturn(basicUserInfo).when(userManagementProviderService)
.getUser(Mockito.anyString());
response = userManagementService.getUser("test", null, null);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"GetUser request failed with valid parameters");
Mockito.reset(this.userManagementProviderService);
BasicUserInfo userInfo = (BasicUserInfo) response.getEntity();
Assert.assertEquals(userInfo.getFirstname(), TEST_USERNAME,
"Retrieved user object is different from the original one " + "saved");
@ -188,15 +207,24 @@ public class UserManagementServiceImplTest {
@Test(description = "This method tests the getRolesOfUser method of UserManagementService", dependsOnMethods =
{"testUpdateUser"})
public void testGetRolesOfUser() {
public void testGetRolesOfUser() throws UserManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager"))
.toReturn(this.userStoreManager);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserManagementService"))
.toReturn(userManagementProviderService);
List<String> roles= new ArrayList<>();
Mockito.doReturn(roles).when(userManagementProviderService)
.getRoles(Mockito.anyString());
Response response = userManagementService.getRolesOfUser(TEST2_USERNAME, null);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode(),
"Roles of a non-existing user was successfully retrieved");
Mockito.reset(userManagementProviderService);
Mockito.doReturn(roles).when(userManagementProviderService)
.getRoles(Mockito.anyString());
response = userManagementService.getRolesOfUser(TEST_USERNAME, null);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"Retrieval of roles of a existing user failed.");
Mockito.reset(this.userManagementProviderService);
}
@Test(description = "This method tests the IsUserExists method of UserManagementService", dependsOnMethods =
@ -232,12 +260,13 @@ public class UserManagementServiceImplTest {
public void testGetUserNames() throws UserStoreException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager"))
.toReturn(this.userStoreManager);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserManagementService"))
.toReturn(userManagementProviderService);
Mockito.doReturn(new String[] { TEST_USERNAME }).when(userStoreManager)
.listUsers(Mockito.anyString(), Mockito.anyInt());
Response response = userManagementService.getUserNames(TEST_USERNAME, null, "00", 0, 0);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
"Getting user names is failed for a valid request");
}
@Test(description = "This method tests the getUsers method of UserManagementService",
@ -245,6 +274,8 @@ public class UserManagementServiceImplTest {
public void testGetUsers() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager"))
.toReturn(userStoreManager);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserManagementService"))
.toReturn(userManagementProviderService);
Response response = userManagementService.getUsers(null, "00", 0, 10, null);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "GetUsers request failed");
}
@ -303,6 +334,8 @@ public class UserManagementServiceImplTest {
+ "DeviceManagementProviderService", dependsOnMethods = {"testGetUserCount"})
public void testNegativeScenarios1()
throws ConfigurationManagementException, DeviceManagementException, OTPManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserManagementService"))
.toReturn(userManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager"))
.toReturn(this.userStoreManager);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
@ -322,41 +355,61 @@ public class UserManagementServiceImplTest {
response = userManagementService.inviteToEnrollDevice(enrollmentInvitation);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Invite existing users to enroll device succeeded under erroneous conditions");
Mockito.reset(this.userManagementProviderService);
}
@Test(description = "This method tests the behaviour of the different methods when there is an issue is "
+ "userStoreManager", dependsOnMethods = {"testNegativeScenarios1"})
public void testNegativeScenarios2() throws UserStoreException {
public void testNegativeScenarios2() throws UserStoreException, UserManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager"))
.toReturn(this.userStoreManager);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserManagementService"))
.toReturn(userManagementProviderService);
Mockito.doThrow(new UserStoreException()).when(userStoreManager).isExistingUser(TEST3_USERNAME);
Response response = userManagementService.getUser(TEST3_USERNAME, null, null);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Response returned successful for a user retrieval with problematic inputs");
Mockito.when(this.userManagementProviderService.getUser(Mockito.anyString()))
.thenThrow(new UserManagementException());
response = userManagementService.getUser(TEST3_USERNAME, null, null);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Response returned successful for a user retrieval with problematic inputs");
UserInfo userInfo = new UserInfo();
userInfo.setUsername(TEST3_USERNAME);
Mockito.reset(this.userManagementProviderService);
Mockito.when(this.userManagementProviderService.getUser(Mockito.anyString()))
.thenThrow(new UserManagementException());
response = userManagementService.addUser(userInfo);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Response returned successful for a user addition with problematic inputs");
Mockito.reset(this.userManagementProviderService);
Mockito.when(this.userManagementProviderService.getUser(Mockito.anyString()))
.thenThrow(new UserManagementException());
response = userManagementService.updateUser(TEST3_USERNAME, null, userInfo);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Response returned successful for a user updating request with problematic inputs");
response = userManagementService.removeUser(TEST3_USERNAME, null);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
"Response returned successful for a user removal request with problematic inputs");
Mockito.reset(this.userManagementProviderService);
Mockito.when(this.userManagementProviderService.getUser(Mockito.anyString()))
.thenThrow(new UserManagementException());
response = userManagementService.getRolesOfUser(TEST3_USERNAME, null);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Response returned successful for a user role retrieval request with problematic inputs");
response = userManagementService.isUserExists(TEST3_USERNAME);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Response returned successful for checking existence of user under problematic conditions");
Mockito.reset(this.userManagementProviderService);
}
@Test(description = "This method tests the behaviour of various methods when there is an issue with UserStore "
+ "Manager", dependsOnMethods = {"testNegativeScenarios2"})
public void testNegativeScenarios3() throws UserStoreException {
public void testNegativeScenarios3() throws UserStoreException, UserManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager"))
.toReturn(this.userStoreManager);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserManagementService"))
.toReturn(userManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserRealm")).toReturn(userRealm);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreCountRetrieverService"))
.toReturn(null);
@ -370,12 +423,17 @@ public class UserManagementServiceImplTest {
.getUserClaimValue(Mockito.any(), Mockito.any(), Mockito.any());
Mockito.doThrow(new UserStoreException()).when(userStoreManager)
.listUsers(Mockito.anyString(), Mockito.anyInt());
Mockito.when(this.userManagementProviderService.getUsers(Mockito.anyString(), Mockito.anyInt(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()))
.thenThrow(new UserManagementException());
Response response = userManagementService.getUsers(TEST_USERNAME, "00", 0, 10, null);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Response returned successful for a users retrieval request.");
response = userManagementService.getUserCount();
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Response returned successful for a user count retrieval request.");
Mockito.reset(this.userManagementProviderService);
Mockito.when(this.userManagementProviderService.getUserNames(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()))
.thenThrow(new UserManagementException());
response = userManagementService.getUserNames(TEST_USERNAME, null, "00", 0, 10);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Response returned successful for a user count retrieval request.");
@ -385,6 +443,7 @@ public class UserManagementServiceImplTest {
response = userManagementService.inviteExistingUsersToEnrollDevice(deviceEnrollmentInvitation);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
"Invite existing users to enroll device succeeded under erroneous conditions");
Mockito.reset(this.userManagementProviderService);
}
/**

@ -17,6 +17,10 @@
*/
package io.entgra.device.mgt.core.device.mgt.common;
import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.ConfigurationEntry;
import io.entgra.device.mgt.core.device.mgt.common.configuration.mgt.PlatformConfiguration;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupFilter;
import java.io.Serializable;
import java.util.List;
@ -31,6 +35,10 @@ public class DeviceFilters implements Serializable {
private List<String> ownerships;
private List<String> statuses;
private List<ConfigurationEntry> configs;
private List<GroupFilter> groups;
public List<String> getDeviceTypes() {
return deviceTypes;
}
@ -54,4 +62,20 @@ public class DeviceFilters implements Serializable {
public void setStatuses(List<String> statuses) {
this.statuses = statuses;
}
public List<GroupFilter> getGroups() {
return groups;
}
public void setGroups(List<GroupFilter> groups) {
this.groups = groups;
}
public List<ConfigurationEntry> getConfigs() {
return configs;
}
public void setConfigs(List<ConfigurationEntry> configs) {
this.configs = configs;
}
}

@ -16,7 +16,7 @@
* under the License.
*/
package io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans;
package io.entgra.device.mgt.core.device.mgt.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ -0,0 +1,48 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.device.mgt.common.group.mgt;
import io.swagger.annotations.ApiModelProperty;
public class GroupFilter {
private static final long serialVersionUID = 1998131711L;
@ApiModelProperty(name = "id", value = "ID of the device group in the device group information database.")
private int id;
@ApiModelProperty(name = "name", value = "The device group name that can be set on the device group by the user.",
required = true)
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

@ -21,9 +21,9 @@ package io.entgra.device.mgt.core.device.mgt.core.dao;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.GroupPaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.ReportManagementException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroup;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupFilter;
import java.util.List;
import java.util.Map;
@ -221,6 +221,16 @@ public interface GroupDAO {
*/
List<DeviceGroup> getGroups(GroupPaginationRequest paginationRequest, int tenantId) throws GroupManagementDAOException;
/**
* Get paginated list of Device Groups Names in tenant for filtering.
*
* @param paginationRequest to filter results.
* @param tenantId of user's tenant.
* @return List of all Groups in the provided filter.
* @throws GroupManagementDAOException
*/
List<GroupFilter> getGroupFilterDetails(GroupPaginationRequest paginationRequest, int tenantId) throws GroupManagementDAOException;
/**
* Get paginated list of Device Groups in tenant with specified device group ids.
*
@ -255,6 +265,15 @@ public interface GroupDAO {
*/
List<DeviceGroup> getGroups(List<Integer> deviceGroupIds, int tenantId) throws GroupManagementDAOException;
/**
* Get the list of Device Groups in tenant for filtering.
*
* @param tenantId of user's tenant.
* @return List of all Device Groups in the provided filter.
* @throws GroupManagementDAOException
*/
List<GroupFilter> getGroupFilterDetails(List<Integer> deviceGroupIds, int tenantId) throws GroupManagementDAOException;
/**
* Get the list of Device Groups in tenant.
*
@ -469,4 +488,4 @@ public interface GroupDAO {
List<String> groupNames)
throws GroupManagementDAOException;
}
}

@ -19,6 +19,7 @@
package io.entgra.device.mgt.core.device.mgt.core.dao.impl;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.DeviceGroupRoleWrapper;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -106,6 +107,48 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
}
}
@Override
public List<GroupFilter> getGroupFilterDetails(GroupPaginationRequest request, int tenantId)
throws GroupManagementDAOException {
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, GROUP_NAME FROM DM_GROUP "
+ "WHERE TENANT_ID = ?";
if (request != null && StringUtils.isNotBlank(request.getOwner())) {
sql += " AND OWNER LIKE ?";
}
if (request != null && request.getRowCount() != 0) {
sql += " LIMIT ? OFFSET ?";
}
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIndex = 1;
stmt.setInt(paramIndex++, tenantId);
if (request != null && StringUtils.isNotBlank(request.getOwner())) {
stmt.setString(paramIndex++, request.getOwner() + "%");
}
if (request != null && request.getRowCount() != 0) {
stmt.setInt(paramIndex++, request.getRowCount());
stmt.setInt(paramIndex, request.getStartIndex());
}
List<GroupFilter> groupFilterDetails = new ArrayList<>();
try (ResultSet resultSet = stmt.executeQuery()) {
while (resultSet.next()) {
GroupFilter group = new GroupFilter();
group.setId(resultSet.getInt("ID"));
group.setName(resultSet.getString("GROUP_NAME"));
groupFilterDetails.add(group);
}
}
return groupFilterDetails;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving groups in tenant: " + tenantId;
log.error(msg);
throw new GroupManagementDAOException(msg, e);
}
}
@Override
public List<DeviceGroup> getGroups(GroupPaginationRequest request, List<Integer> deviceGroupIds,
int tenantId) throws GroupManagementDAOException {
@ -208,6 +251,47 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
}
}
@Override
public List<GroupFilter> getGroupFilterDetails(List<Integer> deviceGroupIds, int tenantId) throws GroupManagementDAOException {
int deviceGroupIdsCount = deviceGroupIds.size();
if (deviceGroupIdsCount == 0) {
return new ArrayList<>();
}
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, GROUP_NAME FROM DM_GROUP WHERE TENANT_ID = ?";
sql += " AND ID IN (";
for (int i = 0; i < deviceGroupIdsCount; i++) {
sql += (deviceGroupIdsCount - 1 != i) ? "?," : "?";
}
sql += ")";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIndex = 1;
stmt.setInt(paramIndex++, tenantId);
for (Integer deviceGroupId : deviceGroupIds) {
stmt.setInt(paramIndex++, deviceGroupId);
}
List<GroupFilter> groupFilters = new ArrayList<>();
try (ResultSet resultSet = stmt.executeQuery()) {
while (resultSet.next()) {
GroupFilter groupFilter = new GroupFilter();
groupFilter.setId(resultSet.getInt("ID"));
groupFilter.setName(resultSet.getString("GROUP_NAME"));
groupFilters.add(groupFilter);
}
}
return groupFilters;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving groups of groups IDs " + deviceGroupIds
+ " in tenant: " + tenantId;
log.error(msg);
throw new GroupManagementDAOException(msg, e);
}
}
@Override
public List<DeviceGroup> getGroups(GroupPaginationRequest request, List<Integer> deviceGroupIds,

@ -30,6 +30,7 @@ import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupAlreadyExistEx
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupNotExistException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.RoleDoesNotExistException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupFilter;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.UserStoreManager;
@ -189,6 +190,17 @@ public interface GroupManagementProviderService {
PaginationResult getGroupsWithHierarchy(String username, GroupPaginationRequest request,
boolean requireGroupProps) throws GroupManagementException;
/**
* Get device groups of the provided filter.
*
* @param username of the user.
* @param request to filter results
* @return {@link PaginationResult} paginated groups.
* @throws GroupManagementException on error during retrieval of groups for provided filter
*/
List<GroupFilter> getGroupFilterValues(String username, GroupPaginationRequest request) throws GroupManagementException;
/**
* Get all hierarchical device groups count in tenant
*

@ -26,6 +26,7 @@ import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupAlreadyExistEx
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupNotExistException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.RoleDoesNotExistException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupFilter;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceDAO;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOException;
import io.entgra.device.mgt.core.device.mgt.core.dao.DeviceManagementDAOFactory;
@ -615,6 +616,44 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
return groupResult;
}
@Override
public List<GroupFilter> getGroupFilterValues(String username, GroupPaginationRequest request) throws GroupManagementException {
if (request != null) {
DeviceManagerUtil.validateGroupListPageSize(request);
}
if (log.isDebugEnabled()) {
log.debug("Get groups filters " + username);
}
List<GroupFilter> groupFilters;
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
if (StringUtils.isBlank(username)) {
GroupManagementDAOFactory.openConnection();
groupFilters = groupDAO.getGroupFilterDetails(request, tenantId);
} else {
List<Integer> allDeviceGroupIdsOfUser = getGroupIds(username);
GroupManagementDAOFactory.openConnection();
groupFilters = groupDAO.getGroupFilterDetails(allDeviceGroupIdsOfUser, tenantId);
}
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source to retrieve all groups of filter.";
log.error(msg, e);
throw new GroupManagementException(msg, e);
} catch (GroupManagementDAOException e) {
String msg = "Error occurred while retrieving all groups of filter";
log.error(msg, e);
throw new GroupManagementException(msg, e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
return groupFilters;
}
private List<DeviceGroup> getGroups(List<Integer> groupIds, int tenantId) throws GroupManagementException {
try {
GroupManagementDAOFactory.openConnection();

@ -18,7 +18,6 @@
package io.entgra.device.mgt.core.device.mgt.core.service;
import com.google.gson.JsonArray;
import io.entgra.device.mgt.core.device.mgt.common.*;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.UserManagementException;
@ -109,28 +108,4 @@ public interface UserManagementProviderService {
*/
List<UserInfo> getUserNames(String filter, String userStoreDomain, int offset, int limit) throws UserManagementException;
/**
* Method to retrieve the list of users based on filter.
*
* @param username data needed for the user search
* @param deviceList domain of the user
* @param domain the maximum number of the users to be retrieved
* @throws UserManagementException If some unusual behaviour is observed while fetching the users.
*/
List<UserInfo> updateUserClaimsForDevices(String username, JsonArray deviceList, String domain) throws UserManagementException;
/**
* Method to send enrollment invitation mail to existing user.
*
* @param enrollmentInvitation data related to the mail
* @throws UserManagementException If some unusual behaviour is observed while fetching the users.
*/
// EmailMetaInfo inviteToEnrollDevice(EnrollmentInvitation enrollmentInvitation) throws UserManagementException;
/**
* Method to retrieve the count of users.
*
* @throws UserManagementException If some unusual behaviour is observed while fetching the count of users.
*/
int getCount() throws UserManagementException;
}

@ -378,52 +378,6 @@ public class UserManagementProviderServiceImpl implements UserManagementProvider
}
}
@Override
public List<UserInfo> updateUserClaimsForDevices(String username, JsonArray deviceList, String domain) throws UserManagementException {
return null;
}
// @Override
// public EmailMetaInfo inviteToEnrollDevice(EnrollmentInvitation enrollmentInvitation) throws UserManagementException {
// try {
// Set<String> recipients = new HashSet<>();
// recipients.addAll(enrollmentInvitation.getRecipients());
// Properties props = new Properties();
// String username = DeviceMgtAPIUtils.getAuthenticatedUser();
// String firstName = getClaimValue(username, DeviceManagementConstants.User.CLAIM_FIRST_NAME);
// String lastName = getClaimValue(username, DeviceManagementConstants.User.CLAIM_LAST_NAME);
// if (firstName == null) {
// firstName = username;
// }
// if (lastName == null) {
// lastName = "";
// }
// props.setProperty("first-name", firstName);
// props.setProperty("last-name", lastName);
// props.setProperty("device-type", enrollmentInvitation.getDeviceType());
// EmailMetaInfo metaInfo = new EmailMetaInfo(recipients, props);
// return metaInfo;
// } catch (DeviceManagementException e) {
// String msg = "Error occurred while inviting user to enrol their device";
// log.error(msg, e);
// throw new UserManagementException(msg, e);
// } catch (UserStoreException e) {
// String msg = "Error occurred while getting claim values to invite user";
// log.error(msg, e);
// throw new UserManagementException(msg, e);
// } catch (ConfigurationManagementException e) {
// String msg = "Error occurred while sending the email invitations. Mail server not configured.";
// throw new UserManagementException(msg, e);
// }
// }
@Override
public int getCount() throws UserManagementException {
return 0;
}
/**
* User search provides an AND search result and if either of the filter returns an empty set of users, there is no
* need to carry on the search further. This method decides whether to carry on the search or not.

@ -1,36 +0,0 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.device.mgt.core.service;
import io.entgra.device.mgt.core.device.mgt.core.common.BaseDeviceManagementTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class UserManagementProviderServiceTest extends BaseDeviceManagementTest {
@BeforeClass
@Override
public void init() throws Exception {
}
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void updateUser() {
}
}
Loading…
Cancel
Save