From 4236744d39c319d471fee34202ade0bbffe1c607 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Mon, 27 Jun 2016 14:20:38 +0530 Subject: [PATCH 01/11] Improving UserManagement and RoleManagement API implementations to return proper error codes when no role/user exists, etc --- .../beans/{RoleWrapper.java => RoleInfo.java} | 4 +- .../service/api/DeviceManagementService.java | 3 - .../service/api/RoleManagementService.java | 59 +-- .../service/api/UserManagementService.java | 47 +-- .../impl/DeviceManagementServiceImpl.java | 14 - .../impl/RoleManagementServiceImpl.java | 181 +++++----- .../impl/UserManagementServiceImpl.java | 340 ++++++++---------- .../impl/util/RequestValidationUtil.java | 4 +- .../SecurityDefinitionConfigurator.java | 58 +++ 9 files changed, 368 insertions(+), 342 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/{RoleWrapper.java => RoleInfo.java} (94%) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/swagger/extension/SecurityDefinitionConfigurator.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleInfo.java similarity index 94% rename from components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleWrapper.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleInfo.java index c0856021e2..e62b5a4a3c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleInfo.java @@ -22,9 +22,9 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.user.mgt.common.UIPermissionNode; -@ApiModel(value = "RoleWrapper", description = "Role details including permission and the users in the roles are " + +@ApiModel(value = "RoleInfo", description = "Role details including permission and the users in the roles are " + "wrapped here.") -public class RoleWrapper { +public class RoleInfo { @ApiModelProperty(name = "roleName", value = "The name of the role.", required = true) private String roleName; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index 7b5b61e2da..f82a9737b6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -603,7 +603,4 @@ public interface DeviceManagementService { required = false) @HeaderParam("If-Modified-Since") String ifModifiedSince); - @GET - @Path("/types") - Response getDeviceTypes(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java index 06f52e1dda..c58604a4a0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java @@ -21,10 +21,9 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.Permission; -import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; -import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper; import org.wso2.carbon.user.mgt.common.UIPermissionNode; import javax.ws.rs.*; @@ -70,16 +69,12 @@ public interface RoleManagementService { @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 = "Not Found. \n Resource does not exist.", - response = ErrorResponse.class), @ApiResponse( code = 406, message = "Not Acceptable.\n The requested media type is not supported"), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching requested list of roles.", + message = "Internal Server Error. \n Server error occurred while fetching requested list of roles.", response = ErrorResponse.class) }) @Permission(scope = "roles-view", permissions = { @@ -157,11 +152,12 @@ public interface RoleManagementService { response = ErrorResponse.class), @ApiResponse( code = 404, - message = "Not Found. \n Resource does not exist.", + message = "Not Found. \n Role does not exist.", 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", + response = ErrorResponse.class), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n Server error occurred while fetching the permission list of the requested role.", @@ -187,14 +183,14 @@ public interface RoleManagementService { httpMethod = "GET", value = "Get details of a role.", notes = "If you wish to get the details of a role in EMM, you can do so using this REST API.", - response = RoleWrapper.class, + response = RoleInfo.class, tags = "Role Management") @ApiResponses( value = { @ApiResponse( code = 200, message = "OK. \n Successfully fetched the requested role.", - response = RoleWrapper.class, + response = RoleInfo.class, responseHeaders = { @ResponseHeader( name = "Content-Type", @@ -218,14 +214,15 @@ public interface RoleManagementService { response = ErrorResponse.class), @ApiResponse( code = 404, - message = "Not Found. \n Resource does not exist.", + message = "Not Found. \n Role does not exist.", 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", + response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching the " + + message = "Internal Server Error. \n Server error occurred while fetching the " + "requested role.", response = ErrorResponse.class) }) @@ -282,11 +279,11 @@ public interface RoleManagementService { response = ErrorResponse.class), @ApiResponse( code = 415, - message = "Unsupported media type. \n The entity of the request was in a not supported format."), + message = "Unsupported media type. \n The entity of the request was in a not supported format.", + response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + - "Server error occurred while adding a new role.", + message = "Internal Server Error. \n Server error occurred while adding a new role.", response = ErrorResponse.class) }) @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/add"}) @@ -294,7 +291,7 @@ public interface RoleManagementService { @ApiParam( name = "role", value = "Details about the role to be added.", - required = true) RoleWrapper role); + required = true) RoleInfo role); @PUT @Path("/{roleName}") @@ -331,14 +328,15 @@ public interface RoleManagementService { response = ErrorResponse.class), @ApiResponse( code = 404, - message = "Not Found. \n Resource to be deleted does not exist."), + message = "Not Found. \n Role to be deleted does not exist.", + response = ErrorResponse.class), @ApiResponse( code = 415, - message = "Unsupported media type. \n The entity of the request was in a not supported format."), + message = "Unsupported media type. \n The entity of the request was in a not supported format.", + response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + - "Server error occurred while updating the role.", + message = "Internal Server Error. \n Server error occurred while updating the role.", response = ErrorResponse.class) }) @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"}) @@ -351,7 +349,7 @@ public interface RoleManagementService { @ApiParam( name = "role", value = "Details about the role to be added.", - required = true) RoleWrapper role); + required = true) RoleInfo role); @DELETE @Path("/{roleName}") @@ -371,11 +369,11 @@ public interface RoleManagementService { response = ErrorResponse.class), @ApiResponse( code = 404, - message = "Not Found. \n Resource to be deleted does not exist."), + message = "Not Found. \n Role to be deleted does not exist.", + response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + - "Server error occurred while removing the role.", + message = "Internal Server Error. \n Server error occurred while removing the role.", response = ErrorResponse.class) }) @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/remove"}) @@ -426,13 +424,16 @@ public interface RoleManagementService { response = ErrorResponse.class), @ApiResponse( code = 404, - message = "Not Found. \n Resource to be deleted does not exist."), + message = "Not Found. \n Resource to be deleted does not exist.", + response = ErrorResponse.class), @ApiResponse( code = 415, - message = "Unsupported media type. \n The entity of the request was in a not supported format."), + message = "Unsupported media type. \n The entity of the request was in a not " + + "supported format.", + response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while updating the user list of the role.", response = ErrorResponse.class) }) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java index fbbeb51736..2429c805ce 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java @@ -64,34 +64,29 @@ public interface UserManagementService { 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."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 409, - message = "Conflict. \n User already exist.", + message = "Conflict. \n User already exists.", response = ErrorResponse.class), @ApiResponse( code = 415, - message = "Unsupported media type. \n The entity of the request was in a not supported format."), + message = "Unsupported media type. \n The entity of the request was in a not " + + "supported format.", + response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + - "Server error occurred while adding a new user.", + message = "Internal Server Error. \n Server error occurred while adding a new user.", response = ErrorResponse.class) }) @Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/add"}) Response addUser( @ApiParam( name = "user", - value = "User related details.", + value = "Information of the user to be added", required = true) UserInfo user); @GET @@ -131,7 +126,8 @@ public interface UserManagementService { 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", + response = ErrorResponse.class), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n Server error occurred while" + @@ -182,14 +178,16 @@ public interface UserManagementService { "Used by caches, or in conditional requests.")}), @ApiResponse( code = 400, - message = "Bad Request. \n Invalid request or validation error."), + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), @ApiResponse( code = 404, message = "Not Found. \n Resource does not exist.", response = ErrorResponse.class), @ApiResponse( code = 415, - message = "Unsupported media type. \n The entity of the request was in a not supported format."), + message = "Unsupported media type. \n The entity of the request was in a not supported format.", + response = ErrorResponse.class), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + @@ -272,7 +270,8 @@ public interface UserManagementService { 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", + response = ErrorResponse.class), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n Server error occurred while fetching the role list" + @@ -296,7 +295,7 @@ public interface UserManagementService { @ApiResponse( code = 200, message = "OK. \n Successfully fetched the requested role.", - response = UserInfoList.class, + response = BasicUserInfoList.class, responseHeaders = { @ResponseHeader( name = "Content-Type", @@ -315,7 +314,8 @@ public interface UserManagementService { message = "Not Modified. \n Empty body because the client already has the latest version of the requested resource."), @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", + response = ErrorResponse.class), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n Server error occurred while fetching the user list.", @@ -380,7 +380,8 @@ public interface UserManagementService { message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."), @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", + response = ErrorResponse.class), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n Server error occurred while fetching the username " + @@ -429,10 +430,12 @@ public interface UserManagementService { response = ErrorResponse.class), @ApiResponse( code = 404, - message = "Not Found. \n Resource to be deleted does not exist."), + message = "Not Found. \n Resource to be deleted does not exist.", + response = ErrorResponse.class), @ApiResponse( code = 415, - message = "Unsupported media type. \n The entity of the request was in a not supported format."), + message = "Unsupported media type. \n The entity of the request was in a not supported format.", + response = ErrorResponse.class), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + 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 00b128e4b3..dca81e2ddd 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 @@ -314,18 +314,4 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } } - @Override - public Response getDeviceTypes() { - List deviceTypes; - try { - deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while fetching the list of device types."; - log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder(). - setCode(500l).setMessage(msg).build()); - } - return Response.status(Response.Status.OK).entity(deviceTypes).build(); - } - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java index 599d4345be..e885138e12 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo; import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException; @@ -30,7 +31,6 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; -import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper; import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; import org.wso2.carbon.user.api.*; import org.wso2.carbon.user.mgt.UserRealmProxy; @@ -40,6 +40,8 @@ import org.wso2.carbon.user.mgt.common.UserAdminException; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.net.URI; +import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -49,6 +51,7 @@ import java.util.List; @Consumes(MediaType.APPLICATION_JSON) public class RoleManagementServiceImpl implements RoleManagementService { + private static final String API_BASE_PATH = "/roles"; private static final Log log = LogFactory.getLog(RoleManagementServiceImpl.class); @GET @@ -61,18 +64,14 @@ public class RoleManagementServiceImpl implements RoleManagementService { List filteredRoles; RoleList targetRoles = new RoleList(); try { + //Get the total role count that matches the given filter filteredRoles = getRolesFromUserStore(filter); - if (filteredRoles == null || filteredRoles.size() == 0) { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No roles found.").build()); - } targetRoles.setCount(filteredRoles.size()); + filteredRoles = FilteringUtil.getFilteredList(getRolesFromUserStore(filter), offset, limit); - if (filteredRoles.size() == 0) { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No roles found").build()); - } targetRoles.setList(filteredRoles); + + Response.ok().entity(targetRoles).build(); } catch (UserStoreException e) { String msg = "Error occurred while retrieving roles from the underlying user stores"; log.error(msg, e); @@ -91,17 +90,16 @@ public class RoleManagementServiceImpl implements RoleManagementService { RequestValidationUtil.validateRoleName(roleName); try { final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); - org.wso2.carbon.user.core.UserRealm userRealmCore = null; - final UIPermissionNode rolePermissions; - if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { - userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; + if (!userRealm.getUserStoreManager().isExistingRole(roleName)) { + throw new NotFoundException(new ErrorResponse.ErrorResponseBuilder().setMessage( + "No role exists with the name '" + roleName + "'").build()); } - final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); - rolePermissions = this.getUIPermissionNode(roleName, userRealmProxy); + + final UIPermissionNode rolePermissions = this.getUIPermissionNode(roleName, userRealm); if (rolePermissions == null) { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No permissions found" + - " for the role '" + roleName + "'").build()); + if (log.isDebugEnabled()) { + log.debug("No permissions found for the role '" + roleName + "'"); + } } return Response.status(Response.Status.OK).entity(rolePermissions).build(); } catch (UserAdminException e) { @@ -118,8 +116,13 @@ public class RoleManagementServiceImpl implements RoleManagementService { } } - private UIPermissionNode getUIPermissionNode(String roleName, UserRealmProxy userRealmProxy) + private UIPermissionNode getUIPermissionNode(String roleName, UserRealm userRealm) throws UserAdminException { + org.wso2.carbon.user.core.UserRealm userRealmCore = null; + if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { + userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; + } + final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); final UIPermissionNode rolePermissions = userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID); UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2]; @@ -144,42 +147,35 @@ public class RoleManagementServiceImpl implements RoleManagementService { @Override public Response getRole(@PathParam("roleName") String roleName, @HeaderParam("If-Modified-Since") String ifModifiedSince) { + if (log.isDebugEnabled()) { + log.debug("Getting the list of user roles"); + } RequestValidationUtil.validateRoleName(roleName); - RoleWrapper roleWrapper = new RoleWrapper(); + RoleInfo roleInfo = new RoleInfo(); try { final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); - org.wso2.carbon.user.core.UserRealm userRealmCore = null; - if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { - userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; - } - - final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); - if (log.isDebugEnabled()) { - log.debug("Getting the list of user roles"); - } - if (userStoreManager.isExistingRole(roleName)) { - roleWrapper.setRoleName(roleName); - roleWrapper.setUsers(userStoreManager.getUserListOfRole(roleName)); - // Get the permission nodes and hand picking only device management and login perms - final UIPermissionNode rolePermissions = getUIPermissionNode(roleName, userRealmProxy); - List permList = new ArrayList<>(); - this.iteratePermissions(rolePermissions, permList); - roleWrapper.setPermissionList(rolePermissions); - String[] permListAr = new String[permList.size()]; - roleWrapper.setPermissions(permList.toArray(permListAr)); - } else { + if (!userStoreManager.isExistingRole(roleName)) { throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("Role name doesn't exist.") - .build()); + new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + + roleName + "'").build()); } + roleInfo.setRoleName(roleName); + roleInfo.setUsers(userStoreManager.getUserListOfRole(roleName)); + // Get the permission nodes and hand picking only device management and login perms + final UIPermissionNode rolePermissions = this.getUIPermissionNode(roleName, userRealm); + List permList = new ArrayList<>(); + this.iteratePermissions(rolePermissions, permList); + roleInfo.setPermissionList(rolePermissions); + String[] permListAr = new String[permList.size()]; + roleInfo.setPermissions(permList.toArray(permListAr)); } catch (UserStoreException | UserAdminException e) { String msg = "Error occurred while retrieving the user role '" + roleName + "'"; log.error(msg, e); throw new UnexpectedServerErrorException( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); } - return Response.status(Response.Status.OK).entity(roleWrapper).build(); + return Response.status(Response.Status.OK).entity(roleInfo).build(); } private List iteratePermissions(UIPermissionNode uiPermissionNode, List list) { @@ -194,78 +190,94 @@ public class RoleManagementServiceImpl implements RoleManagementService { @POST @Override - public Response addRole(RoleWrapper roleWrapper) { - RequestValidationUtil.validateRoleDetails(roleWrapper); - RequestValidationUtil.validateRoleName(roleWrapper.getRoleName()); + public Response addRole(RoleInfo roleInfo) { + RequestValidationUtil.validateRoleDetails(roleInfo); + RequestValidationUtil.validateRoleName(roleInfo.getRoleName()); try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (log.isDebugEnabled()) { - log.debug("Persisting the role to user store"); + log.debug("Persisting the role in the underlying user store"); } Permission[] permissions = null; - if (roleWrapper.getPermissions() != null && roleWrapper.getPermissions().length > 0) { - permissions = new Permission[roleWrapper.getPermissions().length]; - + if (roleInfo.getPermissions() != null && roleInfo.getPermissions().length > 0) { + permissions = new Permission[roleInfo.getPermissions().length]; for (int i = 0; i < permissions.length; i++) { - String permission = roleWrapper.getPermissions()[i]; + String permission = roleInfo.getPermissions()[i]; permissions[i] = new Permission(permission, CarbonConstants.UI_PERMISSION_ACTION); } } - userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions); + userStoreManager.addRole(roleInfo.getRoleName(), roleInfo.getUsers(), permissions); + + //TODO fix what's returned in the entity + return Response.created(new URI(API_BASE_PATH + "/" + roleInfo.getRoleName())).entity( + "Role '" + roleInfo.getRoleName() + "' has " + + "successfully been added").build(); } catch (UserStoreException e) { - String msg = "Error occurred while adding role '" + roleWrapper.getRoleName() + "'"; + String msg = "Error occurred while adding role '" + roleInfo.getRoleName() + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + } catch (URISyntaxException e) { + String msg = "Error occurred while composing the URI at which the information of the newly created role " + + "can be retrieved"; + log.error(msg, e); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); } - return Response.status(Response.Status.OK).entity("Role '" + roleWrapper.getRoleName() + "' has " + - "successfully been added").build(); } @PUT @Path("/{roleName}") @Override - public Response updateRole(@PathParam("roleName") String roleName, RoleWrapper roleWrapper) { + public Response updateRole(@PathParam("roleName") String roleName, RoleInfo roleInfo) { RequestValidationUtil.validateRoleName(roleName); - RequestValidationUtil.validateRoleDetails(roleWrapper); - String newRoleName = roleWrapper.getRoleName(); + RequestValidationUtil.validateRoleDetails(roleInfo); try { - final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager(); + final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); + final UserStoreManager userStoreManager = userRealm.getUserStoreManager(); + if (!userStoreManager.isExistingRole(roleName)) { + throw new NotFoundException( + new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + + roleName + "'").build()); + } + + final AuthorizationManager authorizationManager = userRealm.getAuthorizationManager(); if (log.isDebugEnabled()) { log.debug("Updating the role to user store"); } + + String newRoleName = roleInfo.getRoleName(); if (newRoleName != null && !roleName.equals(newRoleName)) { userStoreManager.updateRoleName(roleName, newRoleName); } - if (roleWrapper.getUsers() != null) { + + if (roleInfo.getUsers() != null) { SetReferenceTransformer transformer = new SetReferenceTransformer<>(); transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(newRoleName)), - Arrays.asList(roleWrapper.getUsers())); + Arrays.asList(roleInfo.getUsers())); final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer .getObjectsToAdd().size()]); final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer .getObjectsToRemove().size()]); userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd); } - if (roleWrapper.getPermissions() != null) { + + if (roleInfo.getPermissions() != null) { // Delete all authorizations for the current role before authorizing the permission tree authorizationManager.clearRoleAuthorization(roleName); - if (roleWrapper.getPermissions().length > 0) { - for (int i = 0; i < roleWrapper.getPermissions().length; i++) { - String permission = roleWrapper.getPermissions()[i]; + if (roleInfo.getPermissions().length > 0) { + for (int i = 0; i < roleInfo.getPermissions().length; i++) { + String permission = roleInfo.getPermissions()[i]; authorizationManager.authorizeRole(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION); } } } + //TODO: Need to send the updated role information in the entity back to the client + return Response.status(Response.Status.OK).entity("Role '" + roleInfo.getRoleName() + "' has " + + "successfully been updated").build(); } catch (UserStoreException e) { String msg = "Error occurred while updating role '" + roleName + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); } - return Response.status(Response.Status.OK).entity("Role '" + roleWrapper.getRoleName() + "' has " + - "successfully been updated").build(); } @DELETE @@ -274,8 +286,15 @@ public class RoleManagementServiceImpl implements RoleManagementService { public Response deleteRole(@PathParam("roleName") String roleName) { RequestValidationUtil.validateRoleName(roleName); try { - final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager(); + final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); + final UserStoreManager userStoreManager = userRealm.getUserStoreManager(); + if (!userStoreManager.isExistingRole(roleName)) { + throw new NotFoundException( + new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + + roleName + "'").build()); + } + + final AuthorizationManager authorizationManager = userRealm.getAuthorizationManager(); if (log.isDebugEnabled()) { log.debug("Deleting the role in user store"); } @@ -285,11 +304,9 @@ public class RoleManagementServiceImpl implements RoleManagementService { } catch (UserStoreException e) { String msg = "Error occurred while deleting the role '" + roleName + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); } - return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " + - "successfully been deleted").build(); + return Response.status(Response.Status.OK).build(); } @PUT @@ -325,7 +342,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { private List getRolesFromUserStore(String filter) throws UserStoreException { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); String[] roles; - boolean filterRolesByName = ((filter == null) || filter.isEmpty() ? false : true); + boolean filterRolesByName = (!((filter == null) || filter.isEmpty())); if (log.isDebugEnabled()) { log.debug("Getting the list of user roles"); } @@ -334,10 +351,10 @@ public class RoleManagementServiceImpl implements RoleManagementService { List filteredRoles = new ArrayList<>(); for (String role : roles) { if (!(role.startsWith("Internal/") || role.startsWith("Authentication/") || role.startsWith("Application/"))) { - if(!filterRolesByName) { + if (!filterRolesByName) { filteredRoles.add(role); - } else{ - if(role.contains(filter)){ + } else { + if (role.contains(filter)) { filteredRoles.add(role); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 177290e9f4..1efb6b4e5a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -39,6 +39,8 @@ import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.net.URI; +import java.net.URISyntaxException; import java.util.*; @Path("/users") @@ -47,117 +49,58 @@ import java.util.*; public class UserManagementServiceImpl implements UserManagementService { private static final String ROLE_EVERYONE = "Internal/everyone"; + private static final String API_BASE_PATH = "/users"; private static final Log log = LogFactory.getLog(UserManagementServiceImpl.class); @POST @Override - public Response addUser(UserInfo userWrapper) { + public Response addUser(UserInfo userInfo) { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (userStoreManager.isExistingUser(userWrapper.getUsername())) { + if (userStoreManager.isExistingUser(userInfo.getUsername())) { // if user already exists if (log.isDebugEnabled()) { - log.debug("User by username: " + userWrapper.getUsername() + + log.debug("User by username: " + userInfo.getUsername() + " already exists. Therefore, request made to add user was refused."); } // returning response with bad request state throw new ConflictException( - new ErrorResponse.ErrorResponseBuilder().setCode(409l).setMessage("User by username: " + - userWrapper.getUsername() + " already exists. Therefore, request made to add user " + + new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + + userInfo.getUsername() + " already exists. Therefore, request made to add user " + "was refused.").build()); - } else { - String initialUserPassword = this.generateInitialUserPassword(); - Map defaultUserClaims = - this.buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(), - userWrapper.getEmailAddress()); - // calling addUser method of carbon user api - userStoreManager.addUser(userWrapper.getUsername(), initialUserPassword, - userWrapper.getRoles(), defaultUserClaims, null); - // invite newly added user to enroll device - this.inviteNewlyAddedUserToEnrollDevice(userWrapper.getUsername(), initialUserPassword); - // Outputting debug message upon successful addition of user - if (log.isDebugEnabled()) { - log.debug("User '" + userWrapper.getUsername() + "' has successfully been added."); - } - // returning response with success state - return Response.status(Response.Status.CREATED).entity("User by username: " + userWrapper.getUsername() + - " was successfully added.").build(); } - } catch (UserStoreException e) { - String msg = "Exception in trying to add user '" + userWrapper.getUsername() + "' to the user store"; - log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); - } catch (DeviceManagementException e) { - String msg = "ErrorResponse occurred while inviting user to enroll the device"; - log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); - } - } - private Map buildDefaultUserClaims(String firstname, String lastname, String emailAddress) { - Map defaultUserClaims = new HashMap<>(); - defaultUserClaims.put(Constants.USER_CLAIM_FIRST_NAME, firstname); - defaultUserClaims.put(Constants.USER_CLAIM_LAST_NAME, lastname); - defaultUserClaims.put(Constants.USER_CLAIM_EMAIL_ADDRESS, emailAddress); - if (log.isDebugEnabled()) { - log.debug("Default claim map is created for new user: " + defaultUserClaims.toString()); - } - return defaultUserClaims; - } + String initialUserPassword = this.generateInitialUserPassword(); + Map defaultUserClaims = + this.buildDefaultUserClaims(userInfo.getFirstname(), userInfo.getLastname(), + userInfo.getEmailAddress()); + // calling addUser method of carbon user api + userStoreManager.addUser(userInfo.getUsername(), initialUserPassword, + userInfo.getRoles(), defaultUserClaims, null); + // Outputting debug message upon successful addition of user + if (log.isDebugEnabled()) { + log.debug("User '" + userInfo.getUsername() + "' has successfully been added."); + } - private String generateInitialUserPassword() { - int passwordLength = 6; - //defining the pool of characters to be used for initial password generation - String lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz"; - String upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - String numericCharset = "0123456789"; - Random randomGenerator = new Random(); - String totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset; - int totalCharsetLength = totalCharset.length(); - StringBuilder initialUserPassword = new StringBuilder(); - for (int i = 0; i < passwordLength; i++) { - initialUserPassword - .append(totalCharset.charAt(randomGenerator.nextInt(totalCharsetLength))); - } - if (log.isDebugEnabled()) { - log.debug("Initial user password is created for new user: " + initialUserPassword); - } - return initialUserPassword.toString(); - } + BasicUserInfo createdUserInfo = this.getBasicUserInfo(userInfo.getUsername()); + // Outputting debug message upon successful retrieval of user + if (log.isDebugEnabled()) { + log.debug("User by username: " + userInfo.getUsername() + " was found."); + } + return Response.created(new URI(API_BASE_PATH + "/" + userInfo.getUsername())).entity( + createdUserInfo).build(); - private void inviteNewlyAddedUserToEnrollDevice(String username, - String password) throws DeviceManagementException, UserStoreException { - if (log.isDebugEnabled()) { - log.debug("Sending invitation mail to user by username: " + username); - } - String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) { - tenantDomain = ""; - } - if (!username.contains("/")) { - username = "/" + username; + } catch (UserStoreException e) { + String msg = "Error occurred while trying to add user '" + userInfo.getUsername() + "' to the " + + "underlying user management system"; + log.error(msg, e); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + } catch (URISyntaxException e) { + String msg = "Error occurred while composing the location URI, which represents information of the " + + "newly created user '" + userInfo.getUsername() + "'"; + log.error(msg, e); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); } - String[] usernameBits = username.split("/"); - DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); - - Properties props = new Properties(); - props.setProperty("username", usernameBits[1]); - props.setProperty("domain-name", tenantDomain); - props.setProperty("first-name", getClaimValue(usernameBits[1], Constants.USER_CLAIM_FIRST_NAME)); - props.setProperty("password", password); - - String recipient = getClaimValue(usernameBits[1], Constants.USER_CLAIM_EMAIL_ADDRESS); - - EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); - - deviceManagementProviderService.sendRegistrationEmail(metaInfo); - } - - private String getClaimValue(String username, String claimUri) throws UserStoreException { - UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - return userStoreManager.getUserClaimValue(username, claimUri, null); } @GET @@ -167,91 +110,77 @@ public class UserManagementServiceImpl implements UserManagementService { @HeaderParam("If-Modified-Since") String ifModifiedSince) { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (userStoreManager.isExistingUser(username)) { - BasicUserInfo user = new BasicUserInfo(); - user.setUsername(username); - user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); - user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); - user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); - // Outputting debug message upon successful retrieval of user - if (log.isDebugEnabled()) { - log.debug("User by username: " + username + " was found."); - } - return Response.status(Response.Status.OK).entity(user).build(); - } else { - // Outputting debug message upon trying to remove non-existing user + if (!userStoreManager.isExistingUser(username)) { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist."); } - // returning response with bad request state - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User doesn't exist.") - .build()); + throw new NotFoundException(new ErrorResponse.ErrorResponseBuilder().setMessage( + "User doesn't exist.").build()); } + + BasicUserInfo user = this.getBasicUserInfo(username); + return Response.status(Response.Status.OK).entity(user).build(); } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while retrieving information of the user '" + username + "'"; + String msg = "Error occurred while retrieving information of the user '" + username + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); } } @PUT @Path("/{username}") @Override - public Response updateUser(@PathParam("username") String username, UserInfo userWrapper) { + public Response updateUser(@PathParam("username") String username, UserInfo userInfo) { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (userStoreManager.isExistingUser(userWrapper.getUsername())) { - Map defaultUserClaims = - this.buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(), - userWrapper.getEmailAddress()); - if (StringUtils.isNotEmpty(userWrapper.getPassword())) { - // Decoding Base64 encoded password - userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(), - userWrapper.getPassword()); - log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed"); - } - List currentRoles = this.getFilteredRoles(userStoreManager, userWrapper.getUsername()); - List newRoles = Arrays.asList(userWrapper.getRoles()); - - List rolesToAdd = new ArrayList<>(newRoles); - List rolesToDelete = new ArrayList<>(); - - for (String role : currentRoles) { - if (newRoles.contains(role)) { - rolesToAdd.remove(role); - } else { - rolesToDelete.add(role); - } - } - rolesToDelete.remove(ROLE_EVERYONE); - userStoreManager.updateRoleListOfUser(userWrapper.getUsername(), - rolesToDelete.toArray(new String[rolesToDelete.size()]), - rolesToAdd.toArray(new String[rolesToAdd.size()])); - userStoreManager.setUserClaimValues(userWrapper.getUsername(), defaultUserClaims, null); - // Outputting debug message upon successful addition of user - if (log.isDebugEnabled()) { - log.debug("User by username: " + userWrapper.getUsername() + " was successfully updated."); - } - // returning response with success state - return Response.status(Response.Status.CREATED).entity("User by username '" + userWrapper.getUsername() + - "' was successfully updated.").build(); - } else { + if (!userStoreManager.isExistingUser(userInfo.getUsername())) { if (log.isDebugEnabled()) { - log.debug("User by username: " + userWrapper.getUsername() + + log.debug("User by username: " + userInfo.getUsername() + " doesn't exists. Therefore, request made to update user was refused."); } throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User by username: " + - userWrapper.getUsername() + " doesn't exists. Therefore, request made to update user" + - " was refused.").build()); + new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + + userInfo.getUsername() + " doesn't exist.").build()); + } + + Map defaultUserClaims = + this.buildDefaultUserClaims(userInfo.getFirstname(), userInfo.getLastname(), + userInfo.getEmailAddress()); + if (StringUtils.isNotEmpty(userInfo.getPassword())) { + // Decoding Base64 encoded password + userStoreManager.updateCredentialByAdmin(userInfo.getUsername(), + userInfo.getPassword()); + log.debug("User credential of username: " + userInfo.getUsername() + " has been changed"); } + List currentRoles = this.getFilteredRoles(userStoreManager, userInfo.getUsername()); + List newRoles = Arrays.asList(userInfo.getRoles()); + + List rolesToAdd = new ArrayList<>(newRoles); + List rolesToDelete = new ArrayList<>(); + + for (String role : currentRoles) { + if (newRoles.contains(role)) { + rolesToAdd.remove(role); + } else { + rolesToDelete.add(role); + } + } + rolesToDelete.remove(ROLE_EVERYONE); + userStoreManager.updateRoleListOfUser(userInfo.getUsername(), + rolesToDelete.toArray(new String[rolesToDelete.size()]), + rolesToAdd.toArray(new String[rolesToAdd.size()])); + userStoreManager.setUserClaimValues(userInfo.getUsername(), defaultUserClaims, null); + // Outputting debug message upon successful addition of user + if (log.isDebugEnabled()) { + log.debug("User by username: " + userInfo.getUsername() + " was successfully updated."); + } + + BasicUserInfo updatedUserInfo = this.getBasicUserInfo(username); + return Response.ok().entity(updatedUserInfo).build(); } catch (UserStoreException e) { - String msg = "Exception in trying to update user by username: " + userWrapper.getUsername(); + String msg = "Error occurred while trying to update user '" + userInfo.getUsername() + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); } } @@ -277,31 +206,25 @@ public class UserManagementServiceImpl implements UserManagementService { public Response removeUser(@PathParam("username") String username) { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (userStoreManager.isExistingUser(username)) { - // if user already exists, trying to remove user - userStoreManager.deleteUser(username); - // Outputting debug message upon successful removal of user - if (log.isDebugEnabled()) { - log.debug("User by username: " + username + " was successfully removed."); - } - // returning response with success state - return Response.status(Response.Status.OK).entity("User by username: " + username + - " was successfully removed.").build(); - } else { - // Outputting debug message upon trying to remove non-existing user + if (!userStoreManager.isExistingUser(username)) { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist for removal."); } - // returning response with bad request state throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User by username: " + + new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + username + " does not exist for removal.").build()); } + + userStoreManager.deleteUser(username); + if (log.isDebugEnabled()) { + log.debug("User by username: " + username + " was successfully removed."); + } + return Response.status(Response.Status.OK).build(); } catch (UserStoreException e) { String msg = "Exception in trying to remove user by username: " + username; log.error(msg, e); throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); } } @@ -311,24 +234,22 @@ public class UserManagementServiceImpl implements UserManagementService { public Response getRolesOfUser(@PathParam("username") String username) { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - if (userStoreManager.isExistingUser(username)) { - RoleList result = new RoleList(); - result.setList(getFilteredRoles(userStoreManager, username)); - return Response.status(Response.Status.OK).entity(result).build(); - } else { - // Outputting debug message upon trying to remove non-existing user + if (!userStoreManager.isExistingUser(username)) { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist for role retrieval."); } throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("User by username: " + username + + new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + username + " does not exist for role retrieval.").build()); } + + RoleList result = new RoleList(); + result.setList(getFilteredRoles(userStoreManager, username)); + return Response.status(Response.Status.OK).entity(result).build(); } catch (UserStoreException e) { - String msg = "Exception in trying to retrieve roles for user by username: " + username; + String msg = "Error occurred while trying to retrieve roles of the user '" + username + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); } } @@ -342,7 +263,7 @@ public class UserManagementServiceImpl implements UserManagementService { } List userList, offsetList; String appliedFilter = ((filter == null) || filter.isEmpty() ? "*" : filter); - int appliedLimit = (limit <= 0) ? -1 : (limit + offset); + int appliedLimit = (limit <= 0) ? -1 : (limit + offset); try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); @@ -371,10 +292,9 @@ public class UserManagementServiceImpl implements UserManagementService { return Response.status(Response.Status.OK).entity(result).build(); } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while retrieving the list of users."; + String msg = "Error occurred while retrieving the list of users."; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); } } @@ -407,8 +327,7 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException e) { String msg = "Error occurred while retrieving the list of users using the filter : " + filter; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); } } @@ -419,4 +338,49 @@ public class UserManagementServiceImpl implements UserManagementService { return CredentialManagementResponseBuilder.buildChangePasswordResponse(username, credentials); } + private Map buildDefaultUserClaims(String firstName, String lastName, String emailAddress) { + Map defaultUserClaims = new HashMap<>(); + defaultUserClaims.put(Constants.USER_CLAIM_FIRST_NAME, firstName); + defaultUserClaims.put(Constants.USER_CLAIM_LAST_NAME, lastName); + defaultUserClaims.put(Constants.USER_CLAIM_EMAIL_ADDRESS, emailAddress); + if (log.isDebugEnabled()) { + log.debug("Default claim map is created for new user: " + defaultUserClaims.toString()); + } + return defaultUserClaims; + } + + private String generateInitialUserPassword() { + int passwordLength = 6; + //defining the pool of characters to be used for initial password generation + String lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz"; + String upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + String numericCharset = "0123456789"; + Random randomGenerator = new Random(); + String totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset; + int totalCharsetLength = totalCharset.length(); + StringBuilder initialUserPassword = new StringBuilder(); + for (int i = 0; i < passwordLength; i++) { + initialUserPassword.append( + totalCharset.charAt(randomGenerator.nextInt(totalCharsetLength))); + } + if (log.isDebugEnabled()) { + log.debug("Initial user password is created for new user: " + initialUserPassword); + } + return initialUserPassword.toString(); + } + + private BasicUserInfo getBasicUserInfo(String username) throws UserStoreException { + BasicUserInfo userInfo = new BasicUserInfo(); + userInfo.setUsername(username); + userInfo.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS)); + userInfo.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME)); + userInfo.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME)); + return userInfo; + } + + private String getClaimValue(String username, String claimUri) throws UserStoreException { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + return userStoreManager.getUserClaimValue(username, claimUri, null); + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java index f4defbdfad..5d0a585ca7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java @@ -304,8 +304,8 @@ public class RequestValidationUtil { } } - public static void validateRoleDetails(RoleWrapper roleWrapper) { - if (roleWrapper == null) { + public static void validateRoleDetails(RoleInfo roleInfo) { + if (roleInfo == null) { throw new InputValidationException( new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request body is incorrect or" + " empty").build()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/swagger/extension/SecurityDefinitionConfigurator.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/swagger/extension/SecurityDefinitionConfigurator.java new file mode 100644 index 0000000000..2ad4b54aa5 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/swagger/extension/SecurityDefinitionConfigurator.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.swagger.extension; + +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.jaxrs.Reader; +import io.swagger.jaxrs.config.ReaderListener; +import io.swagger.models.Swagger; +import io.swagger.models.auth.OAuth2Definition; +import io.swagger.models.auth.SecuritySchemeDefinition; + +import java.util.HashMap; +import java.util.Map; + +@SwaggerDefinition( + basePath = "/api/device-mgt/v1.0", + host = "localhost:9443" +) +public class SecurityDefinitionConfigurator implements ReaderListener { + + public static final String TOKEN_AUTH_SCHEME = "tokenAuthScheme"; + + @Override + public void beforeScan(Reader reader, Swagger swagger) { + + } + + @Override + public void afterScan(Reader reader, Swagger swagger) { + OAuth2Definition tokenScheme = new OAuth2Definition(); + tokenScheme.setType("oauth2"); + tokenScheme.setFlow("password"); + tokenScheme.setTokenUrl("https://" + swagger.getHost() + "/oauth/token"); + tokenScheme.setAuthorizationUrl("https://" + swagger.getHost() + "/oauth/authorize"); + + Map schemes = new HashMap<>(); + schemes.put(TOKEN_AUTH_SCHEME, tokenScheme); + + swagger.setSecurityDefinitions(schemes); + } + +} From ad6b95ff62b862126a664e1b761211e8ac1f2ad5 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Mon, 27 Jun 2016 14:45:43 +0530 Subject: [PATCH 02/11] Code cleanup --- .../impl/RoleManagementServiceImpl.java | 68 ++++++++++--------- .../impl/UserManagementServiceImpl.java | 57 ++++++++-------- 2 files changed, 64 insertions(+), 61 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java index e885138e12..9100c54ac0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -24,12 +24,10 @@ import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo; -import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; +import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; import org.wso2.carbon.user.api.*; @@ -71,14 +69,13 @@ public class RoleManagementServiceImpl implements RoleManagementService { filteredRoles = FilteringUtil.getFilteredList(getRolesFromUserStore(filter), offset, limit); targetRoles.setList(filteredRoles); - Response.ok().entity(targetRoles).build(); + return Response.ok().entity(targetRoles).build(); } catch (UserStoreException e) { String msg = "Error occurred while retrieving roles from the underlying user stores"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - return Response.status(Response.Status.OK).entity(targetRoles).build(); } @GET @@ -91,8 +88,8 @@ public class RoleManagementServiceImpl implements RoleManagementService { try { final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); if (!userRealm.getUserStoreManager().isExistingRole(roleName)) { - throw new NotFoundException(new ErrorResponse.ErrorResponseBuilder().setMessage( - "No role exists with the name '" + roleName + "'").build()); + return Response.status(404).entity(new ErrorResponse.ErrorResponseBuilder().setMessage( + "No role exists with the name '" + roleName + "'").build()).build(); } final UIPermissionNode rolePermissions = this.getUIPermissionNode(roleName, userRealm); @@ -105,14 +102,14 @@ public class RoleManagementServiceImpl implements RoleManagementService { } catch (UserAdminException e) { String msg = "Error occurred while retrieving the permissions of role '" + roleName + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (UserStoreException e) { String msg = "Error occurred while retrieving the underlying user realm attached to the " + "current logged in user"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -156,9 +153,9 @@ public class RoleManagementServiceImpl implements RoleManagementService { final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); if (!userStoreManager.isExistingRole(roleName)) { - throw new NotFoundException( + return Response.status(404).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + - roleName + "'").build()); + roleName + "'").build()).build(); } roleInfo.setRoleName(roleName); roleInfo.setUsers(userStoreManager.getUserListOfRole(roleName)); @@ -169,13 +166,14 @@ public class RoleManagementServiceImpl implements RoleManagementService { roleInfo.setPermissionList(rolePermissions); String[] permListAr = new String[permList.size()]; roleInfo.setPermissions(permList.toArray(permListAr)); + + return Response.status(Response.Status.OK).entity(roleInfo).build(); } catch (UserStoreException | UserAdminException e) { String msg = "Error occurred while retrieving the user role '" + roleName + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - return Response.status(Response.Status.OK).entity(roleInfo).build(); } private List iteratePermissions(UIPermissionNode uiPermissionNode, List list) { @@ -215,12 +213,14 @@ public class RoleManagementServiceImpl implements RoleManagementService { } catch (UserStoreException e) { String msg = "Error occurred while adding role '" + roleInfo.getRoleName() + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (URISyntaxException e) { String msg = "Error occurred while composing the URI at which the information of the newly created role " + "can be retrieved"; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -234,9 +234,9 @@ public class RoleManagementServiceImpl implements RoleManagementService { final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); final UserStoreManager userStoreManager = userRealm.getUserStoreManager(); if (!userStoreManager.isExistingRole(roleName)) { - throw new NotFoundException( + return Response.status(404).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + - roleName + "'").build()); + roleName + "'").build()).build(); } final AuthorizationManager authorizationManager = userRealm.getAuthorizationManager(); @@ -276,7 +276,8 @@ public class RoleManagementServiceImpl implements RoleManagementService { } catch (UserStoreException e) { String msg = "Error occurred while updating role '" + roleName + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -289,9 +290,9 @@ public class RoleManagementServiceImpl implements RoleManagementService { final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); final UserStoreManager userStoreManager = userRealm.getUserStoreManager(); if (!userStoreManager.isExistingRole(roleName)) { - throw new NotFoundException( + return Response.status(404).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + - roleName + "'").build()); + roleName + "'").build()).build(); } final AuthorizationManager authorizationManager = userRealm.getAuthorizationManager(); @@ -301,12 +302,14 @@ public class RoleManagementServiceImpl implements RoleManagementService { userStoreManager.deleteRole(roleName); // Delete all authorizations for the current role before deleting authorizationManager.clearRoleAuthorization(roleName); + + return Response.status(Response.Status.OK).build(); } catch (UserStoreException e) { String msg = "Error occurred while deleting the role '" + roleName + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - return Response.status(Response.Status.OK).build(); } @PUT @@ -329,14 +332,15 @@ public class RoleManagementServiceImpl implements RoleManagementService { .getObjectsToRemove().size()]); userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd); + + return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " + + "successfully been updated with the user list").build(); } catch (UserStoreException e) { String msg = "Error occurred while updating the users of the role '" + roleName + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " + - "successfully been updated with the user list").build(); } private List getRolesFromUserStore(String filter) throws UserStoreException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 1efb6b4e5a..ff6f007ad3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -21,20 +21,13 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl; import org.apache.commons.lang.StringUtils; 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.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; import org.wso2.carbon.device.mgt.jaxrs.beans.*; import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -64,10 +57,10 @@ public class UserManagementServiceImpl implements UserManagementService { " already exists. Therefore, request made to add user was refused."); } // returning response with bad request state - throw new ConflictException( + return Response.status(409).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + userInfo.getUsername() + " already exists. Therefore, request made to add user " + - "was refused.").build()); + "was refused.").build()).build(); } String initialUserPassword = this.generateInitialUserPassword(); @@ -89,17 +82,18 @@ public class UserManagementServiceImpl implements UserManagementService { } return Response.created(new URI(API_BASE_PATH + "/" + userInfo.getUsername())).entity( createdUserInfo).build(); - } catch (UserStoreException e) { String msg = "Error occurred while trying to add user '" + userInfo.getUsername() + "' to the " + "underlying user management system"; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (URISyntaxException e) { String msg = "Error occurred while composing the location URI, which represents information of the " + "newly created user '" + userInfo.getUsername() + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -114,8 +108,8 @@ public class UserManagementServiceImpl implements UserManagementService { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist."); } - throw new NotFoundException(new ErrorResponse.ErrorResponseBuilder().setMessage( - "User doesn't exist.").build()); + return Response.status(404).entity(new ErrorResponse.ErrorResponseBuilder().setMessage( + "User doesn't exist.").build()).build(); } BasicUserInfo user = this.getBasicUserInfo(username); @@ -123,7 +117,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException e) { String msg = "Error occurred while retrieving information of the user '" + username + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -138,9 +133,9 @@ public class UserManagementServiceImpl implements UserManagementService { log.debug("User by username: " + userInfo.getUsername() + " doesn't exists. Therefore, request made to update user was refused."); } - throw new NotFoundException( + return Response.status(404).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + - userInfo.getUsername() + " doesn't exist.").build()); + userInfo.getUsername() + " doesn't exist.").build()).build(); } Map defaultUserClaims = @@ -180,7 +175,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException e) { String msg = "Error occurred while trying to update user '" + userInfo.getUsername() + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -210,21 +206,21 @@ public class UserManagementServiceImpl implements UserManagementService { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist for removal."); } - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + - username + " does not exist for removal.").build()); + return Response.status(404).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("User '" + + username + "' does not exist for removal.").build()).build(); } userStoreManager.deleteUser(username); if (log.isDebugEnabled()) { - log.debug("User by username: " + username + " was successfully removed."); + log.debug("User '" + username + "' was successfully removed."); } return Response.status(Response.Status.OK).build(); } catch (UserStoreException e) { String msg = "Exception in trying to remove user by username: " + username; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -238,9 +234,9 @@ public class UserManagementServiceImpl implements UserManagementService { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist for role retrieval."); } - throw new NotFoundException( + return Response.status(404).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + username + - " does not exist for role retrieval.").build()); + " does not exist for role retrieval.").build()).build(); } RoleList result = new RoleList(); @@ -249,7 +245,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException e) { String msg = "Error occurred while trying to retrieve roles of the user '" + username + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -294,7 +291,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException e) { String msg = "Error occurred while retrieving the list of users."; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -327,7 +325,8 @@ public class UserManagementServiceImpl implements UserManagementService { } catch (UserStoreException e) { String msg = "Error occurred while retrieving the list of users using the filter : " + filter; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } From a23f44e68291de7f7be1678cbb830fc279c20e70 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Mon, 27 Jun 2016 15:04:15 +0530 Subject: [PATCH 03/11] Improving AcitivityManagement API implementation with proper error handling, etc --- .../api/ActivityInfoProviderService.java | 9 ++-- .../impl/ActivityProviderServiceImpl.java | 49 +++++++++---------- 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java index 3cdc31ed07..275a31cd07 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java @@ -78,7 +78,7 @@ public interface ActivityInfoProviderService { response = ErrorResponse.class), @ApiResponse( code = 401, - message = ". \n Invalid request or validation error."), + message = "Unauthorized. \n Unauthorized request."), @ApiResponse( code = 404, message = "Not Found. \n No activity is found under the provided id.", @@ -88,7 +88,7 @@ public interface ActivityInfoProviderService { message = "Not Acceptable.\n The requested media type is not supported"), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching activity data.", + message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) @Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"}) @@ -135,6 +135,9 @@ public interface ActivityInfoProviderService { code = 304, message = "Not Modified. \n Empty body because the client has already the latest version of " + "the requested resource."), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), @ApiResponse( code = 404, message = "Not Found. \n No activities found.", @@ -144,7 +147,7 @@ public interface ActivityInfoProviderService { message = "Not Acceptable.\n The requested media type is not supported"), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching activity data.", + message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) @Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"}) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java index 848b0749a7..444854e1e4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java @@ -26,8 +26,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.jaxrs.beans.ActivityList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.service.api.ActivityInfoProviderService; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.*; @@ -58,17 +57,17 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService dmService = DeviceMgtAPIUtils.getDeviceManagementService(); activity = dmService.getOperationByActivityId(id); if (activity == null) { - throw new NotFoundException(new ErrorResponse.ErrorResponseBuilder().setCode(404l) - .setMessage("No activity can be " + - "found upon the provided activity id '" + id + "'").build()); + return Response.status(404).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("No activity can be " + + "found upon the provided activity id '" + id + "'").build()).build(); } + return Response.status(Response.Status.OK).entity(activity).build(); } catch (OperationManagementException e) { String msg = "ErrorResponse occurred while fetching the activity for the supplied id."; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setCode(500l) - .setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - return Response.status(Response.Status.OK).entity(activity).build(); } @GET @@ -77,19 +76,21 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService @QueryParam("limit") int limit, @HeaderParam("If-Modified-Since") String ifModifiedSince) { - long ifModifiedSinceTimestamp = 0; - long sinceTimestamp = 0; + long ifModifiedSinceTimestamp; + long sinceTimestamp; long timestamp = 0; boolean isIfModifiedSinceSet = false; boolean isSinceSet = false; + if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { Date ifSinceDate; SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); try { ifSinceDate = format.parse(ifModifiedSince); } catch (ParseException e) { - throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder().setCode(400l) - .setMessage("Invalid date string is provided in 'If-Modified-Since' header").build()); + return Response.status(400).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage( + "Invalid date string is provided in 'If-Modified-Since' header").build()).build(); } ifModifiedSinceTimestamp = ifSinceDate.getTime(); isIfModifiedSinceSet = true; @@ -100,13 +101,15 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService try { sinceDate = format.parse(since); } catch (ParseException e) { - throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder().setCode(400l) - .setMessage("Invalid date string is provided in 'since' filter").build()); + return Response.status(400).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage( + "Invalid date string is provided in 'since' filter").build()).build(); } sinceTimestamp = sinceDate.getTime(); isSinceSet = true; timestamp = sinceTimestamp / 1000; } + List activities; ActivityList activityList = new ActivityList(); DeviceManagementProviderService dmService; @@ -117,24 +120,18 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService int count = dmService.getActivityCountUpdatedAfter(timestamp); activityList.setCount(count); if (activities == null || activities.size() == 0) { - if (isIfModifiedSinceSet) { - return Response.status(Response.Status.NOT_MODIFIED).entity( - "No activities " + "after the time provided in 'If-Modified-Since' header") - .build(); - } else if (isSinceSet) { - return Response.status(Response.Status.NOT_MODIFIED).entity( - "No activities " + "after the time provided in 'since' filter").build(); + if (isIfModifiedSinceSet || isSinceSet) { + return Response.notModified().build(); } - throw new NotFoundException(new ErrorResponse.ErrorResponseBuilder().setCode(404l) - .setMessage("No activities " + "found.").build()); } + return Response.ok().entity(activityList).build(); } catch (OperationManagementException e) { String msg = "ErrorResponse occurred while fetching the activities updated after given time stamp."; log.error(msg, e); - throw new UnexpectedServerErrorException(new ErrorResponse.ErrorResponseBuilder().setCode(500l) - .setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - return Response.status(Response.Status.OK).entity(activityList).build(); } + } From 624e7df6889cd994b522deffd10a29e3a76b817c Mon Sep 17 00:00:00 2001 From: prabathabey Date: Mon, 27 Jun 2016 16:28:49 +0530 Subject: [PATCH 04/11] Improving HTTP status code handling and the resource implementations --- .../api/ConfigurationManagementService.java | 10 ++++----- .../service/api/RoleManagementService.java | 6 ----- .../service/api/UserManagementService.java | 15 +++++-------- .../impl/ConfigurationServiceImpl.java | 22 ++++++++++--------- .../PolicyManagementServiceComponent.java | 2 +- .../mgt/core/util/PolicyManagerUtil.java | 2 +- 6 files changed, 24 insertions(+), 33 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java index ab067e0e19..5cbe24305d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java @@ -68,13 +68,14 @@ public interface ConfigurationManagementService { }), @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 = 406, 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 general " + + message = "Internal Server Error. \n Server error occurred while fetching the general " + "platform configuration.", response = ErrorResponse.class) }) @@ -100,9 +101,6 @@ public interface ConfigurationManagementService { code = 200, message = "OK. \n General platform configuration has been updated successfully", responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "URL of the updated general platform configuration."), @ResponseHeader( name = "Content-Type", description = "The content type of the body"), @@ -122,7 +120,7 @@ public interface ConfigurationManagementService { message = "Unsupported media type. \n The entity of the request was in a not supported format."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while modifying general platform configuration.", response = ErrorResponse.class) }) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java index c58604a4a0..a42758e215 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java @@ -308,9 +308,6 @@ public interface RoleManagementService { code = 200, message = "OK. \n Role has been updated successfully", responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "URL of the updated role."), @ResponseHeader( name = "Content-Type", description = "Content type of the body"), @@ -404,9 +401,6 @@ public interface RoleManagementService { code = 200, message = "OK. \n User list of the role has been updated successfully", responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "URL of the updated user list."), @ResponseHeader( name = "Content-Type", description = "Content type of the body"), diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java index 2429c805ce..781cce69a9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java @@ -162,9 +162,6 @@ public interface UserManagementService { code = 200, message = "OK. \n User has been updated successfully", responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "URL of the updated user."), @ResponseHeader( name = "Content-Type", description = "Content type of the body"), @@ -190,7 +187,7 @@ public interface UserManagementService { response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while updating the user.", response = ErrorResponse.class) }) @@ -224,7 +221,7 @@ public interface UserManagementService { response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while removing the user.", response = ErrorResponse.class ) @@ -274,7 +271,7 @@ public interface UserManagementService { response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching the role list" + + message = "Internal Server Error. \n Server error occurred while fetching the role list" + " assigned to the user.", response = ErrorResponse.class) }) @@ -318,7 +315,7 @@ public interface UserManagementService { response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching the user list.", + message = "Internal Server Error. \n Server error occurred while fetching the user list.", response = ErrorResponse.class) }) @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"}) @@ -384,7 +381,7 @@ public interface UserManagementService { response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n Server error occurred while fetching the username " + + message = "Internal Server Error. \n Server error occurred while fetching the username " + "list that matches the given filter.", response = ErrorResponse.class) }) @@ -438,7 +435,7 @@ public interface UserManagementService { response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java index c10e82e762..0c082722fd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java @@ -55,19 +55,19 @@ public class ConfigurationServiceImpl implements ConfigurationManagementService ConfigurationEntry configurationEntry = new ConfigurationEntry(); configurationEntry.setContentType("text"); configurationEntry.setName("notifierFrequency"); - configurationEntry.setValue(PolicyManagerUtil.getMonitoringFequency()); + configurationEntry.setValue(PolicyManagerUtil.getMonitoringFrequency()); List configList = config.getConfiguration(); if (configList == null) { configList = new ArrayList<>(); configList.add(configurationEntry); } config.setConfiguration(configList); - return Response.status(Response.Status.OK).entity(config).build(); + return Response.ok().entity(config).build(); } catch (ConfigurationManagementException | PolicyManagementException e) { - msg = "ErrorResponse occurred while retrieving the configurations."; + msg = "Error occurred while retrieving the general platform configuration"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -80,13 +80,15 @@ public class ConfigurationServiceImpl implements ConfigurationManagementService MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); //Schedule the task service DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(config)); - return Response.status(Response.Status.CREATED) - .entity("Configuration has successfully been updated").build(); + + PlatformConfiguration updatedConfig = DeviceMgtAPIUtils.getPlatformConfigurationManagementService(). + getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH); + return Response.ok().entity(updatedConfig).build(); } catch (ConfigurationManagementException e) { - String msg = "ErrorResponse occurred while updating the configuration."; + String msg = "Error occurred while updating the general platform configuration"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java index 13711f43b0..0c456fce28 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java @@ -91,7 +91,7 @@ public class PolicyManagementServiceComponent { DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getPolicyConfiguration(); if(policyConfiguration.getMonitoringEnable()) { TaskScheduleService taskScheduleService = new TaskScheduleServiceImpl(); - taskScheduleService.startTask(PolicyManagerUtil.getMonitoringFequency()); + taskScheduleService.startTask(PolicyManagerUtil.getMonitoringFrequency()); } } catch (Throwable t) { 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 c0e587b857..0d80901d21 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 @@ -196,7 +196,7 @@ public class PolicyManagerUtil { } - public static int getMonitoringFequency() throws PolicyManagementException { + public static int getMonitoringFrequency() throws PolicyManagementException { PlatformConfigurationManagementService configMgtService = new PlatformConfigurationManagementServiceImpl(); PlatformConfiguration tenantConfiguration; From cf887a2e9337b953a560d7f66b09dc1172a57a1c Mon Sep 17 00:00:00 2001 From: Ace Date: Tue, 28 Jun 2016 17:00:02 +0530 Subject: [PATCH 05/11] Merging emm module changes to devicemgt iot app --- .../app/modules/backend-service-invoker.js | 316 +++++++++--------- .../devicemgt/app/modules/device.js | 114 +++++-- .../app/modules/invoker-request-wrapper.js | 12 +- .../devicemgt/app/modules/policy.js | 147 ++++---- .../jaggeryapps/devicemgt/app/modules/user.js | 84 +++-- 5 files changed, 384 insertions(+), 289 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js index 1e3f0bd69a..6caa5bccd1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js @@ -46,25 +46,25 @@ var backendServiceInvoker = function () { }; /** - * This method add Oauth authentication header to outgoing XMLHTTP Requests if Oauth authentication is enabled. - * @param method HTTP request type. - * @param url target url. - * @param payload payload/data which need to be send. - * @param successCallback a function to be called if the respond if successful. - * @param errorCallback a function to be called if en error is reserved. + * --------------------------------------------------------------------------- + * Start of XML-HTTP-REQUEST based Interceptor implementations + * --------------------------------------------------------------------------- + */ + + /** + * This method add Oauth authentication header to outgoing XML-HTTP Requests if Oauth authentication is enabled. + * @param httpMethod HTTP request type. + * @param requestPayload payload/data if exists which is needed to be send. + * @param endpoint Backend REST API url. + * @param responseCallback a function to be called with response retrieved. * @param count a counter which hold the number of recursive execution */ - privateMethods.execute = function (method, url, successCallback, errorCallback, payload, count, contentType, acceptType) { + privateMethods.execute = function (httpMethod, requestPayload, endpoint, responseCallback, count) { var xmlHttpRequest = new XMLHttpRequest(); - xmlHttpRequest.open(method, url); - if(!contentType){ - contentType = constants.APPLICATION_JSON; - } - if(!acceptType){ - acceptType = constants.APPLICATION_JSON; - } - xmlHttpRequest.setRequestHeader(constants.CONTENT_TYPE_IDENTIFIER, contentType); - xmlHttpRequest.setRequestHeader(constants.ACCEPT_IDENTIFIER, acceptType); + + xmlHttpRequest.open(httpMethod, endpoint); + xmlHttpRequest.setRequestHeader(constants["CONTENT_TYPE_IDENTIFIER"], constants["APPLICATION_JSON"]); + xmlHttpRequest.setRequestHeader(constants["ACCEPT_IDENTIFIER"], constants["APPLICATION_JSON"]); if (IS_OAUTH_ENABLED) { var accessToken = privateMethods.getAccessToken(); if (!accessToken) { @@ -73,43 +73,145 @@ var backendServiceInvoker = function () { xmlHttpRequest.setRequestHeader(constants.AUTHORIZATION_HEADER, constants.BEARER_PREFIX + accessToken); } } - if (payload) { - xmlHttpRequest.send(payload); + + if (requestPayload) { + xmlHttpRequest.send(requestPayload); } else { xmlHttpRequest.send(); } - if ((xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300) || xmlHttpRequest.status == 302) { - if (xmlHttpRequest.responseText != null) { - return successCallback(parse(xmlHttpRequest.responseText)); - } else { - return successCallback({"status": xmlHttpRequest.status, "messageFromServer": "Operation Completed"}); - } - } else if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED || - xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) { + + if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED || + xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) { tokenUtil.refreshToken(); - return privateMethods.execute(method, url, successCallback, errorCallback, payload, (count + 1)); - } else if (xmlHttpRequest.status == 500) { - return errorCallback(xmlHttpRequest); + return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, ++count); } else { - return errorCallback(xmlHttpRequest); + return responseCallback(xmlHttpRequest); } }; /** - * This method add Oauth authentication header to outgoing XMLHTTP Requests if Oauth authentication is enabled. - * @param method HTTP request type. - * @param url target url. - * @param payload payload/data which need to be send. + * This method add Oauth authentication header to outgoing XML-HTTP Requests if Oauth authentication is enabled. + * @param httpMethod HTTP request type. + * @param requestPayload payload/data if exists which is needed to be send. + * @param endpoint Backend REST API url. + * @param responseCallback a function to be called with response retrieved. + */ + privateMethods.initiateXMLHTTPRequest = function (httpMethod, requestPayload, endpoint, responseCallback) { + return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, 0); + }; + + /** + * This method invokes return initiateXMLHttpRequest for get calls + * @param endpoint Backend REST API url. + * @param responseCallback a function to be called with response retrieved. + */ + publicXMLHTTPInvokers.get = function (endpoint, responseCallback) { + var requestPayload = null; + return privateMethods.initiateXMLHTTPRequest(constants["HTTP_GET"], requestPayload, endpoint, responseCallback); + }; + + /** + * This method invokes return initiateXMLHttpRequest for post calls + * @param endpoint Backend REST API url. + * @param requestPayload payload/data if exists which is needed to be send. + * @param responseCallback a function to be called with response retrieved. + */ + publicXMLHTTPInvokers.post = function (endpoint, requestPayload, responseCallback) { + return privateMethods.initiateXMLHTTPRequest(constants["HTTP_POST"], requestPayload, endpoint, responseCallback); + }; + + /** + * This method invokes return initiateXMLHttpRequest for put calls + * @param endpoint Backend REST API url. + * @param requestPayload payload/data if exists which is needed to be send. + * @param responseCallback a function to be called with response retrieved. + */ + publicXMLHTTPInvokers.put = function (endpoint, requestPayload, responseCallback) { + return privateMethods.initiateXMLHTTPRequest(constants["HTTP_PUT"], requestPayload, endpoint, responseCallback); + }; + + /** + * This method invokes return initiateXMLHttpRequest for delete calls + * @param endpoint Backend REST API url. + * @param responseCallback a function to be called with response retrieved. + */ + publicXMLHTTPInvokers.delete = function (endpoint, responseCallback) { + var requestPayload = null; + return privateMethods.initiateXMLHTTPRequest(constants["HTTP_DELETE"], requestPayload, endpoint, responseCallback); + }; + + /** + * --------------------------------------------------------------------------- + * Start of WS-REQUEST based Interceptor implementations + * --------------------------------------------------------------------------- + */ + + /** + * This method add Oauth authentication header to outgoing WS Requests if Oauth authentication is enabled. + * @param action + * @param endpoint service end point to be triggered. + * @param payload soap payload which need to be send. * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. + * @param soapVersion soapVersion which need to used. */ - privateMethods.initiateXMLHTTPRequest = function (method, url, successCallback, errorCallback, payload, contentType, acceptType) { - if (privateMethods.getAccessToken()) { - return privateMethods.execute(method, url, successCallback, errorCallback, payload, 0, contentType, acceptType); + privateMethods.initiateWSRequest = function (action, endpoint, successCallback, errorCallback, soapVersion, payload) { + var ws = require('ws'); + var wsRequest = new ws.WSRequest(); + var options = []; + if (IS_OAUTH_ENABLED) { + var accessToken = privateMethods.getAccessToken(); + if (accessToken) { + var authenticationHeaderName = String(constants.AUTHORIZATION_HEADER); + var authenticationHeaderValue = String(constants.BEARER_PREFIX + accessToken); + var headers = []; + var oAuthAuthenticationData = {}; + oAuthAuthenticationData.name = authenticationHeaderName; + oAuthAuthenticationData.value = authenticationHeaderValue; + headers.push(oAuthAuthenticationData); + options.HTTPHeaders = headers; + } else { + response.sendRedirect(devicemgtProps["httpsURL"] + "/devicemgt/login"); + } } + options.useSOAP = soapVersion; + options.useWSA = constants.WEB_SERVICE_ADDRESSING_VERSION; + options.action = action; + var wsResponse; + try { + wsRequest.open(options, endpoint, false); + if (payload) { + wsRequest.send(payload); + } else { + wsRequest.send(); + } + wsResponse = wsRequest.responseE4X; + } catch (e) { + return errorCallback(e); + } + return successCallback(wsResponse); + }; + + /** + * This method invokes return initiateWSRequest for soap calls + * @param action describes particular soap action. + * @param requestPayload SOAP request payload which is needed to be send. + * @param endpoint service end point to be triggered. + * @param successCallback a function to be called if the respond if successful. + * @param errorCallback a function to be called if en error is reserved. + * @param soapVersion soapVersion which need to used. + */ + publicWSInvokers.soapRequest = function (action, endpoint, payload, successCallback, errorCallback, soapVersion) { + return privateMethods.initiateWSRequest(action, endpoint, successCallback, errorCallback, soapVersion, payload); }; + /** + * --------------------------------------------------------------------------- + * Start of HTTP-CLIENT-REQUEST based Interceptor implementations + * --------------------------------------------------------------------------- + */ + /** * This method add Oauth authentication header to outgoing HTTPClient Requests if Oauth authentication is enabled. * @param method HTTP request type. @@ -118,7 +220,7 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - privateMethods.initiateHTTPClientRequest = function (method, url, successCallback, errorCallback, payload, contentType, acceptType) { + privateMethods.initiateHTTPClientRequest = function (method, url, successCallback, errorCallback, payload) { var HttpClient = Packages.org.apache.commons.httpclient.HttpClient; var httpMethodObject; switch (method) { @@ -144,11 +246,9 @@ var backendServiceInvoker = function () { var Header = Packages.org.apache.commons.httpclient.Header; var header = new Header(); header.setName(constants.CONTENT_TYPE_IDENTIFIER); - header.setValue(contentType); httpMethodObject.addRequestHeader(header); header = new Header(); header.setName(constants.ACCEPT_IDENTIFIER); - header.setValue(acceptType); httpMethodObject.addRequestHeader(header); if (IS_OAUTH_ENABLED) { var accessToken = privateMethods.getAccessToken(); @@ -160,7 +260,6 @@ var backendServiceInvoker = function () { } else { response.sendRedirect(devicemgtProps["httpsURL"] + "/devicemgt/login"); } - } if (payload) { var stringRequestEntity = new StringRequestEntity(stringify(payload)); @@ -187,115 +286,16 @@ var backendServiceInvoker = function () { } }; - /** - * This method add Oauth authentication header to outgoing WS Requests if Oauth authentication is enabled. - * @param action - * @param endpoint service end point to be triggered. - * @param payload soap payload which need to be send. - * @param successCallback a function to be called if the respond if successful. - * @param errorCallback a function to be called if en error is reserved. - * @param soapVersion soapVersion which need to used. - */ - privateMethods.initiateWSRequest = function (action, endpoint, successCallback, errorCallback, soapVersion, payload) { - var ws = require('ws'); - var wsRequest = new ws.WSRequest(); - var options = []; - if (IS_OAUTH_ENABLED) { - var accessToken = privateMethods.getAccessToken(); - if (accessToken) { - var authenticationHeaderName = String(constants.AUTHORIZATION_HEADER); - var authenticationHeaderValue = String(constants.BEARER_PREFIX + accessToken); - var headers = []; - var oAuthAuthenticationData = {}; - oAuthAuthenticationData.name = authenticationHeaderName; - oAuthAuthenticationData.value = authenticationHeaderValue; - headers.push(oAuthAuthenticationData); - options.HTTPHeaders = headers; - } else { - response.sendRedirect(devicemgtProps["httpsURL"] + "/devicemgt/login"); - } - } - options.useSOAP = soapVersion; - options.useWSA = constants.WEB_SERVICE_ADDRESSING_VERSION; - options.action = action; - var wsResponse; - try { - wsRequest.open(options, endpoint, false); - if (payload) { - wsRequest.send(payload); - } else { - wsRequest.send(); - } - wsResponse = wsRequest.responseE4X; - } catch (e) { - return errorCallback(e); - } - return successCallback(wsResponse); - }; - - /** - * This method invokes return initiateXMLHttpRequest for get calls - * @param url target url. - * @param successCallback a function to be called if the respond if successful. - * @param errorCallback a function to be called if en error is reserved. - */ - publicXMLHTTPInvokers.get = function (url, successCallback, errorCallback, contentType, acceptType) { - return privateMethods.initiateXMLHTTPRequest(constants.HTTP_GET, url, successCallback, errorCallback, contentType, acceptType); - }; - - /** - * This method invokes return initiateXMLHttpRequest for post calls - * @param url target url. - * @param payload payload/data which need to be send. - * @param successCallback a function to be called if the respond if successful. - * @param errorCallback a function to be called if en error is reserved. - */ - publicXMLHTTPInvokers.post = function (url, payload, successCallback, errorCallback, contentType, acceptType) { - return privateMethods.initiateXMLHTTPRequest(constants.HTTP_POST, url, successCallback, errorCallback, payload, contentType, acceptType); - }; - - /** - * This method invokes return initiateXMLHttpRequest for put calls - * @param url target url. - * @param payload payload/data which need to be send. - * @param successCallback a function to be called if the respond if successful. - * @param errorCallback a function to be called if en error is reserved. - */ - publicXMLHTTPInvokers.put = function (url, payload, successCallback, errorCallback, contentType, acceptType) { - return privateMethods.initiateXMLHTTPRequest(constants.HTTP_PUT, url, successCallback, errorCallback, payload, contentType, acceptType); - }; - - /** - * This method invokes return initiateXMLHttpRequest for delete calls - * @param url target url. - * @param successCallback a function to be called if the respond if successful. - * @param errorCallback a function to be called if en error is reserved. - */ - publicXMLHTTPInvokers.delete = function (url, successCallback, errorCallback, contentType, acceptType) { - return privateMethods.initiateXMLHTTPRequest(constants.HTTP_DELETE, url, successCallback, errorCallback, contentType, acceptType); - }; - - /** - * This method invokes return initiateWSRequest for soap calls - * @param endpoint service end point to be triggered. - * @param payload soap payload which need to be send. - * @param successCallback a function to be called if the respond if successful. - * @param errorCallback a function to be called if en error is reserved. - * @param soapVersion soapVersion which need to used. - */ - publicWSInvokers.soapRequest = function (action, endpoint, payload, successCallback, errorCallback, soapVersion) { - return privateMethods.initiateWSRequest(action, endpoint, successCallback, errorCallback, soapVersion, payload); - }; - - /** * This method invokes return initiateHTTPClientRequest for get calls * @param url target url. * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.get = function (url, successCallback, errorCallback, contentType, acceptType) { - return privateMethods.initiateHTTPClientRequest(constants.HTTP_GET, url, successCallback, errorCallback, contentType, acceptType); + publicHTTPClientInvokers.get = function (url, successCallback, errorCallback) { + var requestPayload = null; + return privateMethods. + initiateHTTPClientRequest(constants["HTTP_GET"], url, successCallback, errorCallback, requestPayload); }; /** @@ -305,9 +305,9 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.post = function (url, payload, successCallback, errorCallback, contentType, acceptType) { + publicHTTPClientInvokers.post = function (url, payload, successCallback, errorCallback) { return privateMethods. - initiateHTTPClientRequest(constants.HTTP_POST, url, successCallback, errorCallback, payload, contentType, acceptType); + initiateHTTPClientRequest(constants["HTTP_POST"], url, successCallback, errorCallback, payload); }; /** @@ -317,8 +317,9 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.put = function (url, payload, successCallback, errorCallback, contentType, acceptType) { - return privateMethods.initiateHTTPClientRequest(constants.HTTP_PUT, url, successCallback, errorCallback, payload, contentType, acceptType); + publicHTTPClientInvokers.put = function (url, payload, successCallback, errorCallback) { + return privateMethods. + initiateHTTPClientRequest(constants["HTTP_PUT"], url, successCallback, errorCallback, payload); }; /** @@ -327,13 +328,16 @@ var backendServiceInvoker = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.delete = function (url, successCallback, errorCallback, contentType, acceptType) { - return privateMethods.initiateHTTPClientRequest(constants.HTTP_DELETE, url, successCallback, errorCallback, contentType, acceptType); + publicHTTPClientInvokers.delete = function (url, successCallback, errorCallback) { + var requestPayload = null; + return privateMethods. + initiateHTTPClientRequest(constants["HTTP_DELETE"], url, successCallback, errorCallback, requestPayload); }; - var publicInvokers = {}; - publicInvokers.XMLHttp = publicXMLHTTPInvokers; - publicInvokers.WS = publicWSInvokers; - publicInvokers.HttpClient = publicHTTPClientInvokers; - return publicInvokers; -}(); \ No newline at end of file + var publicMethods = {}; + publicMethods.XMLHttp = publicXMLHTTPInvokers; + publicMethods.WS = publicWSInvokers; + publicMethods.HttpClient = publicHTTPClientInvokers; + + return publicMethods; +}(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js index 367db085bc..e1eb9f6859 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js @@ -36,7 +36,8 @@ deviceModule = function () { var publicMethods = {}; var privateMethods = {}; - var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager"; + //var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager"; + var deviceManagementService = utility.getDeviceManagementService(); privateMethods.validateAndReturn = function (value) { return (value == undefined || value == null) ? constants.UNSPECIFIED : value; @@ -97,6 +98,61 @@ deviceModule = function () { } }; + /* + @Deprecated + */ + publicMethods.listDevicesForUser = function (username) { + var carbonUser = session.get(constants.USER_SESSION_KEY); + var utility = require('/modules/utility.js').utility; + if (!carbonUser) { + log.error("User object was not found in the session"); + throw constants.ERRORS.USER_NOT_FOUND; + } + try { + utility.startTenantFlow(carbonUser); + var deviceManagementService = utility.getDeviceManagementService(); + var devices = deviceManagementService.getDeviceListOfUser(username); + var deviceList = []; + var i, device, propertiesList, deviceObject; + for (i = 0; i < devices.size(); i++) { + device = devices.get(i); + propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties()); + + deviceObject = {}; + deviceObject[constants.DEVICE_IDENTIFIER] = + privateMethods.validateAndReturn(device.getDeviceIdentifier()); + deviceObject[constants.DEVICE_NAME] = + privateMethods.validateAndReturn(device.getName()); + deviceObject[constants.DEVICE_OWNERSHIP] = + privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership()); + deviceObject[constants.DEVICE_OWNER] = + privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner()); + deviceObject[constants.DEVICE_TYPE] = + privateMethods.validateAndReturn(device.getType()); + deviceObject[constants.DEVICE_PROPERTIES] = {}; + if (device.getType() == constants.PLATFORM_IOS) { + deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = + privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT)); + deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE; + } else { + deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = + privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL)); + deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = + privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR)); + } + deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] = + privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION)); + + deviceList.push(deviceObject); + } + return deviceList; + } catch (e) { + throw e; + } finally { + utility.endTenantFlow(); + } + }; + /* @Deprecated */ @@ -216,36 +272,36 @@ deviceModule = function () { try { utility.startTenantFlow(carbonUser); - var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/view?type=" + deviceType + "&id=" + deviceId; + var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/api/device-mgt/v1.0/devices/" + deviceType + "/" + deviceId; return serviceInvokers.XMLHttp.get( - url, function (responsePayload) { - var device = responsePayload.responseContent; - if (device) { - var propertiesList = device["properties"]; - var properties = {}; - if (propertiesList){ - for (var i = 0; i < propertiesList.length; i++) { - properties[propertiesList[i]["name"]] = propertiesList[i]["value"]; - } - } - var deviceObject = {}; - deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"]; - deviceObject[constants["DEVICE_NAME"]] = device["name"]; - deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"]; - deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"]; - deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"]; - deviceObject[constants["DEVICE_TYPE"]] = device["type"]; - if (device["type"] == constants["PLATFORM_IOS"]) { - properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]]; - delete properties[constants["DEVICE_PRODUCT"]]; - properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"]; - } - deviceObject[constants["DEVICE_PROPERTIES"]] = properties; - return deviceObject; + url, + function (backendResponse) { + var response = {}; + if (backendResponse.status == 200 && backendResponse.responseText) { + response["status"] = "success"; + var device = parse(backendResponse.responseText); + var propertiesList = device["properties"]; + var properties = {}; + for (var i = 0; i < propertiesList.length; i++) { + properties[propertiesList[i]["name"]] = + propertiesList[i]["value"]; } - }, - function (responsePayload) { - var response = {}; + var deviceObject = {}; + deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"]; + deviceObject[constants["DEVICE_NAME"]] = device["name"]; + deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"]; + deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"]; + deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"]; + deviceObject[constants["DEVICE_TYPE"]] = device["type"]; + if (device["type"] == constants["PLATFORM_IOS"]) { + properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]]; + delete properties[constants["DEVICE_PRODUCT"]]; + properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"]; + } + deviceObject[constants["DEVICE_PROPERTIES"]] = properties; + response["content"] = deviceObject; + return response; + } else { response["status"] = "error"; return response; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js index a8fe2b0fc1..b653b4e163 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js @@ -32,13 +32,11 @@ var invokerRequestWrapper = function () { var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) { var response = {}; response.content = responsePayload["responseContent"]; - response.status = "success"; - return response; - }, - function (responsePayload) { - var response = {}; - response.content = responsePayload; - response.status = "error"; + if (responsePayload.status == 200) { + response.status = "success"; + } else { + response.status = "error"; + } return response; }); return response; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js index a4ee8c1256..a82c8b4732 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js @@ -31,73 +31,91 @@ policyModule = function () { var publicMethods = {}; var privateMethods = {}; - privateMethods.handleGetAllPoliciesError = function (responsePayload) { + privateMethods.handleGetAllPoliciesResponse = function (backendResponse) { var response = {}; - response.status = "error"; - /* responsePayload == "Scope validation failed" - Here the response.context("Scope validation failed") is used other then response.status(401). - Reason for this is IDP return 401 as the status in 4 different situations such as, - 1. UnAuthorized. - 2. Scope Validation Failed. - 3. Permission Denied. - 4. Access Token Expired. - 5. Access Token Invalid. - In these cases in order to identify the correct situation we have to compare the unique value from status and - context which is context. - */ - if (responsePayload == "Scope validation failed") { - response.content = "Permission Denied"; - } else { - response.content = responsePayload; - } - return response; - }; + if (backendResponse.status = 200) { + var isUpdated = false; + var policyListFromRestEndpoint = parse(backendResponse.responseText)["policies"]; + var policyListToView = []; + var i, policyObjectFromRestEndpoint, policyObjectToView; + for (i = 0; i < policyListFromRestEndpoint.length; i++) { + // get list object + policyObjectFromRestEndpoint = policyListFromRestEndpoint[i]; + // populate list object values to view-object + policyObjectToView = {}; + policyObjectToView["id"] = policyObjectFromRestEndpoint["id"]; + policyObjectToView["priorityId"] = policyObjectFromRestEndpoint["priorityId"]; + policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"]; + policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"]["name"]; + policyObjectToView["ownershipType"] = policyObjectFromRestEndpoint["ownershipType"]; + + var assignedRoleCount = policyObjectFromRestEndpoint["roles"].length; + var assignedUserCount = policyObjectFromRestEndpoint["users"].length; + + if (assignedRoleCount == 0) { + policyObjectToView["roles"] = "None"; + } else if (assignedRoleCount == 1) { + policyObjectToView["roles"] = policyObjectFromRestEndpoint["roles"][0]; + } else if (assignedRoleCount > 1) { + policyObjectToView["roles"] = policyObjectFromRestEndpoint["roles"][0] + ", ..."; + } + + if (assignedUserCount == 0) { + policyObjectToView["users"] = "None"; + } else if (assignedUserCount == 1) { + policyObjectToView["users"] = policyObjectFromRestEndpoint["users"][0]; + } else if (assignedUserCount > 1) { + policyObjectToView["users"] = policyObjectFromRestEndpoint["users"][0] + ", ..."; + } - privateMethods.handleGetAllPoliciesSuccess = function (responsePayload) { - var isUpdated = false; - var policyListFromRestEndpoint = responsePayload["responseContent"]; - var policyListToView = []; - var i, policyObjectFromRestEndpoint, policyObjectToView; - for (i = 0; i < policyListFromRestEndpoint.length; i++) { - // get list object - policyObjectFromRestEndpoint = policyListFromRestEndpoint[i]; - // populate list object values to view-object - policyObjectToView = {}; - policyObjectToView["id"] = policyObjectFromRestEndpoint["id"]; - policyObjectToView["priorityId"] = policyObjectFromRestEndpoint["priorityId"]; - policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"]; - policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"]["name"]; - policyObjectToView["icon"] = utility.getDeviceThumb(policyObjectToView["platform"]); - policyObjectToView["ownershipType"] = policyObjectFromRestEndpoint["ownershipType"]; - policyObjectToView["roles"] = privateMethods. - getElementsInAString(policyObjectFromRestEndpoint["roles"]); - policyObjectToView["users"] = privateMethods. - getElementsInAString(policyObjectFromRestEndpoint["users"]); - policyObjectToView["compliance"] = policyObjectFromRestEndpoint["compliance"]; + policyObjectToView["compliance"] = policyObjectFromRestEndpoint["compliance"]; - if (policyObjectFromRestEndpoint["active"] == true && policyObjectFromRestEndpoint["updated"] == true) { - policyObjectToView["status"] = "Active/Updated"; - isUpdated = true; - } else if (policyObjectFromRestEndpoint["active"] == true && - policyObjectFromRestEndpoint["updated"] == false) { - policyObjectToView["status"] = "Active"; - } else if (policyObjectFromRestEndpoint["active"] == false && - policyObjectFromRestEndpoint["updated"] == true) { - policyObjectToView["status"] = "Inactive/Updated"; - isUpdated = true; - } else if (policyObjectFromRestEndpoint["active"] == false && - policyObjectFromRestEndpoint["updated"] == false) { - policyObjectToView["status"] = "Inactive"; + if (policyObjectFromRestEndpoint["active"] == true && + policyObjectFromRestEndpoint["updated"] == true) { + policyObjectToView["status"] = "Active/Updated"; + isUpdated = true; + } else if (policyObjectFromRestEndpoint["active"] == true && + policyObjectFromRestEndpoint["updated"] == false) { + policyObjectToView["status"] = "Active"; + } else if (policyObjectFromRestEndpoint["active"] == false && + policyObjectFromRestEndpoint["updated"] == true) { + policyObjectToView["status"] = "Inactive/Updated"; + isUpdated = true; + } else if (policyObjectFromRestEndpoint["active"] == false && + policyObjectFromRestEndpoint["updated"] == false) { + policyObjectToView["status"] = "Inactive"; + } + // push view-objects to list + policyListToView.push(policyObjectToView); } - // push view-objects to list - policyListToView.push(policyObjectToView); + // generate response + response.updated = isUpdated; + response.status = "success"; + response.content = policyListToView; + + log.info(stringify(policyListToView)); + + return response; + } else { + response.status = "error"; + /* backendResponse.responseText == "Scope validation failed" + Here the response.context("Scope validation failed") is used other then response.status(401). + Reason for this is IDP return 401 as the status in 4 different situations such as, + 1. UnAuthorized. + 2. Scope Validation Failed. + 3. Permission Denied. + 4. Access Token Expired. + 5. Access Token Invalid. + In these cases in order to identify the correct situation we have to compare the unique value from status and + context which is context. + */ + if (backendResponse.responseText == "Scope validation failed") { + response.content = "Permission Denied"; + } else { + response.content = backendResponse.responseText; + } + return response; } - // generate response - var response = {}; - response.updated = isUpdated; - response.status = "success"; - response.content = policyListToView; - return response; }; publicMethods.addPolicy = function (policyName, deviceType, policyDefinition, policyDescription, @@ -155,9 +173,8 @@ policyModule = function () { throw constants["ERRORS"]["USER_NOT_FOUND"]; } try { - var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/policies"; - return serviceInvokers.XMLHttp. - get(url, privateMethods.handleGetAllPoliciesSuccess, privateMethods.handleGetAllPoliciesError); + var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/policies?offset=0&limit=100"; + return serviceInvokers.XMLHttp.get(url, privateMethods.handleGetAllPoliciesResponse); } catch (e) { throw e; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js index b0eb98c554..24cb4c63bb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js @@ -66,22 +66,18 @@ var userModule = function () { */ privateMethods.callBackend = function (url, method) { if (constants.HTTP_GET == method) { - var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) { - var response = {}; - response.content = responsePayload["responseContent"]; - if (responsePayload["responseContent"] == null && responsePayload != null) { - response.content = responsePayload; + return serviceInvokers.XMLHttp.get(url, + function (backendResponse) { + var response = {}; + response.content = backendResponse.responseText; + if (backendResponse.status == 200) { + response.status = "success"; + } else { + response.status = "error"; + } + return response; } - response.status = "success"; - return response; - }, - function (responsePayload) { - var response = {}; - response.content = responsePayload; - response.status = "error"; - return response; - }); - return response; + ); } else { log.error("Programming error : This method only support HTTP GET requests."); } @@ -382,9 +378,12 @@ var userModule = function () { } try { utility.startTenantFlow(carbonUser); - var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users"; - return privateMethods.callBackend(url, constants.HTTP_GET); - + var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users?offset=0&limit=100"; + var response = privateMethods.callBackend(url, constants["HTTP_GET"]); + if (response.status == "success") { + response.content = parse(response.content).users; + } + return response; } catch (e) { throw e; } finally { @@ -409,8 +408,10 @@ var userModule = function () { var carbonUser = privateMethods.getCarbonUser(); try { utility.startTenantFlow(carbonUser); - var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/view?username=" + username; - var response = privateMethods.callBackend(url, constants.HTTP_GET); + var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/" + + encodeURIComponent(username); + var response = privateMethods.callBackend(url, constants["HTTP_GET"]); + response["content"] = parse(response.content); response["userDomain"] = carbonUser.domain; return response; } catch (e) { @@ -420,17 +421,17 @@ var userModule = function () { } }; /** - * TODO: comment + * Returns a set of roles assigned to a particular user * @param username - * @returns {*} + * @returns {object} a response object with status and content on success. */ publicMethods.getRolesByUsername = function (username) { var carbonUser = privateMethods.getCarbonUser(); try { utility.startTenantFlow(carbonUser); - var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/users/roles?username=" + username; - var response = privateMethods.callBackend(url, constants.HTTP_GET); - return response; + var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + + "/users/" + + encodeURIComponent(username) + "/roles"; + return privateMethods.callBackend(url, constants["HTTP_GET"]); } catch (e) { throw e; } finally { @@ -464,6 +465,7 @@ var userModule = function () { */ /** * Get User Roles from user store (Internal roles not included). + * @returns {object} a response object with status and content on success. */ publicMethods.getRoles = function () { var carbonUser = session.get(constants["USER_SESSION_KEY"]); @@ -475,7 +477,11 @@ var userModule = function () { try { utility.startTenantFlow(carbonUser); var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles"; - return privateMethods.callBackend(url, constants.HTTP_GET); + var response = privateMethods.callBackend(url, constants["HTTP_GET"]); + if (response.status == "success") { + response.content = parse(response.content).roles; + } + return response; } catch (e) { throw e; } finally { @@ -488,8 +494,10 @@ var userModule = function () { */ /** * Get User Roles from user store (Internal roles not included). + * @returns {object} a response object with status and content on success. */ - publicMethods.getRolesByUserStore = function (userStore) { + publicMethods.getRolesByUserStore = function () { + var ROLE_LIMIT = devicemgtProps.pageSize; var carbonUser = session.get(constants["USER_SESSION_KEY"]); var utility = require('/app/modules/utility.js')["utility"]; if (!carbonUser) { @@ -498,8 +506,12 @@ var userModule = function () { } try { utility.startTenantFlow(carbonUser); - var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles/" + encodeURIComponent(userStore); - return privateMethods.callBackend(url, constants.HTTP_GET); + var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles?limit=" + ROLE_LIMIT; + var response = privateMethods.callBackend(url, constants["HTTP_GET"]); + if (response.status == "success") { + response.content = parse(response.content).roles; + } + return response; } catch (e) { throw e; } finally { @@ -520,7 +532,11 @@ var userModule = function () { try { utility.startTenantFlow(carbonUser); var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/types"; - return privateMethods.callBackend(url, constants.HTTP_GET); + var response = privateMethods.callBackend(url, constants["HTTP_GET"]); + if (response.status == "success") { + response.content = parse(response.content); + } + return response; } catch (e) { throw e; } finally { @@ -542,8 +558,9 @@ var userModule = function () { } try { utility.startTenantFlow(carbonUser); - var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles/role?rolename=" + encodeURIComponent(roleName); - var response = privateMethods.callBackend(url, constants.HTTP_GET); + var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/roles/" + encodeURIComponent(roleName); + var response = privateMethods.callBackend(url, constants["HTTP_GET"]); + response.content = parse(response.content); return response; } catch (e) { throw e; @@ -683,6 +700,9 @@ var userModule = function () { if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/platform-configs/view")) { permissions["TENANT_CONFIGURATION"] = true; } + if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/devices/list")) { + permissions["LIST_OWN_DEVICES"] = true; + } return permissions; }; From 24b462f4f4dee1633597bac0cf77f5015b31d078 Mon Sep 17 00:00:00 2001 From: Chatura Dilan Date: Wed, 29 Jun 2016 17:41:45 +0530 Subject: [PATCH 06/11] Added is-active field to the Application --- .../device/mgt/common/app/mgt/Application.java | 12 +++++++++++- .../mgt/core/dao/impl/ApplicationDAOImpl.java | 15 +++++++++------ .../src/test/resources/sql/h2.sql | 1 + .../src/test/resources/sql/CreateH2TestDB.sql | 1 + .../src/main/resources/dbscripts/cdm/h2.sql | 1 + .../src/main/resources/dbscripts/cdm/mssql.sql | 1 + .../src/main/resources/dbscripts/cdm/mysql.sql | 1 + .../src/main/resources/dbscripts/cdm/oracle.sql | 1 + .../main/resources/dbscripts/cdm/postgresql.sql | 1 + 9 files changed, 27 insertions(+), 7 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java index 1b17534dcf..82e3108149 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java @@ -49,8 +49,10 @@ public class Application implements Serializable { private Properties appProperties; @ApiModelProperty(name = "applicationIdentifier", value = "The application identifier", required = true) private String applicationIdentifier; - @ApiModelProperty(name = "memoryUsage", value = "AMount of memory used by the application", required = true) + @ApiModelProperty(name = "memoryUsage", value = "Amount of memory used by the application", required = true) private int memoryUsage; + @ApiModelProperty(name = "isActive", value = "Is the application actively running", required = true) + private boolean isActive; public String getType() { @@ -166,4 +168,12 @@ public class Application implements Serializable { this.appProperties = appProperties; } + + public boolean isActive() { + return isActive; + } + + public void setActive(boolean active) { + isActive = active; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java index f6b320682b..a9312623ae 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java @@ -47,8 +47,8 @@ public class ApplicationDAOImpl implements ApplicationDAO { try { conn = this.getConnection(); stmt = conn.prepareStatement("INSERT INTO DM_APPLICATION (NAME, PLATFORM, CATEGORY, " + - "VERSION, TYPE, LOCATION_URL, IMAGE_URL, TENANT_ID, APP_PROPERTIES, APP_IDENTIFIER, MEMORY_USAGE) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + "VERSION, TYPE, LOCATION_URL, IMAGE_URL, TENANT_ID, APP_PROPERTIES, APP_IDENTIFIER, MEMORY_USAGE, IS_ACTIVE) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setString(1, application.getName()); stmt.setString(2, application.getPlatform()); @@ -66,6 +66,7 @@ public class ApplicationDAOImpl implements ApplicationDAO { stmt.setString(10, application.getApplicationIdentifier()); stmt.setInt(11, application.getMemoryUsage()); + stmt.setBoolean(12, application.isActive()); stmt.execute(); rs = stmt.getGeneratedKeys(); @@ -109,8 +110,8 @@ public class ApplicationDAOImpl implements ApplicationDAO { try { conn = this.getConnection(); stmt = conn.prepareStatement("INSERT INTO DM_APPLICATION (NAME, PLATFORM, CATEGORY, " + - "VERSION, TYPE, LOCATION_URL, IMAGE_URL, TENANT_ID,APP_PROPERTIES, APP_IDENTIFIER, MEMORY_USAGE) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", new String[]{"id"}); + "VERSION, TYPE, LOCATION_URL, IMAGE_URL, TENANT_ID,APP_PROPERTIES, APP_IDENTIFIER, MEMORY_USAGE, IS_ACTIVE) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", new String[]{"id"}); for (Application application : applications) { @@ -131,6 +132,7 @@ public class ApplicationDAOImpl implements ApplicationDAO { stmt.setString(10, application.getApplicationIdentifier()); stmt.setInt(11, application.getMemoryUsage()); + stmt.setBoolean(12, application.isActive()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); @@ -208,7 +210,7 @@ public class ApplicationDAOImpl implements ApplicationDAO { try { conn = this.getConnection(); stmt = conn.prepareStatement("SELECT ID, NAME, APP_IDENTIFIER, PLATFORM, CATEGORY, VERSION, TYPE, " + - "LOCATION_URL, IMAGE_URL, APP_PROPERTIES, MEMORY_USAGE, TENANT_ID FROM DM_APPLICATION WHERE APP_IDENTIFIER = ? " + + "LOCATION_URL, IMAGE_URL, APP_PROPERTIES, MEMORY_USAGE, IS_ACTIVE, TENANT_ID FROM DM_APPLICATION WHERE APP_IDENTIFIER = ? " + "AND TENANT_ID = ?"); stmt.setString(1, identifier); stmt.setInt(2, tenantId); @@ -240,7 +242,7 @@ public class ApplicationDAOImpl implements ApplicationDAO { try { conn = this.getConnection(); stmt = conn.prepareStatement("Select ID, NAME, APP_IDENTIFIER, PLATFORM, CATEGORY, VERSION, TYPE, " + - "LOCATION_URL, IMAGE_URL, APP_PROPERTIES, MEMORY_USAGE, TENANT_ID From DM_APPLICATION app " + + "LOCATION_URL, IMAGE_URL, APP_PROPERTIES, MEMORY_USAGE, IS_ACTIVE, TENANT_ID From DM_APPLICATION app " + "INNER JOIN " + "(Select APPLICATION_ID From DM_DEVICE_APPLICATION_MAPPING WHERE DEVICE_ID=?) APPMAP " + "ON " + @@ -287,6 +289,7 @@ public class ApplicationDAOImpl implements ApplicationDAO { application.setPlatform(rs.getString("PLATFORM")); application.setVersion(rs.getString("VERSION")); application.setMemoryUsage(rs.getInt("MEMORY_USAGE")); + application.setActive(rs.getBoolean("IS_ACTIVE")); application.setApplicationIdentifier(rs.getString("APP_IDENTIFIER")); } catch (IOException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index f9062684ae..a370c70ca1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -388,6 +388,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, MEMORY_USAGE INTEGER(10) NULL, + IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index fe3d2de042..d7ab39170b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -392,6 +392,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, MEMORY_USAGE INTEGER(10) NULL, + IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index fe3d2de042..d7ab39170b 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -392,6 +392,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, MEMORY_USAGE INTEGER(10) NULL, + IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql index b810963921..68345b343b 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -399,6 +399,7 @@ CREATE TABLE DM_APPLICATION ( IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES VARBINARY(max) NULL, MEMORY_USAGE INTEGER NULL, + IS_ACTIVE BIT NOT NULL DEFAULT 'FALSE', TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index 651bb734e9..d7f4efab06 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -365,6 +365,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, MEMORY_USAGE INTEGER(10) NULL, + IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) )ENGINE = InnoDB; diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql index de8645df1f..57f55c5d17 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -661,6 +661,7 @@ CREATE TABLE DM_APPLICATION ( IMAGE_URL VARCHAR2(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, MEMORY_USAGE NUMBER(10) NULL, + IS_ACTIVE NUMBER(10) DEFAULT 0 NOT NULL, TENANT_ID NUMBER(10) NOT NULL, CONSTRAINT PK_DM_APPLICATION PRIMARY KEY (ID) ) diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql index 407c2cc155..bfc4a7f062 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -341,6 +341,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BYTEA NULL, MEMORY_USAGE INTEGER NULL, + IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL ); From 37852051ff453d0cc53f04c1bbeeec3900980006 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Wed, 29 Jun 2016 17:49:34 +0530 Subject: [PATCH 07/11] Improving Device and Policy Management APIs and cleaning up code of Role and User Management APIs --- .../impl/DeviceManagementServiceImpl.java | 84 +++++------- .../impl/PolicyManagementServiceImpl.java | 121 +++++++++--------- .../impl/RoleManagementServiceImpl.java | 8 +- .../impl/UserManagementServiceImpl.java | 11 +- 4 files changed, 104 insertions(+), 120 deletions(-) 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 f48e76430c..97a6c549ff 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 @@ -27,7 +27,6 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; -import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; @@ -35,10 +34,7 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList; import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; @@ -100,9 +96,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { try { sinceDate = format.parse(ifModifiedSince); } catch (ParseException e) { - throw new InputValidationException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Invalid date " + - "string is provided in 'If-Modified-Since' header").build()); + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("Invalid date " + + "string is provided in 'If-Modified-Since' header").build()).build(); } request.setSince(sinceDate); result = dms.getAllDevices(request); @@ -116,9 +112,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { try { sinceDate = format.parse(since); } catch (ParseException e) { - throw new InputValidationException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Invalid date " + - "string is provided in 'since' filter").build()); + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("Invalid date " + + "string is provided in 'since' filter").build()).build(); } request.setSince(sinceDate); result = dms.getAllDevices(request); @@ -140,8 +136,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } catch (DeviceManagementException e) { String msg = "Error occurred while fetching all enrolled devices"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -161,13 +157,13 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } catch (DeviceManagementException e) { String msg = "Error occurred while fetching the device information."; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } if (device == null) { - throw new NotFoundException( + return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("Requested device of type '" + - type + "', which carries id '" + id + "' does not exist").build()); + type + "', which carries id '" + id + "' does not exist").build()).build(); } return Response.status(Response.Status.OK).entity(device).build(); } @@ -187,17 +183,17 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { dms = DeviceMgtAPIUtils.getDeviceManagementService(); FeatureManager fm = dms.getFeatureManager(type); if (fm == null) { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No feature manager is " + - "registered with the given type '" + type + "'").build()); + return Response.status(Response.Status.NOT_FOUND).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("No feature manager is " + + "registered with the given type '" + type + "'").build()).build(); } features = fm.getFeatures(); } catch (DeviceManagementException e) { String msg = "Error occurred while retrieving the list of features of '" + type + "' device, which " + "carries the id '" + id + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity(features).build(); } @@ -216,13 +212,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } catch (SearchMgtException e) { String msg = "Error occurred while searching for devices that matches the provided selection criteria"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - if (devices == null || devices.size() == 0) { - Response.status(Response.Status.OK).entity(deviceList); - } - deviceList.setList(devices); return Response.status(Response.Status.OK).entity(deviceList).build(); } @@ -237,23 +229,21 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @QueryParam("offset") int offset, @QueryParam("limit") int limit) { List applications; + //ApplicationList appList; ApplicationManagementProviderService amc; try { RequestValidationUtil.validateDeviceIdentifier(type, id); amc = DeviceMgtAPIUtils.getAppManagementService(); applications = amc.getApplicationListForDevice(new DeviceIdentifier(id, type)); - if (applications == null) { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("It is likely that " + - "no applications is found upon the provided type and id").build()); - } + + //TODO: return app list } catch (ApplicationManagementException e) { String msg = "Error occurred while fetching the apps of the '" + type + "' device, which carries " + "the id '" + id + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity(applications).build(); } @@ -276,23 +266,17 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { dms = DeviceMgtAPIUtils.getDeviceManagementService(); result = dms.getOperations(new DeviceIdentifier(id, type),request); - int resultCount = result.getRecordsTotal(); - if (resultCount == 0) { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("It is likely that" + - " no operation is found upon the provided type and id").build()); - } + operationsList.setList((List) result.getData()); + operationsList.setCount(result.getRecordsTotal()); + return Response.status(Response.Status.OK).entity(operationsList).build(); } catch (OperationManagementException e) { String msg = "Error occurred while fetching the operations for the '" + type + "' device, which " + "carries the id '" + id + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - operationsList.setList((List) result.getData()); - operationsList.setCount(result.getRecordsTotal()); - return Response.status(Response.Status.OK).entity(operationsList).build(); } @GET @@ -306,18 +290,14 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); Policy policy = policyManagementService.getAppliedPolicyToDevice(new DeviceIdentifier(id, type)); - if (policy == null) { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No policy has " + - "been found for the '" + type + "' device, which carries the id '" + id + "'").build()); - } + return Response.status(Response.Status.OK).entity(policy).build(); } catch (PolicyManagementException e) { String msg = "Error occurred while retrieving the current policy associated with the '" + type + "' device, which carries the id '" + id + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java index ca2a7a5096..ffd87ad598 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -31,7 +31,6 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; import org.wso2.carbon.device.mgt.jaxrs.service.api.PolicyManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyList; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; @@ -45,6 +44,8 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import java.net.URI; +import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; @@ -53,6 +54,7 @@ import java.util.List; @Consumes(MediaType.APPLICATION_JSON) public class PolicyManagementServiceImpl implements PolicyManagementService { + private static final String API_BASE_PATH = "/policies"; private static final Log log = LogFactory.getLog(PolicyManagementServiceImpl.class); @POST @@ -74,31 +76,38 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { String username = threadLocalCarbonContext.getUsername(); try { if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, username)) { - throw new UnauthorizedAccessException( - new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage - ("Current logged in user is not authorized to add policies").build()); + return Response.status(Response.Status.UNAUTHORIZED).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage + ("Current logged in user is not authorized to add policies").build()).build(); } } catch (DeviceAccessAuthorizationException e) { - String msg = "ErrorResponse occurred while checking if the current user is authorized to add a policy"; + String msg = "Error occurred while checking if the current user is authorized to add a policy"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } PolicyAdministratorPoint pap = policyManagementService.getPAP(); - pap.addPolicy(policy); - return Response.status(Response.Status.CREATED).entity("Policy has been added successfully").build(); + Policy createdPolicy = pap.addPolicy(policy); + + return Response.created(new URI(API_BASE_PATH + "/" + createdPolicy.getId())).entity(createdPolicy).build(); } catch (PolicyManagementException e) { - String msg = "ErrorResponse occurred while adding policy"; + String msg = "Error occurred while adding policy"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build(); } catch (DeviceManagementException e) { - String msg = "ErrorResponse occurred while retrieving device list."; + String msg = "Error occurred while retrieving device list."; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build(); + } catch (URISyntaxException e) { + String msg = "Error occurred while composing the location URI, which represents information of the " + + "newly created policy"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -138,21 +147,14 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { try { PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); policies = policyAdministratorPoint.getPolicies(); - if (policies == null || policies.size() == 0) { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No policies found.").build()); - } targetPolicies.setCount(policies.size()); filteredPolicies = FilteringUtil.getFilteredList(policies, offset, limit); - if (filteredPolicies.size() == 0) { - return Response.status(Response.Status.NOT_FOUND).entity("No policies found.").build(); - } targetPolicies.setList(filteredPolicies); } catch (PolicyManagementException e) { - String msg = "ErrorResponse occurred while retrieving all available policies"; + String msg = "Error occurred while retrieving all available policies"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity(targetPolicies).build(); @@ -168,14 +170,15 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP(); policy = policyAdministratorPoint.getPolicy(id); if (policy == null) { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No policy found.").build()); + return Response.status(Response.Status.NOT_FOUND).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage( + "No policy found with the id '" + id + "'").build()).build(); } } catch (PolicyManagementException e) { - String msg = "ErrorResponse occurred while retrieving policy corresponding to the id '" + id + "'"; + String msg = "Error occurred while retrieving policy corresponding to the id '" + id + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity(policy).build(); } @@ -190,22 +193,22 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { Policy policy = this.getPolicyFromWrapper(policyWrapper); policy.setId(id); PolicyAdministratorPoint pap = policyManagementService.getPAP(); - Policy exisitingPolicy = pap.getPolicy(id); - if (exisitingPolicy == null) { + Policy existingPolicy = pap.getPolicy(id); + if (existingPolicy == null) { return Response.status(Response.Status.NOT_FOUND).entity("Policy not found.").build(); } pap.updatePolicy(policy); return Response.status(Response.Status.OK).entity("Policy has successfully been updated.").build(); } catch (PolicyManagementException e) { - String msg = "ErrorResponse occurred while updating the policy"; + String msg = "Error occurred while updating the policy"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (DeviceManagementException e) { - String msg = "ErrorResponse occurred while retrieving the device list."; + String msg = "Error occurred while retrieving the device list."; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -227,15 +230,15 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { } catch (PolicyManagementException e) { String msg = "ErrorResponse occurred while removing policies"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } if (policyDeleted) { return Response.status(Response.Status.OK).entity("Policies have been successfully deleted").build(); } else { //TODO:Check of this logic is correct - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("Policy doesn't exist").build()); + return Response.status(Response.Status.NOT_FOUND).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("Policy doesn't exist").build()).build(); } } @@ -256,18 +259,18 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { } } } catch (PolicyManagementException e) { - String msg = "ErrorResponse occurred while activating policies"; + String msg = "Error occurred while activating policies"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build(); } if (isPolicyActivated) { return Response.status(Response.Status.OK).entity("Selected policies have been successfully activated") .build(); } else { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("Selected policies have " + - "not been activated").build()); + return Response.status(Response.Status.NOT_FOUND).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("Selected policies have " + + "not been activated").build()).build(); } } @@ -290,16 +293,16 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { } catch (PolicyManagementException e) { String msg = "Exception in inactivating policies."; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } if (isPolicyDeActivated) { return Response.status(Response.Status.OK).entity("Selected policies have been successfully " + "deactivated").build(); } else { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("Selected policies have " + - "not been deactivated").build()); + return Response.status(Response.Status.NOT_FOUND).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("Selected policies have " + + "not been deactivated").build()).build(); } } @@ -315,8 +318,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { } catch (PolicyManagementException e) { String msg = "Exception in applying changes."; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build(); } return Response.status(Response.Status.OK).entity("Changes have been successfully updated.").build(); } @@ -340,17 +343,17 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { } catch (PolicyManagementException e) { String error = "Exception in updating policy priorities."; log.error(error, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(error).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(error).build()).build(); } if (policiesUpdated) { return Response.status(Response.Status.OK).entity("Policy Priorities successfully " + "updated.").build(); } else { - throw new NotFoundException( + return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Policy priorities did " - + "not update. Bad Request.").build()); + + "not update. Bad Request.").build()).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java index 9100c54ac0..7d5da44c86 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -88,7 +88,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { try { final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); if (!userRealm.getUserStoreManager().isExistingRole(roleName)) { - return Response.status(404).entity(new ErrorResponse.ErrorResponseBuilder().setMessage( + return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponse.ErrorResponseBuilder().setMessage( "No role exists with the name '" + roleName + "'").build()).build(); } @@ -153,7 +153,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); if (!userStoreManager.isExistingRole(roleName)) { - return Response.status(404).entity( + return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + roleName + "'").build()).build(); } @@ -234,7 +234,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); final UserStoreManager userStoreManager = userRealm.getUserStoreManager(); if (!userStoreManager.isExistingRole(roleName)) { - return Response.status(404).entity( + return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + roleName + "'").build()).build(); } @@ -290,7 +290,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); final UserStoreManager userStoreManager = userRealm.getUserStoreManager(); if (!userStoreManager.isExistingRole(roleName)) { - return Response.status(404).entity( + return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + roleName + "'").build()).build(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index ff6f007ad3..3799b68d31 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -57,7 +57,7 @@ public class UserManagementServiceImpl implements UserManagementService { " already exists. Therefore, request made to add user was refused."); } // returning response with bad request state - return Response.status(409).entity( + return Response.status(Response.Status.CONFLICT).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + userInfo.getUsername() + " already exists. Therefore, request made to add user " + "was refused.").build()).build(); @@ -108,7 +108,8 @@ public class UserManagementServiceImpl implements UserManagementService { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist."); } - return Response.status(404).entity(new ErrorResponse.ErrorResponseBuilder().setMessage( + return Response.status(Response.Status.NOT_FOUND).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage( "User doesn't exist.").build()).build(); } @@ -133,7 +134,7 @@ public class UserManagementServiceImpl implements UserManagementService { log.debug("User by username: " + userInfo.getUsername() + " doesn't exists. Therefore, request made to update user was refused."); } - return Response.status(404).entity( + return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + userInfo.getUsername() + " doesn't exist.").build()).build(); } @@ -206,7 +207,7 @@ public class UserManagementServiceImpl implements UserManagementService { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist for removal."); } - return Response.status(404).entity( + return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User '" + username + "' does not exist for removal.").build()).build(); } @@ -234,7 +235,7 @@ public class UserManagementServiceImpl implements UserManagementService { if (log.isDebugEnabled()) { log.debug("User by username: " + username + " does not exist for role retrieval."); } - return Response.status(404).entity( + return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + username + " does not exist for role retrieval.").build()).build(); } From ed5d611c3516c40729c5ca5b310f192174098f6e Mon Sep 17 00:00:00 2001 From: prabathabey Date: Wed, 29 Jun 2016 18:05:09 +0530 Subject: [PATCH 08/11] Code cleanup --- .../service/api/DeviceManagementService.java | 14 ++--- .../api/NotificationManagementService.java | 3 +- .../service/api/PolicyManagementService.java | 10 ++-- .../ApplicationManagementAdminService.java | 4 +- .../admin/DeviceManagementAdminService.java | 2 +- .../api/admin/UserManagementAdminService.java | 2 +- .../impl/DeviceManagementServiceImpl.java | 2 +- .../NotificationManagementServiceImpl.java | 21 +++---- .../impl/PolicyManagementServiceImpl.java | 2 +- .../impl/RoleManagementServiceImpl.java | 2 +- .../impl/UserManagementServiceImpl.java | 2 +- ...ApplicationManagementAdminServiceImpl.java | 33 ++++++----- .../DeviceManagementAdminServiceImpl.java | 19 ++----- .../CredentialManagementResponseBuilder.java | 56 +++++++++---------- 14 files changed, 81 insertions(+), 91 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index f82a9737b6..29e36efd39 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -87,7 +87,7 @@ public interface DeviceManagementService { 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 device list.", + message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) @Permission(scope = "device-list", permissions = {"/permission/admin/device-mgt/admin/devices/list"}) @@ -180,7 +180,7 @@ public interface DeviceManagementService { response = ErrorResponse.class), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while retrieving information requested device.", response = ErrorResponse.class) }) @@ -259,7 +259,7 @@ public interface DeviceManagementService { message = "Not Acceptable. \n The requested media type is not supported."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while retrieving feature list of the device.", response = ErrorResponse.class) }) @@ -331,7 +331,7 @@ public interface DeviceManagementService { message = "Unsupported media type. \n The entity of the request was in a not supported format."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while enrolling the device.", response = ErrorResponse.class) }) @@ -405,7 +405,7 @@ public interface DeviceManagementService { message = "Not Acceptable. \n The requested media type is not supported."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while retrieving installed application list of the device.", response = ErrorResponse.class) }) @@ -494,7 +494,7 @@ public interface DeviceManagementService { message = "Not Acceptable. \n The requested media type is not supported."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while retrieving operation list scheduled for the device.", response = ErrorResponse.class) }) @@ -582,7 +582,7 @@ public interface DeviceManagementService { message = "Not Acceptable. \n The requested media type is not supported."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while retrieving the effective policy calculated for the device.", response = ErrorResponse.class) }) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java index 6a21547885..87134f05c0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java @@ -85,7 +85,8 @@ public interface NotificationManagementService { 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 notification list.", + message = "Internal Server Error. " + + "\n Server error occurred while fetching the notification list.", response = ErrorResponse.class) }) @Permission(scope = "device-notification-view", permissions = { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java index 05515fb655..468c14f42f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java @@ -90,7 +90,7 @@ public interface PolicyManagementService { message = "Unsupported media type. \n The entity of the request was in a not supported format."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while adding a new policy.", response = ErrorResponse.class) }) @@ -142,7 +142,7 @@ public interface PolicyManagementService { message = "Not Acceptable.\n The requested media type is not supported"), @ApiResponse( code = 500, - message = ("Internal Server ErrorResponse. \n Server error occurred while fetching " + + message = ("Internal Server Error. \n Server error occurred while fetching " + "policies."), response = ErrorResponse.class) }) @@ -205,7 +205,7 @@ public interface PolicyManagementService { 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 " + + message = "Internal Server Error. \n Server error occurred while fetching the " + "policy.", response = ErrorResponse.class) }) @@ -265,7 +265,7 @@ public interface PolicyManagementService { message = "Unsupported media type. \n The entity of the request was in a not supported format."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while updating the policy.", response = ErrorResponse.class) }) @@ -307,7 +307,7 @@ public interface PolicyManagementService { message = "Unsupported media type. \n The entity of the request was in a not supported format."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while bulk removing policies.", response = ErrorResponse.class) }) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java index 23b6cba5ab..49f15dccb1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java @@ -68,7 +68,7 @@ public interface ApplicationManagementAdminService { message = "Unsupported media type. \n The entity of the request was in a not supported format."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while bulk issuing application installation operations upon " + "a given set of devices.", response = ErrorResponse.class) @@ -106,7 +106,7 @@ public interface ApplicationManagementAdminService { message = "Unsupported media type. \n The entity of the request was in a not supported format."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while bulk issuing application un-installation operations upon " + "a given set of devices.", response = ErrorResponse.class) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java index 2396de53f1..89b8d9185b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java @@ -80,7 +80,7 @@ public interface DeviceManagementAdminService { 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 device list.", + message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) Response getDevicesByName( diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java index fb8610ce43..66ca21d1fc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java @@ -60,7 +60,7 @@ public interface UserManagementAdminService { message = "Unsupported media type. \n The entity of the request was in a not supported format."), @ApiResponse( code = 500, - message = "Internal Server ErrorResponse. \n " + + message = "Internal Server Error. \n " + "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) 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 97a6c549ff..edac09a140 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 @@ -265,7 +265,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { RequestValidationUtil.validateDeviceIdentifier(type, id); dms = DeviceMgtAPIUtils.getDeviceManagementService(); - result = dms.getOperations(new DeviceIdentifier(id, type),request); + result = dms.getOperations(new DeviceIdentifier(id, type), request); operationsList.setList((List) result.getData()); operationsList.setCount(result.getRecordsTotal()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java index 8d7a2a72b1..2d1171f7a5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java @@ -22,11 +22,10 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; -import org.wso2.carbon.device.mgt.jaxrs.NotificationContext; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.NotificationList; import org.wso2.carbon.device.mgt.jaxrs.service.api.NotificationManagementService; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.*; @@ -49,6 +48,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement @QueryParam("offset") int offset, @QueryParam("limit") int limit) { String msg; List notifications; + NotificationList notificationList = new NotificationList(); try { if (status != null) { RequestValidationUtil.validateNotificationStatus(status); @@ -59,17 +59,14 @@ public class NotificationManagementServiceImpl implements NotificationManagement notifications = DeviceMgtAPIUtils.getNotificationManagementService().getAllNotifications(); } - if (notifications == null || notifications.size() == 0) { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No notification is " + - "available to be retrieved.").build()); - } - return Response.status(Response.Status.OK).entity(notifications).build(); + notificationList.setCount(notifications.size()); + notificationList.setNotifications(notifications); + return Response.status(Response.Status.OK).entity(notificationList).build(); } catch (NotificationManagementException e) { - msg = "Error occurred while retrieving notification info"; + msg = "Error occurred while retrieving notification list"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java index ffd87ad598..455dc0f9ea 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -298,7 +298,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { } if (isPolicyDeActivated) { return Response.status(Response.Status.OK).entity("Selected policies have been successfully " + - "deactivated").build(); + "deactivated").build(); } else { return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("Selected policies have " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java index 7d5da44c86..4e788411e3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -209,7 +209,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { //TODO fix what's returned in the entity return Response.created(new URI(API_BASE_PATH + "/" + roleInfo.getRoleName())).entity( "Role '" + roleInfo.getRoleName() + "' has " + - "successfully been added").build(); + "successfully been added").build(); } catch (UserStoreException e) { String msg = "Error occurred while adding role '" + roleInfo.getRoleName() + "'"; log.error(msg, e); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 3799b68d31..d95f7d6afd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -110,7 +110,7 @@ public class UserManagementServiceImpl implements UserManagementService { } return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage( - "User doesn't exist.").build()).build(); + "User doesn't exist.").build()).build(); } BasicUserInfo user = this.getBasicUserInfo(username); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java index 3aa0e8f3c9..59f32534c9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java @@ -29,9 +29,7 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.exception.UnknownApplicationTypeException; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.ApplicationManagementAdminService; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.MDMAndroidOperationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.MDMIOSOperationUtil; @@ -82,21 +80,22 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem applicationWrapper.getDeviceIdentifiers().size() > 0) { activity = appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); } else { - throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( - "No application installation criteria i.e. user/role/device is given").build()); + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage( + "No application installation criteria i.e. user/role/device is given").build()).build(); } } return Response.status(Response.Status.ACCEPTED).entity(activity).build(); } catch (ApplicationManagementException e) { - String msg = "ErrorResponse occurred while processing application installation request"; + String msg = "Error occurred while processing application installation request"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (UnknownApplicationTypeException e) { String msg = "The type of application requested to be installed is not supported"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -130,22 +129,22 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem applicationWrapper.getDeviceIdentifiers().size() > 0) { activity = appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers()); } else { - throw new InputValidationException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( - "No application un-installation criteria i.e. user/role/device is given").build()); + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage( + "No application un-installation criteria i.e. user/role/device is given").build()).build(); } } return Response.status(Response.Status.ACCEPTED).entity(activity).build(); } catch (ApplicationManagementException e) { - String msg = "ErrorResponse occurred while processing application un-installation request"; + String msg = "Error occurred while processing application un-installation request"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (UnknownApplicationTypeException e) { String msg = "The type of application requested to be un-installed is not supported"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).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/DeviceManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index 589127b211..4956583627 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -28,8 +28,6 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.*; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.NotFoundException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.*; @@ -55,21 +53,16 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe try { int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) { - throw new UnauthorizedAccessException( - new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage( - "Current logged in user is not authorized to perform this operation").build()); + return Response.status(Response.Status.UNAUTHORIZED).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage( + "Current logged in user is not authorized to perform this operation").build()).build(); } PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(DeviceMgtAPIUtils.getTenantId(tenantDomain)); List devices = DeviceMgtAPIUtils.getDeviceManagementService(). - getDevicesByNameAndType(name, type, offset, limit); - if (devices == null || devices.size() == 0) { - throw new NotFoundException( - new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No device, which carries" + - " the name '" + name + "', is currently enrolled in the system").build()); - } + getDevicesByNameAndType(name, type, offset, limit); // setting up paginated result DeviceList deviceList = new DeviceList(); @@ -80,8 +73,8 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe } catch (DeviceManagementException e) { String msg = "Error occurred at server side while fetching device list."; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } finally { PrivilegedCarbonContext.endTenantFlow(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java index 6fe5706243..09371c3c5d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/CredentialManagementResponseBuilder.java @@ -21,11 +21,9 @@ package org.wso2.carbon.device.mgt.jaxrs.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; -import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException; +import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; @@ -44,7 +42,8 @@ public class CredentialManagementResponseBuilder { /** * Builds the response to change the password of a user - * @param username - Username of the user. + * + * @param username - Username of the user. * @param credentials - User credentials * @return Response Object */ @@ -52,38 +51,39 @@ public class CredentialManagementResponseBuilder { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (!userStoreManager.isExistingUser(username)) { - throw new InputValidationException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("No user found with the username " - + username).build()); + return Response.status(Response.Status.NOT_FOUND).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("No user found with the username '" + + username + "'").build()).build(); } RequestValidationUtil.validateCredentials(credentials); if (!validateCredential(credentials.getNewPassword())) { String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration() .getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG); - throw new InputValidationException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMsg).build()); + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(errorMsg).build()).build(); } userStoreManager.updateCredential(username, credentials.getNewPassword(), - credentials.getOldPassword()); + credentials.getOldPassword()); return Response.status(Response.Status.OK).entity("UserImpl password by username: " + username + " was successfully changed.").build(); } catch (UserStoreException e) { log.error(e.getMessage(), e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(e.getMessage()).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(e.getMessage()).build()).build(); } catch (UnsupportedEncodingException e) { String msg = "Could not change the password of the user: " + username + ". The Character Encoding is not supported."; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } /** * Builds the response to reset the password of a user - * @param username - Username of the user. + * + * @param username - Username of the user. * @param credentials - User credentials * @return Response Object */ @@ -91,35 +91,35 @@ public class CredentialManagementResponseBuilder { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (!userStoreManager.isExistingUser(username)) { - throw new InputValidationException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("No user found with the username " - + username).build()); + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("No user found with the username " + + username).build()).build(); } if (credentials == null || credentials.getNewPassword() == null) { - throw new InputValidationException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Password cannot be empty." - + username).build()); + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("Password cannot be empty." + + username).build()).build(); } if (!validateCredential(credentials.getNewPassword())) { String errorMsg = DeviceMgtAPIUtils.getRealmService().getBootstrapRealmConfiguration() .getUserStoreProperty(PASSWORD_VALIDATION_ERROR_MSG_TAG); - throw new InputValidationException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMsg).build()); + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(errorMsg).build()).build(); } userStoreManager.updateCredentialByAdmin(username, credentials.getNewPassword()); return Response.status(Response.Status.OK).entity("UserImpl password by username: " + username + " was successfully changed.").build(); } catch (UserStoreException e) { - String msg = "ErrorResponse occurred while updating the credentials of user '" + username + "'"; + String msg = "Error occurred while updating the credentials of user '" + username + "'"; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (UnsupportedEncodingException e) { String msg = "Could not change the password of the user: " + username + ". The Character Encoding is not supported."; log.error(msg, e); - throw new UnexpectedServerErrorException( - new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } From 49ce42b7973a98ec8039bfdfa6a3e94450f7437e Mon Sep 17 00:00:00 2001 From: prabathabey Date: Thu, 30 Jun 2016 18:19:11 +0530 Subject: [PATCH 09/11] Code cleanup --- .../org.wso2.carbon.apimgt.application.extension.api/pom.xml | 4 ---- features/oauth-extensions/pom.xml | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml index f4d54e7492..835ed077f3 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml @@ -83,10 +83,6 @@ com.googlecode.json-simple.wso2 json-simple - - org.wso2.carbon - org.wso2.carbon.user.api - org.wso2.carbon org.wso2.carbon.utils diff --git a/features/oauth-extensions/pom.xml b/features/oauth-extensions/pom.xml index 3fb7ebf607..2deaf76f43 100644 --- a/features/oauth-extensions/pom.xml +++ b/features/oauth-extensions/pom.xml @@ -31,7 +31,7 @@ oauth-extensions-feature 1.1.1-SNAPSHOT pom - WSO2 Carbon Device Management - OAuth Extensions Feature + WSO2 Carbon - Device Management OAuth Extensions Feature http://wso2.org From dbf938416bb79466ca490ba6a88261ac7582f0b7 Mon Sep 17 00:00:00 2001 From: madhawap Date: Thu, 30 Jun 2016 20:24:01 +0530 Subject: [PATCH 10/11] added 'updateNotificationStatus' endpoint and minor formattings to swagger annotations --- .../api/ActivityInfoProviderService.java | 10 +- .../api/ConfigurationManagementService.java | 33 ++-- .../api/NotificationManagementService.java | 18 +- .../service/api/PolicyManagementService.java | 73 +++++--- .../service/api/RoleManagementService.java | 173 ++++++++++++------ .../service/api/UserManagementService.java | 172 +++++++++++------ .../NotificationManagementServiceImpl.java | 25 +++ .../mgt/NotificationManagementService.java | 2 + .../NotificationManagementServiceImpl.java | 13 ++ .../notification/mgt/dao/NotificationDAO.java | 2 + .../mgt/dao/impl/NotificationDAOImpl.java | 29 +++ 11 files changed, 405 insertions(+), 145 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java index 3cdc31ed07..fce8e6a61e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java @@ -91,7 +91,10 @@ public interface ActivityInfoProviderService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"}) + @Permission( + scope = "activity-view", + permissions = {"/permission/admin/device-mgt/admin/activities/view"} + ) Response getActivity( @ApiParam( name = "id", @@ -147,7 +150,10 @@ public interface ActivityInfoProviderService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"}) + @Permission( + scope = "activity-view", + permissions = {"/permission/admin/device-mgt/admin/activities/view"} + ) Response getActivities( @ApiParam( name = "since", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java index ab067e0e19..ddab683239 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java @@ -47,7 +47,8 @@ public interface ConfigurationManagementService { value = "Get the general platform configurations.", notes = "Get the general platform level configuration details.", tags = "Configuration Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 200, message = "OK. \n Successfully fetched general platform configuration.", @@ -65,7 +66,8 @@ public interface ConfigurationManagementService { 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."), @@ -77,15 +79,19 @@ public interface ConfigurationManagementService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching the general " + "platform configuration.", response = ErrorResponse.class) - }) - @Permission(scope = "configuration-view", - permissions = {"/permission/admin/device-mgt/admin/platform-configs/view"}) + } + ) + @Permission( + scope = "configuration-view", + permissions = {"/permission/admin/device-mgt/admin/platform-configs/view"} + ) Response getConfiguration( @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time specified", required = false) - @HeaderParam("If-Modified-Since") String ifModifiedSince); + @HeaderParam("If-Modified-Since") + String ifModifiedSince); @PUT @ApiOperation( @@ -95,7 +101,8 @@ public interface ConfigurationManagementService { value = "Update General Platform Configurations.", notes = "This resource is used to update the general platform configuration.", tags = "Configuration Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 200, message = "OK. \n General platform configuration has been updated successfully", @@ -125,13 +132,17 @@ public interface ConfigurationManagementService { message = "Internal Server ErrorResponse. \n " + "Server error occurred while modifying general platform configuration.", response = ErrorResponse.class) - }) - @Permission(scope = "configuration-modify", - permissions = {"/permission/admin/device-mgt/admin/platform-configs/modify"}) + } + ) + @Permission( + scope = "configuration-modify", + permissions = {"/permission/admin/device-mgt/admin/platform-configs/modify"} + ) Response updateConfiguration( @ApiParam( name = "configuration", value = "The required properties to be updated in the platform configuration.", - required = true) PlatformConfiguration configuration); + required = true) + PlatformConfiguration configuration); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java index de119c553e..e6eb6062ce 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java @@ -88,13 +88,14 @@ public interface NotificationManagementService { code = 500, message = "Internal Server ErrorResponse. \n Server error occurred while fetching the notification list.", response = ErrorResponse.class) - }) + } + ) @Permission( scope = "device-notification-view", permissions = { "/permission/admin/device-mgt/admin/notifications/view", - "/permission/admin/device-mgt/user/notifications/view" - }) + "/permission/admin/device-mgt/user/notifications/view" } + ) Response getNotifications( @ApiParam( name = "status", @@ -121,4 +122,15 @@ public interface NotificationManagementService { required = false) @QueryParam("limit") int limit); + + @PUT + @Path("{id}/{status}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "", + notes = "", + tags = "Device Notification Management") + Response updateNotificationStatus( + @PathParam("id") int id); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java index 9b63bd0e47..eb3a4b811e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java @@ -69,7 +69,8 @@ public interface PolicyManagementService { 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.", @@ -93,10 +94,12 @@ public interface PolicyManagementService { message = "Internal Server ErrorResponse. \n " + "Server error occurred while adding a new policy.", response = ErrorResponse.class) - }) + } + ) @Permission( scope = "policy-modify", - permissions = {"/permission/admin/device-mgt/admin/policies/add"}) + permissions = {"/permission/admin/device-mgt/admin/policies/add"} + ) Response addPolicy( @ApiParam( name = "policy", @@ -132,7 +135,8 @@ public interface PolicyManagementService { 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."), @@ -148,10 +152,12 @@ public interface PolicyManagementService { message = ("Internal Server ErrorResponse. \n Server error occurred while fetching " + "policies."), response = ErrorResponse.class) - }) + } + ) @Permission( scope = "policy-view", - permissions = {"/permission/admin/device-mgt/admin/policies/list"}) + permissions = {"/permission/admin/device-mgt/admin/policies/list"} + ) Response getPolicies( @ApiParam( name = "If-Modified-Since", @@ -199,15 +205,15 @@ public interface PolicyManagementService { 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 = "Not Found. \n No policy is found with the given id.", - response = ErrorResponse.class - ), + response = ErrorResponse.class), @ApiResponse( code = 406, message = "Not Acceptable.\n The requested media type is not supported"), @@ -219,7 +225,8 @@ public interface PolicyManagementService { }) @Permission( scope = "policy-view", - permissions = {"/permission/admin/device-mgt/admin/policies/list"}) + permissions = {"/permission/admin/device-mgt/admin/policies/list"} + ) Response getPolicy( @ApiParam( name = "id", @@ -263,7 +270,9 @@ public interface PolicyManagementService { @ResponseHeader( name = "Last-Modified", 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( code = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -280,10 +289,12 @@ public interface PolicyManagementService { message = "Internal Server ErrorResponse. \n " + "Server error occurred while updating the policy.", response = ErrorResponse.class) - }) + } + ) @Permission( scope = "policy-modify", - permissions = {"/permission/admin/device-mgt/admin/policies/update"}) + permissions = {"/permission/admin/device-mgt/admin/policies/update"} + ) Response updatePolicy( @ApiParam( name = "id", @@ -321,16 +332,19 @@ public interface PolicyManagementService { response = ErrorResponse.class), @ApiResponse( code = 415, - message = "Unsupported media type. \n The entity of the request was in a not supported format."), + message = "Unsupported media type. \n The entity of the request was in a not " + + "supported format."), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + "Server error occurred while bulk removing policies.", response = ErrorResponse.class) - }) + } + ) @Permission( scope = "policy-modify", - permissions = {"/permission/admin/device-mgt/admin/policies/remove"}) + permissions = {"/permission/admin/device-mgt/admin/policies/remove"} + ) Response removePolicies( @ApiParam( name = "policyIds", @@ -365,11 +379,13 @@ public interface PolicyManagementService { code = 500, message = "ErrorResponse in activating policies.", response = ErrorResponse.class) - }) + } + ) @Permission( scope = "policy-modify", permissions = { "/permission/admin/device-mgt/admin/policies/update", - "/permission/admin/device-mgt/admin/policies/add"}) + "/permission/admin/device-mgt/admin/policies/add"} + ) Response activatePolicies( @ApiParam( name = "policyIds", @@ -384,8 +400,8 @@ public interface PolicyManagementService { produces = MediaType.APPLICATION_JSON, httpMethod = "PUT", value = "Deactivating policies.", - notes = "Using the REST API command you are able to unpublish a policy in order to bring a policy that " + - "is in the active state to the inactive state.", + notes = "Using the REST API command you are able to unpublish a policy in order to bring a " + + "policy that is in the active state to the inactive state.", tags = "Device Policy Management") @ApiResponses( value = { @@ -404,12 +420,14 @@ public interface PolicyManagementService { code = 500, message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) - }) + } + ) @Permission( scope = "policy-modify", permissions = { "/permission/admin/device-mgt/admin/policies/update", - "/permission/admin/device-mgt/admin/policies/add"}) + "/permission/admin/device-mgt/admin/policies/add"} + ) Response deactivatePolicies( @ApiParam( name = "policyIds", @@ -441,8 +459,12 @@ public interface PolicyManagementService { code = 500, message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) - }) - @Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/update"}) + } + ) + @Permission( + scope = "policy-modify", + permissions = {"/permission/admin/device-mgt/admin/policies/update"} + ) Response applyChanges(); @@ -470,7 +492,8 @@ public interface PolicyManagementService { code = 500, message = "Exception in updating policy priorities.", response = ErrorResponse.class) - }) + } + ) @Permission( scope = "", permissions = {}) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java index 06f52e1dda..fc2556e87f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java @@ -45,8 +45,9 @@ public interface RoleManagementService { produces = MediaType.APPLICATION_JSON, httpMethod = "GET", value = "Get the list of roles.", - notes = "If you wish to get the details of all the roles in EMM, you can do so using this REST API. All " + - "internal roles, roles created for Service-providers and application related roles are omitted.", + notes = "If you wish to get the details of all the roles in EMM, you can do so using this REST " + + "API. All internal roles, roles created for Service-providers and application related " + + "roles are omitted.", tags = "Role Management") @ApiResponses( value = { @@ -64,12 +65,15 @@ public interface RoleManagementService { "Used by caches, or in conditional requests."), @ResponseHeader( 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."), - }), + } + ), @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 = "Not Found. \n Resource does not exist.", @@ -81,38 +85,47 @@ public interface RoleManagementService { code = 500, message = "Internal Server ErrorResponse. \n Server error occurred while fetching requested list of roles.", response = ErrorResponse.class) - }) - @Permission(scope = "roles-view", permissions = { + } + ) + @Permission( + scope = "roles-view", + permissions = { "/permission/admin/device-mgt/admin/roles/list", "/permission/admin/device-mgt/admin/users/view", "/permission/admin/device-mgt/admin/policies/add", - "/permission/admin/device-mgt/admin/policies/update"}) + "/permission/admin/device-mgt/admin/policies/update"} + ) Response getRoles( @ApiParam( name = "filter", value = "Role name or a part of it to search.", required = false) - @QueryParam("filter") String filter, + @QueryParam("filter") + String filter, @ApiParam( name = "user-store", value = "From which user store the roles must be fetched.", required = false) - @QueryParam("user-store") String userStoreName, + @QueryParam("user-store") + String userStoreName, @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time specified", required = false) - @HeaderParam("If-Modified-Since") String ifModifiedSince, + @HeaderParam("If-Modified-Since") + String ifModifiedSince, @ApiParam( name = "offset", value = "Starting point within the complete list of items qualified.", required = false) - @QueryParam("offset") int offset, + @QueryParam("offset") + int offset, @ApiParam( name = "limit", value = "Maximum size of resource array to return.", required = false) - @QueryParam("limit") int limit); + @QueryParam("limit") + int limit); @GET @Path("/{roleName}/permissions") @@ -120,9 +133,10 @@ public interface RoleManagementService { produces = MediaType.APPLICATION_JSON, httpMethod = "GET", value = "Getting permission details of a role.", - notes = "In an organization an individual is associated a with set of responsibilities based on their " + - "role. In EMM you are able to configure permissions based on the responsibilities carried " + - "out by a role. Therefore if you wish to retrieve the permission details of a role, you can do " + + notes = "In an organization an individual is associated a with set of responsibilities based " + + "on their role. In EMM you are able to configure permissions based on the " + + "responsibilities carried out by a role. Therefore if you wish to retrieve the " + + "permission details of a role, you can do " + "so using this REST API.", response = UIPermissionNode.class, responseContainer = "List", @@ -145,12 +159,15 @@ public interface RoleManagementService { "Used by caches, or in conditional requests."), @ResponseHeader( 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."), - }), + } + ), @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 = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -164,21 +181,28 @@ public interface RoleManagementService { 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 permission list of the requested role.", + message = "Internal Server ErrorResponse. \n Server error occurred while fetching" + + " the permission list of the requested role.", response = ErrorResponse.class) - }) - @Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"}) + } + ) + @Permission( + scope = "roles-view", + permissions = {"/permission/admin/device-mgt/admin/roles/list"} + ) Response getPermissionsOfRole( @ApiParam( name = "roleName", value = "Name of the role.", required = true) - @PathParam("roleName") String roleName, + @PathParam("roleName") + String roleName, @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time specified", required = false) - @HeaderParam("If-Modified-Since") String ifModifiedSince); + @HeaderParam("If-Modified-Since") + String ifModifiedSince); @GET @Path("/{roleName}") @@ -205,12 +229,15 @@ public interface RoleManagementService { "Used by caches, or in conditional requests."), @ResponseHeader( 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."), - }), + } + ), @ApiResponse( code = 304, - message = "Not Modified. \n Empty body because the client has already the latest version of" + + message = "Not Modified. \n Empty body because the client has already the " + + "latest version of" + " the requested resource."), @ApiResponse( code = 400, @@ -228,19 +255,25 @@ public interface RoleManagementService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching the " + "requested role.", response = ErrorResponse.class) - }) - @Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"}) + } + ) + @Permission( + scope = "roles-view", + permissions = {"/permission/admin/device-mgt/admin/roles/list"} + ) Response getRole( @ApiParam( name = "roleName", value = "Name of the role.", required = true) - @PathParam("roleName") String roleName, + @PathParam("roleName") + String roleName, @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time specified", required = false) - @HeaderParam("If-Modified-Since") String ifModifiedSince); + @HeaderParam("If-Modified-Since") + String ifModifiedSince); @POST @ApiOperation( @@ -250,7 +283,8 @@ public interface RoleManagementService { value = "Add a role.", notes = "You are able to add a new role to EMM using the REST API.", tags = "Role Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 201, message = "Created. \n Role has successfully been created", @@ -268,33 +302,43 @@ public interface RoleManagementService { @ResponseHeader( name = "Last-Modified", 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( 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.")}), + description = "The Source URL of the document.") + } + ), @ApiResponse( code = 400, message = "Bad Request. \n Invalid request or validation error.", response = ErrorResponse.class), @ApiResponse( code = 415, - message = "Unsupported media type. \n The entity of the request was in a not supported format."), + message = "Unsupported media type. \n The entity of the request was in a not " + + "supported format."), @ApiResponse( code = 500, message = "Internal Server ErrorResponse. \n " + "Server error occurred while adding a new role.", response = ErrorResponse.class) - }) - @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/add"}) + } + ) + @Permission( + scope = "roles-modify", + permissions = {"/permission/admin/device-mgt/admin/roles/add"} + ) Response addRole( @ApiParam( name = "role", value = "Details about the role to be added.", - required = true) RoleWrapper role); + required = true) + RoleWrapper role); @PUT @Path("/{roleName}") @@ -306,7 +350,8 @@ public interface RoleManagementService { notes = "There will be situations where you will need to update the role details, such as the permissions" + " or the role name. In such situation you can update the role details.", tags = "Role Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 200, message = "OK. \n Role has been updated successfully", @@ -324,7 +369,9 @@ public interface RoleManagementService { @ResponseHeader( name = "Last-Modified", 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( code = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -340,18 +387,24 @@ public interface RoleManagementService { message = "Internal Server ErrorResponse. \n " + "Server error occurred while updating the role.", response = ErrorResponse.class) - }) - @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"}) + } + ) + @Permission( + scope = "roles-modify", + permissions = {"/permission/admin/device-mgt/admin/roles/update"} + ) Response updateRole( @ApiParam( name = "roleName", value = "Name of the role.", required = true) - @PathParam("roleName") String roleName, + @PathParam("roleName") + String roleName, @ApiParam( name = "role", value = "Details about the role to be added.", - required = true) RoleWrapper role); + required = true) + RoleWrapper role); @DELETE @Path("/{roleName}") @@ -361,7 +414,8 @@ public interface RoleManagementService { notes = "In a situation when your Organization identifies that a specific role is no longer required you " + "will need to remove the role details from EMM.", tags = "Role Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 200, message = "OK. \n Role has successfully been removed"), @@ -377,14 +431,19 @@ public interface RoleManagementService { message = "Internal Server ErrorResponse. \n " + "Server error occurred while removing the role.", response = ErrorResponse.class) - }) - @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/remove"}) + } + ) + @Permission( + scope = "roles-modify", + permissions = {"/permission/admin/device-mgt/admin/roles/remove"} + ) Response deleteRole( @ApiParam( name = "roleName", value = "Name of the role to de deleted.", required = true) - @PathParam("roleName") String roleName); + @PathParam("roleName") + String roleName); @PUT @Path("/{roleName}/users") @@ -419,7 +478,9 @@ public interface RoleManagementService { @ResponseHeader( name = "Last-Modified", 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( code = 400, message = "Bad Request. \n Invalid request or validation error.", @@ -435,17 +496,23 @@ public interface RoleManagementService { message = "Internal Server ErrorResponse. \n " + "Server error occurred while updating the user list of the role.", response = ErrorResponse.class) - }) - @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"}) + } + ) + @Permission( + scope = "roles-modify", + permissions = {"/permission/admin/device-mgt/admin/roles/update"} + ) Response updateUsersOfRole( @ApiParam( name = "roleName", value = "Name of the role.", required = true) - @PathParam("roleName") String roleName, + @PathParam("roleName") + String roleName, @ApiParam( name = "users", value = "List of usernames to be added.", - required = true) List users); + required = true) + List users); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java index fbbeb51736..2f6d173d22 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java @@ -63,7 +63,9 @@ public interface UserManagementService { @ResponseHeader( name = "Last-Modified", 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( code = 303, message = "See Other. \n Source can be retrieved from the URL specified at the Location header.", @@ -86,13 +88,18 @@ public interface UserManagementService { message = "Internal Server ErrorResponse. \n " + "Server error occurred while adding a new user.", response = ErrorResponse.class) - }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/add"}) + } + ) + @Permission( + scope = "user-modify", + permissions = {"/permission/admin/device-mgt/admin/user/add"} + ) Response addUser( @ApiParam( name = "user", value = "User related details.", - required = true) UserInfo user); + required = true) + UserInfo user); @GET @Path("/{username}") @@ -104,7 +111,8 @@ public interface UserManagementService { + " you can do so using the REST API.", response = BasicUserInfo.class, tags = "User Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 200, message = "OK. \n Successfully fetched the requested role.", @@ -121,10 +129,12 @@ public interface UserManagementService { 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 = "Not Found. \n Resource does not exist.", @@ -137,19 +147,25 @@ public interface UserManagementService { message = "Internal Server ErrorResponse. \n Server error occurred while" + " fetching the requested user.", response = ErrorResponse.class) - }) - @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"}) + } + ) + @Permission( + scope = "user-view", + permissions = {"/permission/admin/device-mgt/admin/user/view"} + ) Response getUser( @ApiParam( name = "username", value = "Username of the user to be fetched.", required = true) - @PathParam("username") String username, + @PathParam("username") + String username, @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time specified", required = false) - @HeaderParam("If-Modified-Since") String ifModifiedSince); + @HeaderParam("If-Modified-Since") + String ifModifiedSince); @PUT @Path("/{username}") @@ -161,7 +177,8 @@ public interface UserManagementService { notes = "There will be situations where you will want to update the user details. In such " + "situation you can update the user details using this REST API.", tags = "User Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 200, message = "OK. \n User has been updated successfully", @@ -179,7 +196,9 @@ public interface UserManagementService { @ResponseHeader( name = "Last-Modified", 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( code = 400, message = "Bad Request. \n Invalid request or validation error."), @@ -195,18 +214,24 @@ public interface UserManagementService { message = "Internal Server ErrorResponse. \n " + "Server error occurred while updating the user.", response = ErrorResponse.class) - }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/update"}) + } + ) + @Permission( + scope = "user-modify", + permissions = {"/permission/admin/device-mgt/admin/user/update"} + ) Response updateUser( @ApiParam( name = "username", value = "Username of the user to be updated.", required = true) - @PathParam("username") String username, + @PathParam("username") + String username, @ApiParam( name = "userData", value = "User related details.", - required = true) UserInfo userData); + required = true) + UserInfo userData); @DELETE @Path("/{username}") @@ -216,7 +241,8 @@ public interface UserManagementService { notes = "In a situation where an employee leaves the organization you will need to remove the" + " user details from EMM. In such situations you can use this REST API to remove a user.", tags = "User Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 200, message = "OK. \n User has successfully been removed"), @@ -228,13 +254,20 @@ public interface UserManagementService { code = 500, message = "Internal Server ErrorResponse. \n " + "Server error occurred while removing the user.", - response = ErrorResponse.class - ) - }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/remove"}) + response = ErrorResponse.class) + } + ) + @Permission( + scope = "user-modify", + permissions = {"/permission/admin/device-mgt/admin/user/remove"} + ) Response removeUser( - @ApiParam(name = "username", value = "Username of the user to be deleted.", required = true) - @PathParam("username") String username); + @ApiParam( + name = "username", + value = "Username of the user to be deleted.", + required = true) + @PathParam("username") + String username); @GET @Path("/{username}/roles") @@ -245,7 +278,8 @@ public interface UserManagementService { notes = "A user can be assigned to one or more role in EMM. Using this REST API you are " + "able to get the role/roles a user is assigned to.", tags = "User Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 200, message = "OK. \n Successfully fetched the role list assigned to the user.", @@ -262,7 +296,8 @@ public interface UserManagementService { 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."), @@ -278,11 +313,19 @@ public interface UserManagementService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching the role list" + " assigned to the user.", response = ErrorResponse.class) - }) - @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"}) + } + ) + @Permission( + scope = "user-view", + permissions = {"/permission/admin/device-mgt/admin/user/view"} + ) Response getRolesOfUser( - @ApiParam(name = "username", value = "Username of the user.", required = true) - @PathParam("username") String username); + @ApiParam( + name = "username", + value = "Username of the user.", + required = true) + @PathParam("username") + String username); @GET @ApiOperation( @@ -292,7 +335,8 @@ public interface UserManagementService { notes = "If you wish to get the details of all the users registered with EMM, you can do so " + "using the REST API", tags = "User Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 200, message = "OK. \n Successfully fetched the requested role.", @@ -309,7 +353,8 @@ public interface UserManagementService { 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 already has the latest version of the requested resource."), @@ -320,29 +365,37 @@ public interface UserManagementService { code = 500, message = "Internal Server ErrorResponse. \n Server error occurred while fetching the user list.", response = ErrorResponse.class) - }) - @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"}) + } + ) + @Permission( + scope = "user-view", + permissions = {"/permission/admin/device-mgt/admin/user/list"} + ) Response getUsers( @ApiParam( name = "filter", value = "Username of the user details to be fetched.", required = false) - @QueryParam("filter") String filter, + @QueryParam("filter") + String filter, @ApiParam( name = "If-Modified-Since", value = "Timestamp of the last modified date", required = false) - @HeaderParam("If-Modified-Since") String timestamp, + @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, + @QueryParam("offset") + int offset, @ApiParam( name = "limit", value = "Maximum size of resource array to return.", required = false) - @QueryParam("limit") int limit); + @QueryParam("limit") + int limit); @GET @Path("/search/usernames") @@ -356,7 +409,8 @@ public interface UserManagementService { + "You will be given a list of users having the user name with the exact order of the " + "characters you provided.", tags = "User Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 200, message = "OK. \n Successfully fetched the username list that matches the given filter.", @@ -374,7 +428,8 @@ public interface UserManagementService { 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."), @@ -386,29 +441,37 @@ public interface UserManagementService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching the username " + "list that matches the given filter.", response = ErrorResponse.class) - }) - @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"}) + } + ) + @Permission( + scope = "user-view", + permissions = {"/permission/admin/device-mgt/admin/user/list"} + ) Response getUserNames( @ApiParam( name = "filter", value = "Username/part of the user name to search.", required = true) - @QueryParam("filter") String filter, + @QueryParam("filter") + String filter, @ApiParam( name = "If-Modified-Since", value = "Timestamp of the last modified date", required = false) - @HeaderParam("If-Modified-Since") String timestamp, + @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, + @QueryParam("offset") + int offset, @ApiParam( name = "limit", value = "Maximum size of resource array to return.", required = false) - @QueryParam("limit") int limit); + @QueryParam("limit") + int limit); @PUT @Path("/{username}/credentials") @@ -419,7 +482,8 @@ public interface UserManagementService { value = "Changing the user password.", notes = "A user is able to change the password to secure their EMM profile via this REST API.", tags = "User Management") - @ApiResponses(value = { + @ApiResponses( + value = { @ApiResponse( code = 200, message = "OK. \n Credentials of the user have been updated successfully"), @@ -438,17 +502,23 @@ public interface UserManagementService { message = "Internal Server ErrorResponse. \n " + "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) - }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/login"}) + } + ) + @Permission( + scope = "user-modify", + permissions = {"/permission/admin/login"} + ) Response resetPassword( @ApiParam( name = "username", value = "Username of the user.", required = true) - @PathParam("username") String username, + @PathParam("username") + String username, @ApiParam( name = "credentials", value = "Credential.", - required = true) OldPasswordResetWrapper credentials); + required = true) + OldPasswordResetWrapper credentials); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java index 7b510223e2..d7ad8c30b5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java @@ -88,4 +88,29 @@ public class NotificationManagementServiceImpl implements NotificationManagement } } + @PUT + @Path("{id}/mark-checked") + public Response updateNotificationStatus( + @PathParam("id") int id) { + String msg; + Notification.Status status = Notification.Status.CHECKED; + Notification notification; + try { + DeviceMgtAPIUtils.getNotificationManagementService().updateNotificationStatus(id, status); + } catch (NotificationManagementException e) { + msg = "Error occurred while updating notification status."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + try { + notification = DeviceMgtAPIUtils.getNotificationManagementService().getNotification(id); + return Response.status(Response.Status.OK).entity(notification).build(); + } catch (NotificationManagementException e) { + msg = "Notification updated successfully. But the retrial of the updated notification failed"; + log.error(msg, e); + return Response.status(Response.Status.OK).build(); + } + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java index c854e47279..cbf26cc4cf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java @@ -71,6 +71,8 @@ public interface NotificationManagementService { */ List getAllNotifications() throws NotificationManagementException; + Notification getNotification(int notificationId) throws NotificationManagementException; + PaginationResult getAllNotifications(PaginationRequest request) throws NotificationManagementException; /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java index ffac513eca..59692da94d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java @@ -160,6 +160,19 @@ public class NotificationManagementServiceImpl implements NotificationManagement } } + @Override + public Notification getNotification(int notificationId) throws NotificationManagementException { + try { + NotificationManagementDAOFactory.openConnection(); + return notificationDAO.getNotification(NotificationDAOUtil.getTenantId(), notificationId); + } catch (SQLException e) { + throw new NotificationManagementException("Error occurred while opening a connection to" + + " the data source", e); + } finally { + NotificationManagementDAOFactory.closeConnection(); + } + } + @Override public PaginationResult getAllNotifications(PaginationRequest request) throws NotificationManagementException { PaginationResult paginationResult = new PaginationResult(); 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 d2fc0efcb1..978d2cc3b7 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 @@ -71,6 +71,8 @@ public interface NotificationDAO { */ List getAllNotifications(int tenantId) throws NotificationManagementException; + Notification getNotification(int tenantId, int notificationId) throws NotificationManagementException; + List getAllNotifications(PaginationRequest request, int tenantId) throws NotificationManagementException; int getNotificationCount(int tenantId) throws NotificationManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java index 695832b3d2..608c5a4f2e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java @@ -70,6 +70,35 @@ public class NotificationDAOImpl implements NotificationDAO { return notificationId; } + @Override + public Notification getNotification(int tenantId, int notificationId) throws NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + Notification notification = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "SELECT NOTIFICATION_ID, OPERATION_ID, DESCRIPTION, STATUS FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ? AND NOTIFICATION_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, notificationId); + rs = stmt.executeQuery(); + + while (rs.next()) { + notification = this.getNotification(rs); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all notifications", e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notification; + + } + @Override public int updateNotification(Notification notification) throws NotificationManagementException { From 2befefc96781b6d5462f62be7e6841f8cf10cacb Mon Sep 17 00:00:00 2001 From: Chatura Dilan Date: Fri, 1 Jul 2016 15:45:59 +0530 Subject: [PATCH 11/11] Added OS build date --- .../mgt/common/device/details/DeviceInfo.java | 16 ++++++++++ .../dao/util/DeviceManagementDAOUtil.java | 1 + .../mgt/dao/impl/DeviceDetailsDAOImpl.java | 30 ++++++++++--------- .../search/mgt/dao/impl/SearchDAOImpl.java | 2 ++ .../search/mgt/impl/QueryBuilderImpl.java | 4 +-- .../mgt/core/search/mgt/impl/Utils.java | 1 + .../device/mgt/core/Search/util/Utils.java | 1 + .../src/test/resources/sql/h2.sql | 1 + .../devicemgt/app/modules/constants.js | 1 + .../src/test/resources/sql/CreateH2TestDB.sql | 1 + .../src/main/resources/dbscripts/cdm/h2.sql | 1 + .../main/resources/dbscripts/cdm/mssql.sql | 1 + .../main/resources/dbscripts/cdm/mysql.sql | 1 + .../main/resources/dbscripts/cdm/oracle.sql | 1 + .../resources/dbscripts/cdm/postgresql.sql | 2 ++ 15 files changed, 48 insertions(+), 16 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java index cc8913c6b6..343add988e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java @@ -57,6 +57,9 @@ public class DeviceInfo implements Serializable { @ApiModelProperty(name = "osVersion", value = "Operating system version.", required = true) private String osVersion; + @ApiModelProperty(name = "osBuildDate", value = "Operating system build date.", required = true) + private String osBuildDate; + @ApiModelProperty(name = "batteryLevel", value = "Battery level of the device.", required = true) private Double batteryLevel; @@ -201,6 +204,19 @@ public class DeviceInfo implements Serializable { this.osVersion = osVersion; } + + public String getOsBuildDate() { + if (osBuildDate != null) { + return osBuildDate; + } else { + return ""; + } + } + + public void setOsBuildDate(String osBuildDate) { + this.osBuildDate = osBuildDate; + } + public Double getBatteryLevel() { if (batteryLevel != null) { return batteryLevel; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java index 7c1a5a6dce..39b5670109 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java @@ -209,6 +209,7 @@ public final class DeviceManagementDAOUtil { deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); deviceInfo.setVendor(rs.getString("VENDOR")); deviceInfo.setOsVersion(rs.getString("OS_VERSION")); + deviceInfo.setOsBuildDate(rs.getString("OS_BUILD_DATE")); deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); deviceInfo.setInternalTotalMemory(rs.getDouble("INTERNAL_TOTAL_MEMORY")); deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java index b0460a7c34..0d45c19838 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java @@ -48,27 +48,28 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { conn = this.getConnection(); stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_DETAIL (DEVICE_ID, DEVICE_MODEL, " + - "VENDOR, OS_VERSION, BATTERY_LEVEL, INTERNAL_TOTAL_MEMORY, INTERNAL_AVAILABLE_MEMORY, " + + "VENDOR, OS_VERSION, OS_BUILD_DATE, BATTERY_LEVEL, INTERNAL_TOTAL_MEMORY, INTERNAL_AVAILABLE_MEMORY, " + "EXTERNAL_TOTAL_MEMORY, EXTERNAL_AVAILABLE_MEMORY, CONNECTION_TYPE, " + "SSID, CPU_USAGE, TOTAL_RAM_MEMORY, AVAILABLE_RAM_MEMORY, PLUGGED_IN, UPDATE_TIMESTAMP) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setInt(1, deviceId); stmt.setString(2, deviceInfo.getDeviceModel()); stmt.setString(3, deviceInfo.getVendor()); stmt.setString(4, deviceInfo.getOsVersion()); - stmt.setDouble(5, deviceInfo.getBatteryLevel()); - stmt.setDouble(6, deviceInfo.getInternalTotalMemory()); - stmt.setDouble(7, deviceInfo.getInternalAvailableMemory()); - stmt.setDouble(8, deviceInfo.getExternalTotalMemory()); - stmt.setDouble(9, deviceInfo.getExternalAvailableMemory()); - stmt.setString(10, deviceInfo.getConnectionType()); - stmt.setString(11, deviceInfo.getSsid()); - stmt.setDouble(12, deviceInfo.getCpuUsage()); - stmt.setDouble(13, deviceInfo.getTotalRAMMemory()); - stmt.setDouble(14, deviceInfo.getAvailableRAMMemory()); - stmt.setBoolean(15, deviceInfo.isPluggedIn()); - stmt.setLong(16, System.currentTimeMillis()); + stmt.setString(5, deviceInfo.getOsBuildDate()); + stmt.setDouble(6, deviceInfo.getBatteryLevel()); + stmt.setDouble(7, deviceInfo.getInternalTotalMemory()); + stmt.setDouble(8, deviceInfo.getInternalAvailableMemory()); + stmt.setDouble(9, deviceInfo.getExternalTotalMemory()); + stmt.setDouble(10, deviceInfo.getExternalAvailableMemory()); + stmt.setString(11, deviceInfo.getConnectionType()); + stmt.setString(12, deviceInfo.getSsid()); + stmt.setDouble(13, deviceInfo.getCpuUsage()); + stmt.setDouble(14, deviceInfo.getTotalRAMMemory()); + stmt.setDouble(15, deviceInfo.getAvailableRAMMemory()); + stmt.setBoolean(16, deviceInfo.isPluggedIn()); + stmt.setLong(17, System.currentTimeMillis()); stmt.execute(); @@ -131,6 +132,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); deviceInfo.setVendor(rs.getString("VENDOR")); deviceInfo.setOsVersion(rs.getString("OS_VERSION")); + deviceInfo.setOsBuildDate(rs.getString("OS_BUILD_DATE")); deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); deviceInfo.setInternalTotalMemory(rs.getDouble("INTERNAL_TOTAL_MEMORY")); deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java index fc162c59b9..1090e88c62 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java @@ -79,6 +79,7 @@ public class SearchDAOImpl implements SearchDAO { deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); deviceInfo.setOsVersion(rs.getString("OS_VERSION")); + deviceInfo.setOsBuildDate(rs.getString("OS_BUILD_DATE")); deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); deviceInfo.setSsid(rs.getString("SSID")); deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); @@ -156,6 +157,7 @@ public class SearchDAOImpl implements SearchDAO { deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); deviceInfo.setOsVersion(rs.getString("OS_VERSION")); + deviceInfo.setOsBuildDate(rs.getString("OS_BUILD_DATE")); deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); deviceInfo.setSsid(rs.getString("SSID")); deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java index 826e94d18c..b86e3c1bcc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java @@ -192,7 +192,7 @@ public class QueryBuilderImpl implements QueryBuilder { return "SELECT D.ID, D.DESCRIPTION, D.NAME, \n" + "D.DEVICE_TYPE_ID, D.DEVICE_IDENTIFICATION, DT.ID AS DEVICE_TYPE_ID, \n" + "DT.NAME AS DEVICE_TYPE_NAME, DD.DEVICE_ID, DD.DEVICE_MODEL, DD.VENDOR, \n" + - "DD.OS_VERSION, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + + "DD.OS_VERSION, DD.OS_BUILD_DATE, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.CONNECTION_TYPE, \n" + "DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + "DD.PLUGGED_IN, DD.UPDATE_TIMESTAMP, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + @@ -211,7 +211,7 @@ public class QueryBuilderImpl implements QueryBuilder { return "SELECT D.ID, D.DESCRIPTION, D.NAME, \n" + "D.DEVICE_TYPE_ID, D.DEVICE_IDENTIFICATION, DT.ID AS DEVICE_TYPE_ID, \n" + "DT.NAME AS DEVICE_TYPE_NAME, DD.DEVICE_ID, DD.DEVICE_MODEL, DD.VENDOR, \n" + - "DD.OS_VERSION, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + + "DD.OS_VERSION, DD.OS_BUILD_DATE, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.CONNECTION_TYPE, \n" + "DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + "DD.PLUGGED_IN, DD.UPDATE_TIMESTAMP, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java index 4c73b33cf7..d28666ba88 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java @@ -35,6 +35,7 @@ public class Utils { genericColumnsMap.put("deviceModel", "DEVICE_MODEL"); genericColumnsMap.put("vendor", "VENDOR"); genericColumnsMap.put("osVersion", "OS_VERSION"); + genericColumnsMap.put("osBuildDate", "OS_BUILD_DATE"); genericColumnsMap.put("batteryLevel", "BATTERY_LEVEL"); genericColumnsMap.put("internalTotalMemory", "INTERNAL_TOTAL_MEMORY"); genericColumnsMap.put("internalAvailableMemory", "INTERNAL_AVAILABLE_MEMORY"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java index 27b5f349c0..8cc205f210 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/util/Utils.java @@ -52,6 +52,7 @@ public class Utils { deviceInfo.setMobileSignalStrength(0.67); deviceInfo.setOperator("Dialog"); deviceInfo.setOsVersion("Lolipop"); + deviceInfo.setOsBuildDate("1467366458"); deviceInfo.setPluggedIn(true); deviceInfo.setSsid("SSSSSS"); deviceInfo.setTotalRAMMemory(4.00); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index a370c70ca1..9b734652da 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -469,6 +469,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, + OS_BUILD_DATE VARCHAR(100) NULL, BATTERY_LEVEL DECIMAL(4) NULL, INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js index 2ede7f9c2d..890a7e500e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js @@ -33,6 +33,7 @@ var DEVICE_VENDOR = "vendor"; var DEVICE_MODEL = "model"; var DEVICE_PRODUCT = "PRODUCT"; var DEVICE_OS_VERSION = "osVersion"; +var DEVICE_OS_BUILD_DATE = "osBuildDate"; var DEVICE_PROPERTIES = "properties"; var DEVICE_ENROLLMENT_INFO = "enrolmentInfo"; var DEVICE_STATUS = "status"; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index d7ab39170b..bf0be00ccc 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -473,6 +473,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, + OS_BUILD_DATE VARCHAR(100) NULL, BATTERY_LEVEL DECIMAL(4) NULL, INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index d7ab39170b..bf0be00ccc 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -473,6 +473,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, + OS_BUILD_DATE VARCHAR(100) NULL, BATTERY_LEVEL DECIMAL(4) NULL, INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql index 68345b343b..a67d67f9e0 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -486,6 +486,7 @@ CREATE TABLE DM_DEVICE_DETAIL ( DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, + OS_BUILD_DATE VARCHAR(100) NULL, BATTERY_LEVEL DECIMAL(4) NULL, INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index d7f4efab06..40535450ac 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -507,6 +507,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, + OS_BUILD_DATE VARCHAR(100) NULL, BATTERY_LEVEL DECIMAL(4) NULL, INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql index 57f55c5d17..41f539cee0 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -825,6 +825,7 @@ CREATE TABLE DM_DEVICE_DETAIL ( DEVICE_MODEL VARCHAR2(45) NULL, VENDOR VARCHAR2(45) NULL, OS_VERSION VARCHAR2(45) NULL, + OS_BUILD_DATE VARCHAR(100) NULL, BATTERY_LEVEL NUMBER(4) NULL, INTERNAL_TOTAL_MEMORY NUMBER(30,3) NULL, INTERNAL_AVAILABLE_MEMORY NUMBER(30,3) NULL, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql index bfc4a7f062..c29d18e021 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -416,6 +416,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, + + OS_BUILD_DATE VARCHAR(100) NULL, BATTERY_LEVEL DECIMAL(4) NULL, INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL,