Upgrade to comply with latest CDMF changes

revert-70aa11f8
charitha 8 years ago
parent a0050d8f4d
commit f22d392978

@ -24,8 +24,6 @@ import io.swagger.annotations.ApiModelProperty;
public class BasePaginatedResult { public class BasePaginatedResult {
private int count; private int count;
private String next;
private String previous;
/** /**
* Number of Resources returned. * Number of Resources returned.

@ -44,10 +44,7 @@ public class DeviceGroupList extends BasePaginatedResult {
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("{\n"); sb.append("{\n");
sb.append(" count: ").append(getCount()).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(" groups: [").append(deviceGroups).append("\n");
sb.append("]}\n"); sb.append("]}\n");
return sb.toString(); return sb.toString();

@ -44,8 +44,6 @@ public class DeviceGroupUsersList extends BasePaginatedResult {
sb.append("{\n"); sb.append("{\n");
sb.append(" count: ").append(getCount()).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(" users: [").append(users).append("\n");
sb.append("]}\n"); sb.append("]}\n");
return sb.toString(); return sb.toString();

@ -16,6 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.mgt.jaxrs.service.api; package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
@ -110,6 +111,49 @@ public interface GroupManagementService {
value = "Maximum size of resource array to return.") value = "Maximum size of resource array to return.")
@QueryParam("limit") int limit); @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 @POST
@ApiOperation( @ApiOperation(
consumes = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON,
@ -170,7 +214,7 @@ public interface GroupManagementService {
required = true) required = true)
@Valid DeviceGroup group); @Valid DeviceGroup group);
@Path("/{groupName}") @Path("/name/{groupName}")
@GET @GET
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -217,7 +261,7 @@ public interface GroupManagementService {
required = true) required = true)
@PathParam("groupName") String groupName); @PathParam("groupName") String groupName);
@Path("/{groupName}") @Path("/name/{groupName}")
@PUT @PUT
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -269,7 +313,7 @@ public interface GroupManagementService {
required = true) required = true)
@Valid DeviceGroup deviceGroup); @Valid DeviceGroup deviceGroup);
@Path("/{groupName}") @Path("/name/{groupName}")
@DELETE @DELETE
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -316,7 +360,7 @@ public interface GroupManagementService {
required = true) required = true)
@PathParam("groupName") String groupName); @PathParam("groupName") String groupName);
@Path("/{groupName}/share") @Path("/name/{groupName}/share")
@POST @POST
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -368,7 +412,7 @@ public interface GroupManagementService {
required = true) required = true)
@Valid DeviceGroupShare deviceGroupShare); @Valid DeviceGroupShare deviceGroupShare);
@Path("/{groupName}/users") @Path("/name/{groupName}/users")
@GET @GET
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -415,7 +459,7 @@ public interface GroupManagementService {
required = true) required = true)
@PathParam("groupName") String groupName); @PathParam("groupName") String groupName);
@Path("/{groupName}/devices") @Path("/name/{groupName}/devices")
@GET @GET
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -470,7 +514,54 @@ public interface GroupManagementService {
value = "Maximum size of resource array to return.") value = "Maximum size of resource array to return.")
@QueryParam("limit") int limit); @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 @POST
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -521,7 +612,7 @@ public interface GroupManagementService {
required = true) required = true)
@Valid List<DeviceIdentifier> deviceIdentifiers); @Valid List<DeviceIdentifier> deviceIdentifiers);
@Path("/{groupName}/devices") @Path("/name/{groupName}/devices")
@DELETE @DELETE
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,

@ -16,6 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; package org.wso2.carbon.device.mgt.jaxrs.service.api.admin;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
@ -24,13 +25,14 @@ import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ResponseHeader; 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.API;
import org.wso2.carbon.apimgt.annotations.api.Permission; 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.Consumes;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
@ -50,60 +52,92 @@ public interface GroupManagementAdminService {
@GET @GET
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = HTTPConstants.HEADER_GET,
value = "Get groups by the name.", value = "Get the list of groups.",
notes = "Get devices the name of device and tenant.", notes = "Returns all groups enrolled with the system.",
response = DeviceGroupWrapper.class, tags = "Device Group Management")
responseContainer = "List", @ApiResponses(value = {
tags = "Group Management Administrative Service") @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 = { @ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of groups.", @ApiResponse(code = 200, message = "OK. \n Successfully fetched the device group count.",
response = DeviceGroupWrapper.class, response = DeviceGroupList.class,
responseContainer = "List", responseHeaders = {
responseHeaders = { @ResponseHeader(
@ResponseHeader( name = "Content-Type",
name = "Content-Type", description = "The content type of the body"),
description = "The content type of the body"), @ResponseHeader(
@ResponseHeader( name = "ETag",
name = "ETag", description = "Entity Tag of the response resource.\n" +
description = "Entity Tag of the response resource.\n" + "Used by caches, or in conditional requests."),
"Used by caches, or in conditional requests."), @ResponseHeader(
@ResponseHeader( name = "Last-Modified",
name = "Last-Modified", description = "Date and time the resource has been modified the last time.\n" +
description = "Date and time the resource has been modified the last time.\n" + "Used by caches, or in conditional requests."),
"Used by caches, or in conditional requests."), }),
}),
@ApiResponse( @ApiResponse(
code = 304, code = 304,
message = "Not Modified. \n Empty body because the client has already the latest version of the " + message = "Not Modified. \n Empty body because the client has already the latest version of " +
"requested resource."), "the requested resource."),
@ApiResponse(
code = 404,
message = "No groups found.",
response = ErrorResponse.class),
@ApiResponse( @ApiResponse(
code = 406, 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( @ApiResponse(
code = 500, 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") @Permission(name = "View Groups", permission = "/device-mgt/admin/groups/view")
Response getGroupsOfUser( Response getGroupCount();
@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);
} }

@ -16,6 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.mgt.jaxrs.service.impl; package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import org.apache.commons.logging.Log; 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.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupList;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupShare; 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.api.GroupManagementService;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; 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 javax.ws.rs.core.Response;
import java.util.ArrayList; import java.util.Date;
import java.util.List; import java.util.List;
@Path("/groups")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class GroupManagementServiceImpl implements GroupManagementService { public class GroupManagementServiceImpl implements GroupManagementService {
private static final Log log = LogFactory.getLog(GroupManagementServiceImpl.class); 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 @Override
public Response getGroups(int offset, int limit) { public Response getGroups(int offset, int limit) {
try { try {
List<DeviceGroupWrapper> groupWrappers = new ArrayList<>();
GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService();
String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
List<DeviceGroup> deviceGroups = service.getGroups(currentUser); List<DeviceGroup> deviceGroups = service.getGroups(currentUser, offset, limit);
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); DeviceGroupList deviceGroupList = new DeviceGroupList();
for (DeviceGroup dg : deviceGroups) { deviceGroupList.setList(deviceGroups);
DeviceGroupWrapper gw = new DeviceGroupWrapper(); deviceGroupList.setCount(service.getGroupCount(currentUser));
gw.setId(dg.getId()); return Response.status(Response.Status.OK).entity(deviceGroupList).build();
gw.setOwner(dg.getOwner());
gw.setName(dg.getName());
gw.setTenantId(tenantId);
groupWrappers.add(gw);
}
return Response.status(Response.Status.OK).entity(groupWrappers).build();
} catch (GroupManagementException e) { } 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); log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); 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 @Override
public Response createGroup(DeviceGroup group) { 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 @Override
@ -106,12 +129,18 @@ public class GroupManagementServiceImpl implements GroupManagementService {
} }
@Override @Override
public Response addDeviceToGroup(String groupName, DeviceIdentifier deviceIdentifier) { public Response getDeviceCountOfGroup(String groupName) {
return null; return null;
} }
@Override @Override
public Response removeDevicesFromGroup(String groupName, String type, String id) { public Response addDevicesToGroup(String groupName, List<DeviceIdentifier> deviceIdentifiers) {
return null; return null;
} }
}
@Override
public Response removeDevicesFromGroup(String groupName, List<DeviceIdentifier> deviceIdentifiers) {
return null;
}
}

@ -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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceGroupList;
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.GroupManagementAdminService; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.GroupManagementAdminService;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List;
@Path("/admin/groups") @Path("/admin/groups")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ -41,26 +43,35 @@ public class GroupManagementAdminServiceImpl implements GroupManagementAdminServ
private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class); private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class);
@GET
@Override @Override
public Response getGroupsOfUser( public Response getGroups(int offset, int limit) {
@QueryParam("username") String username,
@HeaderParam("If-Modified-Since") String timestamp,
@QueryParam("offset") int offset,
@QueryParam("limit") int limit) {
try { try {
PaginationResult result = GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService();
DeviceMgtAPIUtils.getGroupManagementProviderService().getGroups(username, offset, limit); List<DeviceGroup> deviceGroups = service.getGroups(offset, limit);
if (result != null && result.getRecordsTotal() > 0) { DeviceGroupList deviceGroupList = new DeviceGroupList();
return Response.status(Response.Status.OK).entity(result).build(); deviceGroupList.setList(deviceGroups);
deviceGroupList.setCount(service.getGroupCount());
if (deviceGroups != null && deviceGroups.size() > 0) {
return Response.status(Response.Status.OK).entity(deviceGroupList).build();
} else { } else {
return Response.status(Response.Status.NOT_FOUND).build(); return Response.status(Response.Status.NOT_FOUND).build();
} }
} catch (GroupManagementException e) { } 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); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@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();
}
}
} }

@ -34,7 +34,7 @@
<ref bean="roleManagementService"/> <ref bean="roleManagementService"/>
<ref bean="userManagementService"/> <ref bean="userManagementService"/>
<ref bean="userManagementAdminService"/> <ref bean="userManagementAdminService"/>
<!--<ref bean="groupManagementService"/>--> <ref bean="groupManagementService"/>
<ref bean="groupManagementAdminService"/> <ref bean="groupManagementAdminService"/>
<ref bean="applicationManagementAdminService"/> <ref bean="applicationManagementAdminService"/>
<ref bean="deviceTypeManagementAdminService"/> <ref bean="deviceTypeManagementAdminService"/>

@ -33,8 +33,7 @@ public class DeviceGroup implements Serializable {
private static final long serialVersionUID = 1998121711L; private static final long serialVersionUID = 1998121711L;
@ApiModelProperty(name = "id", value = "ID of the device group in the device group information database.", @ApiModelProperty(name = "id", value = "ID of the device group in the device group information database.")
required = true)
private int id; private int id;
@ApiModelProperty(name = "description", value = "The device group description that can be set on the device group by the user.", @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<GroupUser> users; private List<GroupUser> users;
private List<String> roles; private List<String> roles;
public int getId() { public int getGroupId() {
return id; return id;
} }
public void setId(int id) { public void setGroupId(int id) {
this.id = id; this.id = id;
} }
@ -103,7 +102,7 @@ public class DeviceGroup implements Serializable {
return users; return users;
} }
protected void setUsers(List<GroupUser> users) { public void setUsers(List<GroupUser> users) {
this.users = users; this.users = users;
} }
@ -111,21 +110,8 @@ public class DeviceGroup implements Serializable {
return roles; return roles;
} }
protected void setRoles(List<String> roles) { public void setRoles(List<String> roles) {
this.roles = 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;
}
} }

@ -203,7 +203,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
Iterator<DeviceGroup> groupsWithDeviceIterator = groupsWithDevice.iterator(); Iterator<DeviceGroup> groupsWithDeviceIterator = groupsWithDevice.iterator();
while (groupsWithDeviceIterator.hasNext()) { while (groupsWithDeviceIterator.hasNext()) {
DeviceGroup deviceGroup = groupsWithDeviceIterator.next(); DeviceGroup deviceGroup = groupsWithDeviceIterator.next();
if (deviceGroup.getId() == group.getId()) { if (deviceGroup.getGroupId() == group.getGroupId()) {
return true; return true;
} }
} }

@ -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<GroupUser> users) {
super.setUsers(users);
}
@Override
public void setRoles(List<String> roles) {
super.setRoles(roles);
}
@Override
public DeviceGroup getGroup() {
return super.getGroup();
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
}

@ -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.Device;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
import java.util.List; import java.util.List;
@ -68,8 +67,7 @@ public interface GroupDAO {
* @return Device Group in tenant with specified name. * @return Device Group in tenant with specified name.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException; DeviceGroup getGroup(int groupId, int tenantId) throws GroupManagementDAOException;
/** /**
* Get device group by name. * Get device group by name.
@ -80,7 +78,7 @@ public interface GroupDAO {
* @return Device Group in tenant with specified name. * @return Device Group in tenant with specified name.
* @throws GroupManagementDAOException * @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 * Get the groups of device with device id provided
@ -88,7 +86,7 @@ public interface GroupDAO {
* @return * @return
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
List<DeviceGroupBuilder> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException; List<DeviceGroup> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException;
/** /**
* Get the list of Device Groups in tenant. * Get the list of Device Groups in tenant.
@ -99,7 +97,7 @@ public interface GroupDAO {
* @return List of all Device Groups in tenant. * @return List of all Device Groups in tenant.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
List<DeviceGroupBuilder> getGroups(int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException; List<DeviceGroup> 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. * @return List of DeviceGroup that matches with the given DeviceGroup name.
* @throws GroupManagementDAOException * @throws GroupManagementDAOException
*/ */
List<DeviceGroupBuilder> findInGroups(String groupName, int tenantId) throws GroupManagementDAOException; List<DeviceGroup> findInGroups(String groupName, int tenantId) throws GroupManagementDAOException;
/** /**
* Check group already existed with given name. * Check group already existed with given name.

@ -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.Device;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -127,7 +126,7 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException { public DeviceGroup getGroup(int groupId, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
try { try {
@ -152,7 +151,7 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public DeviceGroupBuilder getGroup(String groupName, String owner, int tenantId) public DeviceGroup getGroup(String groupName, String owner, int tenantId)
throws GroupManagementDAOException { throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
@ -179,11 +178,11 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public List<DeviceGroupBuilder> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException { public List<DeviceGroup> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<DeviceGroupBuilder> deviceGroupBuilders = new ArrayList<>(); List<DeviceGroup> deviceGroupBuilders = new ArrayList<>();
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT G.ID, G.GROUP_NAME, G.DESCRIPTION, G.DATE_OF_CREATE, G.DATE_OF_LAST_UPDATE, \n" + String sql = "SELECT G.ID, G.GROUP_NAME, G.DESCRIPTION, G.DATE_OF_CREATE, G.DATE_OF_LAST_UPDATE, \n" +
@ -205,11 +204,11 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public List<DeviceGroupBuilder> getGroups(int startIndex, int rowCount, int tenantId) public List<DeviceGroup> getGroups(int startIndex, int rowCount, int tenantId)
throws GroupManagementDAOException { throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<DeviceGroupBuilder> deviceGroupList = null; List<DeviceGroup> deviceGroupList = null;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER "
@ -256,11 +255,11 @@ public class GroupDAOImpl implements GroupDAO {
} }
@Override @Override
public List<DeviceGroupBuilder> findInGroups(String groupName, int tenantId) public List<DeviceGroup> findInGroups(String groupName, int tenantId)
throws GroupManagementDAOException { throws GroupManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<DeviceGroupBuilder> deviceGroups = new ArrayList<>(); List<DeviceGroup> deviceGroups = new ArrayList<>();
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER " String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER "

@ -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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
import javax.naming.InitialContext; import javax.naming.InitialContext;
import javax.sql.DataSource; import javax.sql.DataSource;
@ -80,8 +79,8 @@ public final class GroupManagementDAOUtil {
} }
} }
public static DeviceGroupBuilder loadGroup(ResultSet resultSet) throws SQLException { public static DeviceGroup loadGroup(ResultSet resultSet) throws SQLException {
DeviceGroupBuilder group = new DeviceGroupBuilder(new DeviceGroup()); DeviceGroup group = new DeviceGroup();
group.setGroupId(resultSet.getInt("ID")); group.setGroupId(resultSet.getInt("ID"));
group.setDescription(resultSet.getString("DESCRIPTION")); group.setDescription(resultSet.getString("DESCRIPTION"));
group.setName(resultSet.getString("GROUP_NAME")); group.setName(resultSet.getString("GROUP_NAME"));

@ -60,6 +60,7 @@ public interface GroupManagementProviderService {
* *
* @param groupName to be deleted. * @param groupName to be deleted.
* @param owner of the group. * @param owner of the group.
* @return status of the delete operation.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
boolean deleteGroup(String groupName, String owner) throws GroupManagementException; boolean deleteGroup(String groupName, String owner) throws GroupManagementException;
@ -84,25 +85,15 @@ public interface GroupManagementProviderService {
*/ */
DeviceGroup getGroup(int groupId) throws GroupManagementException; 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<DeviceGroup> findInGroups(String groupName, String username) throws GroupManagementException;
/** /**
* Get paginated device groups in tenant * Get paginated device groups in tenant
* *
* @param startIndex for pagination. * @param startIndex for pagination.
* @param rowCount for pagination. * @param rowCount for pagination.
* @return paginated list of groups * @return list of groups.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
PaginationResult getGroups(int startIndex, int rowCount) throws GroupManagementException; List<DeviceGroup> getGroups(int startIndex, int rowCount) throws GroupManagementException;
/** /**
* Get paginated device groups in tenant * Get paginated device groups in tenant
@ -110,10 +101,10 @@ public interface GroupManagementProviderService {
* @param username of user. * @param username of user.
* @param startIndex for pagination. * @param startIndex for pagination.
* @param rowCount for pagination. * @param rowCount for pagination.
* @return paginated list of groups * @return list of groups
* @throws GroupManagementException * @throws GroupManagementException
*/ */
PaginationResult getGroups(String username, int startIndex, int rowCount) throws GroupManagementException; List<DeviceGroup> getGroups(String username, int startIndex, int rowCount) throws GroupManagementException;
/** /**
* Get all device group count in tenant * Get all device group count in tenant
@ -123,15 +114,6 @@ public interface GroupManagementProviderService {
*/ */
int getGroupCount() throws GroupManagementException; int getGroupCount() throws GroupManagementException;
/**
* Get device groups of user
*
* @param username of the user
* @return list of groups
* @throws GroupManagementException
*/
List<DeviceGroup> getGroups(String username) throws GroupManagementException;
/** /**
* Get device group count of user * Get device group count of user
* *
@ -224,16 +206,6 @@ public interface GroupManagementProviderService {
*/ */
List<GroupUser> getUsers(String groupName, String owner) throws GroupManagementException; List<GroupUser> 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<Device> getDevices(String groupName, String owner) throws GroupManagementException;
/** /**
* Get all devices in device group as paginated result. * Get all devices in device group as paginated result.
* *
@ -241,10 +213,10 @@ public interface GroupManagementProviderService {
* @param owner of the group. * @param owner of the group.
* @param startIndex for pagination. * @param startIndex for pagination.
* @param rowCount for pagination. * @param rowCount for pagination.
* @return Paginated list of devices. * @return list of devices in group.
* @throws GroupManagementException * @throws GroupManagementException
*/ */
PaginationResult getDevices(String groupName, String owner, int startIndex, int rowCount) List<Device> getDevices(String groupName, String owner, int startIndex, int rowCount)
throws GroupManagementException; throws GroupManagementException;
/** /**

@ -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.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
import org.wso2.carbon.device.mgt.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.GroupDAO;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOException; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOException;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory;
@ -65,14 +64,13 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
if (deviceGroup == null) { if (deviceGroup == null) {
throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException()); throw new GroupManagementException("DeviceGroup cannot be null.", new NullPointerException());
} }
DeviceGroupBuilder groupBroker = new DeviceGroupBuilder(deviceGroup);
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
int groupId = -1; int groupId = -1;
try { try {
GroupManagementDAOFactory.beginTransaction(); GroupManagementDAOFactory.beginTransaction();
boolean nameIsExists = this.groupDAO.isGroupExist(deviceGroup.getName(), deviceGroup.getOwner(), tenantId); boolean nameIsExists = this.groupDAO.isGroupExist(deviceGroup.getName(), deviceGroup.getOwner(), tenantId);
if (!nameIsExists) { if (!nameIsExists) {
groupId = this.groupDAO.addGroup(groupBroker, tenantId); groupId = this.groupDAO.addGroup(deviceGroup, tenantId);
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
} else { } else {
throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName()); throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName());
@ -87,9 +85,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
addGroupSharingRole(groupBroker.getOwner(), groupId, defaultRole, defaultPermissions); addGroupSharingRole(deviceGroup.getOwner(), groupId, defaultRole, defaultPermissions);
if (log.isDebugEnabled()) { 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 @Override
public boolean deleteGroup(String groupName, String owner) throws GroupManagementException { public boolean deleteGroup(String groupName, String owner) throws GroupManagementException {
String roleName; String roleName;
DeviceGroupBuilder deviceGroup = getGroupBuilder(groupName, owner); DeviceGroup deviceGroup = buildDeviceGroup(groupName, owner);
if (deviceGroup == null) { if (deviceGroup == null) {
return false; return false;
} }
@ -160,16 +158,15 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
*/ */
@Override @Override
public DeviceGroup getGroup(String groupName, String owner) throws GroupManagementException { public DeviceGroup getGroup(String groupName, String owner) throws GroupManagementException {
return getGroupBuilder(groupName, owner).getGroup(); return buildDeviceGroup(groupName, owner);
} }
@SuppressWarnings("Duplicates") private DeviceGroup buildDeviceGroup(String groupName, String owner) throws GroupManagementException {
private DeviceGroupBuilder getGroupBuilder(String groupName, String owner) throws GroupManagementException { DeviceGroup deviceGroup;
DeviceGroupBuilder deviceGroupBuilder;
try { try {
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
deviceGroupBuilder = this.groupDAO.getGroup(groupName, owner, tenantId); deviceGroup = this.groupDAO.getGroup(groupName, owner, tenantId);
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while obtaining group '" + groupName + "'", e); throw new GroupManagementException("Error occurred while obtaining group '" + groupName + "'", e);
} catch (SQLException e) { } catch (SQLException e) {
@ -177,19 +174,19 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
if (deviceGroupBuilder != null) { if (deviceGroup != null) {
deviceGroupBuilder.setUsers(this.getUsers(deviceGroupBuilder.getGroupId())); deviceGroup.setUsers(this.getUsers(deviceGroup.getGroupId()));
deviceGroupBuilder.setRoles(this.getRoles(deviceGroupBuilder.getGroupId())); deviceGroup.setRoles(this.getRoles(deviceGroup.getGroupId()));
} }
return deviceGroupBuilder; return deviceGroup;
} }
private DeviceGroupBuilder getGroupBuilder(int groupId) throws GroupManagementException { private DeviceGroup buildDeviceGroup(int groupId) throws GroupManagementException {
DeviceGroupBuilder groupBroker; DeviceGroup deviceGroup;
try { try {
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
groupBroker = this.groupDAO.getGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId()); deviceGroup = this.groupDAO.getGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId());
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while obtaining group '" + groupId + "'", e); throw new GroupManagementException("Error occurred while obtaining group '" + groupId + "'", e);
} catch (SQLException e) { } catch (SQLException e) {
@ -197,11 +194,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
if (groupBroker != null) { if (deviceGroup != null) {
groupBroker.setUsers(this.getUsers(groupBroker.getGroupId())); deviceGroup.setUsers(this.getUsers(groupId));
groupBroker.setRoles(this.getRoles(groupBroker.getGroupId())); deviceGroup.setRoles(this.getRoles(groupId));
} }
return groupBroker; return deviceGroup;
} }
/** /**
@ -209,43 +206,17 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
*/ */
@Override @Override
public DeviceGroup getGroup(int groupId) throws GroupManagementException { public DeviceGroup getGroup(int groupId) throws GroupManagementException {
DeviceGroupBuilder groupBroker = this.getGroupBuilder(groupId); DeviceGroup deviceGroup = this.buildDeviceGroup(groupId);
if (groupBroker != null) { if (deviceGroup != null) {
groupBroker.setUsers(this.getUsers(groupBroker.getGroupId())); deviceGroup.setUsers(this.getUsers(groupId));
groupBroker.setRoles(this.getRoles(groupBroker.getGroupId())); deviceGroup.setRoles(this.getRoles(groupId));
} }
return groupBroker.getGroup(); return deviceGroup;
}
/**
* {@inheritDoc}
*/
@Override
public List<DeviceGroup> findInGroups(String groupName, String owner) throws GroupManagementException {
List<DeviceGroupBuilder> 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<DeviceGroup> 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;
} }
@Override @Override
public PaginationResult getGroups(int startIndex, int rowCount) throws GroupManagementException { public List<DeviceGroup> getGroups(int startIndex, int rowCount) throws GroupManagementException {
List<DeviceGroupBuilder> deviceGroups = new ArrayList<>(); List<DeviceGroup> deviceGroups = new ArrayList<>();
try { try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
@ -257,21 +228,15 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
List<DeviceGroup> groupsWithData = new ArrayList<>(); for (DeviceGroup group : deviceGroups) {
for (DeviceGroupBuilder groupBroker : deviceGroups) { group.setUsers(this.getUsers(group.getGroupId()));
groupBroker.setUsers(this.getUsers(groupBroker.getGroupId())); group.setRoles(this.getRoles(group.getGroupId()));
groupBroker.setRoles(this.getRoles(groupBroker.getGroupId()));
groupsWithData.add(groupBroker.getGroup());
} }
PaginationResult paginationResult = new PaginationResult(); return deviceGroups;
paginationResult.setRecordsTotal(getGroupCount());
paginationResult.setData(groupsWithData);
paginationResult.setRecordsFiltered(groupsWithData.size());
return paginationResult;
} }
@Override @Override
public PaginationResult getGroups(String username, int startIndex, int rowCount) throws GroupManagementException { public List<DeviceGroup> getGroups(String username, int startIndex, int rowCount) throws GroupManagementException {
Map<Integer, DeviceGroup> groups = new HashMap<>(); Map<Integer, DeviceGroup> groups = new HashMap<>();
UserStoreManager userStoreManager; UserStoreManager userStoreManager;
try { try {
@ -282,20 +247,16 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
int index = 0; int index = 0;
for (String role : roleList) { for (String role : roleList) {
if (role != null && role.contains("Internal/group-")) { if (role != null && role.contains("Internal/group-")) {
DeviceGroupBuilder deviceGroupBuilder = extractNewGroupFromRole(groups, role); DeviceGroup deviceGroupBuilder = extractNewGroupFromRole(groups, role);
if (deviceGroupBuilder != null && startIndex <= index++ && index <= rowCount) { if (deviceGroupBuilder != null && startIndex <= index++ && index <= rowCount) {
groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder.getGroup()); groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder);
} }
} }
} }
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new GroupManagementException("Error occurred while getting user store manager.", e); throw new GroupManagementException("Error occurred while getting user store manager.", e);
} }
PaginationResult paginationResult = new PaginationResult(); return new ArrayList<>(groups.values());
paginationResult.setRecordsTotal(getGroupCount());
paginationResult.setData(new ArrayList<>(groups.values()));
paginationResult.setRecordsFiltered(groups.size());
return paginationResult;
} }
@Override @Override
@ -313,32 +274,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} }
} }
/**
* {@inheritDoc}
*/
@Override
public List<DeviceGroup> 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<Integer, DeviceGroup> 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} * {@inheritDoc}
*/ */
@ -421,11 +356,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} }
private int getGroupId(String groupName, String owner) throws GroupManagementException { private int getGroupId(String groupName, String owner) throws GroupManagementException {
DeviceGroupBuilder deviceGroupBuilder = getGroupBuilder(groupName, owner); DeviceGroup deviceGroup = buildDeviceGroup(groupName, owner);
if (deviceGroupBuilder == null) { if (deviceGroup == null) {
return -1; return -1;
} }
return deviceGroupBuilder.getGroupId(); return deviceGroup.getGroupId();
} }
/** /**
@ -610,25 +545,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List<Device> getDevices(String groupName, String owner) throws GroupManagementException { public List<Device> getDevices(String groupName, String owner, int startIndex, int rowCount)
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)
throws GroupManagementException { throws GroupManagementException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
List<Device> devices; List<Device> devices;
@ -642,11 +559,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
PaginationResult paginationResult = new PaginationResult(); return devices;
paginationResult.setRecordsTotal(getDeviceCount(groupName, owner));
paginationResult.setData(devices);
paginationResult.setRecordsFiltered(devices.size());
return paginationResult;
} }
/** /**
@ -774,9 +687,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
for (String role : roles) { for (String role : roles) {
if (role != null && role.contains("Internal/group-") && userRealm.getAuthorizationManager() if (role != null && role.contains("Internal/group-") && userRealm.getAuthorizationManager()
.isRoleAuthorized(role, permission, CarbonConstants.UI_PERMISSION_ACTION)) { .isRoleAuthorized(role, permission, CarbonConstants.UI_PERMISSION_ACTION)) {
DeviceGroupBuilder deviceGroupBuilder = extractNewGroupFromRole(groups, role); DeviceGroup group = extractNewGroupFromRole(groups, role);
if (deviceGroupBuilder != null) { if (group != null) {
groups.put(deviceGroupBuilder.getGroupId(), deviceGroupBuilder.getGroup()); groups.put(group.getGroupId(), group);
} }
} }
} }
@ -789,15 +702,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
@Override @Override
public List<DeviceGroup> getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException { public List<DeviceGroup> getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException {
DeviceManagementProviderService managementProviderService = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService managementProviderService = new DeviceManagementProviderServiceImpl();
List<DeviceGroup> deviceGroups = new ArrayList<>();
try { try {
Device device = managementProviderService.getDevice(deviceIdentifier); Device device = managementProviderService.getDevice(deviceIdentifier);
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
List<DeviceGroupBuilder> builders = groupDAO.getGroups(device.getId(), return groupDAO.getGroups(device.getId(),
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
for (DeviceGroupBuilder d : builders){
deviceGroups.add(d.getGroup());
}
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
throw new GroupManagementException("Error occurred while retrieving the device details.", e); throw new GroupManagementException("Error occurred while retrieving the device details.", e);
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
@ -807,15 +716,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} finally { } finally {
GroupManagementDAOFactory.closeConnection(); GroupManagementDAOFactory.closeConnection();
} }
return deviceGroups;
} }
private DeviceGroupBuilder extractNewGroupFromRole(Map<Integer, DeviceGroup> groups, String role) private DeviceGroup extractNewGroupFromRole(Map<Integer, DeviceGroup> groups, String role)
throws GroupManagementException { throws GroupManagementException {
try { try {
int groupId = Integer.parseInt(role.split("-")[1]); int groupId = Integer.parseInt(role.split("-")[1]);
if (!groups.containsKey(groupId)) { if (!groups.containsKey(groupId)) {
return getGroupBuilder(groupId); return buildDeviceGroup(groupId);
} }
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
log.error("Unable to extract groupId from role " + role, e); log.error("Unable to extract groupId from role " + role, e);

@ -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.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; 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.Date;
import java.util.Properties; import java.util.Properties;
@ -82,7 +81,6 @@ public class TestDataHolder {
deviceGroup.setDateOfCreation(new Date().getTime()); deviceGroup.setDateOfCreation(new Date().getTime());
deviceGroup.setDateOfLastUpdate(new Date().getTime()); deviceGroup.setDateOfLastUpdate(new Date().getTime());
deviceGroup.setOwner(OWNER); deviceGroup.setOwner(OWNER);
DeviceGroupBuilder broker = new DeviceGroupBuilder(deviceGroup); return deviceGroup;
return broker.getGroup();
} }
} }

@ -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.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest; import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
import org.wso2.carbon.device.mgt.core.common.TestDataHolder; import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
import 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.GroupDAO;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOException; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOException;
import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory; import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory;
@ -80,7 +79,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
public void findGroupTest() { public void findGroupTest() {
try { try {
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
List<DeviceGroupBuilder> groups = groupDAO.findInGroups("Test", TestDataHolder.SUPER_TENANT_ID); List<DeviceGroup> groups = groupDAO.findInGroups("Test", TestDataHolder.SUPER_TENANT_ID);
Assert.assertNotEquals(groups.size(), 0, "No groups found"); Assert.assertNotEquals(groups.size(), 0, "No groups found");
Assert.assertNotNull(groups.get(0), "Group is null"); Assert.assertNotNull(groups.get(0), "Group is null");
log.debug("Group found: " + groups.get(0).getName()); log.debug("Group found: " + groups.get(0).getName());
@ -101,7 +100,7 @@ public class GroupPersistTests extends BaseDeviceManagementTest {
public void getGroupTest() { public void getGroupTest() {
try { try {
GroupManagementDAOFactory.openConnection(); GroupManagementDAOFactory.openConnection();
List<DeviceGroupBuilder> groups = groupDAO.getGroups(0, 100, TestDataHolder.SUPER_TENANT_ID); List<DeviceGroup> groups = groupDAO.getGroups(0, 100, TestDataHolder.SUPER_TENANT_ID);
Assert.assertNotEquals(groups.size(), 0, "No groups found"); Assert.assertNotEquals(groups.size(), 0, "No groups found");
Assert.assertNotNull(groups.get(0), "Group is null"); Assert.assertNotNull(groups.get(0), "Group is null");
log.debug("No of Groups found: " + groups.size()); log.debug("No of Groups found: " + groups.size());

@ -22,7 +22,7 @@ package org.wso2.carbon.policy.mgt.common;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; 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 { public class DeviceGroupWrapper {
@ApiModelProperty(name = "id", value = "Id of the group", required = true) @ApiModelProperty(name = "id", value = "Id of the group", required = true)

@ -231,7 +231,7 @@ public class PolicyManagerUtil {
public static Map<Integer, DeviceGroup> convertDeviceGroupMap(List<DeviceGroup> deviceGroups) { public static Map<Integer, DeviceGroup> convertDeviceGroupMap(List<DeviceGroup> deviceGroups) {
Map<Integer, DeviceGroup> groupMap = new HashMap<>(); Map<Integer, DeviceGroup> groupMap = new HashMap<>();
for (DeviceGroup dg: deviceGroups){ for (DeviceGroup dg: deviceGroups){
groupMap.put(dg.getId(), dg); groupMap.put(dg.getGroupId(), dg);
} }
return groupMap; return groupMap;
} }

Loading…
Cancel
Save