From d1d6eefd174e73a2b275943fbfbf78c3964a8434 Mon Sep 17 00:00:00 2001 From: charitha Date: Tue, 4 Oct 2016 12:24:40 +0530 Subject: [PATCH 1/8] Upgrading grouping backend --- .../mgt/jaxrs/beans/DeviceGroupList.java | 57 ++ .../mgt/jaxrs/beans/DeviceGroupShare.java | 58 ++ .../mgt/jaxrs/beans/DeviceGroupUsersList.java | 55 ++ .../service/api/GroupManagementService.java | 548 ++++++++++++++++-- .../impl/GroupManagementServiceImpl.java | 45 +- .../mgt/common/group/mgt/DeviceGroup.java | 24 +- .../mgt/common/group/mgt/GroupUser.java | 13 +- 7 files changed, 713 insertions(+), 87 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupShare.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java new file mode 100644 index 00000000000..15a3e1698cb --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java @@ -0,0 +1,57 @@ +/* + * 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.jaxrs.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; + +import java.util.ArrayList; +import java.util.List; + +public class DeviceGroupList extends BasePaginatedResult { + + @ApiModelProperty(value = "List of device groups returned") + @JsonProperty("groups") + private List deviceGroups = new ArrayList<>(); + + public List getList() { + return deviceGroups; + } + + public void setList(List deviceGroups) { + this.deviceGroups = deviceGroups; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" next: ").append(getNext()).append(",\n"); + sb.append(" previous: ").append(getPrevious()).append(",\n"); + sb.append(" groups: [").append(deviceGroups).append("\n"); + sb.append("]}\n"); + return sb.toString(); + } + +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupShare.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupShare.java new file mode 100644 index 00000000000..af436c80f89 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupShare.java @@ -0,0 +1,58 @@ +/* + * 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.jaxrs.beans; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.List; + + +/** + * This class holds Device Group user name and assigned roles of user for particular group. Exposed to external access. + */ +@ApiModel(value = "DeviceGroupShare", description = "This class carries roles assigned to a user of a managed device group.") +public class DeviceGroupShare implements Serializable { + + private static final long serialVersionUID = 1998141711L; + + @ApiModelProperty(name = "username", value = "Username of the user.", required = true) + private String username; + + @ApiModelProperty(name = "roles", value = "List of roles assigned to user from the group.") + private List groupRoles; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public List getGroupRoles() { + return groupRoles; + } + + public void setGroupRoles(List groupRoles) { + this.groupRoles = groupRoles; + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java new file mode 100644 index 00000000000..ed369ced60a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java @@ -0,0 +1,55 @@ +/* + * 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.jaxrs.beans; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; + +import java.util.ArrayList; +import java.util.List; + +public class DeviceGroupUsersList extends BasePaginatedResult { + + @ApiModelProperty(value = "List of device group users returned") + @JsonProperty("users") + private List users = new ArrayList<>(); + + public List getList() { + return users; + } + + public void setList(List users) { + this.users = users; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" next: ").append(getNext()).append(",\n"); + sb.append(" previous: ").append(getPrevious()).append(",\n"); + sb.append(" users: [").append(users).append("\n"); + sb.append("]}\n"); + return sb.toString(); + } + +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java index f21d1c9a4b1..c6c050fa71a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java @@ -18,11 +18,24 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.api; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.ResponseHeader; +import org.apache.axis2.transport.http.HTTPConstants; import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupList; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupShare; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupUsersList; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import javax.validation.Valid; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -34,80 +47,529 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.util.List; +/** + * Device group related REST-API. This can be used to manipulated device group related details. + */ @API(name = "Group Management", version = "1.0.0", context = "/api/device-mgt/v1.0/groups", tags = {"devicemgt_admin"}) @Path("/groups") +@Api(value = "Device Group Management", description = "This API carries all device group management related operations " + + "such as get all the available groups, etc.") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public interface GroupManagementService { @GET - @Permission(name = "View Group", permission = "/permission/admin/device-mgt/user/groups/list") - Response getGroups(@QueryParam("user") String user, @QueryParam("offset") int offset, + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "Get the list of groups belongs to current user.", + notes = "Returns all permitted groups enrolled with the system.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of device groups.", + response = DeviceGroupList.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the groups list.", + response = ErrorResponse.class) + }) + @Permission(name = "View Groups", permission = "/device-mgt/groups/view") + Response getGroups(@ApiParam( + name = "offset", + value = "Starting point within the complete list of items qualified.") + @QueryParam("offset") int offset, + @ApiParam( + name = "limit", + value = "Maximum size of resource array to return.") @QueryParam("limit") int limit); @POST - @Permission(name = "Add Group", permission = "/permission/admin/device-mgt/user/groups/add") - Response createGroup(DeviceGroup group); + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_POST, + value = "Add new device group to the system.", + notes = "Add device group with current user as the owner.", + tags = "Device Group Management") + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "Created. \n Device group has successfully been created", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The URL of the added group."), + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests.") + } + ), + @ApiResponse( + code = 303, + message = "See Other. \n Source can be retrieved from the URL specified at the Location header.", + responseHeaders = { + @ResponseHeader( + name = "Content-Location", + description = "The Source URL of the document.")}), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Current logged in user is not authorized to add device groups.", + response = ErrorResponse.class), + @ApiResponse( + code = 415, + message = "Unsupported media type. \n The entity of the request was in a not supported format."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while adding a new device group.", + response = ErrorResponse.class) + }) + @Permission(name = "Add Group", permission = "/device-mgt/groups/add") + Response createGroup(@ApiParam( + name = "group", + value = "Group object with data.", + required = true) + @Valid DeviceGroup group); @Path("/{groupName}") @GET - @Permission(name = "View Group", permission = "/permission/admin/device-mgt/user/groups/view") - Response getGroup(@PathParam("groupName") String groupName); + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "View group specified with name.", + notes = "Returns details of group enrolled with the system.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the device group.", + response = DeviceGroup.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the group details.", + response = ErrorResponse.class) + }) + @Permission(name = "View Groups", permission = "/device-mgt/groups/view") + Response getGroup(@ApiParam( + name = "groupName", + value = "Name of the group to view.", + required = true) + @PathParam("groupName") String groupName); @Path("/{groupName}") @PUT - @Permission(name = "Update Group", permission = "/permission/admin/device-mgt/user/groups/update") - Response updateGroup(@PathParam("groupName") String groupName, DeviceGroup deviceGroup); + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_PUT, + value = "Update a group.", + notes = "If you wish to make changes to an existing group, that can be done by updating the group using " + + "this resource.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Group has been updated successfully.", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body."), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while updating the group.", + response = ErrorResponse.class) + }) + @Permission(name = "Update Group", permission = "/device-mgt/groups/update") + Response updateGroup(@ApiParam( + name = "groupName", + value = "Name of the group to be updated.", + required = true) + @PathParam("groupName") String groupName, + @ApiParam( + name = "group", + value = "Group object with data.", + required = true) + @Valid DeviceGroup deviceGroup); @Path("/{groupName}") @DELETE - @Permission(name = "Remove Groups", permission = "/permission/admin/device-mgt/user/groups/remove") - Response deleteGroup(@PathParam("groupName") String groupName); - - @Path("/{groupName}/share-with-user") - @POST - @Permission(name = "Share Group to a User", permission = "/permission/admin/device-mgt/user/groups/share") - Response shareGroupWithUser(@PathParam("groupName") String groupName, String targetUser); - - @Path("/{groupName}/share-with-role") - @POST - @Permission(name = "Share Group to a Role", permission = "/permission/admin/device-mgt/user/groups/share") - Response shareGroupWithRole(@PathParam("groupName") String groupName, String targetRole); - - @Path("/{groupName}/remove-share-with-user") - @POST - @Permission(name = "Unshare a Group", permission = "/permission/admin/device-mgt/user/groups/unshare") - Response removeShareWithUser(@PathParam("groupName") String groupName, String targetUser); + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_DELETE, + value = "Delete a group.", + notes = "If you wish to remove an existing group, that can be done by updating the group using " + + "this resource.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Group has been deleted successfully.", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body."), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while removing the group.", + response = ErrorResponse.class) + }) + @Permission(name = "Remove Group", permission = "/device-mgt/groups/remove") + Response deleteGroup(@ApiParam( + name = "groupName", + value = "Name of the group to be deleted.", + required = true) + @PathParam("groupName") String groupName); - @Path("/{groupName}/remove-share-with-role") + @Path("/{groupName}/share") @POST - @Permission(name = "Unshare a Group", permission = "/permission/admin/device-mgt/user/groups/unshare") - Response removeShareWithRole(@PathParam("groupName") String groupName, String targetUser); + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_POST, + value = "Manage group sharing with a user.", + notes = "If you wish to share /un share an existing group with a user under defined sharing roles, " + + "that can be done using this resource.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Sharing has been updated successfully.", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body."), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while sharing the group.", + response = ErrorResponse.class) + }) + @Permission(name = "Share Group", permission = "/device-mgt/groups/share") + Response manageGroupSharing(@ApiParam( + name = "groupName", + value = "Name of the group to be shared or unshared.", + required = true) + @PathParam("groupName") String groupName, + @ApiParam( + name = "deviceGroupShare", + value = "User name and the assigned roles for the share.", + required = true) + @Valid DeviceGroupShare deviceGroupShare); - @GET @Path("/{groupName}/users") - @Permission(name = "Get Users of Group", permission = "/permission/admin/device-mgt/user/groups/list") - Response getUsersOfGroup(@PathParam("groupName") String groupName); - @GET + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "View list of users of a device group.", + notes = "Returns details of users which particular group has been shared with.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the users.", + response = DeviceGroupUsersList.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the users.", + response = ErrorResponse.class) + }) + @Permission(name = "View users", permission = "/device-mgt/groups/users/view") + Response getUsersOfGroup(@ApiParam( + name = "groupName", + value = "Name of the group.", + required = true) + @PathParam("groupName") String groupName); + @Path("/{groupName}/devices") - @Permission(name = "Get Devices of Group", permission = "/permission/admin/device-mgt/groups/roles") - Response getDevicesOfGroup(@PathParam("groupName") String groupName, @QueryParam("offset") int offset, + @GET + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "View list of devices in the device group.", + notes = "Returns list of devices in the device group.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the devices.", + response = DeviceList.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the devices.", + response = ErrorResponse.class) + }) + @Permission(name = "View devices", permission = "/device-mgt/groups/devices/view") + Response getDevicesOfGroup(@ApiParam( + name = "groupName", + value = "Name of the group.", + required = true) + @PathParam("groupName") String groupName, + @ApiParam( + name = "offset", + value = "Starting point within the complete list of items qualified.") + @QueryParam("offset") int offset, + @ApiParam( + name = "limit", + value = "Maximum size of resource array to return.") @QueryParam("limit") int limit); - @POST @Path("/{groupName}/devices") - @Produces("application/json") - @Permission(name = "Add Device to a Group", permission = "/permission/admin/device-mgt/user/groups/devices/add") - Response addDeviceToGroup(@PathParam("groupName") String groupName, DeviceIdentifier deviceIdentifier); + @POST + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_POST, + value = "Add devices to group.", + notes = "Add existing devices to the device group.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully add devices to the group.", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while adding devices to the group.", + response = ErrorResponse.class) + }) + @Permission(name = "Add devices", permission = "/device-mgt/groups/devices/add") + Response addDevicesToGroup(@ApiParam( + name = "groupName", + value = "Name of the group.", + required = true) + @PathParam("groupName") String groupName, + @ApiParam( + name = "deviceIdentifiers", + value = "Device identifiers of the devices which needed be added.", + required = true) + @Valid List deviceIdentifiers); - @DELETE @Path("/{groupName}/devices") - @Permission(name = "Remove Devices from Group", - permission = "/permission/admin/device-mgt/user/groups/devices/remove") - Response removeDeviceFromGroup(@PathParam("groupName") String groupName, @QueryParam("type") String type, - @QueryParam("id") String id); + @DELETE + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_DELETE, + value = "Remove devices from group.", + notes = "Remove existing devices from the device group.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully removed devices from the group.", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while removing devices from the group.", + response = ErrorResponse.class) + }) + @Permission(name = "Remove devices", permission = "/device-mgt/groups/devices/remove") + Response removeDevicesFromGroup(@ApiParam( + name = "groupName", + value = "Name of the group.", + required = true) + @PathParam("groupName") String groupName, + @ApiParam( + name = "deviceIdentifiers", + value = "Device identifiers of the devices which needed to be removed.", + required = true) + @Valid List deviceIdentifiers); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java index 10e6fef2c92..02ec2514c43 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java @@ -20,20 +20,20 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupShare; import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper; import javax.ws.rs.Consumes; import javax.ws.rs.Path; -import javax.ws.rs.PathParam; import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; @@ -47,12 +47,12 @@ public class GroupManagementServiceImpl implements GroupManagementService { private static final Log log = LogFactory.getLog(GroupManagementServiceImpl.class); @Override - public Response getGroups(@QueryParam("user") String user, @QueryParam("offset") int offset, - @QueryParam("limit") int limit) { + public Response getGroups(int offset, int limit) { try { List groupWrappers = new ArrayList<>(); GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); - List deviceGroups = service.getGroups(user); + String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); + List deviceGroups = service.getGroups(currentUser); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); for (DeviceGroup dg : deviceGroups) { DeviceGroupWrapper gw = new DeviceGroupWrapper(); @@ -76,61 +76,42 @@ public class GroupManagementServiceImpl implements GroupManagementService { } @Override - public Response getGroup(@PathParam("groupName") String groupName) { + public Response getGroup(String groupName) { return null; } @Override - public Response updateGroup(@PathParam("groupName") String groupName, DeviceGroup deviceGroup) { + public Response updateGroup(String groupName, DeviceGroup deviceGroup) { return null; } @Override - public Response deleteGroup(@PathParam("groupName") String groupName) { + public Response deleteGroup(String groupName) { return null; } @Override - public Response shareGroupWithUser(String groupName, String targetUser) { + public Response manageGroupSharing(String groupName, DeviceGroupShare deviceGroupShare) { return null; } @Override - public Response shareGroupWithRole(String groupName, String targetRole) { + public Response getUsersOfGroup(String groupName) { return null; } @Override - public Response removeShareWithUser(@PathParam("groupName") String groupName, - @QueryParam("username") String targetUser) { + public Response getDevicesOfGroup(String groupName, int offset, int limit) { return null; } @Override - public Response removeShareWithRole(@PathParam("groupName") String groupName, - @QueryParam("roleName") String targetUser) { + public Response addDeviceToGroup(String groupName, DeviceIdentifier deviceIdentifier) { return null; } @Override - public Response getUsersOfGroup(@PathParam("groupName") String groupName) { - return null; - } - - @Override - public Response getDevicesOfGroup(@PathParam("groupName") String groupName, @QueryParam("offset") int offset, - @QueryParam("limit") int limit) { - return null; - } - - @Override - public Response addDeviceToGroup(@PathParam("groupName") String groupName, DeviceIdentifier deviceIdentifier) { - return null; - } - - @Override - public Response removeDeviceFromGroup(@PathParam("groupName") String groupName, @QueryParam("type") String type, - @QueryParam("id") String id) { + public Response removeDevicesFromGroup(String groupName, String type, String id) { return null; } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java index cb404d1b92d..4f54a37705e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java @@ -17,6 +17,9 @@ */ package org.wso2.carbon.device.mgt.common.group.mgt; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; @@ -25,19 +28,29 @@ import java.util.List; /** * Holds Device Group details and expose to external access */ -@XmlRootElement +@ApiModel(value = "DeviceGroup", description = "This class carries all information related to a managed device group.") public class DeviceGroup implements Serializable { + private static final long serialVersionUID = 1998121711L; + + @ApiModelProperty(name = "id", value = "ID of the device group in the device group information database.", + required = true) private int id; + + @ApiModelProperty(name = "description", value = "The device group description that can be set on the device group by the user.", + required = true) private String description; + + @ApiModelProperty(name = "name", value = "The device group name that can be set on the device group by the user.", + required = true) private String name; + private Long dateOfCreation; private Long dateOfLastUpdate; private String owner; private List users; private List roles; - @XmlElement public int getId() { return id; } @@ -46,7 +59,6 @@ public class DeviceGroup implements Serializable { this.id = id; } - @XmlElement public String getDescription() { return description; } @@ -55,7 +67,6 @@ public class DeviceGroup implements Serializable { this.description = description; } - @XmlElement public String getName() { return name; } @@ -64,7 +75,6 @@ public class DeviceGroup implements Serializable { this.name = name; } - @XmlElement public Long getDateOfCreation() { return dateOfCreation; } @@ -73,7 +83,6 @@ public class DeviceGroup implements Serializable { this.dateOfCreation = dateOfCreation; } - @XmlElement public Long getDateOfLastUpdate() { return dateOfLastUpdate; } @@ -82,7 +91,6 @@ public class DeviceGroup implements Serializable { this.dateOfLastUpdate = dateOfLastUpdate; } - @XmlElement public String getOwner() { return owner; } @@ -91,7 +99,6 @@ public class DeviceGroup implements Serializable { this.owner = owner; } - @XmlElement public List getUsers() { return users; } @@ -100,7 +107,6 @@ public class DeviceGroup implements Serializable { this.users = users; } - @XmlElement public List getRoles() { return roles; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupUser.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupUser.java index 1932c50309f..2d80b30574c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupUser.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/GroupUser.java @@ -18,6 +18,9 @@ */ package org.wso2.carbon.device.mgt.common.group.mgt; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; @@ -26,12 +29,17 @@ import java.util.List; /** * This class holds Device Group user name and assigned group roles of user. Exposed to external access */ -@XmlRootElement +@ApiModel(value = "GroupUser", description = "This class carries all information related to a user of a managed device group.") public class GroupUser implements Serializable { + + private static final long serialVersionUID = 1998131711L; + + @ApiModelProperty(name = "username", value = "Username of the user.", required = true) private String username; + + @ApiModelProperty(name = "roles", value = "List of roles assigned to the user.") private List groupRoles; - @XmlElement public String getUsername() { return username; } @@ -40,7 +48,6 @@ public class GroupUser implements Serializable { this.username = username; } - @XmlElement public List getGroupRoles() { return groupRoles; } From f22d392978dc2541fbaf5784600f8c01ff262b18 Mon Sep 17 00:00:00 2001 From: charitha Date: Tue, 4 Oct 2016 19:03:07 +0530 Subject: [PATCH 2/8] Upgrade to comply with latest CDMF changes --- .../mgt/jaxrs/beans/BasePaginatedResult.java | 2 - .../mgt/jaxrs/beans/DeviceGroupList.java | 3 - .../mgt/jaxrs/beans/DeviceGroupUsersList.java | 2 - .../service/api/GroupManagementService.java | 107 +++++++++- .../admin/GroupManagementAdminService.java | 134 ++++++++----- .../impl/GroupManagementServiceImpl.java | 81 +++++--- .../GroupManagementAdminServiceImpl.java | 39 ++-- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 +- .../mgt/common/group/mgt/DeviceGroup.java | 24 +-- .../DeviceAccessAuthorizationServiceImpl.java | 2 +- .../core/group/mgt/DeviceGroupBuilder.java | 71 ------- .../mgt/core/group/mgt/dao/GroupDAO.java | 12 +- .../mgt/core/group/mgt/dao/GroupDAOImpl.java | 17 +- .../group/mgt/dao/GroupManagementDAOUtil.java | 5 +- .../GroupManagementProviderService.java | 42 +--- .../GroupManagementProviderServiceImpl.java | 184 +++++------------- .../mgt/core/common/TestDataHolder.java | 4 +- .../mgt/core/dao/GroupPersistTests.java | 5 +- .../policy/mgt/common/DeviceGroupWrapper.java | 2 +- .../mgt/core/util/PolicyManagerUtil.java | 2 +- 20 files changed, 343 insertions(+), 397 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/BasePaginatedResult.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/BasePaginatedResult.java index b3a60032e11..92ec04424f9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/BasePaginatedResult.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/BasePaginatedResult.java @@ -24,8 +24,6 @@ import io.swagger.annotations.ApiModelProperty; public class BasePaginatedResult { private int count; - private String next; - private String previous; /** * Number of Resources returned. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java index 15a3e1698cb..d1e472255a5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java @@ -44,10 +44,7 @@ public class DeviceGroupList extends BasePaginatedResult { public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{\n"); - sb.append(" count: ").append(getCount()).append(",\n"); - sb.append(" next: ").append(getNext()).append(",\n"); - sb.append(" previous: ").append(getPrevious()).append(",\n"); sb.append(" groups: [").append(deviceGroups).append("\n"); sb.append("]}\n"); return sb.toString(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java index ed369ced60a..21e72562ffa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java @@ -44,8 +44,6 @@ public class DeviceGroupUsersList extends BasePaginatedResult { sb.append("{\n"); sb.append(" count: ").append(getCount()).append(",\n"); - sb.append(" next: ").append(getNext()).append(",\n"); - sb.append(" previous: ").append(getPrevious()).append(",\n"); sb.append(" users: [").append(users).append("\n"); sb.append("]}\n"); return sb.toString(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java index c6c050fa71a..4509547abde 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java @@ -16,6 +16,7 @@ * under the License. * */ + package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.Api; @@ -110,6 +111,49 @@ public interface GroupManagementService { value = "Maximum size of resource array to return.") @QueryParam("limit") int limit); + @Path("/count") + @GET + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "Get the count of groups belongs to current user.", + notes = "Returns count of all permitted groups enrolled with the system.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the device group count.", + response = DeviceGroupList.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the group count.", + response = ErrorResponse.class) + }) + @Permission(name = "View Groups", permission = "/device-mgt/groups/view") + Response getGroupCount(); + @POST @ApiOperation( consumes = MediaType.APPLICATION_JSON, @@ -170,7 +214,7 @@ public interface GroupManagementService { required = true) @Valid DeviceGroup group); - @Path("/{groupName}") + @Path("/name/{groupName}") @GET @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -217,7 +261,7 @@ public interface GroupManagementService { required = true) @PathParam("groupName") String groupName); - @Path("/{groupName}") + @Path("/name/{groupName}") @PUT @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -269,7 +313,7 @@ public interface GroupManagementService { required = true) @Valid DeviceGroup deviceGroup); - @Path("/{groupName}") + @Path("/name/{groupName}") @DELETE @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -316,7 +360,7 @@ public interface GroupManagementService { required = true) @PathParam("groupName") String groupName); - @Path("/{groupName}/share") + @Path("/name/{groupName}/share") @POST @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -368,7 +412,7 @@ public interface GroupManagementService { required = true) @Valid DeviceGroupShare deviceGroupShare); - @Path("/{groupName}/users") + @Path("/name/{groupName}/users") @GET @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -415,7 +459,7 @@ public interface GroupManagementService { required = true) @PathParam("groupName") String groupName); - @Path("/{groupName}/devices") + @Path("/name/{groupName}/devices") @GET @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -470,7 +514,54 @@ public interface GroupManagementService { value = "Maximum size of resource array to return.") @QueryParam("limit") int limit); - @Path("/{groupName}/devices") + @Path("/name/{groupName}/devices/count") + @GET + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "View list of device count in the device group.", + notes = "Returns device count in the device group.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the device count.", + response = DeviceList.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching device count.", + response = ErrorResponse.class) + }) + @Permission(name = "View devices", permission = "/device-mgt/groups/devices/view") + Response getDeviceCountOfGroup(@ApiParam( + name = "groupName", + value = "Name of the group.", + required = true) + @PathParam("groupName") String groupName); + + @Path("/name/{groupName}/devices") @POST @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -521,7 +612,7 @@ public interface GroupManagementService { required = true) @Valid List deviceIdentifiers); - @Path("/{groupName}/devices") + @Path("/name/{groupName}/devices") @DELETE @ApiOperation( produces = MediaType.APPLICATION_JSON, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java index 885005944a4..056bb743b0a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java @@ -16,6 +16,7 @@ * under the License. * */ + package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; import io.swagger.annotations.Api; @@ -24,13 +25,14 @@ import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ResponseHeader; +import org.apache.axis2.transport.http.HTTPConstants; import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.Permission; -import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupList; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import javax.ws.rs.Consumes; import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; @@ -50,60 +52,92 @@ public interface GroupManagementAdminService { @GET @ApiOperation( produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Get groups by the name.", - notes = "Get devices the name of device and tenant.", - response = DeviceGroupWrapper.class, - responseContainer = "List", - tags = "Group Management Administrative Service") + httpMethod = HTTPConstants.HEADER_GET, + value = "Get the list of groups.", + notes = "Returns all groups enrolled with the system.", + tags = "Device Group Management") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of device groups.", + response = DeviceGroupList.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the groups list.", + response = ErrorResponse.class) + }) + @Permission(name = "View Groups", permission = "/device-mgt/admin/groups/view") + Response getGroups(@ApiParam( + name = "offset", + value = "Starting point within the complete list of items qualified.") + @QueryParam("offset") int offset, + @ApiParam( + name = "limit", + value = "Maximum size of resource array to return.") + @QueryParam("limit") int limit); + + @GET + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = HTTPConstants.HEADER_GET, + value = "Get the count of groups belongs to current user.", + notes = "Returns count of all permitted groups enrolled with the system.", + tags = "Device Group Management") @ApiResponses(value = { - @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of groups.", - response = DeviceGroupWrapper.class, - responseContainer = "List", - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource has been modified the last time.\n" + - "Used by caches, or in conditional requests."), - }), + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the device group count.", + response = DeviceGroupList.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), @ApiResponse( code = 304, - message = "Not Modified. \n Empty body because the client has already the latest version of the " + - "requested resource."), + message = "Not Modified. \n Empty body because the client has already the latest version of " + + "the requested resource."), + @ApiResponse( + code = 404, + message = "No groups found.", + response = ErrorResponse.class), @ApiResponse( code = 406, - message = "Not Acceptable.\n The requested media type is not supported"), + message = "Not Acceptable.\n The requested media type is not supported."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching the group list.") + message = "Internal Server Error. \n Server error occurred while fetching the group count.", + response = ErrorResponse.class) }) - @Permission(name = "View All Groups", permission = "/permission/admin/device-mgt/user/groups/list") - Response getGroupsOfUser( - @ApiParam( - name = "username", - value = "Username of the user.", - required = true) - @QueryParam("username") String username, - @ApiParam( - name = "If-Modified-Since", - value = "Timestamp of the last modified date", - required = false) - @HeaderParam("If-Modified-Since") String timestamp, - @ApiParam( - name = "offset", - value = "Starting point within the complete list of items qualified.", - required = false) - @QueryParam("offset") int offset, - @ApiParam( - name = "limit", - value = "Maximum size of resource array to return.", - required = false) - @QueryParam("limit") int limit); + @Permission(name = "View Groups", permission = "/device-mgt/admin/groups/view") + Response getGroupCount(); + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java index 02ec2514c43..e1e874ad1f8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java @@ -16,6 +16,7 @@ * under the License. * */ + package org.wso2.carbon.device.mgt.jaxrs.service.impl; import org.apache.commons.logging.Log; @@ -24,55 +25,77 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; 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.jaxrs.beans.DeviceGroupList; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupShare; import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; -import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper; -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 java.util.ArrayList; +import java.util.Date; import java.util.List; -@Path("/groups") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) public class GroupManagementServiceImpl implements GroupManagementService { private static final Log log = LogFactory.getLog(GroupManagementServiceImpl.class); + private static final String DEFAULT_ADMIN_ROLE = "admin"; + private static final String[] DEFAULT_ADMIN_PERMISSIONS = {"/permission/device-mgt/admin/groups", + "/permission/device-mgt/user/groups"}; + @Override public Response getGroups(int offset, int limit) { try { - List groupWrappers = new ArrayList<>(); GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); - List deviceGroups = service.getGroups(currentUser); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - for (DeviceGroup dg : deviceGroups) { - DeviceGroupWrapper gw = new DeviceGroupWrapper(); - gw.setId(dg.getId()); - gw.setOwner(dg.getOwner()); - gw.setName(dg.getName()); - gw.setTenantId(tenantId); - groupWrappers.add(gw); - } - return Response.status(Response.Status.OK).entity(groupWrappers).build(); + List deviceGroups = service.getGroups(currentUser, offset, limit); + DeviceGroupList deviceGroupList = new DeviceGroupList(); + deviceGroupList.setList(deviceGroups); + deviceGroupList.setCount(service.getGroupCount(currentUser)); + return Response.status(Response.Status.OK).entity(deviceGroupList).build(); } catch (GroupManagementException e) { - String error = "ErrorResponse occurred while getting the groups related to users for policy."; + String error = "Error occurred while getting the groups related to users for policy."; log.error(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); } } + @Override + public Response getGroupCount() { + try { + String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); + int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(currentUser); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (GroupManagementException e) { + String msg = "Error occurred while retrieving group count."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + @Override public Response createGroup(DeviceGroup group) { - return null; + String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + if (group == null) { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + group.setOwner(owner); + group.setDateOfCreation(new Date().getTime()); + group.setDateOfLastUpdate(new Date().getTime()); + try { + DeviceMgtAPIUtils.getGroupManagementProviderService().createGroup(group, DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS); + return Response.status(Response.Status.OK).build(); + } catch (GroupManagementException e) { + String msg = "Error occurred while adding new group."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (GroupAlreadyExistException e) { + String msg = "Group already exists with name '" + group.getName() + "'."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } } @Override @@ -106,12 +129,18 @@ public class GroupManagementServiceImpl implements GroupManagementService { } @Override - public Response addDeviceToGroup(String groupName, DeviceIdentifier deviceIdentifier) { + public Response getDeviceCountOfGroup(String groupName) { return null; } @Override - public Response removeDevicesFromGroup(String groupName, String type, String id) { + public Response addDevicesToGroup(String groupName, List deviceIdentifiers) { return null; } -} \ No newline at end of file + + @Override + public Response removeDevicesFromGroup(String groupName, List deviceIdentifiers) { + return null; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java index 9cf5253c2c9..887be40c08d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java @@ -20,19 +20,21 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; +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.service.api.admin.GroupManagementAdminService; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.util.List; @Path("/admin/groups") @Produces(MediaType.APPLICATION_JSON) @@ -41,26 +43,35 @@ public class GroupManagementAdminServiceImpl implements GroupManagementAdminServ private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class); - @GET @Override - public Response getGroupsOfUser( - @QueryParam("username") String username, - @HeaderParam("If-Modified-Since") String timestamp, - @QueryParam("offset") int offset, - @QueryParam("limit") int limit) { + public Response getGroups(int offset, int limit) { try { - PaginationResult result = - DeviceMgtAPIUtils.getGroupManagementProviderService().getGroups(username, offset, limit); - if (result != null && result.getRecordsTotal() > 0) { - return Response.status(Response.Status.OK).entity(result).build(); + GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); + List deviceGroups = service.getGroups(offset, limit); + DeviceGroupList deviceGroupList = new DeviceGroupList(); + deviceGroupList.setList(deviceGroups); + deviceGroupList.setCount(service.getGroupCount()); + if (deviceGroups != null && deviceGroups.size() > 0) { + return Response.status(Response.Status.OK).entity(deviceGroupList).build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); } } catch (GroupManagementException e) { - String msg = "ErrorResponse occurred while retrieving the groups of user '" + username + "'"; + String msg = "ErrorResponse occurred while retrieving all groups."; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } + @Override + public Response getGroupCount() { + try { + int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(); + return Response.status(Response.Status.OK).entity(count).build(); + } catch (GroupManagementException e) { + String msg = "ErrorResponse occurred while retrieving group count."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml index a5f5ed308a9..ac127d15006 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -34,7 +34,7 @@ - + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java index 4f54a37705e..61d02b2e6b4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java @@ -33,8 +33,7 @@ public class DeviceGroup implements Serializable { private static final long serialVersionUID = 1998121711L; - @ApiModelProperty(name = "id", value = "ID of the device group in the device group information database.", - required = true) + @ApiModelProperty(name = "id", value = "ID of the device group in the device group information database.") private int id; @ApiModelProperty(name = "description", value = "The device group description that can be set on the device group by the user.", @@ -51,11 +50,11 @@ public class DeviceGroup implements Serializable { private List users; private List roles; - public int getId() { + public int getGroupId() { return id; } - public void setId(int id) { + public void setGroupId(int id) { this.id = id; } @@ -103,7 +102,7 @@ public class DeviceGroup implements Serializable { return users; } - protected void setUsers(List users) { + public void setUsers(List users) { this.users = users; } @@ -111,21 +110,8 @@ public class DeviceGroup implements Serializable { return roles; } - protected void setRoles(List roles) { + public void setRoles(List roles) { this.roles = roles; } - protected DeviceGroup getGroup() { - DeviceGroup deviceGroup = new DeviceGroup(); - deviceGroup.setId(getId()); - deviceGroup.setDescription(getDescription()); - deviceGroup.setName(getName()); - deviceGroup.setDateOfCreation(getDateOfCreation()); - deviceGroup.setDateOfLastUpdate(getDateOfLastUpdate()); - deviceGroup.setOwner(getOwner()); - deviceGroup.setUsers(getUsers()); - deviceGroup.setRoles(getRoles()); - return deviceGroup; - } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java index 97b5a21c047..0703d4d39d1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java @@ -203,7 +203,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori Iterator groupsWithDeviceIterator = groupsWithDevice.iterator(); while (groupsWithDeviceIterator.hasNext()) { DeviceGroup deviceGroup = groupsWithDeviceIterator.next(); - if (deviceGroup.getId() == group.getId()) { + if (deviceGroup.getGroupId() == group.getGroupId()) { return true; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java deleted file mode 100644 index c1e37bbd6d3..00000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.core.group.mgt; - -import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; -import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; - -import java.util.List; - -/** - * This class is used to expose protected methods to the core. Use with internal access only. - */ -public class DeviceGroupBuilder extends DeviceGroup { - - private int groupId; - - /** - * Set device group to be decorated with the builder - * - * @param deviceGroup to decorate - */ - public DeviceGroupBuilder(DeviceGroup deviceGroup) { - this.setId(deviceGroup.getId()); - this.setDescription(deviceGroup.getDescription()); - this.setName(deviceGroup.getName()); - this.setDateOfCreation(deviceGroup.getDateOfCreation()); - this.setDateOfLastUpdate(deviceGroup.getDateOfLastUpdate()); - this.setOwner(deviceGroup.getOwner()); - this.setUsers(deviceGroup.getUsers()); - this.setRoles(deviceGroup.getRoles()); - } - - @Override - public void setUsers(List users) { - super.setUsers(users); - } - - @Override - public void setRoles(List roles) { - super.setRoles(roles); - } - - @Override - public DeviceGroup getGroup() { - return super.getGroup(); - } - - public int getGroupId() { - return groupId; - } - - public void setGroupId(int groupId) { - this.groupId = groupId; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java index 7e8132fedf0..b164a4ba110 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java @@ -20,7 +20,6 @@ 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.group.mgt.DeviceGroup; -import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import java.util.List; @@ -68,8 +67,7 @@ public interface GroupDAO { * @return Device Group in tenant with specified name. * @throws GroupManagementDAOException */ - DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException; - + DeviceGroup getGroup(int groupId, int tenantId) throws GroupManagementDAOException; /** * Get device group by name. @@ -80,7 +78,7 @@ public interface GroupDAO { * @return Device Group in tenant with specified name. * @throws GroupManagementDAOException */ - DeviceGroupBuilder getGroup(String groupName, String owner, int tenantId) throws GroupManagementDAOException; + DeviceGroup getGroup(String groupName, String owner, int tenantId) throws GroupManagementDAOException; /** * Get the groups of device with device id provided @@ -88,7 +86,7 @@ public interface GroupDAO { * @return * @throws GroupManagementDAOException */ - List getGroups(int deviceId, int tenantId) throws GroupManagementDAOException; + List getGroups(int deviceId, int tenantId) throws GroupManagementDAOException; /** * Get the list of Device Groups in tenant. @@ -99,7 +97,7 @@ public interface GroupDAO { * @return List of all Device Groups in tenant. * @throws GroupManagementDAOException */ - List getGroups(int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException; + List getGroups(int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException; /** @@ -119,7 +117,7 @@ public interface GroupDAO { * @return List of DeviceGroup that matches with the given DeviceGroup name. * @throws GroupManagementDAOException */ - List findInGroups(String groupName, int tenantId) throws GroupManagementDAOException; + List findInGroups(String groupName, int tenantId) throws GroupManagementDAOException; /** * Check group already existed with given name. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java index df70f43502d..4b2134d6b93 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java @@ -21,7 +21,6 @@ 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.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; -import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import java.sql.Connection; import java.sql.PreparedStatement; @@ -127,7 +126,7 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException { + public DeviceGroup getGroup(int groupId, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; try { @@ -152,7 +151,7 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public DeviceGroupBuilder getGroup(String groupName, String owner, int tenantId) + public DeviceGroup getGroup(String groupName, String owner, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; @@ -179,11 +178,11 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public List getGroups(int deviceId, int tenantId) throws GroupManagementDAOException { + public List getGroups(int deviceId, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; - List deviceGroupBuilders = new ArrayList<>(); + List deviceGroupBuilders = new ArrayList<>(); try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT G.ID, G.GROUP_NAME, G.DESCRIPTION, G.DATE_OF_CREATE, G.DATE_OF_LAST_UPDATE, \n" + @@ -205,11 +204,11 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public List getGroups(int startIndex, int rowCount, int tenantId) + public List getGroups(int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; - List deviceGroupList = null; + List deviceGroupList = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " @@ -256,11 +255,11 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public List findInGroups(String groupName, int tenantId) + public List findInGroups(String groupName, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; - List deviceGroups = new ArrayList<>(); + List deviceGroups = new ArrayList<>(); try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java index 9a206c7b713..2352ef149e0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java @@ -21,7 +21,6 @@ package org.wso2.carbon.device.mgt.core.group.mgt.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; -import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import javax.naming.InitialContext; import javax.sql.DataSource; @@ -80,8 +79,8 @@ public final class GroupManagementDAOUtil { } } - public static DeviceGroupBuilder loadGroup(ResultSet resultSet) throws SQLException { - DeviceGroupBuilder group = new DeviceGroupBuilder(new DeviceGroup()); + public static DeviceGroup loadGroup(ResultSet resultSet) throws SQLException { + DeviceGroup group = new DeviceGroup(); group.setGroupId(resultSet.getInt("ID")); group.setDescription(resultSet.getString("DESCRIPTION")); group.setName(resultSet.getString("GROUP_NAME")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java index 1b16cc05073..b1c9a8468ca 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java @@ -60,6 +60,7 @@ public interface GroupManagementProviderService { * * @param groupName to be deleted. * @param owner of the group. + * @return status of the delete operation. * @throws GroupManagementException */ boolean deleteGroup(String groupName, String owner) throws GroupManagementException; @@ -84,25 +85,15 @@ public interface GroupManagementProviderService { */ DeviceGroup getGroup(int groupId) throws GroupManagementException; - /** - * Get list of device groups matched with %groupName% - * - * @param groupName of the groups. - * @param username of user - * @return List of Groups that matches with the given DeviceGroup name. - * @throws GroupManagementException - */ - List findInGroups(String groupName, String username) throws GroupManagementException; - /** * Get paginated device groups in tenant * * @param startIndex for pagination. * @param rowCount for pagination. - * @return paginated list of groups + * @return list of groups. * @throws GroupManagementException */ - PaginationResult getGroups(int startIndex, int rowCount) throws GroupManagementException; + List getGroups(int startIndex, int rowCount) throws GroupManagementException; /** * Get paginated device groups in tenant @@ -110,10 +101,10 @@ public interface GroupManagementProviderService { * @param username of user. * @param startIndex for pagination. * @param rowCount for pagination. - * @return paginated list of groups + * @return list of groups * @throws GroupManagementException */ - PaginationResult getGroups(String username, int startIndex, int rowCount) throws GroupManagementException; + List getGroups(String username, int startIndex, int rowCount) throws GroupManagementException; /** * Get all device group count in tenant @@ -123,15 +114,6 @@ public interface GroupManagementProviderService { */ int getGroupCount() throws GroupManagementException; - /** - * Get device groups of user - * - * @param username of the user - * @return list of groups - * @throws GroupManagementException - */ - List getGroups(String username) throws GroupManagementException; - /** * Get device group count of user * @@ -224,16 +206,6 @@ public interface GroupManagementProviderService { */ List getUsers(String groupName, String owner) throws GroupManagementException; - /** - * Get all devices in device group. - * - * @param groupName of the group. - * @param owner of the group. - * @return list of group devices. - * @throws GroupManagementException - */ - List getDevices(String groupName, String owner) throws GroupManagementException; - /** * Get all devices in device group as paginated result. * @@ -241,10 +213,10 @@ public interface GroupManagementProviderService { * @param owner of the group. * @param startIndex for pagination. * @param rowCount for pagination. - * @return Paginated list of devices. + * @return list of devices in group. * @throws GroupManagementException */ - PaginationResult getDevices(String groupName, String owner, int startIndex, int rowCount) + List getDevices(String groupName, String owner, int startIndex, int rowCount) throws GroupManagementException; /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index e9beade43e2..762478c5927 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -28,7 +28,6 @@ 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.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; -import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupDAO; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOException; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory; @@ -65,14 +64,13 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid if (deviceGroup == null) { throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException()); } - DeviceGroupBuilder groupBroker = new DeviceGroupBuilder(deviceGroup); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int groupId = -1; try { GroupManagementDAOFactory.beginTransaction(); boolean nameIsExists = this.groupDAO.isGroupExist(deviceGroup.getName(), deviceGroup.getOwner(), tenantId); if (!nameIsExists) { - groupId = this.groupDAO.addGroup(groupBroker, tenantId); + groupId = this.groupDAO.addGroup(deviceGroup, tenantId); GroupManagementDAOFactory.commitTransaction(); } else { throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName()); @@ -87,9 +85,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid GroupManagementDAOFactory.closeConnection(); } - addGroupSharingRole(groupBroker.getOwner(), groupId, defaultRole, defaultPermissions); + addGroupSharingRole(deviceGroup.getOwner(), groupId, defaultRole, defaultPermissions); if (log.isDebugEnabled()) { - log.debug("DeviceGroup added: " + groupBroker.getName()); + log.debug("DeviceGroup added: " + deviceGroup.getName()); } } @@ -125,7 +123,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid @Override public boolean deleteGroup(String groupName, String owner) throws GroupManagementException { String roleName; - DeviceGroupBuilder deviceGroup = getGroupBuilder(groupName, owner); + DeviceGroup deviceGroup = buildDeviceGroup(groupName, owner); if (deviceGroup == null) { return false; } @@ -160,16 +158,15 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid */ @Override public DeviceGroup getGroup(String groupName, String owner) throws GroupManagementException { - return getGroupBuilder(groupName, owner).getGroup(); + return buildDeviceGroup(groupName, owner); } - @SuppressWarnings("Duplicates") - private DeviceGroupBuilder getGroupBuilder(String groupName, String owner) throws GroupManagementException { - DeviceGroupBuilder deviceGroupBuilder; + private DeviceGroup buildDeviceGroup(String groupName, String owner) throws GroupManagementException { + DeviceGroup deviceGroup; try { GroupManagementDAOFactory.openConnection(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - deviceGroupBuilder = this.groupDAO.getGroup(groupName, owner, tenantId); + deviceGroup = this.groupDAO.getGroup(groupName, owner, tenantId); } catch (GroupManagementDAOException e) { throw new GroupManagementException("Error occurred while obtaining group '" + groupName + "'", e); } catch (SQLException e) { @@ -177,19 +174,19 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } finally { GroupManagementDAOFactory.closeConnection(); } - if (deviceGroupBuilder != null) { - deviceGroupBuilder.setUsers(this.getUsers(deviceGroupBuilder.getGroupId())); - deviceGroupBuilder.setRoles(this.getRoles(deviceGroupBuilder.getGroupId())); + if (deviceGroup != null) { + deviceGroup.setUsers(this.getUsers(deviceGroup.getGroupId())); + deviceGroup.setRoles(this.getRoles(deviceGroup.getGroupId())); } - return deviceGroupBuilder; + return deviceGroup; } - private DeviceGroupBuilder getGroupBuilder(int groupId) throws GroupManagementException { - DeviceGroupBuilder groupBroker; + private DeviceGroup buildDeviceGroup(int groupId) throws GroupManagementException { + DeviceGroup deviceGroup; try { GroupManagementDAOFactory.openConnection(); - groupBroker = this.groupDAO.getGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId()); + deviceGroup = this.groupDAO.getGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId()); } catch (GroupManagementDAOException e) { throw new GroupManagementException("Error occurred while obtaining group '" + groupId + "'", e); } catch (SQLException e) { @@ -197,11 +194,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } finally { GroupManagementDAOFactory.closeConnection(); } - if (groupBroker != null) { - groupBroker.setUsers(this.getUsers(groupBroker.getGroupId())); - groupBroker.setRoles(this.getRoles(groupBroker.getGroupId())); + if (deviceGroup != null) { + deviceGroup.setUsers(this.getUsers(groupId)); + deviceGroup.setRoles(this.getRoles(groupId)); } - return groupBroker; + return deviceGroup; } /** @@ -209,43 +206,17 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid */ @Override public DeviceGroup getGroup(int groupId) throws GroupManagementException { - DeviceGroupBuilder groupBroker = this.getGroupBuilder(groupId); - if (groupBroker != null) { - groupBroker.setUsers(this.getUsers(groupBroker.getGroupId())); - groupBroker.setRoles(this.getRoles(groupBroker.getGroupId())); + DeviceGroup deviceGroup = this.buildDeviceGroup(groupId); + if (deviceGroup != null) { + deviceGroup.setUsers(this.getUsers(groupId)); + deviceGroup.setRoles(this.getRoles(groupId)); } - return groupBroker.getGroup(); - } - - /** - * {@inheritDoc} - */ - @Override - public List findInGroups(String groupName, String owner) throws GroupManagementException { - List deviceGroups = new ArrayList<>(); - try { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - GroupManagementDAOFactory.openConnection(); - deviceGroups = this.groupDAO.findInGroups(groupName, tenantId); - } catch (GroupManagementDAOException e) { - throw new GroupManagementException("Error occurred while finding group " + groupName, e); - } catch (SQLException e) { - throw new GroupManagementException("Error occurred while opening a connection to the data source.", e); - } finally { - GroupManagementDAOFactory.closeConnection(); - } - List groupsWithData = new ArrayList<>(); - for (DeviceGroupBuilder groupBroker : deviceGroups) { - groupBroker.setUsers(this.getUsers(groupBroker.getGroupId())); - groupBroker.setRoles(this.getRoles(groupBroker.getGroupId())); - groupsWithData.add(groupBroker.getGroup()); - } - return groupsWithData; + return deviceGroup; } @Override - public PaginationResult getGroups(int startIndex, int rowCount) throws GroupManagementException { - List deviceGroups = new ArrayList<>(); + public List getGroups(int startIndex, int rowCount) throws GroupManagementException { + List deviceGroups = new ArrayList<>(); try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); GroupManagementDAOFactory.openConnection(); @@ -257,21 +228,15 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } finally { GroupManagementDAOFactory.closeConnection(); } - List groupsWithData = new ArrayList<>(); - for (DeviceGroupBuilder groupBroker : deviceGroups) { - groupBroker.setUsers(this.getUsers(groupBroker.getGroupId())); - groupBroker.setRoles(this.getRoles(groupBroker.getGroupId())); - groupsWithData.add(groupBroker.getGroup()); + for (DeviceGroup group : deviceGroups) { + group.setUsers(this.getUsers(group.getGroupId())); + group.setRoles(this.getRoles(group.getGroupId())); } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setRecordsTotal(getGroupCount()); - paginationResult.setData(groupsWithData); - paginationResult.setRecordsFiltered(groupsWithData.size()); - return paginationResult; + return deviceGroups; } @Override - public PaginationResult getGroups(String username, int startIndex, int rowCount) throws GroupManagementException { + public List getGroups(String username, int startIndex, int rowCount) throws GroupManagementException { Map groups = new HashMap<>(); UserStoreManager userStoreManager; try { @@ -282,20 +247,16 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid int index = 0; for (String role : roleList) { if (role != null && role.contains("Internal/group-")) { - DeviceGroupBuilder deviceGroupBuilder = extractNewGroupFromRole(groups, role); + DeviceGroup deviceGroupBuilder = extractNewGroupFromRole(groups, role); if (deviceGroupBuilder != null && startIndex <= index++ && index <= rowCount) { - groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder.getGroup()); + groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder); } } } } catch (UserStoreException e) { throw new GroupManagementException("Error occurred while getting user store manager.", e); } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setRecordsTotal(getGroupCount()); - paginationResult.setData(new ArrayList<>(groups.values())); - paginationResult.setRecordsFiltered(groups.size()); - return paginationResult; + return new ArrayList<>(groups.values()); } @Override @@ -313,32 +274,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } } - /** - * {@inheritDoc} - */ - @Override - public List getGroups(String username) throws GroupManagementException { - UserStoreManager userStoreManager; - try { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) - .getUserStoreManager(); - String[] roleList = userStoreManager.getRoleListOfUser(username); - Map groups = new HashMap<>(); - for (String role : roleList) { - if (role != null && role.contains("Internal/group-")) { - DeviceGroupBuilder deviceGroupBuilder = extractNewGroupFromRole(groups, role); - if (deviceGroupBuilder != null) { - groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder.getGroup()); - } - } - } - return new ArrayList<>(groups.values()); - } catch (UserStoreException e) { - throw new GroupManagementException("Error occurred while getting user store manager.", e); - } - } - /** * {@inheritDoc} */ @@ -421,11 +356,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } private int getGroupId(String groupName, String owner) throws GroupManagementException { - DeviceGroupBuilder deviceGroupBuilder = getGroupBuilder(groupName, owner); - if (deviceGroupBuilder == null) { + DeviceGroup deviceGroup = buildDeviceGroup(groupName, owner); + if (deviceGroup == null) { return -1; } - return deviceGroupBuilder.getGroupId(); + return deviceGroup.getGroupId(); } /** @@ -610,25 +545,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public List getDevices(String groupName, String owner) throws GroupManagementException { - try { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - GroupManagementDAOFactory.openConnection(); - return this.groupDAO.getDevices(groupName, owner, tenantId); - } catch (GroupManagementDAOException e) { - throw new GroupManagementException("Error occurred while getting devices in group.", e); - } catch (SQLException e) { - throw new GroupManagementException("Error occurred while opening a connection to the data source.", e); - } finally { - GroupManagementDAOFactory.closeConnection(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public PaginationResult getDevices(String groupName, String owner, int startIndex, int rowCount) + public List getDevices(String groupName, String owner, int startIndex, int rowCount) throws GroupManagementException { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); List devices; @@ -642,11 +559,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } finally { GroupManagementDAOFactory.closeConnection(); } - PaginationResult paginationResult = new PaginationResult(); - paginationResult.setRecordsTotal(getDeviceCount(groupName, owner)); - paginationResult.setData(devices); - paginationResult.setRecordsFiltered(devices.size()); - return paginationResult; + return devices; } /** @@ -774,9 +687,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid for (String role : roles) { if (role != null && role.contains("Internal/group-") && userRealm.getAuthorizationManager() .isRoleAuthorized(role, permission, CarbonConstants.UI_PERMISSION_ACTION)) { - DeviceGroupBuilder deviceGroupBuilder = extractNewGroupFromRole(groups, role); - if (deviceGroupBuilder != null) { - groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder.getGroup()); + DeviceGroup group = extractNewGroupFromRole(groups, role); + if (group != null) { + groups.put(group.getGroupId(), group); } } } @@ -789,15 +702,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid @Override public List getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException { DeviceManagementProviderService managementProviderService = new DeviceManagementProviderServiceImpl(); - List deviceGroups = new ArrayList<>(); try { Device device = managementProviderService.getDevice(deviceIdentifier); GroupManagementDAOFactory.openConnection(); - List builders = groupDAO.getGroups(device.getId(), - PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); - for (DeviceGroupBuilder d : builders){ - deviceGroups.add(d.getGroup()); - } + return groupDAO.getGroups(device.getId(), + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); } catch (DeviceManagementException e) { throw new GroupManagementException("Error occurred while retrieving the device details.", e); } catch (GroupManagementDAOException e) { @@ -807,15 +716,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } finally { GroupManagementDAOFactory.closeConnection(); } - return deviceGroups; } - private DeviceGroupBuilder extractNewGroupFromRole(Map groups, String role) + private DeviceGroup extractNewGroupFromRole(Map groups, String role) throws GroupManagementException { try { int groupId = Integer.parseInt(role.split("-")[1]); if (!groups.containsKey(groupId)) { - return getGroupBuilder(groupId); + return buildDeviceGroup(groupId); } } catch (NumberFormatException e) { log.error("Unable to extract groupId from role " + role, e); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java index bb467761e71..895deab36c7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java @@ -20,7 +20,6 @@ import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.dto.DeviceType; -import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import java.util.Date; import java.util.Properties; @@ -82,7 +81,6 @@ public class TestDataHolder { deviceGroup.setDateOfCreation(new Date().getTime()); deviceGroup.setDateOfLastUpdate(new Date().getTime()); deviceGroup.setOwner(OWNER); - DeviceGroupBuilder broker = new DeviceGroupBuilder(deviceGroup); - return broker.getGroup(); + return deviceGroup; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java index fa733444bb8..d6e435a7c6c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java @@ -28,7 +28,6 @@ import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; import org.wso2.carbon.device.mgt.core.common.TestDataHolder; -import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupDAO; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOException; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory; @@ -80,7 +79,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest { public void findGroupTest() { try { GroupManagementDAOFactory.openConnection(); - List groups = groupDAO.findInGroups("Test", TestDataHolder.SUPER_TENANT_ID); + List groups = groupDAO.findInGroups("Test", TestDataHolder.SUPER_TENANT_ID); Assert.assertNotEquals(groups.size(), 0, "No groups found"); Assert.assertNotNull(groups.get(0), "Group is null"); log.debug("Group found: " + groups.get(0).getName()); @@ -101,7 +100,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest { public void getGroupTest() { try { GroupManagementDAOFactory.openConnection(); - List groups = groupDAO.getGroups(0, 100, TestDataHolder.SUPER_TENANT_ID); + List groups = groupDAO.getGroups(0, 100, TestDataHolder.SUPER_TENANT_ID); Assert.assertNotEquals(groups.size(), 0, "No groups found"); Assert.assertNotNull(groups.get(0), "Group is null"); log.debug("No of Groups found: " + groups.size()); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/DeviceGroupWrapper.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/DeviceGroupWrapper.java index aee0576a4cb..3457873b084 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/DeviceGroupWrapper.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/DeviceGroupWrapper.java @@ -22,7 +22,7 @@ package org.wso2.carbon.policy.mgt.common; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -@ApiModel(value = "DeviceGroupWrapper", description = "This class carries all information related to device groups") +@ApiModel(value = "DeviceGroupWrapper", description = "This class carries information related to device groups expect users and devices.") public class DeviceGroupWrapper { @ApiModelProperty(name = "id", value = "Id of the group", required = true) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java index e5c983ed6f0..7f96729c7eb 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java @@ -231,7 +231,7 @@ public class PolicyManagerUtil { public static Map convertDeviceGroupMap(List deviceGroups) { Map groupMap = new HashMap<>(); for (DeviceGroup dg: deviceGroups){ - groupMap.put(dg.getId(), dg); + groupMap.put(dg.getGroupId(), dg); } return groupMap; } From 06176898d09b2822cd4c3628f8704566222ba405 Mon Sep 17 00:00:00 2001 From: charitha Date: Wed, 5 Oct 2016 12:20:35 +0530 Subject: [PATCH 3/8] Exposed group id to API level --- .../service/api/GroupManagementService.java | 70 +++---- .../impl/GroupManagementServiceImpl.java | 63 ++++-- .../GroupManagementAdminServiceImpl.java | 11 +- .../mgt/core/group/mgt/dao/GroupDAO.java | 66 ++---- .../mgt/core/group/mgt/dao/GroupDAOImpl.java | 189 +++++------------- .../GroupManagementProviderService.java | 94 +++------ .../GroupManagementProviderServiceImpl.java | 136 ++++--------- .../mgt/core/dao/GroupPersistTests.java | 15 +- 8 files changed, 224 insertions(+), 420 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java index 4509547abde..b8c8c461feb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java @@ -214,12 +214,12 @@ public interface GroupManagementService { required = true) @Valid DeviceGroup group); - @Path("/name/{groupName}") + @Path("/id/{groupId}") @GET @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = HTTPConstants.HEADER_GET, - value = "View group specified with name.", + value = "View group specified.", notes = "Returns details of group enrolled with the system.", tags = "Device Group Management") @ApiResponses(value = { @@ -256,12 +256,12 @@ public interface GroupManagementService { }) @Permission(name = "View Groups", permission = "/device-mgt/groups/view") Response getGroup(@ApiParam( - name = "groupName", - value = "Name of the group to view.", + name = "groupId", + value = "ID of the group to view.", required = true) - @PathParam("groupName") String groupName); + @PathParam("groupId") int groupId); - @Path("/name/{groupName}") + @Path("/id/{groupId}") @PUT @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -303,17 +303,17 @@ public interface GroupManagementService { }) @Permission(name = "Update Group", permission = "/device-mgt/groups/update") Response updateGroup(@ApiParam( - name = "groupName", - value = "Name of the group to be updated.", + name = "groupId", + value = "ID of the group to be updated.", required = true) - @PathParam("groupName") String groupName, + @PathParam("groupId") int groupId, @ApiParam( name = "group", value = "Group object with data.", required = true) @Valid DeviceGroup deviceGroup); - @Path("/name/{groupName}") + @Path("/id/{groupId}") @DELETE @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -355,12 +355,12 @@ public interface GroupManagementService { }) @Permission(name = "Remove Group", permission = "/device-mgt/groups/remove") Response deleteGroup(@ApiParam( - name = "groupName", - value = "Name of the group to be deleted.", + name = "groupId", + value = "ID of the group to be deleted.", required = true) - @PathParam("groupName") String groupName); + @PathParam("groupId") int groupId); - @Path("/name/{groupName}/share") + @Path("/id/{groupId}/share") @POST @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -405,14 +405,14 @@ public interface GroupManagementService { name = "groupName", value = "Name of the group to be shared or unshared.", required = true) - @PathParam("groupName") String groupName, + @PathParam("groupId") int groupId, @ApiParam( name = "deviceGroupShare", value = "User name and the assigned roles for the share.", required = true) @Valid DeviceGroupShare deviceGroupShare); - @Path("/name/{groupName}/users") + @Path("/id/{groupId}/users") @GET @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -454,12 +454,12 @@ public interface GroupManagementService { }) @Permission(name = "View users", permission = "/device-mgt/groups/users/view") Response getUsersOfGroup(@ApiParam( - name = "groupName", - value = "Name of the group.", + name = "groupId", + value = "ID of the group.", required = true) - @PathParam("groupName") String groupName); + @PathParam("groupId") int groupId); - @Path("/name/{groupName}/devices") + @Path("/id/{groupId}/devices") @GET @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -501,10 +501,10 @@ public interface GroupManagementService { }) @Permission(name = "View devices", permission = "/device-mgt/groups/devices/view") Response getDevicesOfGroup(@ApiParam( - name = "groupName", - value = "Name of the group.", + name = "groupId", + value = "ID of the group.", required = true) - @PathParam("groupName") String groupName, + @PathParam("groupId") int groupId, @ApiParam( name = "offset", value = "Starting point within the complete list of items qualified.") @@ -514,7 +514,7 @@ public interface GroupManagementService { value = "Maximum size of resource array to return.") @QueryParam("limit") int limit); - @Path("/name/{groupName}/devices/count") + @Path("/id/{groupId}/devices/count") @GET @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -556,12 +556,12 @@ public interface GroupManagementService { }) @Permission(name = "View devices", permission = "/device-mgt/groups/devices/view") Response getDeviceCountOfGroup(@ApiParam( - name = "groupName", - value = "Name of the group.", + name = "groupId", + value = "ID of the group.", required = true) - @PathParam("groupName") String groupName); + @PathParam("groupId") int groupId); - @Path("/name/{groupName}/devices") + @Path("/id/{groupId}/devices") @POST @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -602,17 +602,17 @@ public interface GroupManagementService { }) @Permission(name = "Add devices", permission = "/device-mgt/groups/devices/add") Response addDevicesToGroup(@ApiParam( - name = "groupName", - value = "Name of the group.", + name = "groupId", + value = "ID of the group.", required = true) - @PathParam("groupName") String groupName, + @PathParam("groupId") int groupId, @ApiParam( name = "deviceIdentifiers", value = "Device identifiers of the devices which needed be added.", required = true) @Valid List deviceIdentifiers); - @Path("/name/{groupName}/devices") + @Path("/id/{groupId}/devices") @DELETE @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -653,10 +653,10 @@ public interface GroupManagementService { }) @Permission(name = "Remove devices", permission = "/device-mgt/groups/devices/remove") Response removeDevicesFromGroup(@ApiParam( - name = "groupName", - value = "Name of the group.", + name = "groupId", + value = "ID of the group.", required = true) - @PathParam("groupName") String groupName, + @PathParam("groupId") int groupId, @ApiParam( name = "deviceIdentifiers", value = "Device identifiers of the devices which needed to be removed.", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java index e1e874ad1f8..93307aa361b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java @@ -31,6 +31,7 @@ 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.DeviceGroupShare; 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.util.DeviceMgtAPIUtils; import javax.ws.rs.core.Response; @@ -48,15 +49,20 @@ public class GroupManagementServiceImpl implements GroupManagementService { @Override public Response getGroups(int offset, int limit) { try { + RequestValidationUtil.validatePaginationParameters(offset, limit); GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); List deviceGroups = service.getGroups(currentUser, offset, limit); - DeviceGroupList deviceGroupList = new DeviceGroupList(); - deviceGroupList.setList(deviceGroups); - deviceGroupList.setCount(service.getGroupCount(currentUser)); - return Response.status(Response.Status.OK).entity(deviceGroupList).build(); + if (deviceGroups != null && deviceGroups.size() > 0) { + DeviceGroupList deviceGroupList = new DeviceGroupList(); + deviceGroupList.setList(deviceGroups); + deviceGroupList.setCount(service.getGroupCount(currentUser)); + return Response.status(Response.Status.OK).entity(deviceGroupList).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } } catch (GroupManagementException e) { - String error = "Error occurred while getting the groups related to users for policy."; + String error = "Error occurred while getting the groups."; log.error(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); } @@ -94,52 +100,75 @@ public class GroupManagementServiceImpl implements GroupManagementService { } catch (GroupAlreadyExistException e) { String msg = "Group already exists with name '" + group.getName() + "'."; log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + return Response.status(Response.Status.CONFLICT).entity(msg).build(); } } @Override - public Response getGroup(String groupName) { - return null; + public Response getGroup(int groupId) { + try { + GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); + DeviceGroup deviceGroup = service.getGroup(groupId); + if (deviceGroup != null) { + return Response.status(Response.Status.OK).entity(deviceGroup).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + String error = "Error occurred while getting the group."; + log.error(error, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } } @Override - public Response updateGroup(String groupName, DeviceGroup deviceGroup) { - return null; + public Response updateGroup(int groupId, DeviceGroup deviceGroup) { + if (deviceGroup == null) { + return Response.status(Response.Status.BAD_REQUEST).build(); + } + deviceGroup.setDateOfLastUpdate(new Date().getTime()); + try { + DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(deviceGroup, groupId); + return Response.status(Response.Status.OK).build(); + } catch (GroupManagementException e) { + String msg = "Error occurred while adding new group."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } } @Override - public Response deleteGroup(String groupName) { + public Response deleteGroup(int groupId) { return null; } @Override - public Response manageGroupSharing(String groupName, DeviceGroupShare deviceGroupShare) { + public Response manageGroupSharing(int groupId, DeviceGroupShare deviceGroupShare) { return null; } @Override - public Response getUsersOfGroup(String groupName) { + public Response getUsersOfGroup(int groupId) { return null; } @Override - public Response getDevicesOfGroup(String groupName, int offset, int limit) { + public Response getDevicesOfGroup(int groupId, int offset, int limit) { return null; } @Override - public Response getDeviceCountOfGroup(String groupName) { + public Response getDeviceCountOfGroup(int groupId) { return null; } @Override - public Response addDevicesToGroup(String groupName, List deviceIdentifiers) { + public Response addDevicesToGroup(int groupId, List deviceIdentifiers) { return null; } @Override - public Response removeDevicesFromGroup(String groupName, List deviceIdentifiers) { + public Response removeDevicesFromGroup(int groupId, List deviceIdentifiers) { return null; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java index 887be40c08d..01415da80a8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java @@ -27,6 +27,7 @@ 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.jaxrs.beans.DeviceGroupList; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.GroupManagementAdminService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.Consumes; @@ -36,9 +37,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; -@Path("/admin/groups") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) public class GroupManagementAdminServiceImpl implements GroupManagementAdminService { private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class); @@ -46,12 +44,13 @@ public class GroupManagementAdminServiceImpl implements GroupManagementAdminServ @Override public Response getGroups(int offset, int limit) { try { + RequestValidationUtil.validatePaginationParameters(offset, limit); GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); List deviceGroups = service.getGroups(offset, limit); - DeviceGroupList deviceGroupList = new DeviceGroupList(); - deviceGroupList.setList(deviceGroups); - deviceGroupList.setCount(service.getGroupCount()); if (deviceGroups != null && deviceGroups.size() > 0) { + DeviceGroupList deviceGroupList = new DeviceGroupList(); + deviceGroupList.setList(deviceGroups); + deviceGroupList.setCount(service.getGroupCount()); return Response.status(Response.Status.OK).entity(deviceGroupList).build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java index b164a4ba110..8d91c08cff8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java @@ -40,24 +40,22 @@ public interface GroupDAO { /** * Update an existing Device Group. * - * @param deviceGroup group to update. - * @param oldGroupName of the group. - * @param oldOwner of the group. - * @param tenantId of the group. + * @param deviceGroup group to update. + * @param groupId of Device Group. + * @param tenantId of the group. * @throws GroupManagementDAOException */ - void updateGroup(DeviceGroup deviceGroup, String oldGroupName, String oldOwner, int tenantId) + void updateGroup(DeviceGroup deviceGroup, int groupId, int tenantId) throws GroupManagementDAOException; /** * Delete an existing Device Group. * - * @param groupName to be deleted. - * @param owner of the group. + * @param groupId of Device Group. * @param tenantId of the group. * @throws GroupManagementDAOException */ - void deleteGroup(String groupName, String owner, int tenantId) throws GroupManagementDAOException; + void deleteGroup(int groupId, int tenantId) throws GroupManagementDAOException; /** * Get device group by id. @@ -69,21 +67,10 @@ public interface GroupDAO { */ DeviceGroup getGroup(int groupId, int tenantId) throws GroupManagementDAOException; - /** - * Get device group by name. - * - * @param groupName of Device Group. - * @param owner of the group. - * @param tenantId of the group. - * @return Device Group in tenant with specified name. - * @throws GroupManagementDAOException - */ - DeviceGroup getGroup(String groupName, String owner, int tenantId) throws GroupManagementDAOException; - /** * Get the groups of device with device id provided * @param deviceId - * @return + * @return groups which has the device. * @throws GroupManagementDAOException */ List getGroups(int deviceId, int tenantId) throws GroupManagementDAOException; @@ -123,81 +110,64 @@ public interface GroupDAO { * Check group already existed with given name. * * @param groupName of the Device Group. - * @param owner of the Device Group. * @param tenantId of user's tenant. * @return existence of group with name * @throws GroupManagementDAOException */ - boolean isGroupExist(String groupName, String owner, int tenantId) throws GroupManagementDAOException; + boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException; /** * Add device to a given Device Group. * - * @param groupName of the Device Group. - * @param owner of the Device Group. + * @param groupId of Device Group. * @param deviceId of the device. * @param tenantId of user's tenant. * @throws GroupManagementDAOException */ - void addDevice(String groupName, String owner, int deviceId, int tenantId) throws GroupManagementDAOException; + void addDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException; /** * Remove device from the Device Group. * - * @param groupName of the Device Group. - * @param owner of the Device Group. + * @param groupId of Device Group. * @param deviceId of the device. * @param tenantId of user's tenant. * @throws GroupManagementDAOException */ - void removeDevice(String groupName, String owner, int deviceId, int tenantId) throws GroupManagementDAOException; + void removeDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException; /** * Check device is belonging to a Device Group. * - * @param groupName of the Device Group. - * @param owner of the Device Group. + * @param groupId of Device Group. * @param deviceId of the device. * @param tenantId of user's tenant. * @throws GroupManagementDAOException */ - boolean isDeviceMappedToGroup(String groupName, String owner, int deviceId, int tenantId) + boolean isDeviceMappedToGroup(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException; /** * Get count of devices in a Device Group. * - * @param groupName of the Device Group. - * @param owner of the Device Group. + * @param groupId of Device Group. * @param tenantId of user's tenant. * @return device count. * @throws GroupManagementDAOException */ - int getDeviceCount(String groupName, String owner, int tenantId) throws GroupManagementDAOException; - - /** - * Get all devices of a given tenant and device group. - * - * @param groupName of the group. - * @param owner of the Device Group. - * @param tenantId of user's tenant. - * @return list of device in group - * @throws GroupManagementDAOException - */ - List getDevices(String groupName, String owner, int tenantId) throws GroupManagementDAOException; + int getDeviceCount(int groupId, int tenantId) throws GroupManagementDAOException; /** * Get paginated result of devices of a given tenant and device group. * - * @param groupName of the group. - * @param owner of the Device Group. + * @param groupId of Device Group. * @param startIndex for pagination. * @param rowCount for pagination. * @param tenantId of user's tenant. * @return list of device in group * @throws GroupManagementDAOException */ - List getDevices(String groupName, String owner, int startIndex, int rowCount, int tenantId) + List getDevices(int groupId, int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java index 4b2134d6b93..43928cc821b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java @@ -66,21 +66,20 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public void updateGroup(DeviceGroup deviceGroup, String oldGroupName, String oldOwner, int tenantId) + public void updateGroup(DeviceGroup deviceGroup, int groupId, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "UPDATE DM_GROUP SET DESCRIPTION = ?, GROUP_NAME = ?, DATE_OF_LAST_UPDATE = ?, OWNER = ? " - + "WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?"; + + "WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceGroup.getDescription()); stmt.setString(2, deviceGroup.getName()); stmt.setLong(3, deviceGroup.getDateOfLastUpdate()); stmt.setString(4, deviceGroup.getOwner()); - stmt.setString(5, oldGroupName); - stmt.setString(6, oldOwner); - stmt.setInt(7, tenantId); + stmt.setInt(5, groupId); + stmt.setInt(6, tenantId); stmt.executeUpdate(); } catch (SQLException e) { throw new GroupManagementDAOException("Error occurred while updating deviceGroup '" + @@ -91,35 +90,31 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public void deleteGroup(String groupName, String owner, int tenantId) throws GroupManagementDAOException { + public void deleteGroup(int groupId, int tenantId) throws GroupManagementDAOException { Connection conn; PreparedStatement stmt = null; try { conn = GroupManagementDAOFactory.getConnection(); - String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = (SELECT ID AS GROUP_ID FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) AND TENANT_ID = ?"; + String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, groupName); - stmt.setString(2, owner); - stmt.setInt(3, tenantId); - stmt.setInt(4, tenantId); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); stmt.executeUpdate(); } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while removing mappings for group '" + groupName + - "'", e); + throw new GroupManagementDAOException("Error occurred while removing mappings for group.'", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, null); } try { conn = GroupManagementDAOFactory.getConnection(); - String sql = "DELETE FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?"; + String sql = "DELETE FROM DM_GROUP WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, groupName); - stmt.setString(2, owner); - stmt.setInt(3, tenantId); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); stmt.executeUpdate(); } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while deleting group '" + groupName + "'", e); + throw new GroupManagementDAOException("Error occurred while deleting group.'", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, null); } @@ -150,33 +145,6 @@ public class GroupDAOImpl implements GroupDAO { } } - @Override - public DeviceGroup getGroup(String groupName, String owner, int tenantId) - throws GroupManagementDAOException { - PreparedStatement stmt = null; - ResultSet resultSet = null; - try { - Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " - + "FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, groupName); - stmt.setString(2, owner); - stmt.setInt(3, tenantId); - resultSet = stmt.executeQuery(); - if (resultSet.next()) { - return GroupManagementDAOUtil.loadGroup(resultSet); - } else { - return null; - } - } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while obtaining information of Device Group '" + - groupName + "'", e); - } finally { - GroupManagementDAOUtil.cleanupResources(stmt, resultSet); - } - } - @Override public List getGroups(int deviceId, int tenantId) throws GroupManagementDAOException { @@ -281,114 +249,95 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public boolean isGroupExist(String groupName, String owner, int tenantId) throws GroupManagementDAOException { + public boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT GROUP_NAME FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?"; + String sql = "SELECT GROUP_NAME FROM DM_GROUP WHERE GROUP_NAME = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, groupName); - stmt.setString(2, owner); - stmt.setInt(3, tenantId); + stmt.setInt(2, tenantId); resultSet = stmt.executeQuery(); return resultSet.next(); } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" + - groupName + "'", e); + throw new GroupManagementDAOException("Error occurred while group Id listing by group name.'", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, resultSet); } } @Override - public void addDevice(String groupName, String owner, int deviceId, int tenantId) + public void addDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "INSERT INTO DM_DEVICE_GROUP_MAP(DEVICE_ID, GROUP_ID, TENANT_ID) " + - "VALUES (?, (SELECT ID as GROUP_ID FROM DM_GROUP " + - "WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?), ?)"; + String sql = "INSERT INTO DM_DEVICE_GROUP_MAP(DEVICE_ID, GROUP_ID, TENANT_ID) VALUES (?, ?, ?)"; stmt = conn.prepareStatement(sql); stmt.setInt(1, deviceId); - stmt.setString(2, groupName); - stmt.setString(3, owner); - stmt.setInt(4, tenantId); - stmt.setInt(5, tenantId); + stmt.setInt(2, groupId); + stmt.setInt(3, tenantId); stmt.executeUpdate(); stmt.getGeneratedKeys(); } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while adding device to Group '" + groupName + "'", e); + throw new GroupManagementDAOException("Error occurred while adding device to Group.", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, null); } } @Override - public void removeDevice(String groupName, String owner, int deviceId, int tenantId) + public void removeDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ? AND GROUP_ID = (SELECT ID as GROUP_ID " + - "FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) AND TENANT_ID = ?"; + String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ? AND GROUP_ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, deviceId); - stmt.setString(2, groupName); - stmt.setString(3, owner); - stmt.setInt(4, tenantId); - stmt.setInt(5, tenantId); + stmt.setInt(2, groupId); + stmt.setInt(3, tenantId); stmt.executeUpdate(); stmt.getGeneratedKeys(); } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while removing device from Group '" + - groupName + "'", e); + throw new GroupManagementDAOException("Error occurred while removing device from Group.", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, null); } } @Override - public boolean isDeviceMappedToGroup(String groupName, String owner, int deviceId, int tenantId) + public boolean isDeviceMappedToGroup(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT dm.ID FROM DM_DEVICE_GROUP_MAP dm, (SELECT ID as GROUP_ID FROM DM_GROUP " + - "WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) dg " + - "WHERE dm.GROUP_ID = dg.GROUP_ID AND dm.ID = ? AND dm.TENANT_ID = ?"; + String sql = "SELECT ID FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? AND DEVICE_ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, groupName); - stmt.setString(2, owner); + stmt.setInt(1, groupId); + stmt.setInt(2, deviceId); stmt.setInt(3, tenantId); - stmt.setInt(4, deviceId); - stmt.setInt(5, tenantId); resultSet = stmt.executeQuery(); return resultSet.next(); } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" + - groupName + "'", e); + throw new GroupManagementDAOException("Error occurred while checking device mapping with group.", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, resultSet); } } @Override - public int getDeviceCount(String groupName, String owner, int tenantId) throws GroupManagementDAOException { + public int getDeviceCount(int groupId, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT COUNT(gm.ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP gm, (SELECT ID " + - "FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) dg " + - "WHERE gm.GROUP_ID = dg.ID AND gm.TENANT_ID = ?"; + String sql = "SELECT COUNT(ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, groupName); - stmt.setString(2, owner); - stmt.setInt(3, tenantId); - stmt.setInt(4, tenantId); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); resultSet = stmt.executeQuery(); if (resultSet.next()) { return resultSet.getInt("DEVICE_COUNT"); @@ -396,54 +345,14 @@ public class GroupDAOImpl implements GroupDAO { return 0; } } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" + - groupName + "'", e); + throw new GroupManagementDAOException("Error occurred while getting device count from the group.", e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, resultSet); } } @Override - public List getDevices(String groupName, String owner, int tenantId) throws GroupManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List devices = null; - try { - conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + - "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, " + - "d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID " + - "FROM DM_DEVICE_GROUP_MAP dgm, DM_GROUP dg WHERE dgm.GROUP_ID = dg.ID AND dg.GROUP_NAME = ? " + - "AND dg.OWNER = ? AND dg.TENANT_ID = ?) dgm1 WHERE d.ID = dgm1.DEVICE_ID " + - "AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t WHERE gd.DEVICE_TYPE_ID = t.ID) d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, groupName); - stmt.setString(2, owner); - stmt.setInt(3, tenantId); - stmt.setInt(4, tenantId); - stmt.setInt(5, tenantId); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); - } - } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while retrieving information of all " + - "registered devices", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return devices; - } - - @Override - public List getDevices(String groupName, String owner, int startIndex, int rowCount, int tenantId) + public List getDevices(int groupId, int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException { Connection conn; PreparedStatement stmt = null; @@ -454,24 +363,20 @@ public class GroupDAOImpl implements GroupDAO { String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + - "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, " + - "d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID " + - "FROM DM_DEVICE_GROUP_MAP dgm, DM_GROUP dg WHERE dgm.GROUP_ID = dg.ID AND dg.GROUP_NAME = ? " + - "AND dg.OWNER = ? AND dg.TENANT_ID = ?) dgm1 WHERE d.ID = dgm1.DEVICE_ID " + - "AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t WHERE gd.DEVICE_TYPE_ID = t.ID) d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?, ?"; + "(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "(SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID FROM DM_DEVICE d, (" + + "SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 " + + "WHERE d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " + + "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? , ?"; stmt = conn.prepareStatement(sql); - stmt.setString(1, groupName); - stmt.setString(2, owner); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); - stmt.setInt(4, tenantId); - stmt.setInt(5, tenantId); //noinspection JpaQueryApiInspection - stmt.setInt(6, startIndex); + stmt.setInt(4, startIndex); //noinspection JpaQueryApiInspection - stmt.setInt(7, rowCount); + stmt.setInt(5, rowCount); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java index b1c9a8468ca..f04226943ce 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java @@ -49,44 +49,31 @@ public interface GroupManagementProviderService { * Update existing device group. * * @param deviceGroup to update. - * @param oldGroupName of the group. - * @param oldOwner of the group. + * @param groupId of the group. * @throws GroupManagementException */ - void updateGroup(DeviceGroup deviceGroup, String oldGroupName, String oldOwner) throws GroupManagementException; + void updateGroup(DeviceGroup deviceGroup, int groupId) throws GroupManagementException; /** * Delete existing device group. * - * @param groupName to be deleted. - * @param owner of the group. + * @param groupId to be deleted. * @return status of the delete operation. * @throws GroupManagementException */ - boolean deleteGroup(String groupName, String owner) throws GroupManagementException; - - /** - * Get device group specified by group name. - * - * @param groupName of the group. - * @param owner of the group. - * @return group - * @throws GroupManagementException - */ - DeviceGroup getGroup(String groupName, String owner) throws GroupManagementException; - + boolean deleteGroup(int groupId) throws GroupManagementException; /** * Get the device group provided the device group id. * - * @param groupId - * @return + * @param groupId of the group. + * @return group with details. * @throws GroupManagementException */ DeviceGroup getGroup(int groupId) throws GroupManagementException; /** - * Get paginated device groups in tenant + * Get paginated device groups in tenant. * * @param startIndex for pagination. * @param rowCount for pagination. @@ -96,9 +83,9 @@ public interface GroupManagementProviderService { List getGroups(int startIndex, int rowCount) throws GroupManagementException; /** - * Get paginated device groups in tenant + * Get paginated device groups for user. * - * @param username of user. + * @param username of the user. * @param startIndex for pagination. * @param rowCount for pagination. * @return list of groups @@ -127,141 +114,126 @@ public interface GroupManagementProviderService { * Share device group with user specified by role * * @param username of the user - * @param groupName of the group - * @param owner of the group + * @param groupId of the group * @param sharingRole to be shared * @return is group shared * @throws GroupManagementException UserDoesNotExistException */ - boolean shareGroup(String username, String groupName, String owner, String sharingRole) + 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 groupName of the group - * @param owner of the group + * @param groupId of the group * @param sharingRole to be un shared * @return is group un shared * @throws GroupManagementException UserDoesNotExistException */ - boolean unshareGroup(String userName, String groupName, String owner, String sharingRole) + boolean unshareGroup(String userName, int groupId, String sharingRole) throws GroupManagementException, UserDoesNotExistException; /** * Add new sharing role for device group * * @param userName of the user - * @param groupName of the group - * @param owner of the group + * @param groupId of the group * @param roleName to add * @param permissions to bind with role * @return is role added * @throws GroupManagementException */ - boolean addGroupSharingRole(String userName, String groupName, String owner, String roleName, String[] permissions) + boolean addGroupSharingRole(String userName, int groupId, String roleName, String[] permissions) throws GroupManagementException; /** * Remove existing sharing role for device group * - * @param groupName of the group - * @param owner of the group + * @param groupId of the group * @param roleName to remove * @return is role removed * @throws GroupManagementException */ - boolean removeGroupSharingRole(String groupName, String owner, String roleName) throws GroupManagementException; + boolean removeGroupSharingRole(int groupId, String roleName) throws GroupManagementException; /** * Get all sharing roles for device group * - * @param groupName of the group - * @param owner of the group + * @param groupId of the group * @return list of roles * @throws GroupManagementException */ - List getRoles(String groupName, String owner) throws GroupManagementException; + List getRoles(int groupId) throws GroupManagementException; /** * Get specific device group sharing roles for user * * @param userName of the user - * @param groupName of the group - * @param owner of the group + * @param groupId of the group * @return list of roles * @throws GroupManagementException UserDoesNotExistException */ - List getRoles(String userName, String groupName, String owner) - throws GroupManagementException, UserDoesNotExistException; + List getRoles(String userName, int groupId) throws GroupManagementException, UserDoesNotExistException; /** * Get device group users * - * @param groupName of the group - * @param owner of the group + * @param groupId of the group * @return list of group users * @throws GroupManagementException */ - List getUsers(String groupName, String owner) throws GroupManagementException; + List getUsers(int groupId) throws GroupManagementException; /** * Get all devices in device group as paginated result. * - * @param groupName of the group. - * @param owner of the group. + * @param groupId of the group * @param startIndex for pagination. * @param rowCount for pagination. * @return list of devices in group. * @throws GroupManagementException */ - List getDevices(String groupName, String owner, int startIndex, int rowCount) - throws GroupManagementException; + List getDevices(int groupId, int startIndex, int rowCount) throws GroupManagementException; /** * This method is used to retrieve the device count of a given group. * - * @param groupName of the group. - * @param owner of the group. + * @param groupId of the group * @return returns the device count. * @throws GroupManagementException */ - int getDeviceCount(String groupName, String owner) throws GroupManagementException; + int getDeviceCount(int groupId) throws GroupManagementException; /** * Add device to device group. * * @param deviceId of the device. - * @param groupName of the group. - * @param owner of the group. + * @param groupId of the group * @return is device added. * @throws GroupManagementException */ - boolean addDevice(DeviceIdentifier deviceId, String groupName, String owner) throws GroupManagementException; + boolean addDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException; /** * Remove device from device group. * * @param deviceId of the device. - * @param groupName of the group. - * @param owner of the group. + * @param groupId of the group * @return is device removed. * @throws GroupManagementException */ - boolean removeDevice(DeviceIdentifier deviceId, String groupName, String owner) throws GroupManagementException; + boolean removeDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException; /** * Get device group permissions of user. * * @param username of the user. - * @param groupName of the group. - * @param owner of the group. + * @param groupId of the group * @return array of permissions. * @throws GroupManagementException UserDoesNotExistException */ - String[] getPermissions(String username, String groupName, String owner) - throws GroupManagementException, UserDoesNotExistException; + String[] getPermissions(String username, int groupId) throws GroupManagementException, UserDoesNotExistException; /** * Get device groups of user with permission. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 762478c5927..a76c9566461 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -23,7 +23,10 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.*; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.TransactionManagementException; 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.GroupManagementException; @@ -40,7 +43,11 @@ import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException; import org.wso2.carbon.user.core.util.UserCoreUtil; import java.sql.SQLException; -import java.util.*; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class GroupManagementProviderServiceImpl implements GroupManagementProviderService { @@ -68,7 +75,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid int groupId = -1; try { GroupManagementDAOFactory.beginTransaction(); - boolean nameIsExists = this.groupDAO.isGroupExist(deviceGroup.getName(), deviceGroup.getOwner(), tenantId); + boolean nameIsExists = this.groupDAO.isGroupExist(deviceGroup.getName(), tenantId); if (!nameIsExists) { groupId = this.groupDAO.addGroup(deviceGroup, tenantId); GroupManagementDAOFactory.commitTransaction(); @@ -95,7 +102,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public void updateGroup(DeviceGroup deviceGroup, String oldGroupName, String oldOwner) + public void updateGroup(DeviceGroup deviceGroup, int groupId) throws GroupManagementException { if (deviceGroup == null) { throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException()); @@ -104,7 +111,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); GroupManagementDAOFactory.beginTransaction(); deviceGroup.setDateOfLastUpdate(new Date().getTime()); - this.groupDAO.updateGroup(deviceGroup, oldGroupName, oldOwner, tenantId); + this.groupDAO.updateGroup(deviceGroup, groupId, tenantId); GroupManagementDAOFactory.commitTransaction(); } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.rollbackTransaction(); @@ -121,13 +128,13 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public boolean deleteGroup(String groupName, String owner) throws GroupManagementException { + public boolean deleteGroup(int groupId) throws GroupManagementException { String roleName; - DeviceGroup deviceGroup = buildDeviceGroup(groupName, owner); + DeviceGroup deviceGroup = buildDeviceGroup(groupId); if (deviceGroup == null) { return false; } - List groupRoles = getRoles(groupName, owner); + List groupRoles = getRoles(groupId); for (String role : groupRoles) { if (role != null) { roleName = role.replace("Internal/group-" + deviceGroup.getGroupId() + "-", ""); @@ -136,7 +143,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } try { GroupManagementDAOFactory.beginTransaction(); - this.groupDAO.deleteGroup(groupName, owner, CarbonContext.getThreadLocalCarbonContext().getTenantId()); + this.groupDAO.deleteGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId()); GroupManagementDAOFactory.commitTransaction(); if (log.isDebugEnabled()) { log.debug("DeviceGroup " + deviceGroup.getName() + " removed."); @@ -144,8 +151,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid return true; } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.rollbackTransaction(); - throw new GroupManagementException("Error occurred while removing group " + - "'" + groupName + "' data.", e); + throw new GroupManagementException("Error occurred while removing group data.", e); } catch (TransactionManagementException e) { throw new GroupManagementException("Error occurred while initiating transaction.", e); } finally { @@ -153,35 +159,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } } - /** - * {@inheritDoc} - */ - @Override - public DeviceGroup getGroup(String groupName, String owner) throws GroupManagementException { - return buildDeviceGroup(groupName, owner); - } - - private DeviceGroup buildDeviceGroup(String groupName, String owner) throws GroupManagementException { - DeviceGroup deviceGroup; - try { - GroupManagementDAOFactory.openConnection(); - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - deviceGroup = this.groupDAO.getGroup(groupName, owner, tenantId); - } catch (GroupManagementDAOException e) { - throw new GroupManagementException("Error occurred while obtaining group '" + groupName + "'", e); - } catch (SQLException e) { - throw new GroupManagementException("Error occurred while opening a connection to the data source.", e); - } finally { - GroupManagementDAOFactory.closeConnection(); - } - if (deviceGroup != null) { - deviceGroup.setUsers(this.getUsers(deviceGroup.getGroupId())); - deviceGroup.setRoles(this.getRoles(deviceGroup.getGroupId())); - } - return deviceGroup; - } - - private DeviceGroup buildDeviceGroup(int groupId) throws GroupManagementException { DeviceGroup deviceGroup; try { @@ -306,9 +283,8 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public boolean shareGroup(String username, String groupName, String owner, String sharingRole) + public boolean shareGroup(String username, int groupId, String sharingRole) throws GroupManagementException, UserDoesNotExistException { - int groupId = getGroupId(groupName, owner); return modifyGroupShare(username, groupId, sharingRole, true); } @@ -316,9 +292,8 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public boolean unshareGroup(String username, String groupName, String owner, String sharingRole) + public boolean unshareGroup(String username, int groupId, String sharingRole) throws GroupManagementException, UserDoesNotExistException { - int groupId = getGroupId(groupName, owner); return modifyGroupShare(username, groupId, sharingRole, false); } @@ -355,26 +330,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } } - private int getGroupId(String groupName, String owner) throws GroupManagementException { - DeviceGroup deviceGroup = buildDeviceGroup(groupName, owner); - if (deviceGroup == null) { - return -1; - } - return deviceGroup.getGroupId(); - } - /** * {@inheritDoc} */ @Override - public boolean addGroupSharingRole(String userName, String groupName, String owner, String roleName, - String[] permissions) throws GroupManagementException { - int groupId = getGroupId(groupName, owner); - return addGroupSharingRole(userName, groupId, roleName, permissions); - } - - private boolean addGroupSharingRole(String username, int groupId, String roleName, - String[] permissions) + public boolean addGroupSharingRole(String username, int groupId, String roleName, String[] permissions) throws GroupManagementException { if (groupId == -1) { return false; @@ -404,14 +364,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public boolean removeGroupSharingRole(String groupName, String owner, String roleName) - throws GroupManagementException { - int groupId = getGroupId(groupName, owner); - return removeGroupSharingRole(groupId, roleName); - } - - private boolean removeGroupSharingRole(int groupId, String roleName) - throws GroupManagementException { + public boolean removeGroupSharingRole(int groupId, String roleName) throws GroupManagementException { if (groupId == -1) { return false; } @@ -435,12 +388,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public List getRoles(String groupName, String owner) throws GroupManagementException { - int groupId = getGroupId(groupName, owner); - return getRoles(groupId); - } - - private List getRoles(int groupId) throws GroupManagementException { + public List getRoles(int groupId) throws GroupManagementException { UserStoreManager userStoreManager; String[] roles; List groupRoles; @@ -467,13 +415,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public List getRoles(String username, String groupName, String owner) - throws GroupManagementException, UserDoesNotExistException { - int groupId = getGroupId(groupName, owner); - return getRoles(username, groupId); - } - - private List getRoles(String username, int groupId) + public List getRoles(String username, int groupId) throws GroupManagementException, UserDoesNotExistException { UserStoreManager userStoreManager; List groupRoleList = new ArrayList<>(); @@ -504,11 +446,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public List getUsers(String groupName, String owner) throws GroupManagementException { - int groupId = getGroupId(groupName, owner); - return getUsers(groupId); - } - public List getUsers(int groupId) throws GroupManagementException { UserStoreManager userStoreManager; Map groupUserHashMap = new HashMap<>(); @@ -545,13 +482,13 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public List getDevices(String groupName, String owner, int startIndex, int rowCount) + public List getDevices(int groupId, int startIndex, int rowCount) throws GroupManagementException { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); List devices; try { GroupManagementDAOFactory.openConnection(); - devices = this.groupDAO.getDevices(groupName, owner, startIndex, rowCount, tenantId); + devices = this.groupDAO.getDevices(groupId, startIndex, rowCount, tenantId); } catch (GroupManagementDAOException e) { throw new GroupManagementException("Error occurred while getting devices in group.", e); } catch (SQLException e) { @@ -566,13 +503,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public int getDeviceCount(String groupName, String owner) throws GroupManagementException { + public int getDeviceCount(int groupId) throws GroupManagementException { try { - int count; GroupManagementDAOFactory.openConnection(); - count = groupDAO.getDeviceCount(groupName, owner, - CarbonContext.getThreadLocalCarbonContext().getTenantId()); - return count; + return groupDAO.getDeviceCount(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId()); } catch (GroupManagementDAOException e) { throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e); } catch (SQLException e) { @@ -586,7 +520,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public boolean addDevice(DeviceIdentifier deviceIdentifier, String groupName, String owner) + public boolean addDevice(DeviceIdentifier deviceIdentifier, int groupId) throws GroupManagementException { Device device; try { @@ -596,13 +530,13 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); GroupManagementDAOFactory.beginTransaction(); - this.groupDAO.addDevice(groupName, owner, device.getId(), tenantId); + this.groupDAO.addDevice(groupId, device.getId(), tenantId); GroupManagementDAOFactory.commitTransaction(); } catch (DeviceManagementException e) { throw new GroupManagementException("Error occurred while retrieving device.", e); } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.rollbackTransaction(); - throw new GroupManagementException("Error occurred while adding device to group '" + groupName + "'.", e); + throw new GroupManagementException("Error occurred while adding device to group.", e); } catch (TransactionManagementException e) { throw new GroupManagementException("Error occurred while initiating transaction.", e); } finally { @@ -615,8 +549,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public boolean removeDevice(DeviceIdentifier deviceIdentifier, String groupName, String owner) - throws GroupManagementException { + public boolean removeDevice(DeviceIdentifier deviceIdentifier, int groupId) throws GroupManagementException { Device device; try { device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier); @@ -625,7 +558,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); GroupManagementDAOFactory.beginTransaction(); - this.groupDAO.removeDevice(groupName, owner, device.getId(), tenantId); + this.groupDAO.removeDevice(groupId, device.getId(), tenantId); GroupManagementDAOFactory.commitTransaction(); } catch (DeviceManagementException e) { throw new GroupManagementException("Error occurred while retrieving device.", e); @@ -633,7 +566,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid throw new GroupManagementException("Error occurred while initiating transaction.", e); } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.rollbackTransaction(); - throw new GroupManagementException("Error occurred while adding device to group '" + groupName + "'.", e); + throw new GroupManagementException("Error occurred while adding device to group.", e); } finally { GroupManagementDAOFactory.closeConnection(); } @@ -644,10 +577,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public String[] getPermissions(String username, String groupName, String owner) + public String[] getPermissions(String username, int groupId) throws GroupManagementException, UserDoesNotExistException { UserRealm userRealm; - int groupId = getGroupId(groupName, owner); List roles = getRoles(username, groupId); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java index d6e435a7c6c..6ef90d78c76 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java @@ -56,7 +56,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest { GroupManagementDAOFactory.beginTransaction(); groupId = groupDAO.addGroup(deviceGroup, TestDataHolder.SUPER_TENANT_ID); GroupManagementDAOFactory.commitTransaction(); - log.debug("Group added to database."); + log.debug("Group added to database. ID: " + groupId); } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while adding device type '" + deviceGroup.getName() + "'."; @@ -123,8 +123,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest { DeviceGroup deviceGroup = getGroupById(groupId); try { GroupManagementDAOFactory.beginTransaction(); - groupDAO.addDevice(deviceGroup.getName(), deviceGroup.getOwner(), initialTestDevice.getId(), - TestDataHolder.SUPER_TENANT_ID); + groupDAO.addDevice(deviceGroup.getGroupId(), initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID); GroupManagementDAOFactory.commitTransaction(); log.debug("Device added to group."); } catch (GroupManagementDAOException e) { @@ -142,8 +141,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest { try { GroupManagementDAOFactory.openConnection(); - List groupedDevices = groupDAO.getDevices(deviceGroup.getName(), deviceGroup.getOwner(), - TestDataHolder.SUPER_TENANT_ID); + List groupedDevices = groupDAO.getDevices(deviceGroup.getGroupId(), 0, 10, TestDataHolder.SUPER_TENANT_ID); Assert.assertNotEquals(groupedDevices.size(), 0, "No device found"); Assert.assertNotNull(groupedDevices.get(0), "Device is null"); Assert.assertEquals(groupedDevices.get(0).getId(), initialTestDevice.getId(), "Device ids not matched"); @@ -166,7 +164,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest { DeviceGroup deviceGroup = getGroupById(groupId); try { GroupManagementDAOFactory.beginTransaction(); - groupDAO.removeDevice(deviceGroup.getName(), deviceGroup.getOwner(), initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID); + groupDAO.removeDevice(deviceGroup.getGroupId(), initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID); GroupManagementDAOFactory.commitTransaction(); log.debug("Device added to group."); } catch (GroupManagementDAOException e) { @@ -195,8 +193,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest { group.setDescription(desc); try { GroupManagementDAOFactory.beginTransaction(); - groupDAO.updateGroup(group, TestDataHolder.generateDummyGroupData().getName(), - TestDataHolder.generateDummyGroupData().getOwner(), TestDataHolder.SUPER_TENANT_ID); + groupDAO.updateGroup(group, groupId, TestDataHolder.SUPER_TENANT_ID); GroupManagementDAOFactory.commitTransaction(); log.debug("Group updated"); } catch (GroupManagementDAOException e) { @@ -225,7 +222,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest { try { Assert.assertNotNull(group, "Group is null"); GroupManagementDAOFactory.beginTransaction(); - groupDAO.deleteGroup(group.getName(), group.getOwner(), TestDataHolder.SUPER_TENANT_ID); + groupDAO.deleteGroup(group.getGroupId(), TestDataHolder.SUPER_TENANT_ID); GroupManagementDAOFactory.commitTransaction(); log.debug("Group deleted"); } catch (GroupManagementDAOException e) { From e89b4015b6e9649363b900acfc90c2af591676be Mon Sep 17 00:00:00 2001 From: charitha Date: Thu, 6 Oct 2016 11:51:54 +0530 Subject: [PATCH 4/8] Introduced pagination --- .../mgt/jaxrs/beans/DeviceGroupUsersList.java | 7 +- .../service/api/GroupManagementService.java | 8 + .../admin/GroupManagementAdminService.java | 8 + .../impl/DeviceManagementServiceImpl.java | 1 - .../impl/GroupManagementServiceImpl.java | 112 ++++++++++-- .../GroupManagementAdminServiceImpl.java | 15 +- .../mgt/common/DeviceNotFoundException.java | 44 +++++ .../mgt/common/GroupPaginationRequest.java | 68 +++++++ .../device/mgt/common/PaginationRequest.java | 11 +- .../group/mgt/RoleDoesNotExistException.java | 60 +++++++ .../pagination/PaginationConfiguration.java | 10 ++ .../core/dao/impl/AbstractDeviceDAOImpl.java | 1 - .../mgt/core/group/mgt/dao/GroupDAO.java | 18 +- .../mgt/core/group/mgt/dao/GroupDAOImpl.java | 70 ++++++-- .../notification/mgt/dao/NotificationDAO.java | 1 - .../core/operation/mgt/dao/OperationDAO.java | 1 - .../mgt/dao/impl/GenericOperationDAOImpl.java | 2 - .../operation/OracleOperationDAOImpl.java | 2 +- .../GroupManagementProviderService.java | 79 ++++---- .../GroupManagementProviderServiceImpl.java | 170 ++++++++++++------ .../mgt/core/util/DeviceManagerUtil.java | 17 ++ .../mgt/core/dao/GroupPersistTests.java | 6 +- .../src/main/resources/conf/cdm-config.xml | 1 + 23 files changed, 572 insertions(+), 140 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceNotFoundException.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/GroupPaginationRequest.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/RoleDoesNotExistException.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java index 21e72562ffa..40823d002fc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupUsersList.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import java.util.ArrayList; import java.util.List; @@ -28,13 +29,13 @@ public class DeviceGroupUsersList extends BasePaginatedResult { @ApiModelProperty(value = "List of device group users returned") @JsonProperty("users") - private List users = new ArrayList<>(); + private List users = new ArrayList<>(); - public List getList() { + public List getList() { return users; } - public void setList(List users) { + public void setList(List users) { this.users = users; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java index b8c8c461feb..9611a27783c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java @@ -103,6 +103,14 @@ public interface GroupManagementService { }) @Permission(name = "View Groups", permission = "/device-mgt/groups/view") 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", value = "Starting point within the complete list of items qualified.") @QueryParam("offset") int offset, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java index 056bb743b0a..b908520834c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java @@ -90,6 +90,14 @@ public interface GroupManagementAdminService { }) @Permission(name = "View Groups", permission = "/device-mgt/admin/groups/view") 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", value = "Starting point within the complete list of items qualified.") @QueryParam("offset") int offset, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index fa4e20d85ff..6f34a450857 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -18,7 +18,6 @@ */ 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.LogFactory; import org.wso2.carbon.context.CarbonContext; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java index 93307aa361b..afae7a94958 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java @@ -23,16 +23,24 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; 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.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.GroupAlreadyExistException; 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.jaxrs.beans.DeviceGroupList; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupShare; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupUsersList; +import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException; import javax.ws.rs.core.Response; import java.util.Date; @@ -47,12 +55,15 @@ public class GroupManagementServiceImpl implements GroupManagementService { "/permission/device-mgt/user/groups"}; @Override - public Response getGroups(int offset, int limit) { + public Response getGroups(String name, String owner, int offset, int limit) { try { RequestValidationUtil.validatePaginationParameters(offset, limit); GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); - List deviceGroups = service.getGroups(currentUser, offset, limit); + GroupPaginationRequest request = new GroupPaginationRequest(offset, limit); + request.setGroupName(name); + request.setOwner(owner); + List deviceGroups = service.getGroups(currentUser, request); if (deviceGroups != null && deviceGroups.size() > 0) { DeviceGroupList deviceGroupList = new DeviceGroupList(); deviceGroupList.setList(deviceGroups); @@ -92,14 +103,14 @@ public class GroupManagementServiceImpl implements GroupManagementService { group.setDateOfLastUpdate(new Date().getTime()); try { 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) { String msg = "Error occurred while adding new group."; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } catch (GroupAlreadyExistException e) { 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(); } } @@ -126,7 +137,6 @@ public class GroupManagementServiceImpl implements GroupManagementService { if (deviceGroup == null) { return Response.status(Response.Status.BAD_REQUEST).build(); } - deviceGroup.setDateOfLastUpdate(new Date().getTime()); try { DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(deviceGroup, groupId); return Response.status(Response.Status.OK).build(); @@ -134,42 +144,120 @@ public class GroupManagementServiceImpl implements GroupManagementService { String msg = "Error occurred while adding new group."; log.error(msg, e); 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 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 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 public Response getUsersOfGroup(int groupId) { - return null; + try { + List 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 public Response getDevicesOfGroup(int groupId, int offset, int limit) { - return null; + try { + GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); + List 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 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 public Response addDevicesToGroup(int groupId, List 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 public Response removeDevicesFromGroup(int groupId, List 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(); + } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java index 01415da80a8..729f32af436 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java @@ -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.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.device.mgt.common.PaginationResult; +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.GroupManagementException; 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.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 java.util.List; @@ -42,11 +38,14 @@ public class GroupManagementAdminServiceImpl implements GroupManagementAdminServ private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class); @Override - public Response getGroups(int offset, int limit) { + public Response getGroups(String name, String owner, int offset, int limit) { try { RequestValidationUtil.validatePaginationParameters(offset, limit); GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); - List deviceGroups = service.getGroups(offset, limit); + GroupPaginationRequest request = new GroupPaginationRequest(offset, limit); + request.setGroupName(name); + request.setOwner(owner); + List deviceGroups = service.getGroups(request); if (deviceGroups != null && deviceGroups.size() > 0) { DeviceGroupList deviceGroupList = new DeviceGroupList(); deviceGroupList.setList(deviceGroups); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceNotFoundException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceNotFoundException.java new file mode 100644 index 00000000000..7115405c2b0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceNotFoundException.java @@ -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); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/GroupPaginationRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/GroupPaginationRequest.java new file mode 100644 index 00000000000..a0dfb9351bc --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/GroupPaginationRequest.java @@ -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; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java index e39106cadb6..6c3a6c9f606 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java @@ -21,12 +21,13 @@ package org.wso2.carbon.device.mgt.common; 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 { private int startIndex; private int rowCount; + private int groupId; private String owner; private String status; private String deviceType; @@ -55,6 +56,14 @@ public class PaginationRequest { this.rowCount = rowCount; } + public int getGroupId() { + return groupId; + } + + public void setGroupId(int groupId) { + this.groupId = groupId; + } + public String getOwner() { return owner; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/RoleDoesNotExistException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/RoleDoesNotExistException.java new file mode 100644 index 00000000000..c3a42f197b4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/RoleDoesNotExistException.java @@ -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; + } + +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pagination/PaginationConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pagination/PaginationConfiguration.java index f60f33d98f6..46e16aff6dc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pagination/PaginationConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pagination/PaginationConfiguration.java @@ -28,6 +28,7 @@ import javax.xml.bind.annotation.XmlRootElement; public class PaginationConfiguration { private int deviceListPageSize; + private int groupListPageSize; private int operationListPageSize; private int notificationListPageSize; private int activityListPageSize; @@ -41,6 +42,15 @@ public class PaginationConfiguration { this.deviceListPageSize = deviceListPageSize; } + public int getGroupListPageSize() { + return groupListPageSize; + } + + @XmlElement(name = "GroupListPageSize", required = true) + public void setGroupListPageSize(int groupListPageSize) { + this.groupListPageSize = groupListPageSize; + } + public int getOperationListPageSize() { return operationListPageSize; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 648c7e2a424..61ef702ac94 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -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.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dto.DeviceType; -import org.wso2.carbon.utils.xml.StringUtils; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java index 8d91c08cff8..f9412fcff90 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java @@ -19,6 +19,7 @@ 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.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import java.util.List; @@ -76,16 +77,23 @@ public interface GroupDAO { List 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 rowCount for pagination. + * @param paginationRequest to filter results * @param tenantId of user's tenant. * @return List of all Device Groups in tenant. * @throws GroupManagementDAOException */ - List getGroups(int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException; + List 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 getGroups(int tenantId) throws GroupManagementDAOException; /** * Get count of Device Groups in tenant. @@ -114,7 +122,7 @@ public interface GroupDAO { * @return existence of group with name * @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. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java index 43928cc821b..2286f6dbba7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java @@ -19,6 +19,7 @@ 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.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; @@ -147,7 +148,6 @@ public class GroupDAOImpl implements GroupDAO { @Override public List getGroups(int deviceId, int tenantId) throws GroupManagementDAOException { - PreparedStatement stmt = null; ResultSet resultSet = null; List deviceGroupBuilders = new ArrayList<>(); @@ -172,21 +172,66 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public List getGroups(int startIndex, int rowCount, int tenantId) + public List getGroups(GroupPaginationRequest request, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; List deviceGroupList = null; + + String groupName = request.getGroupName(); + boolean hasGroupName = false; + String owner = request.getOwner(); + boolean hasOwner = false; + 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 = ? 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 getGroups(int tenantId) throws GroupManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + List 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.setInt(1, tenantId); - //noinspection JpaQueryApiInspection - stmt.setInt(2, startIndex); - //noinspection JpaQueryApiInspection - stmt.setInt(3, rowCount); resultSet = stmt.executeQuery(); deviceGroupList = new ArrayList<>(); while (resultSet.next()) { @@ -249,17 +294,21 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException { + public DeviceGroup getGroup(String groupName, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; try { 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.setString(1, groupName); stmt.setInt(2, tenantId); resultSet = stmt.executeQuery(); - return resultSet.next(); + if (resultSet.next()) { + return GroupManagementDAOUtil.loadGroup(resultSet); + } + return null; } catch (SQLException e) { throw new GroupManagementDAOException("Error occurred while group Id listing by group name.'", e); } finally { @@ -351,6 +400,7 @@ public class GroupDAOImpl implements GroupDAO { } } + //TODO: Move this to device mgt @Override public List getDevices(int groupId, int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationDAO.java index 978d2cc3b7f..f9787b45010 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationDAO.java @@ -19,7 +19,6 @@ 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.PaginationResult; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java index 99c71a5ba16..d8c6b789877 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java @@ -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.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.core.dto.operation.mgt.Operation; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index 760a2f6e754..a43a089640c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -17,7 +17,6 @@ */ 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.LogFactory; 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.ActivityStatus; 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.operation.mgt.dao.OperationDAO; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java index f37419422d3..2591a267ba1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java @@ -90,7 +90,7 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { @Override public List getOperationsByDeviceAndStatus(int enrolmentId, - PaginationRequest request, Operation.Status status) throws OperationManagementDAOException { + PaginationRequest request, Operation.Status status) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; Operation operation; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java index f04226943ce..934e652927d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java @@ -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.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.GroupAlreadyExistException; 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.user.core.multiplecredentials.UserDoesNotExistException; import java.util.List; @@ -52,7 +55,7 @@ public interface GroupManagementProviderService { * @param groupId of the group. * @throws GroupManagementException */ - void updateGroup(DeviceGroup deviceGroup, int groupId) throws GroupManagementException; + void updateGroup(DeviceGroup deviceGroup, int groupId) throws GroupManagementException, GroupAlreadyExistException; /** * Delete existing device group. @@ -73,25 +76,40 @@ public interface GroupManagementProviderService { 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. * @throws GroupManagementException */ - List getGroups(int startIndex, int rowCount) throws GroupManagementException; + List getGroups() throws GroupManagementException; /** - * Get paginated device groups for user. + * Get all device groups for user. * * @param username of the user. - * @param startIndex for pagination. - * @param rowCount for pagination. * @return list of groups * @throws GroupManagementException */ - List getGroups(String username, int startIndex, int rowCount) throws GroupManagementException; + List getGroups(String username) throws GroupManagementException; + + /** + * Get device groups with pagination. + * + * @param paginationRequest to filter results + * @return list of groups. + * @throws GroupManagementException + */ + List 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 getGroups(String username, GroupPaginationRequest paginationRequest) throws GroupManagementException; /** * Get all device group count in tenant @@ -111,28 +129,15 @@ public interface GroupManagementProviderService { int getGroupCount(String username) throws GroupManagementException; /** - * Share device group with user specified by role - * - * @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 + * Manage device group sharing with user with list of roles. * - * @param userName of the user - * @param groupId of the group - * @param sharingRole to be un shared - * @return is group un shared + * @param username of the user + * @param groupId of the group + * @param newRoles to be shared * @throws GroupManagementException UserDoesNotExistException */ - boolean unshareGroup(String userName, int groupId, String sharingRole) - throws GroupManagementException, UserDoesNotExistException; + void manageGroupSharing(int groupId, String username, List newRoles) + throws GroupManagementException, UserDoesNotExistException, RoleDoesNotExistException; /** * Add new sharing role for device group @@ -208,22 +213,22 @@ public interface GroupManagementProviderService { /** * Add device to device group. * - * @param deviceId of the device. - * @param groupId of the group - * @return is device added. + * @param groupId of the group. + * @param deviceIdentifiers of devices. * @throws GroupManagementException */ - boolean addDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException; + void addDevices(int groupId, List deviceIdentifiers) throws GroupManagementException, + DeviceNotFoundException; /** * Remove device from device group. * - * @param deviceId of the device. - * @param groupId of the group - * @return is device removed. + * @param groupId of the group. + * @param deviceIdentifiers of devices. * @throws GroupManagementException */ - boolean removeDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException; + void removeDevice(int groupId, List deviceIdentifiers) throws GroupManagementException, + DeviceNotFoundException; /** * Get device group permissions of user. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index a76c9566461..012bc9b18ef 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -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.DeviceIdentifier; 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.group.mgt.DeviceGroup; 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.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.GroupManagementDAOException; 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.util.DeviceManagerUtil; import org.wso2.carbon.user.api.Permission; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; @@ -75,8 +79,8 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid int groupId = -1; try { GroupManagementDAOFactory.beginTransaction(); - boolean nameIsExists = this.groupDAO.isGroupExist(deviceGroup.getName(), tenantId); - if (!nameIsExists) { + DeviceGroup existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId); + if (existingGroup == null) { groupId = this.groupDAO.addGroup(deviceGroup, tenantId); GroupManagementDAOFactory.commitTransaction(); } else { @@ -103,16 +107,21 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid */ @Override public void updateGroup(DeviceGroup deviceGroup, int groupId) - throws GroupManagementException { + throws GroupManagementException, GroupAlreadyExistException { if (deviceGroup == null) { throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException()); } try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); GroupManagementDAOFactory.beginTransaction(); - deviceGroup.setDateOfLastUpdate(new Date().getTime()); - this.groupDAO.updateGroup(deviceGroup, groupId, tenantId); - GroupManagementDAOFactory.commitTransaction(); + DeviceGroup existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId); + if (existingGroup == null || existingGroup.getGroupId() == groupId) { + 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) { GroupManagementDAOFactory.rollbackTransaction(); throw new GroupManagementException("Error occurred while modifying deviceGroup " + @@ -192,12 +201,34 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } @Override - public List getGroups(int startIndex, int rowCount) throws GroupManagementException { + public List getGroups() throws GroupManagementException { + List 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 getGroups(GroupPaginationRequest request) throws GroupManagementException { List deviceGroups = new ArrayList<>(); + request = DeviceManagerUtil.validateGroupListPageSize(request); try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); GroupManagementDAOFactory.openConnection(); - deviceGroups = this.groupDAO.getGroups(startIndex, rowCount, tenantId); + deviceGroups = this.groupDAO.getGroups(request, tenantId); } catch (GroupManagementDAOException e) { throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e); } catch (SQLException e) { @@ -213,7 +244,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } @Override - public List getGroups(String username, int startIndex, int rowCount) throws GroupManagementException { + public List getGroups(String username) throws GroupManagementException { Map groups = new HashMap<>(); UserStoreManager userStoreManager; try { @@ -221,11 +252,36 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) .getUserStoreManager(); 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 getGroups(String currentUser, GroupPaginationRequest request) throws GroupManagementException { + request = DeviceManagerUtil.validateGroupListPageSize(request); + Map 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; for (String role : roleList) { if (role != null && role.contains("Internal/group-")) { 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); } } @@ -283,50 +339,49 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public boolean shareGroup(String username, int groupId, String sharingRole) - throws GroupManagementException, UserDoesNotExistException { - return modifyGroupShare(username, groupId, sharingRole, true); - } - - /** - * {@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; - } + @SuppressWarnings("Duplicates") + public void manageGroupSharing(int groupId, String username, List newRoles) + throws GroupManagementException, UserDoesNotExistException, RoleDoesNotExistException { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); UserStoreManager userStoreManager; - String[] roles = new String[1]; try { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm( tenantId).getUserStoreManager(); if (!userStoreManager.isExistingUser(username)) { throw new UserDoesNotExistException("User not exists with name " + username); } - roles[0] = "Internal/group-" + groupId + "-" + sharingRole; - List currentRoles = getRoles(username, groupId); - if (isAddNew && !currentRoles.contains(sharingRole)) { - userStoreManager.updateRoleListOfUser(username, null, roles); - } else if (!isAddNew && currentRoles.contains(sharingRole)) { - userStoreManager.updateRoleListOfUser(username, roles, null); + List currentGroupRoles = getRoles(groupId); + List currentUserRoles = getRoles(username, groupId); + List rolesToAdd = new ArrayList<>(); + List rolesToRemove = new ArrayList<>(); + String roleNamePrefix = "Internal/group-" + groupId + "-"; + 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) { if (e instanceof UserDoesNotExistException) { throw (UserDoesNotExistException) e; } - throw new GroupManagementException("User store error in adding user " + username + " to group name:" + - groupId, e); + throw new GroupManagementException("User store error in updating sharing roles.", e); } } @@ -520,17 +575,19 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid * {@inheritDoc} */ @Override - public boolean addDevice(DeviceIdentifier deviceIdentifier, int groupId) - throws GroupManagementException { + public void addDevices(int groupId, List deviceIdentifiers) + throws GroupManagementException, DeviceNotFoundException { Device device; try { - device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier); - if (device == null) { - return false; - } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); 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(); } catch (DeviceManagementException e) { throw new GroupManagementException("Error occurred while retrieving device.", e); @@ -542,23 +599,25 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } finally { GroupManagementDAOFactory.closeConnection(); } - return true; } /** * {@inheritDoc} */ @Override - public boolean removeDevice(DeviceIdentifier deviceIdentifier, int groupId) throws GroupManagementException { + public void removeDevice(int groupId, List deviceIdentifiers) + throws GroupManagementException, DeviceNotFoundException { Device device; try { - device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier); - if (device == null) { - return false; - } int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); 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(); } catch (DeviceManagementException e) { throw new GroupManagementException("Error occurred while retrieving device.", e); @@ -570,7 +629,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } finally { GroupManagementDAOFactory.closeConnection(); } - return true; } /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index 033e3fcccad..c5558fe92a6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -22,6 +22,7 @@ import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.wso2.carbon.base.MultitenantConstants; 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.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; @@ -327,6 +328,22 @@ public final class DeviceManagerUtil { 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 { if (limit == 0) { DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java index 6ef90d78c76..ae6bcc0126f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java @@ -24,6 +24,7 @@ import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; 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.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; @@ -100,7 +101,10 @@ public class GroupPersistTests extends BaseDeviceManagementTest { public void getGroupTest() { try { GroupManagementDAOFactory.openConnection(); - List groups = groupDAO.getGroups(0, 100, TestDataHolder.SUPER_TENANT_ID); + GroupPaginationRequest request = new GroupPaginationRequest(0, 10); + request.setGroupName(null); + request.setOwner(null); + List groups = groupDAO.getGroups(request, TestDataHolder.SUPER_TENANT_ID); Assert.assertNotEquals(groups.size(), 0, "No groups found"); Assert.assertNotNull(groups.get(0), "Group is null"); log.debug("No of Groups found: " + groups.size()); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml index 84af9068726..97340bd5a3a 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml @@ -65,6 +65,7 @@ 20 + 20 20 20 20 From 94a50584f4920199c755c075200ea8cd1a9aa4e3 Mon Sep 17 00:00:00 2001 From: charitha Date: Thu, 6 Oct 2016 16:01:41 +0530 Subject: [PATCH 5/8] Improve group listing with pagination --- .../mgt/jaxrs/beans/DeviceGroupList.java | 8 +- .../impl/GroupManagementServiceImpl.java | 11 +- .../GroupManagementAdminServiceImpl.java | 11 +- .../mgt/core/group/mgt/dao/GroupDAO.java | 12 +- .../mgt/core/group/mgt/dao/GroupDAOImpl.java | 60 +++++++--- .../GroupManagementProviderService.java | 5 +- .../GroupManagementProviderServiceImpl.java | 110 ++++++++++++------ .../mgt/core/dao/GroupPersistTests.java | 27 +---- 8 files changed, 144 insertions(+), 100 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java index d1e472255a5..3e588444dae 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceGroupList.java @@ -20,8 +20,6 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import java.util.ArrayList; import java.util.List; @@ -30,13 +28,13 @@ public class DeviceGroupList extends BasePaginatedResult { @ApiModelProperty(value = "List of device groups returned") @JsonProperty("groups") - private List deviceGroups = new ArrayList<>(); + private List deviceGroups = new ArrayList<>(); - public List getList() { + public List getList() { return deviceGroups; } - public void setList(List deviceGroups) { + public void setList(List deviceGroups) { this.deviceGroups = deviceGroups; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java index afae7a94958..0d9bea2e8bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java @@ -27,6 +27,7 @@ import org.wso2.carbon.device.mgt.common.Device; 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.PaginationResult; 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.GroupManagementException; @@ -58,16 +59,16 @@ public class GroupManagementServiceImpl implements GroupManagementService { public Response getGroups(String name, String owner, int offset, int limit) { try { RequestValidationUtil.validatePaginationParameters(offset, limit); - GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); GroupPaginationRequest request = new GroupPaginationRequest(offset, limit); request.setGroupName(name); request.setOwner(owner); - List deviceGroups = service.getGroups(currentUser, request); - if (deviceGroups != null && deviceGroups.size() > 0) { + PaginationResult deviceGroupsResult = DeviceMgtAPIUtils.getGroupManagementProviderService() + .getGroups(currentUser, request); + if (deviceGroupsResult.getData() != null && deviceGroupsResult.getRecordsTotal() > 0) { DeviceGroupList deviceGroupList = new DeviceGroupList(); - deviceGroupList.setList(deviceGroups); - deviceGroupList.setCount(service.getGroupCount(currentUser)); + deviceGroupList.setList(deviceGroupsResult.getData()); + deviceGroupList.setCount(deviceGroupsResult.getRecordsTotal()); return Response.status(Response.Status.OK).entity(deviceGroupList).build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java index 729f32af436..55b67029fab 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java @@ -22,6 +22,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; @@ -41,15 +42,15 @@ public class GroupManagementAdminServiceImpl implements GroupManagementAdminServ public Response getGroups(String name, String owner, int offset, int limit) { try { RequestValidationUtil.validatePaginationParameters(offset, limit); - GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); GroupPaginationRequest request = new GroupPaginationRequest(offset, limit); request.setGroupName(name); request.setOwner(owner); - List deviceGroups = service.getGroups(request); - if (deviceGroups != null && deviceGroups.size() > 0) { + PaginationResult deviceGroupsResult = DeviceMgtAPIUtils.getGroupManagementProviderService() + .getGroups(request); + if (deviceGroupsResult.getData() != null && deviceGroupsResult.getRecordsTotal() > 0) { DeviceGroupList deviceGroupList = new DeviceGroupList(); - deviceGroupList.setList(deviceGroups); - deviceGroupList.setCount(service.getGroupCount()); + deviceGroupList.setList(deviceGroupsResult.getData()); + deviceGroupList.setCount(deviceGroupsResult.getRecordsTotal()); return Response.status(Response.Status.OK).entity(deviceGroupList).build(); } else { return Response.status(Response.Status.NOT_FOUND).build(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java index f9412fcff90..2637f0b0ceb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java @@ -79,7 +79,7 @@ public interface GroupDAO { /** * Get paginated list of Device Groups in tenant. * - * @param paginationRequest to filter results + * @param paginationRequest to filter results. * @param tenantId of user's tenant. * @return List of all Device Groups in tenant. * @throws GroupManagementDAOException @@ -105,14 +105,14 @@ public interface GroupDAO { int getGroupCount(int tenantId) throws GroupManagementDAOException; /** - * Get the list of Groups that matches with the given DeviceGroup name. + * Get paginated count of Device Groups in tenant. * - * @param groupName of the Device Group. - * @param tenantId of user's tenant. - * @return List of DeviceGroup that matches with the given DeviceGroup name. + * @param paginationRequest to filter results. + * @param tenantId of user's tenant. + * @return List of all Device Groups in tenant. * @throws GroupManagementDAOException */ - List findInGroups(String groupName, int tenantId) throws GroupManagementDAOException; + int getGroupCount(GroupPaginationRequest paginationRequest, int tenantId) throws GroupManagementDAOException; /** * Check group already existed with given name. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java index 2286f6dbba7..0ea00073000 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java @@ -182,32 +182,37 @@ public class GroupDAOImpl implements GroupDAO { boolean hasGroupName = false; String owner = request.getOwner(); boolean hasOwner = false; + boolean hasLimit = request.getRowCount() != 0; try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " + "FROM DM_GROUP WHERE TENANT_ID = ?"; if (groupName != null && !groupName.isEmpty()) { - sql += " GROUP_NAME LIKE ?"; + sql += " AND GROUP_NAME LIKE ?"; hasGroupName = true; } if (owner != null && !owner.isEmpty()) { - sql += " OWNER LIKE ?"; + sql += " AND OWNER LIKE ?"; hasOwner = true; } - sql += " LIMIT ?, ?"; + if (hasLimit) { + sql += " LIMIT ?, ?"; + } int paramIndex = 1; stmt = conn.prepareStatement(sql); stmt.setInt(paramIndex++, tenantId); if (hasGroupName) { - stmt.setString(paramIndex++, groupName); + stmt.setString(paramIndex++, groupName + "%"); } if (hasOwner) { - stmt.setString(paramIndex++, owner); + stmt.setString(paramIndex++, owner + "%"); + } + if (hasLimit) { + stmt.setInt(paramIndex++, request.getStartIndex()); + stmt.setInt(paramIndex, request.getRowCount()); } - stmt.setInt(paramIndex++, request.getStartIndex()); - stmt.setInt(paramIndex, request.getRowCount()); resultSet = stmt.executeQuery(); deviceGroupList = new ArrayList<>(); while (resultSet.next()) { @@ -268,29 +273,48 @@ public class GroupDAOImpl implements GroupDAO { } @Override - public List findInGroups(String groupName, int tenantId) + public int getGroupCount(GroupPaginationRequest request, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; - List deviceGroups = new ArrayList<>(); + + String groupName = request.getGroupName(); + boolean hasGroupName = false; + String owner = request.getOwner(); + boolean hasOwner = false; + try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " - + "FROM DM_GROUP WHERE GROUP_NAME LIKE ? AND TENANT_ID = ?"; + String sql = "SELECT COUNT(ID) AS GROUP_COUNT FROM DM_GROUP WHERE TENANT_ID = ?"; + if (groupName != null && !groupName.isEmpty()) { + sql += " AND GROUP_NAME LIKE ?"; + hasGroupName = true; + } + if (owner != null && !owner.isEmpty()) { + sql += " AND OWNER LIKE ?"; + hasOwner = true; + } + + int paramIndex = 1; stmt = conn.prepareStatement(sql); - stmt.setString(1, "%" + groupName + "%"); - stmt.setInt(2, tenantId); + stmt.setInt(paramIndex++, tenantId); + if (hasGroupName) { + stmt.setString(paramIndex++, groupName + "%"); + } + if (hasOwner) { + stmt.setString(paramIndex, owner + "%"); + } resultSet = stmt.executeQuery(); - while (resultSet.next()) { - deviceGroups.add(GroupManagementDAOUtil.loadGroup(resultSet)); + if (resultSet.next()) { + return resultSet.getInt("GROUP_COUNT"); + } else { + return 0; } } catch (SQLException e) { - throw new GroupManagementDAOException("Error occurred while listing Device Groups by name '" + - groupName + "' in tenant '" + tenantId + "'", e); + throw new GroupManagementDAOException("Error occurred while listing all groups in tenant: " + tenantId, e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, resultSet); } - return deviceGroups; } @Override diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java index 934e652927d..ab84bb4cc5f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java @@ -23,6 +23,7 @@ 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.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; @@ -99,7 +100,7 @@ public interface GroupManagementProviderService { * @return list of groups. * @throws GroupManagementException */ - List getGroups(GroupPaginationRequest paginationRequest) throws GroupManagementException; + PaginationResult getGroups(GroupPaginationRequest paginationRequest) throws GroupManagementException; /** * Get device groups with pagination. @@ -109,7 +110,7 @@ public interface GroupManagementProviderService { * @return list of groups. * @throws GroupManagementException */ - List getGroups(String username, GroupPaginationRequest paginationRequest) throws GroupManagementException; + PaginationResult getGroups(String username, GroupPaginationRequest paginationRequest) throws GroupManagementException; /** * Get all device group count in tenant diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 012bc9b18ef..11ea9592259 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -28,6 +28,7 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier; 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.PaginationResult; import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; @@ -139,7 +140,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid @Override public boolean deleteGroup(int groupId) throws GroupManagementException { String roleName; - DeviceGroup deviceGroup = buildDeviceGroup(groupId); + DeviceGroup deviceGroup = getGroup(groupId); if (deviceGroup == null) { return false; } @@ -168,7 +169,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } } - private DeviceGroup buildDeviceGroup(int groupId) throws GroupManagementException { + /** + * {@inheritDoc} + */ + @Override + public DeviceGroup getGroup(int groupId) throws GroupManagementException { DeviceGroup deviceGroup; try { GroupManagementDAOFactory.openConnection(); @@ -187,19 +192,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid return deviceGroup; } - /** - * {@inheritDoc} - */ - @Override - public DeviceGroup getGroup(int groupId) throws GroupManagementException { - DeviceGroup deviceGroup = this.buildDeviceGroup(groupId); - if (deviceGroup != null) { - deviceGroup.setUsers(this.getUsers(groupId)); - deviceGroup.setRoles(this.getRoles(groupId)); - } - return deviceGroup; - } - @Override public List getGroups() throws GroupManagementException { List deviceGroups = new ArrayList<>(); @@ -222,9 +214,21 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } @Override - public List getGroups(GroupPaginationRequest request) throws GroupManagementException { - List deviceGroups = new ArrayList<>(); + public PaginationResult getGroups(GroupPaginationRequest request) throws GroupManagementException { request = DeviceManagerUtil.validateGroupListPageSize(request); + List deviceGroups = getPlainDeviceGroups(request); + for (DeviceGroup group : deviceGroups) { + group.setUsers(this.getUsers(group.getGroupId())); + group.setRoles(this.getRoles(group.getGroupId())); + } + PaginationResult groupResult = new PaginationResult(); + groupResult.setData(deviceGroups); + groupResult.setRecordsTotal(getGroupCount(request)); + return groupResult; + } + + private List getPlainDeviceGroups(GroupPaginationRequest request) throws GroupManagementException { + List deviceGroups = new ArrayList<>(); try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); GroupManagementDAOFactory.openConnection(); @@ -236,10 +240,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } finally { GroupManagementDAOFactory.closeConnection(); } - for (DeviceGroup group : deviceGroups) { - group.setUsers(this.getUsers(group.getGroupId())); - group.setRoles(this.getRoles(group.getGroupId())); - } return deviceGroups; } @@ -254,7 +254,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid String[] roleList = userStoreManager.getRoleListOfUser(username); for (String role : roleList) { if (role != null && role.contains("Internal/group-")) { - DeviceGroup deviceGroup = extractNewGroupFromRole(groups, role); + DeviceGroup deviceGroup = checkAndExtractNonExistingGroup(groups, role); if (deviceGroup != null) { groups.put(deviceGroup.getGroupId(), deviceGroup); } @@ -266,30 +266,46 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid return new ArrayList<>(groups.values()); } - public List getGroups(String currentUser, GroupPaginationRequest request) throws GroupManagementException { + public PaginationResult getGroups(String currentUser, GroupPaginationRequest request) throws GroupManagementException { request = DeviceManagerUtil.validateGroupListPageSize(request); - Map groups = new HashMap<>(); - UserStoreManager userStoreManager; + int startIndex = request.getStartIndex(); + int count = request.getRowCount(); + int index = 0; + request.setRowCount(0); + List allMatchingGroups = this.getPlainDeviceGroups(request); + List deviceGroups = new ArrayList<>(); try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) + UserStoreManager userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId) .getUserStoreManager(); String[] roleList = userStoreManager.getRoleListOfUser(currentUser); - int index = 0; + List groupIds = new ArrayList<>(); for (String role : roleList) { if (role != null && role.contains("Internal/group-")) { - DeviceGroup deviceGroupBuilder = extractNewGroupFromRole(groups, role); - if (deviceGroupBuilder != null - && request.getStartIndex() <= index++ - && index <= request.getRowCount()) { - groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder); + int groupId = Integer.parseInt(role.split("-")[1]); + if (!groupIds.contains(groupId)) { + groupIds.add(groupId); } } } + for (DeviceGroup group : allMatchingGroups) { + int groupId = group.getGroupId(); + if (groupIds.contains(groupId)) { + if (startIndex <= index && index < count) { + group.setUsers(this.getUsers(groupId)); + group.setRoles(this.getRoles(groupId)); + deviceGroups.add(group); + } + index++; + } + } } catch (UserStoreException e) { throw new GroupManagementException("Error occurred while getting user store manager.", e); } - return new ArrayList<>(groups.values()); + PaginationResult groupResult = new PaginationResult(); + groupResult.setData(deviceGroups); + groupResult.setRecordsTotal(index); + return groupResult; } @Override @@ -307,6 +323,20 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } } + private int getGroupCount(GroupPaginationRequest request) throws GroupManagementException { + try { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + GroupManagementDAOFactory.openConnection(); + return groupDAO.getGroupCount(request, 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(); + } + } + /** * {@inheritDoc} */ @@ -677,7 +707,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid for (String role : roles) { if (role != null && role.contains("Internal/group-") && userRealm.getAuthorizationManager() .isRoleAuthorized(role, permission, CarbonConstants.UI_PERMISSION_ACTION)) { - DeviceGroup group = extractNewGroupFromRole(groups, role); + DeviceGroup group = checkAndExtractNonExistingGroup(groups, role); if (group != null) { groups.put(group.getGroupId(), group); } @@ -708,12 +738,20 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } } - private DeviceGroup extractNewGroupFromRole(Map groups, String role) + /** + * This method returns group belongs to particular role, if it is not existed in groups map. + * + * @param groups existing groups map. + * @param role group related role which needs to evaluate. + * @return device group if it is not existing in the groups map. + * @throws GroupManagementException + */ + private DeviceGroup checkAndExtractNonExistingGroup(Map groups, String role) throws GroupManagementException { try { int groupId = Integer.parseInt(role.split("-")[1]); if (!groups.containsKey(groupId)) { - return buildDeviceGroup(groupId); + return getGroup(groupId); } } catch (NumberFormatException e) { log.error("Unable to extract groupId from role " + role, e); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java index ae6bcc0126f..0f58cfb6a1c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java @@ -40,7 +40,7 @@ import java.util.List; public class GroupPersistTests extends BaseDeviceManagementTest { private static final Log log = LogFactory.getLog(GroupPersistTests.class); - int groupId = -1; + private int groupId = -1; private GroupDAO groupDAO; @BeforeClass @@ -76,27 +76,6 @@ public class GroupPersistTests extends BaseDeviceManagementTest { log.debug("Group name: " + group.getName()); } - @Test(dependsOnMethods = {"testAddGroupTest"}) - public void findGroupTest() { - try { - GroupManagementDAOFactory.openConnection(); - List groups = groupDAO.findInGroups("Test", TestDataHolder.SUPER_TENANT_ID); - Assert.assertNotEquals(groups.size(), 0, "No groups found"); - Assert.assertNotNull(groups.get(0), "Group is null"); - log.debug("Group found: " + groups.get(0).getName()); - } catch (GroupManagementDAOException e) { - String msg = "Error occurred while find group by name."; - log.error(msg, e); - Assert.fail(msg, e); - } catch (SQLException e) { - String msg = "Error occurred while opening a connection to the data source."; - log.error(msg, e); - Assert.fail(msg, e); - } finally { - GroupManagementDAOFactory.closeConnection(); - } - } - @Test(dependsOnMethods = {"testAddGroupTest"}) public void getGroupTest() { try { @@ -125,6 +104,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest { public void addDeviceToGroupTest() { Device initialTestDevice = TestDataHolder.initialTestDevice; DeviceGroup deviceGroup = getGroupById(groupId); + Assert.assertNotNull(deviceGroup, "Group is null"); try { GroupManagementDAOFactory.beginTransaction(); groupDAO.addDevice(deviceGroup.getGroupId(), initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID); @@ -166,6 +146,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest { public void removeDeviceFromGroupTest() { Device initialTestDevice = TestDataHolder.initialTestDevice; DeviceGroup deviceGroup = getGroupById(groupId); + Assert.assertNotNull(deviceGroup, "Group is null"); try { GroupManagementDAOFactory.beginTransaction(); groupDAO.removeDevice(deviceGroup.getGroupId(), initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID); @@ -245,7 +226,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest { Assert.assertNull(group, "Group is not deleted"); } - public DeviceGroup getGroupById(int groupId) { + private DeviceGroup getGroupById(int groupId) { try { GroupManagementDAOFactory.openConnection(); return groupDAO.getGroup(groupId, TestDataHolder.SUPER_TENANT_ID); From 664b3d4d43ddb6360e9da26f0a04904aede63120 Mon Sep 17 00:00:00 2001 From: charitha Date: Thu, 6 Oct 2016 20:32:09 +0530 Subject: [PATCH 6/8] Fix issue in duplicate mapping --- .../mgt/core/service/GroupManagementProviderServiceImpl.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 11ea9592259..1753f9696ab 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -616,7 +616,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid if (device == null) { throw new DeviceNotFoundException("Device not found for id '" + deviceIdentifier.getId() + "'"); } - this.groupDAO.addDevice(groupId, device.getId(), tenantId); + if (!this.groupDAO.isDeviceMappedToGroup(groupId, device.getId(), tenantId)){ + this.groupDAO.addDevice(groupId, device.getId(), tenantId); + } } GroupManagementDAOFactory.commitTransaction(); } catch (DeviceManagementException e) { From a2c0526b40b3b969d34f21b45a4ce56cc38810b8 Mon Sep 17 00:00:00 2001 From: charitha Date: Mon, 10 Oct 2016 15:34:18 +0530 Subject: [PATCH 7/8] Fix typo --- .../mgt/core/service/GroupManagementProviderServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 1753f9696ab..d4f462b1bc1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -392,7 +392,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid rolesToAdd.add(roleNamePrefix + role); } } else { - throw new RoleDoesNotExistException("Role '" + role + "' is not exists iin requested group."); + throw new RoleDoesNotExistException("Role '" + role + "' is not exists in requested group."); } } for (String role : currentUserRoles) { @@ -401,7 +401,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid rolesToRemove.add(roleNamePrefix + role); } } else { - throw new RoleDoesNotExistException("Role '" + role + "' is not exists iin requested group."); + throw new RoleDoesNotExistException("Role '" + role + "' is not exists in requested group."); } } userStoreManager.updateRoleListOfUser(username, From e53b0c386058b5e3a48e93bdb982342899b45534 Mon Sep 17 00:00:00 2001 From: charitha Date: Mon, 10 Oct 2016 20:00:39 +0530 Subject: [PATCH 8/8] Fix group count listing in dashboard --- .../jaxrs/service/api/GroupManagementService.java | 2 +- .../api/admin/GroupManagementAdminService.java | 1 + .../app/modules/business-controllers/group.js | 15 +++++++-------- .../app/modules/business-controllers/user.js | 4 ++-- .../app/pages/cdmf.page.dashboard/dashboard.js | 4 +--- 5 files changed, 12 insertions(+), 14 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java index ce409aa02c2..0fa5b9e0b5e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java @@ -53,7 +53,7 @@ import java.util.List; /** * Device group related REST-API. This can be used to manipulated device group related details. */ -@API(name = "Group Management", version = "1.0.0", context = "/api/device-mgt/v1.0/groups", tags = {"device_management"}) +@API(name = "GroupManagement", version = "1.0.0", context = "/api/device-mgt/v1.0/groups", tags = {"device_management"}) @Path("/groups") @Api(value = "Device Group Management", description = "This API carries all device group management related operations " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java index 670fcab3232..6757c471b5c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java @@ -106,6 +106,7 @@ public interface GroupManagementAdminService { value = "Maximum size of resource array to return.") @QueryParam("limit") int limit); + @Path("/count") @GET @ApiOperation( produces = MediaType.APPLICATION_JSON, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js index fcbeea8a5a3..d4569b68046 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js @@ -26,8 +26,7 @@ var groupModule = {}; var utility = require("/app/modules/utility.js").utility; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; - var groupServiceEndpoint = devicemgtProps["httpsURL"] + - devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/groups"; + var deviceServiceEndpoint = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0"; var user = session.get(constants.USER_SESSION_KEY); @@ -36,26 +35,26 @@ var groupModule = {}; groupModule.getGroupCount = function () { var permissions = userModule.getUIPermissions(); if (permissions.LIST_ALL_GROUPS) { - endPoint = groupServiceEndpoint + "/count"; + endPoint = deviceServiceEndpoint + "/admin/groups/count"; } else if (permissions.LIST_GROUPS) { - endPoint = groupServiceEndpoint + "/user/" + user.username + "/count"; + endPoint = deviceServiceEndpoint + "/groups/count"; } else { log.error("Access denied for user: " + carbonUser.username); return -1; } return serviceInvokers.XMLHttp.get( endPoint, function (responsePayload) { - return responsePayload; + return responsePayload["responseText"]; }, function (responsePayload) { - log.error(responsePayload); + log.error(responsePayload["responseText"]); return -1; } ); }; groupModule.getGroupDeviceCount = function (groupName, owner) { - endPoint = groupServiceEndpoint + "/owner/" + owner + "/name/" + groupName + "/devices/count"; + endPoint = deviceServiceEndpoint + "/owner/" + owner + "/name/" + groupName + "/devices/count"; return serviceInvokers.XMLHttp.get( endPoint, function (responsePayload) { return responsePayload; @@ -68,7 +67,7 @@ var groupModule = {}; }; groupModule.getGroupDevices = function (groupName, owner) { - endPoint = groupServiceEndpoint + "/owner/" + owner + "/name/" + groupName + "/devices"; + endPoint = deviceServiceEndpoint + "/owner/" + owner + "/name/" + groupName + "/devices"; return serviceInvokers.XMLHttp.get( endPoint, function (responsePayload) { return responsePayload; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js index b229ab8ef87..8103c6b5bb5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js @@ -477,10 +477,10 @@ var userModule = function () { if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/devices/list")) { permissions["LIST_OWN_DEVICES"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/list")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/groups/view")) { permissions["LIST_ALL_GROUPS"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/groups/list")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/view")) { permissions["LIST_GROUPS"] = true; } if (publicMethods.isAuthorized("/permission/admin/device-mgt/users/list")) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js index c848b86f6eb..35a4eb0c054 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js @@ -36,9 +36,7 @@ function onRequest() { viewModel.permissions = permissions; viewModel.enrollmentURL = devicemgtProps.enrollmentURL; viewModel.deviceCount = deviceModule.getDevicesCount(); - //TODO: Enable Group Management Service API on CDMF - //page.group_count = groupModule.getGroupCount(); - viewModel.groupCount = -1; + viewModel.groupCount = groupModule.getGroupCount(); viewModel.userCount = userModule.getUsersCount(); viewModel.policyCount = policyModule.getPoliciesCount(); viewModel.roleCount = userModule.getRolesCount();