Introduced pagination

revert-70aa11f8
charitha 8 years ago
parent 06176898d0
commit e89b4015b6

@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.beans;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -28,13 +29,13 @@ public class DeviceGroupUsersList extends BasePaginatedResult {
@ApiModelProperty(value = "List of device group users returned") @ApiModelProperty(value = "List of device group users returned")
@JsonProperty("users") @JsonProperty("users")
private List<DeviceGroupShare> users = new ArrayList<>(); private List<GroupUser> users = new ArrayList<>();
public List<DeviceGroupShare> getList() { public List<GroupUser> getList() {
return users; return users;
} }
public void setList(List<DeviceGroupShare> users) { public void setList(List<GroupUser> users) {
this.users = users; this.users = users;
} }

@ -103,6 +103,14 @@ public interface GroupManagementService {
}) })
@Permission(name = "View Groups", permission = "/device-mgt/groups/view") @Permission(name = "View Groups", permission = "/device-mgt/groups/view")
Response getGroups(@ApiParam( Response getGroups(@ApiParam(
name = "name",
value = "Name of the group.")
@QueryParam("name") String name,
@ApiParam(
name = "owner",
value = "Owner of the group.")
@QueryParam("owner") String owner,
@ApiParam(
name = "offset", name = "offset",
value = "Starting point within the complete list of items qualified.") value = "Starting point within the complete list of items qualified.")
@QueryParam("offset") int offset, @QueryParam("offset") int offset,

@ -90,6 +90,14 @@ public interface GroupManagementAdminService {
}) })
@Permission(name = "View Groups", permission = "/device-mgt/admin/groups/view") @Permission(name = "View Groups", permission = "/device-mgt/admin/groups/view")
Response getGroups(@ApiParam( Response getGroups(@ApiParam(
name = "name",
value = "Name of the group.")
@QueryParam("name") String name,
@ApiParam(
name = "owner",
value = "Owner of the group.")
@QueryParam("owner") String owner,
@ApiParam(
name = "offset", name = "offset",
value = "Starting point within the complete list of items qualified.") value = "Starting point within the complete list of items qualified.")
@QueryParam("offset") int offset, @QueryParam("offset") int offset,

@ -18,7 +18,6 @@
*/ */
package org.wso2.carbon.device.mgt.jaxrs.service.impl; package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import com.google.gson.JsonArray;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;

@ -23,16 +23,24 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupList; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupList;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupShare; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupShare;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupUsersList;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.Date; import java.util.Date;
@ -47,12 +55,15 @@ public class GroupManagementServiceImpl implements GroupManagementService {
"/permission/device-mgt/user/groups"}; "/permission/device-mgt/user/groups"};
@Override @Override
public Response getGroups(int offset, int limit) { public Response getGroups(String name, String owner, int offset, int limit) {
try { try {
RequestValidationUtil.validatePaginationParameters(offset, limit); RequestValidationUtil.validatePaginationParameters(offset, limit);
GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService();
String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
List<DeviceGroup> deviceGroups = service.getGroups(currentUser, offset, limit); GroupPaginationRequest request = new GroupPaginationRequest(offset, limit);
request.setGroupName(name);
request.setOwner(owner);
List<DeviceGroup> deviceGroups = service.getGroups(currentUser, request);
if (deviceGroups != null && deviceGroups.size() > 0) { if (deviceGroups != null && deviceGroups.size() > 0) {
DeviceGroupList deviceGroupList = new DeviceGroupList(); DeviceGroupList deviceGroupList = new DeviceGroupList();
deviceGroupList.setList(deviceGroups); deviceGroupList.setList(deviceGroups);
@ -92,14 +103,14 @@ public class GroupManagementServiceImpl implements GroupManagementService {
group.setDateOfLastUpdate(new Date().getTime()); group.setDateOfLastUpdate(new Date().getTime());
try { try {
DeviceMgtAPIUtils.getGroupManagementProviderService().createGroup(group, DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS); DeviceMgtAPIUtils.getGroupManagementProviderService().createGroup(group, DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS);
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.CREATED).build();
} catch (GroupManagementException e) { } catch (GroupManagementException e) {
String msg = "Error occurred while adding new group."; String msg = "Error occurred while adding new group.";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (GroupAlreadyExistException e) { } catch (GroupAlreadyExistException e) {
String msg = "Group already exists with name '" + group.getName() + "'."; String msg = "Group already exists with name '" + group.getName() + "'.";
log.error(msg, e); log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build(); return Response.status(Response.Status.CONFLICT).entity(msg).build();
} }
} }
@ -126,7 +137,6 @@ public class GroupManagementServiceImpl implements GroupManagementService {
if (deviceGroup == null) { if (deviceGroup == null) {
return Response.status(Response.Status.BAD_REQUEST).build(); return Response.status(Response.Status.BAD_REQUEST).build();
} }
deviceGroup.setDateOfLastUpdate(new Date().getTime());
try { try {
DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(deviceGroup, groupId); DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(deviceGroup, groupId);
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
@ -134,42 +144,120 @@ public class GroupManagementServiceImpl implements GroupManagementService {
String msg = "Error occurred while adding new group."; String msg = "Error occurred while adding new group.";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (GroupAlreadyExistException e) {
String msg = "There is another group already exists with name '" + deviceGroup.getName() + "'.";
log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
} }
} }
@Override @Override
public Response deleteGroup(int groupId) { public Response deleteGroup(int groupId) {
return null; try {
if (DeviceMgtAPIUtils.getGroupManagementProviderService().deleteGroup(groupId)) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("Group not found.").build();
}
} catch (GroupManagementException e) {
String msg = "Error occurred while deleting the group.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
} }
@Override @Override
public Response manageGroupSharing(int groupId, DeviceGroupShare deviceGroupShare) { public Response manageGroupSharing(int groupId, DeviceGroupShare deviceGroupShare) {
return null; try {
DeviceMgtAPIUtils.getGroupManagementProviderService()
.manageGroupSharing(groupId, deviceGroupShare.getUsername(), deviceGroupShare.getGroupRoles());
return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) {
String msg = "Error occurred while managing group share.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (RoleDoesNotExistException | UserDoesNotExistException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
}
} }
@Override @Override
public Response getUsersOfGroup(int groupId) { public Response getUsersOfGroup(int groupId) {
return null; try {
List<GroupUser> groupUsers = DeviceMgtAPIUtils.getGroupManagementProviderService().getUsers(groupId);
if (groupUsers != null && groupUsers.size() > 0) {
DeviceGroupUsersList deviceGroupUsersList = new DeviceGroupUsersList();
deviceGroupUsersList.setList(groupUsers);
deviceGroupUsersList.setCount(groupUsers.size());
return Response.status(Response.Status.OK).entity(deviceGroupUsersList).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
String msg = "Error occurred while getting users of the group.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
} }
@Override @Override
public Response getDevicesOfGroup(int groupId, int offset, int limit) { public Response getDevicesOfGroup(int groupId, int offset, int limit) {
return null; try {
GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService();
List<Device> deviceList = service.getDevices(groupId, offset, limit);
if (deviceList != null && deviceList.size() > 0) {
DeviceList deviceListWrapper = new DeviceList();
deviceListWrapper.setList(deviceList);
deviceListWrapper.setCount(service.getDeviceCount(groupId));
return Response.status(Response.Status.OK).entity(deviceListWrapper).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
String msg = "Error occurred while getting devices the group.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
} }
@Override @Override
public Response getDeviceCountOfGroup(int groupId) { public Response getDeviceCountOfGroup(int groupId) {
return null; try {
int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getDeviceCount(groupId);
return Response.status(Response.Status.OK).entity(count).build();
} catch (GroupManagementException e) {
String msg = "Error occurred while getting device count of the group.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
} }
@Override @Override
public Response addDevicesToGroup(int groupId, List<DeviceIdentifier> deviceIdentifiers) { public Response addDevicesToGroup(int groupId, List<DeviceIdentifier> deviceIdentifiers) {
return null; try {
DeviceMgtAPIUtils.getGroupManagementProviderService().addDevices(groupId, deviceIdentifiers);
return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) {
String msg = "Error occurred while adding devices to group.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceNotFoundException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
}
} }
@Override @Override
public Response removeDevicesFromGroup(int groupId, List<DeviceIdentifier> deviceIdentifiers) { public Response removeDevicesFromGroup(int groupId, List<DeviceIdentifier> deviceIdentifiers) {
return null; try {
DeviceMgtAPIUtils.getGroupManagementProviderService().removeDevice(groupId, deviceIdentifiers);
return Response.status(Response.Status.OK).build();
} catch (GroupManagementException e) {
String msg = "Error occurred while removing devices from group.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceNotFoundException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
}
} }
} }

@ -20,8 +20,8 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; 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.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
@ -30,10 +30,6 @@ import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.GroupManagementAdminSe
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List; import java.util.List;
@ -42,11 +38,14 @@ public class GroupManagementAdminServiceImpl implements GroupManagementAdminServ
private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class); private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class);
@Override @Override
public Response getGroups(int offset, int limit) { public Response getGroups(String name, String owner, int offset, int limit) {
try { try {
RequestValidationUtil.validatePaginationParameters(offset, limit); RequestValidationUtil.validatePaginationParameters(offset, limit);
GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService();
List<DeviceGroup> deviceGroups = service.getGroups(offset, limit); GroupPaginationRequest request = new GroupPaginationRequest(offset, limit);
request.setGroupName(name);
request.setOwner(owner);
List<DeviceGroup> deviceGroups = service.getGroups(request);
if (deviceGroups != null && deviceGroups.size() > 0) { if (deviceGroups != null && deviceGroups.size() > 0) {
DeviceGroupList deviceGroupList = new DeviceGroupList(); DeviceGroupList deviceGroupList = new DeviceGroupList();
deviceGroupList.setList(deviceGroups); deviceGroupList.setList(deviceGroups);

@ -0,0 +1,44 @@
/*
* Copyright (c) 2014, 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;
public class DeviceNotFoundException extends Exception {
private static final long serialVersionUID = -3151279311996070297L;
public DeviceNotFoundException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public DeviceNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public DeviceNotFoundException(String msg) {
super(msg);
}
public DeviceNotFoundException() {
super();
}
public DeviceNotFoundException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,68 @@
/*
* Copyright (c) 2015, 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;
/**
* This class holds required parameters for a querying a paginated device group response.
*/
public class GroupPaginationRequest {
private int startIndex;
private int rowCount;
private String owner;
private String groupName;
public GroupPaginationRequest(int start, int rowCount) {
this.startIndex = start;
this.rowCount = rowCount;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public int getRowCount() {
return rowCount;
}
public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}

@ -21,12 +21,13 @@ package org.wso2.carbon.device.mgt.common;
import java.util.Date; import java.util.Date;
/** /**
* This class holds required parameters for a querying a paginated response. * This class holds required parameters for a querying a paginated device response.
*/ */
public class PaginationRequest { public class PaginationRequest {
private int startIndex; private int startIndex;
private int rowCount; private int rowCount;
private int groupId;
private String owner; private String owner;
private String status; private String status;
private String deviceType; private String deviceType;
@ -55,6 +56,14 @@ public class PaginationRequest {
this.rowCount = rowCount; this.rowCount = rowCount;
} }
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public String getOwner() { public String getOwner() {
return owner; return owner;
} }

@ -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 RoleDoesNotExistException extends Exception {
private static final long serialVersionUID = -312678379574556874L;
private String errorMessage;
public RoleDoesNotExistException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public RoleDoesNotExistException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public RoleDoesNotExistException(String msg) {
super(msg);
setErrorMessage(msg);
}
public RoleDoesNotExistException() {
super();
}
public RoleDoesNotExistException(Throwable cause) {
super(cause);
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -28,6 +28,7 @@ import javax.xml.bind.annotation.XmlRootElement;
public class PaginationConfiguration { public class PaginationConfiguration {
private int deviceListPageSize; private int deviceListPageSize;
private int groupListPageSize;
private int operationListPageSize; private int operationListPageSize;
private int notificationListPageSize; private int notificationListPageSize;
private int activityListPageSize; private int activityListPageSize;
@ -41,6 +42,15 @@ public class PaginationConfiguration {
this.deviceListPageSize = deviceListPageSize; this.deviceListPageSize = deviceListPageSize;
} }
public int getGroupListPageSize() {
return groupListPageSize;
}
@XmlElement(name = "GroupListPageSize", required = true)
public void setGroupListPageSize(int groupListPageSize) {
this.groupListPageSize = groupListPageSize;
}
public int getOperationListPageSize() { public int getOperationListPageSize() {
return operationListPageSize; return operationListPageSize;
} }

@ -28,7 +28,6 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.utils.xml.StringUtils;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;

@ -19,6 +19,7 @@
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.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import java.util.List; import java.util.List;
@ -76,16 +77,23 @@ public interface GroupDAO {
List<DeviceGroup> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException; List<DeviceGroup> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException;
/** /**
* Get the list of Device Groups in tenant. * Get paginated list of Device Groups in tenant.
* *
* @param startIndex for pagination. * @param paginationRequest to filter results
* @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<DeviceGroup> getGroups(int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException; List<DeviceGroup> getGroups(GroupPaginationRequest paginationRequest, int tenantId) throws GroupManagementDAOException;
/**
* Get the list of Device Groups in tenant.
*
* @param tenantId of user's tenant.
* @return List of all Device Groups in tenant.
* @throws GroupManagementDAOException
*/
List<DeviceGroup> getGroups(int tenantId) throws GroupManagementDAOException;
/** /**
* Get count of Device Groups in tenant. * Get count of Device Groups in tenant.
@ -114,7 +122,7 @@ public interface GroupDAO {
* @return existence of group with name * @return existence of group with name
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException; DeviceGroup getGroup(String groupName, int tenantId) throws GroupManagementDAOException;
/** /**
* Add device to a given Device Group. * Add device to a given Device Group.

@ -19,6 +19,7 @@
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.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
@ -147,7 +148,6 @@ public class GroupDAOImpl implements GroupDAO {
@Override @Override
public List<DeviceGroup> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException { public List<DeviceGroup> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<DeviceGroup> deviceGroupBuilders = new ArrayList<>(); List<DeviceGroup> deviceGroupBuilders = new ArrayList<>();
@ -172,21 +172,66 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public List<DeviceGroup> getGroups(int startIndex, int rowCount, int tenantId) public List<DeviceGroup> getGroups(GroupPaginationRequest request, int tenantId)
throws GroupManagementDAOException { throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<DeviceGroup> deviceGroupList = null; List<DeviceGroup> deviceGroupList = null;
String groupName = request.getGroupName();
boolean hasGroupName = false;
String owner = request.getOwner();
boolean hasOwner = false;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER "
+ "FROM DM_GROUP WHERE TENANT_ID = ? LIMIT ?, ?"; + "FROM DM_GROUP WHERE TENANT_ID = ?";
if (groupName != null && !groupName.isEmpty()) {
sql += " GROUP_NAME LIKE ?";
hasGroupName = true;
}
if (owner != null && !owner.isEmpty()) {
sql += " OWNER LIKE ?";
hasOwner = true;
}
sql += " LIMIT ?, ?";
int paramIndex = 1;
stmt = conn.prepareStatement(sql);
stmt.setInt(paramIndex++, tenantId);
if (hasGroupName) {
stmt.setString(paramIndex++, groupName);
}
if (hasOwner) {
stmt.setString(paramIndex++, owner);
}
stmt.setInt(paramIndex++, request.getStartIndex());
stmt.setInt(paramIndex, request.getRowCount());
resultSet = stmt.executeQuery();
deviceGroupList = new ArrayList<>();
while (resultSet.next()) {
deviceGroupList.add(GroupManagementDAOUtil.loadGroup(resultSet));
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return deviceGroupList;
}
@Override
public List<DeviceGroup> getGroups(int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<DeviceGroup> deviceGroupList = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER "
+ "FROM DM_GROUP WHERE TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
//noinspection JpaQueryApiInspection
stmt.setInt(2, startIndex);
//noinspection JpaQueryApiInspection
stmt.setInt(3, rowCount);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
deviceGroupList = new ArrayList<>(); deviceGroupList = new ArrayList<>();
while (resultSet.next()) { while (resultSet.next()) {
@ -249,17 +294,21 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException { public DeviceGroup getGroup(String groupName, 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 GROUP_NAME FROM DM_GROUP WHERE GROUP_NAME = ? AND TENANT_ID = ?"; String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " +
"FROM DM_GROUP WHERE GROUP_NAME = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, groupName); stmt.setString(1, groupName);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
return resultSet.next(); if (resultSet.next()) {
return GroupManagementDAOUtil.loadGroup(resultSet);
}
return null;
} catch (SQLException e) { } catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while group Id listing by group name.'", e); throw new GroupManagementDAOException("Error occurred while group Id listing by group name.'", e);
} finally { } finally {
@ -351,6 +400,7 @@ public class GroupDAOImpl implements GroupDAO {
} }
} }
//TODO: Move this to device mgt
@Override @Override
public List<Device> getDevices(int groupId, int startIndex, int rowCount, int tenantId) public List<Device> getDevices(int groupId, int startIndex, int rowCount, int tenantId)
throws GroupManagementDAOException { throws GroupManagementDAOException {

@ -19,7 +19,6 @@
package org.wso2.carbon.device.mgt.core.notification.mgt.dao; package org.wso2.carbon.device.mgt.core.notification.mgt.dao;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;

@ -20,7 +20,6 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationResponse; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationResponse;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;

@ -17,7 +17,6 @@
*/ */
package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl; package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl;
import org.apache.axis2.databinding.types.soapencoding.Integer;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
@ -26,7 +25,6 @@ import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus; import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationResponse; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationResponse;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationDAO; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationDAO;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException;

@ -90,7 +90,7 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl {
@Override @Override
public List<? extends Operation> getOperationsByDeviceAndStatus(int enrolmentId, public List<? extends Operation> getOperationsByDeviceAndStatus(int enrolmentId,
PaginationRequest request, Operation.Status status) throws OperationManagementDAOException { PaginationRequest request, Operation.Status status) throws OperationManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
Operation operation; Operation operation;

@ -20,11 +20,14 @@ 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.PaginationResult; import org.wso2.carbon.device.mgt.common.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
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.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException;
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException; import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
import java.util.List; import java.util.List;
@ -52,7 +55,7 @@ public interface GroupManagementProviderService {
* @param groupId of the group. * @param groupId of the group.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
void updateGroup(DeviceGroup deviceGroup, int groupId) throws GroupManagementException; void updateGroup(DeviceGroup deviceGroup, int groupId) throws GroupManagementException, GroupAlreadyExistException;
/** /**
* Delete existing device group. * Delete existing device group.
@ -73,25 +76,40 @@ public interface GroupManagementProviderService {
DeviceGroup getGroup(int groupId) throws GroupManagementException; DeviceGroup getGroup(int groupId) throws GroupManagementException;
/** /**
* Get paginated device groups in tenant. * Get all device groups in tenant.
* *
* @param startIndex for pagination.
* @param rowCount for pagination.
* @return list of groups. * @return list of groups.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<DeviceGroup> getGroups(int startIndex, int rowCount) throws GroupManagementException; List<DeviceGroup> getGroups() throws GroupManagementException;
/** /**
* Get paginated device groups for user. * Get all device groups for user.
* *
* @param username of the user. * @param username of the user.
* @param startIndex for pagination.
* @param rowCount for pagination.
* @return list of groups * @return list of groups
* @throws GroupManagementException * @throws GroupManagementException
*/ */
List<DeviceGroup> getGroups(String username, int startIndex, int rowCount) throws GroupManagementException; List<DeviceGroup> getGroups(String username) throws GroupManagementException;
/**
* Get device groups with pagination.
*
* @param paginationRequest to filter results
* @return list of groups.
* @throws GroupManagementException
*/
List<DeviceGroup> getGroups(GroupPaginationRequest paginationRequest) throws GroupManagementException;
/**
* Get device groups with pagination.
*
* @param username of the user.
* @param paginationRequest to filter results
* @return list of groups.
* @throws GroupManagementException
*/
List<DeviceGroup> getGroups(String username, GroupPaginationRequest paginationRequest) throws GroupManagementException;
/** /**
* Get all device group count in tenant * Get all device group count in tenant
@ -111,28 +129,15 @@ public interface GroupManagementProviderService {
int getGroupCount(String username) throws GroupManagementException; int getGroupCount(String username) throws GroupManagementException;
/** /**
* Share device group with user specified by role * Manage device group sharing with user with list of roles.
*
* @param username of the user
* @param groupId of the group
* @param sharingRole to be shared
* @return is group shared
* @throws GroupManagementException UserDoesNotExistException
*/
boolean shareGroup(String username, int groupId, String sharingRole)
throws GroupManagementException, UserDoesNotExistException;
/**
* 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 * @param groupId of the group
* @param sharingRole to be un shared * @param newRoles to be shared
* @return is group un shared
* @throws GroupManagementException UserDoesNotExistException * @throws GroupManagementException UserDoesNotExistException
*/ */
boolean unshareGroup(String userName, int groupId, String sharingRole) void manageGroupSharing(int groupId, String username, List<String> newRoles)
throws GroupManagementException, UserDoesNotExistException; throws GroupManagementException, UserDoesNotExistException, RoleDoesNotExistException;
/** /**
* Add new sharing role for device group * Add new sharing role for device group
@ -208,22 +213,22 @@ public interface GroupManagementProviderService {
/** /**
* Add device to device group. * Add device to device group.
* *
* @param deviceId of the device. * @param groupId of the group.
* @param groupId of the group * @param deviceIdentifiers of devices.
* @return is device added.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean addDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException; void addDevices(int groupId, List<DeviceIdentifier> deviceIdentifiers) throws GroupManagementException,
DeviceNotFoundException;
/** /**
* Remove device from device group. * Remove device from device group.
* *
* @param deviceId of the device. * @param groupId of the group.
* @param groupId of the group * @param deviceIdentifiers of devices.
* @return is device removed.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean removeDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException; void removeDevice(int groupId, List<DeviceIdentifier> deviceIdentifiers) throws GroupManagementException,
DeviceNotFoundException;
/** /**
* Get device group permissions of user. * Get device group permissions of user.

@ -26,15 +26,19 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
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.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
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.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupDAO; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupDAO;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOException; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOException;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.user.api.Permission; import org.wso2.carbon.user.api.Permission;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
@ -75,8 +79,8 @@ 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); DeviceGroup existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId);
if (!nameIsExists) { if (existingGroup == null) {
groupId = this.groupDAO.addGroup(deviceGroup, tenantId); groupId = this.groupDAO.addGroup(deviceGroup, tenantId);
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
} else { } else {
@ -103,16 +107,21 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
*/ */
@Override @Override
public void updateGroup(DeviceGroup deviceGroup, int groupId) public void updateGroup(DeviceGroup deviceGroup, int groupId)
throws GroupManagementException { throws GroupManagementException, GroupAlreadyExistException {
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(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
deviceGroup.setDateOfLastUpdate(new Date().getTime()); DeviceGroup existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId);
this.groupDAO.updateGroup(deviceGroup, groupId, tenantId); if (existingGroup == null || existingGroup.getGroupId() == groupId) {
GroupManagementDAOFactory.commitTransaction(); deviceGroup.setDateOfLastUpdate(new Date().getTime());
this.groupDAO.updateGroup(deviceGroup, groupId, tenantId);
GroupManagementDAOFactory.commitTransaction();
} else {
throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName());
}
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction(); GroupManagementDAOFactory.rollbackTransaction();
throw new GroupManagementException("Error occurred while modifying deviceGroup " + throw new GroupManagementException("Error occurred while modifying deviceGroup " +
@ -192,12 +201,34 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} }
@Override @Override
public List<DeviceGroup> getGroups(int startIndex, int rowCount) throws GroupManagementException { public List<DeviceGroup> getGroups() throws GroupManagementException {
List<DeviceGroup> deviceGroups = new ArrayList<>();
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection();
deviceGroups = this.groupDAO.getGroups(tenantId);
} catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e);
} catch (SQLException e) {
throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
for (DeviceGroup group : deviceGroups) {
group.setUsers(this.getUsers(group.getGroupId()));
group.setRoles(this.getRoles(group.getGroupId()));
}
return deviceGroups;
}
@Override
public List<DeviceGroup> getGroups(GroupPaginationRequest request) throws GroupManagementException {
List<DeviceGroup> deviceGroups = new ArrayList<>(); List<DeviceGroup> deviceGroups = new ArrayList<>();
request = DeviceManagerUtil.validateGroupListPageSize(request);
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
deviceGroups = this.groupDAO.getGroups(startIndex, rowCount, tenantId); deviceGroups = this.groupDAO.getGroups(request, 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) {
@ -213,7 +244,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} }
@Override @Override
public List<DeviceGroup> getGroups(String username, int startIndex, int rowCount) throws GroupManagementException { public List<DeviceGroup> getGroups(String username) throws GroupManagementException {
Map<Integer, DeviceGroup> groups = new HashMap<>(); Map<Integer, DeviceGroup> groups = new HashMap<>();
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
try { try {
@ -221,11 +252,36 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager(); .getUserStoreManager();
String[] roleList = userStoreManager.getRoleListOfUser(username); String[] roleList = userStoreManager.getRoleListOfUser(username);
for (String role : roleList) {
if (role != null && role.contains("Internal/group-")) {
DeviceGroup deviceGroup = extractNewGroupFromRole(groups, role);
if (deviceGroup != null) {
groups.put(deviceGroup.getGroupId(), deviceGroup);
}
}
}
} catch (UserStoreException e) {
throw new GroupManagementException("Error occurred while getting user store manager.", e);
}
return new ArrayList<>(groups.values());
}
public List<DeviceGroup> getGroups(String currentUser, GroupPaginationRequest request) throws GroupManagementException {
request = DeviceManagerUtil.validateGroupListPageSize(request);
Map<Integer, DeviceGroup> groups = new HashMap<>();
UserStoreManager userStoreManager;
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager();
String[] roleList = userStoreManager.getRoleListOfUser(currentUser);
int index = 0; int index = 0;
for (String role : roleList) { for (String role : roleList) {
if (role != null && role.contains("Internal/group-")) { if (role != null && role.contains("Internal/group-")) {
DeviceGroup deviceGroupBuilder = extractNewGroupFromRole(groups, role); DeviceGroup deviceGroupBuilder = extractNewGroupFromRole(groups, role);
if (deviceGroupBuilder != null && startIndex <= index++ && index <= rowCount) { if (deviceGroupBuilder != null
&& request.getStartIndex() <= index++
&& index <= request.getRowCount()) {
groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder); groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder);
} }
} }
@ -283,50 +339,49 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean shareGroup(String username, int groupId, String sharingRole) @SuppressWarnings("Duplicates")
throws GroupManagementException, UserDoesNotExistException { public void manageGroupSharing(int groupId, String username, List<String> newRoles)
return modifyGroupShare(username, groupId, sharingRole, true); throws GroupManagementException, UserDoesNotExistException, RoleDoesNotExistException {
} int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
/**
* {@inheritDoc}
*/
@Override
public boolean unshareGroup(String username, int groupId, String sharingRole)
throws GroupManagementException, UserDoesNotExistException {
return modifyGroupShare(username, groupId, sharingRole, false);
}
private boolean modifyGroupShare(String username, int groupId, String sharingRole,
boolean isAddNew)
throws GroupManagementException, UserDoesNotExistException {
if (groupId == -1) {
return false;
}
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
String[] roles = new String[1];
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = userStoreManager =
DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
tenantId).getUserStoreManager(); tenantId).getUserStoreManager();
if (!userStoreManager.isExistingUser(username)) { if (!userStoreManager.isExistingUser(username)) {
throw new UserDoesNotExistException("User not exists with name " + username); throw new UserDoesNotExistException("User not exists with name " + username);
} }
roles[0] = "Internal/group-" + groupId + "-" + sharingRole; List<String> currentGroupRoles = getRoles(groupId);
List<String> currentRoles = getRoles(username, groupId); List<String> currentUserRoles = getRoles(username, groupId);
if (isAddNew && !currentRoles.contains(sharingRole)) { List<String> rolesToAdd = new ArrayList<>();
userStoreManager.updateRoleListOfUser(username, null, roles); List<String> rolesToRemove = new ArrayList<>();
} else if (!isAddNew && currentRoles.contains(sharingRole)) { String roleNamePrefix = "Internal/group-" + groupId + "-";
userStoreManager.updateRoleListOfUser(username, roles, null); for (String role : newRoles) {
if (currentGroupRoles.contains(role)) {
if (!currentUserRoles.contains(role)) {
rolesToAdd.add(roleNamePrefix + role);
}
} else {
throw new RoleDoesNotExistException("Role '" + role + "' is not exists iin requested group.");
}
} }
return true; for (String role : currentUserRoles) {
if (currentGroupRoles.contains(role)) {
if (!newRoles.contains(role)) {
rolesToRemove.add(roleNamePrefix + role);
}
} else {
throw new RoleDoesNotExistException("Role '" + role + "' is not exists iin requested group.");
}
}
userStoreManager.updateRoleListOfUser(username,
rolesToRemove.toArray(new String[rolesToRemove.size()]),
rolesToAdd.toArray(new String[rolesToAdd.size()]));
} catch (UserStoreException e) { } catch (UserStoreException e) {
if (e instanceof UserDoesNotExistException) { if (e instanceof UserDoesNotExistException) {
throw (UserDoesNotExistException) e; throw (UserDoesNotExistException) e;
} }
throw new GroupManagementException("User store error in adding user " + username + " to group name:" + throw new GroupManagementException("User store error in updating sharing roles.", e);
groupId, e);
} }
} }
@ -520,17 +575,19 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean addDevice(DeviceIdentifier deviceIdentifier, int groupId) public void addDevices(int groupId, List<DeviceIdentifier> deviceIdentifiers)
throws GroupManagementException { throws GroupManagementException, DeviceNotFoundException {
Device device; Device device;
try { try {
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier);
if (device == null) {
return false;
}
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
this.groupDAO.addDevice(groupId, device.getId(), tenantId); for (DeviceIdentifier deviceIdentifier : deviceIdentifiers){
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier);
if (device == null) {
throw new DeviceNotFoundException("Device not found for id '" + deviceIdentifier.getId() + "'");
}
this.groupDAO.addDevice(groupId, 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);
@ -542,23 +599,25 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
return true;
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public boolean removeDevice(DeviceIdentifier deviceIdentifier, int groupId) throws GroupManagementException { public void removeDevice(int groupId, List<DeviceIdentifier> deviceIdentifiers)
throws GroupManagementException, DeviceNotFoundException {
Device device; Device device;
try { try {
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier);
if (device == null) {
return false;
}
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
this.groupDAO.removeDevice(groupId, device.getId(), tenantId); for (DeviceIdentifier deviceIdentifier : deviceIdentifiers){
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier);
if (device == null) {
throw new DeviceNotFoundException("Device not found for id '" + deviceIdentifier.getId() + "'");
}
this.groupDAO.removeDevice(groupId, 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);
@ -570,7 +629,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
return true;
} }
/** /**

@ -22,6 +22,7 @@ import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
@ -327,6 +328,22 @@ public final class DeviceManagerUtil {
return paginationRequest; return paginationRequest;
} }
public static GroupPaginationRequest validateGroupListPageSize(GroupPaginationRequest paginationRequest) throws
GroupManagementException {
if (paginationRequest.getRowCount() == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance()
.getDeviceManagementConfig();
if (deviceManagementConfig != null) {
paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration()
.getDeviceListPageSize());
} else {
throw new GroupManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
}
}
return paginationRequest;
}
public static int validateDeviceListPageSize(int limit) throws DeviceManagementException { public static int validateDeviceListPageSize(int limit) throws DeviceManagementException {
if (limit == 0) { if (limit == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().

@ -24,6 +24,7 @@ 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.GroupPaginationRequest;
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;
@ -100,7 +101,10 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
public void getGroupTest() { public void getGroupTest() {
try { try {
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
List<DeviceGroup> groups = groupDAO.getGroups(0, 100, TestDataHolder.SUPER_TENANT_ID); GroupPaginationRequest request = new GroupPaginationRequest(0, 10);
request.setGroupName(null);
request.setOwner(null);
List<DeviceGroup> groups = groupDAO.getGroups(request, 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());

@ -65,6 +65,7 @@
<!-- Default Page size configuration for paginated DM APIs--> <!-- Default Page size configuration for paginated DM APIs-->
<PaginationConfiguration> <PaginationConfiguration>
<DeviceListPageSize>20</DeviceListPageSize> <DeviceListPageSize>20</DeviceListPageSize>
<GroupListPageSize>20</GroupListPageSize>
<NotificationListPageSize>20</NotificationListPageSize> <NotificationListPageSize>20</NotificationListPageSize>
<ActivityListPageSize>20</ActivityListPageSize> <ActivityListPageSize>20</ActivityListPageSize>
<OperationListPageSize>20</OperationListPageSize> <OperationListPageSize>20</OperationListPageSize>

Loading…
Cancel
Save