From b863d2fa5e8bbce31783354e160b62593415503c Mon Sep 17 00:00:00 2001 From: Asanka Kumara Date: Mon, 27 May 2019 06:25:21 +0000 Subject: [PATCH] Get Device By ID API --- .gitignore | 1 + .../service/api/DeviceManagementService.java | 245 +++++++++++----- .../impl/DeviceManagementServiceImpl.java | 97 ++++++- .../service/impl/DeviceAgentServiceTest.java | 22 +- .../impl/DeviceManagementServiceImplTest.java | 144 +++++++++- .../carbon/device/mgt/core/dao/DeviceDAO.java | 41 +++ .../core/dao/impl/AbstractDeviceDAOImpl.java | 268 ++++++++++++------ .../DeviceManagementProviderService.java | 41 +++ .../DeviceManagementProviderServiceImpl.java | 105 +++++++ .../DeviceManagementProviderServiceTest.java | 101 +++++-- .../service/impl/DeviceAgentServiceTest.java | 22 +- 11 files changed, 878 insertions(+), 209 deletions(-) diff --git a/.gitignore b/.gitignore index 379d4a33ffe..fe21460b43b 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ target *.ipr .idea *.ids +.editorconfig # Mac crap .DS_Store 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 ab50ccc8abf..db0902ee362 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 @@ -16,6 +16,24 @@ * under the License. * */ +/* + * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.Api; @@ -143,11 +161,11 @@ import java.util.List; permissions = {"/device-mgt/devices/owning-device/view"} ), @Scope( - name = "Change device status.", - description = "Change device status.", - key = "perm:devices:change-status", - permissions = {"/device-mgt/devices/change-status"} - ), + name = "Change device status.", + description = "Change device status.", + key = "perm:devices:change-status", + permissions = {"/device-mgt/devices/change-status"} + ), } ) @Path("/devices") @@ -165,10 +183,10 @@ public interface DeviceManagementService { notes = "Provides details of all the devices enrolled with WSO2 IoT Server.", tags = "Device Management", extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") - }) - } + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + }) + } ) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.", @@ -212,14 +230,14 @@ public interface DeviceManagementService { value = "The device name. For example, Nexus devices can have names, suhc as shamu, bullhead or angler.", required = false) @Size(max = 45) - String name, + String name, @ApiParam( name = "type", value = "The device type, such as ios, android, or windows.", required = false) @QueryParam("type") @Size(max = 45) - String type, + String type, @ApiParam( name = "user", value = "The username of the owner of the device.", @@ -248,14 +266,14 @@ public interface DeviceManagementService { required = false) @QueryParam("ownership") @Size(max = 45) - String ownership, + String ownership, @ApiParam( name = "status", value = "Provide the device status details, such as active or inactive.", required = false) @QueryParam("status") @Size(max = 45) - String status, + String status, @ApiParam( name = "groupId", value = "Id of the group which device belongs", @@ -269,7 +287,7 @@ public interface DeviceManagementService { "Example: Mon, 05 Jan 2014 15:10:00 +0200", required = false) @QueryParam("since") - String since, + String since, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time.\n" + @@ -277,7 +295,7 @@ public interface DeviceManagementService { "Example: Mon, 05 Jan 2014 15:10:00 +0200", required = false) @HeaderParam("If-Modified-Since") - String timestamp, + String timestamp, @ApiParam( name = "requireDeviceInfo", value = "Boolean flag indicating whether to include device-info (location, application list etc) \n" + @@ -291,14 +309,14 @@ public interface DeviceManagementService { required = false, defaultValue = "0") @QueryParam("offset") - int offset, + int offset, @ApiParam( name = "limit", value = "Provide how many device details you require from the starting pagination index/offset.", required = false, defaultValue = "5") @QueryParam("limit") - int limit); + int limit); @GET @ApiOperation( @@ -323,16 +341,16 @@ public interface DeviceManagementService { @ResponseHeader( name = "ETag", description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), + "Used by caches, or in conditional requests."), @ResponseHeader( name = "Last-Modified", description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), + "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.\n"), + "the requested resource.\n"), @ApiResponse( code = 400, message = "The incoming request has more than one selection criteria defined via the query parameters.", @@ -383,9 +401,9 @@ public interface DeviceManagementService { "the owner.", tags = "Device Management", extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") - }) + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") + }) } ) @ApiResponses( @@ -446,16 +464,92 @@ public interface DeviceManagementService { required = false) @QueryParam("owner") @Size(max = 100) - String owner, + String owner, @ApiParam( - name = "If-Modified-Since", - value = "Checks if the requested variant was modified, since the specified date-time. \n" + - "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z. \n" + - "Example: Mon, 05 Jan 2014 15:10:00 +0200", - required = false) + name = "If-Modified-Since", + value = "Checks if the requested variant was modified, since the specified date-time. \n" + + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z. \n" + + "Example: Mon, 05 Jan 2014 15:10:00 +0200", + required = false) @HeaderParam("If-Modified-Since") String ifModifiedSince); + @GET + @Path("/type/any/id/{id}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Details of a Device", + notes = "Get the details of a device by specifying the device identifier.", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the details of the device.", + response = Device.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. Empty body because the client already has the latest version" + + " of the requested resource.\n"), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n A device with the specified device type and id was not found.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n " + + "Server error occurred while retrieving the device details.", + response = ErrorResponse.class) + }) + Response getDeviceByID( + @ApiParam( + name = "id", + value = "The device identifier of the device you want ot get details.", + required = true) + @PathParam("id") + @Size(max = 45) + String id, + @ApiParam( + name = "If-Modified-Since", + value = "Checks if the requested variant was modified, since the specified date-time.\n" + + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z\n" + + "Example: Mon, 05 Jan 2014 15:10:00 +0200", + required = false) + @HeaderParam("If-Modified-Since") + String timestamp, + @ApiParam( + name = "requireDeviceInfo", + value = "Boolean flag indicating whether to include device-info \n" + + "(location, application list etc) to the device object.", + required = false) + @QueryParam("requireDeviceInfo") + boolean requireDeviceInfo); + + @PUT @Path("/{type}/{id}") @ApiOperation( @@ -587,7 +681,6 @@ public interface DeviceManagementService { String ifModifiedSince); - @GET @Path("/{type}/{id}/info") @ApiOperation( @@ -646,14 +739,14 @@ public interface DeviceManagementService { required = true) @PathParam("type") @Size(max = 45) - String type, + String type, @ApiParam( name = "id", value = "The device identifier of the device you want ot get details.", required = true) @PathParam("id") @Size(max = 45) - String id, + String id, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time. \n" + @@ -661,7 +754,7 @@ public interface DeviceManagementService { "Example: Mon, 05 Jan 2014 15:10:00 +0200", required = false) @HeaderParam("If-Modified-Since") - String ifModifiedSince); + String ifModifiedSince); //device rename request would looks like follows //POST devices/type/virtual_firealarm/id/us06ww93auzp/rename @@ -820,10 +913,10 @@ public interface DeviceManagementService { " such as iOS, Android or Windows.", tags = "Device Management", extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:features") - }) - } + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:features") + }) + } ) @ApiResponses( value = { @@ -880,7 +973,7 @@ public interface DeviceManagementService { required = true) @PathParam("type") @Size(max = 45) - String type, + String type, @ApiParam( name = "id", value = "The device identifier of the device.\n" + @@ -888,7 +981,7 @@ public interface DeviceManagementService { required = true) @PathParam("id") @Size(max = 45) - String id, + String id, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time. \n" + @@ -896,7 +989,7 @@ public interface DeviceManagementService { "Example: Mon, 05 Jan 2014 15:10:00 +0200", required = false) @HeaderParam("If-Modified-Since") - String ifModifiedSince); + String ifModifiedSince); @POST @Path("/search-devices") @@ -908,9 +1001,9 @@ public interface DeviceManagementService { notes = "Search for devices by filtering the search result through the specified search terms.", tags = "Device Management", extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:search") - }) + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:search") + }) } ) @ApiResponses( @@ -962,19 +1055,19 @@ public interface DeviceManagementService { required = false, defaultValue = "0") @QueryParam("offset") - int offset, + int offset, @ApiParam( name = "limit", value = "Provide how many activity details you require from the starting pagination index/offset.", required = false, defaultValue = "5") @QueryParam("limit") - int limit, + int limit, @ApiParam( name = "searchContext", value = "The properties to advanced search devices.", required = true) - SearchContext searchContext); + SearchContext searchContext); @GET @Path("/{type}/{id}/applications") @@ -985,11 +1078,11 @@ public interface DeviceManagementService { notes = "Get the list of applications subscribed to by a device.", tags = "Device Management", extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:applications") - }) + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:applications") + }) - } + } ) @ApiResponses( value = { @@ -1046,14 +1139,14 @@ public interface DeviceManagementService { required = true) @PathParam("type") @Size(max = 45) - String type, + String type, @ApiParam( name = "id", value = "The device identifier of the device.", required = true) @PathParam("id") @Size(max = 45) - String id, + String id, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time. \n" + @@ -1061,21 +1154,21 @@ public interface DeviceManagementService { "Example: Mon, 05 Jan 2014 15:10:00 +0200", required = false) @HeaderParam("If-Modified-Since") - String ifModifiedSince, + String ifModifiedSince, @ApiParam( name = "offset", value = "The starting pagination index for the complete list of qualified items.", required = false, defaultValue = "0") @QueryParam("offset") - int offset, + int offset, @ApiParam( name = "limit", value = "Provide how many application details you require from the starting pagination index/offset.", required = false, defaultValue = "5") @QueryParam("limit") - int limit); + int limit); @GET @@ -1087,10 +1180,10 @@ public interface DeviceManagementService { notes = "Get the details of operations carried out on a selected device.", tags = "Device Management", extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:operations") - }) - } + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:operations") + }) + } ) @ApiResponses( value = { @@ -1147,7 +1240,7 @@ public interface DeviceManagementService { required = true) @PathParam("type") @Size(max = 45) - String type, + String type, @ApiParam( name = "id", value = "The device identifier of the device you wish to get details.\n" + @@ -1155,7 +1248,7 @@ public interface DeviceManagementService { required = true) @PathParam("id") @Size(max = 45) - String id, + String id, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time. \n" + @@ -1163,21 +1256,21 @@ public interface DeviceManagementService { "Example: Mon, 05 Jan 2014 15:10:00 +0200", required = false) @HeaderParam("If-Modified-Since") - String ifModifiedSince, + String ifModifiedSince, @ApiParam( name = "offset", value = "The starting pagination index for the complete list of qualified items.", required = false, defaultValue = "0") @QueryParam("offset") - int offset, + int offset, @ApiParam( name = "limit", value = "Provide how many activity details you require from the starting pagination index/offset.", required = false, defaultValue = "5") @QueryParam("limit") - int limit, + int limit, @ApiParam( name = "owner", value = "Provides the owner of the required device.", @@ -1197,10 +1290,10 @@ public interface DeviceManagementService { "the device ownership type, the user role or name and finally, the policy that matches these filters will be enforced on the device.", tags = "Device Management", extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:effective-policy") - }) - } + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:effective-policy") + }) + } ) @ApiResponses( value = { @@ -1257,14 +1350,14 @@ public interface DeviceManagementService { required = true) @PathParam("type") @Size(max = 45) - String type, + String type, @ApiParam( name = "id", value = "The device ID.", required = true) @PathParam("id") @Size(max = 45) - String id, + String id, @ApiParam( name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time. \n" + @@ -1272,7 +1365,7 @@ public interface DeviceManagementService { "Example: Mon, 05 Jan 2014 15:10:00 +0200", required = false) @HeaderParam("If-Modified-Since") - String ifModifiedSince); + String ifModifiedSince); @GET @@ -1285,9 +1378,9 @@ public interface DeviceManagementService { "The server checks if the settings in the device comply with the policy that is enforced on the device using this REST API.", tags = "Device Management", extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:compliance-data") - }) + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:compliance-data") + }) } ) @ApiResponses( @@ -1313,14 +1406,14 @@ public interface DeviceManagementService { required = true) @PathParam("type") @Size(max = 45) - String type, + String type, @ApiParam( name = "id", value = "Device Identifier", required = true) @PathParam("id") @Size(max = 45) - String id); + String id); @PUT @Path("/{type}/{id}/changestatus") 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 5c69f0bd4d4..b679323f97e 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 @@ -16,6 +16,24 @@ * under the License. * */ +/* + * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.device.mgt.jaxrs.service.impl; import org.apache.commons.lang.StringUtils; @@ -447,6 +465,77 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { return Response.status(Response.Status.OK).entity(device).build(); } + @GET + @Path("/type/any/id/{id}") + @Override + public Response getDeviceByID( + @PathParam("id") @Size(max = 45) String id, + @HeaderParam("If-Modified-Since") String ifModifiedSince, + @QueryParam("requireDeviceInfo") boolean requireDeviceInfo) { + Device device; + try { + RequestValidationUtil.validateDeviceIdentifier("any", id); + DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); + DeviceAccessAuthorizationService deviceAccessAuthorizationService = + DeviceMgtAPIUtils.getDeviceAccessAuthorizationService(); + + // this is the user who initiates the request + String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); + + Date sinceDate = null; + if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { + SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); + try { + sinceDate = format.parse(ifModifiedSince); + } catch (ParseException e) { + String message = "Error occurred while parse the since date.Invalid date string is provided in " + + "'If-Modified-Since' header"; + log.error(message, e); + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("Invalid date " + + "string is provided in 'If-Modified-Since' header").build()).build(); + } + } + if (sinceDate != null) { + device = dms.getDevice(id, sinceDate, requireDeviceInfo); + if (device == null) { + String message = "No device is modified after the timestamp provided in 'If-Modified-Since' header"; + log.error(message); + return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " + + "after the timestamp provided in 'If-Modified-Since' header").build(); + } + } else { + device = dms.getDevice(id, requireDeviceInfo); + } + if (device == null) { + String message = "Device does not exist with id '" + id + "'"; + log.error(message); + return Response.status(Response.Status.NOT_FOUND).entity( + new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage(message).build()).build(); + } + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, device.getType()); + // check whether the user is authorized + if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, authorizedUser)) { + String message = "User '" + authorizedUser + "' is not authorized to retrieve the given " + + "device id '" + id + "'"; + log.error(message); + return Response.status(Response.Status.UNAUTHORIZED).entity( + new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(message).build()).build(); + } + } catch (DeviceManagementException e) { + String message = "Error occurred while fetching the device information."; + log.error(message, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(message).build()).build(); + } catch (DeviceAccessAuthorizationException e) { + String message = "Error occurred while checking the device authorization."; + log.error(message, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(message).build()).build(); + } + return Response.status(Response.Status.OK).entity(device).build(); + } + @GET @Path("/{type}/{id}/location") @Override @@ -491,7 +580,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); } catch (DeviceDetailsMgtException e) { - String msg = "Error occurred while getting the device information of id : " + id + " type : " + type ; + String msg = "Error occurred while getting the device information of id : " + id + " type : " + type; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); @@ -681,8 +770,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { /** * Change device status. * - * @param type Device type - * @param id Device id + * @param type Device type + * @param id Device id * @param newsStatus Device new status * @return {@link Response} object */ @@ -766,7 +855,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { String date = new SimpleDateFormat(DATE_FORMAT_NOW).format(new Date()); operation.setCreatedTimeStamp(date); Activity activity = DeviceMgtAPIUtils.getDeviceManagementService().addOperation(type, operation, - deviceIdentifiers); + deviceIdentifiers); return Response.status(Response.Status.CREATED).entity(activity).build(); } else { String message = "Only Command and Config operation is supported through this api"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java index 44c23440d9a..c66851e35db 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java @@ -154,9 +154,9 @@ public class DeviceAgentServiceTest { public void testEnrollExistingDevice() throws DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(demoDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(demoDevice); Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(device); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(device); Response response = this.deviceAgentService.enrollDevice(device); Assert.assertNotNull(response, "Response should not be null"); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), @@ -173,7 +173,7 @@ public class DeviceAgentServiceTest { EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo(); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); demoDevice.setEnrolmentInfo(enrolmentInfo); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(demoDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(demoDevice); Response response = this.deviceAgentService.enrollDevice(demoDevice); Assert.assertNotNull(response, "Response should not be null"); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), @@ -191,7 +191,7 @@ public class DeviceAgentServiceTest { EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); device.setEnrolmentInfo(enrolmentInfo); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(device); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(device); Mockito.when(this.deviceManagementProviderService.enrollDevice(Mockito.any())) .thenThrow(new DeviceManagementException()); Response response = this.deviceAgentService.enrollDevice(device); @@ -240,7 +240,7 @@ public class DeviceAgentServiceTest { public void testUpdateDeviceWithDeviceManagementException() throws DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenThrow(new + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenThrow(new DeviceManagementException()); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); @@ -264,7 +264,7 @@ public class DeviceAgentServiceTest { public void testUpdateDeviceWithNonExistingDevice() throws DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(null); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(null); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Assert.assertNotNull(response, "Response should not be null"); @@ -281,7 +281,7 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenThrow(new DeviceAccessAuthorizationException()); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); @@ -300,7 +300,7 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(false); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); @@ -321,7 +321,7 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false); @@ -343,7 +343,7 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())) @@ -365,7 +365,7 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true)); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java index 27e84c7fc9c..fc26189f409 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java @@ -1,19 +1,37 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 + * 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. + * 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. + * + */ +/* + * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.wso2.carbon.device.mgt.jaxrs.service.impl; @@ -52,13 +70,17 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; import org.wso2.carbon.device.mgt.core.search.mgt.impl.SearchManagerServiceImpl; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceAgentService; import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.DeviceMgtAPITestHelper; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.Calendar; import java.util.Date; import java.util.UUID; import javax.ws.rs.core.Response; @@ -75,6 +97,7 @@ import static org.mockito.MockitoAnnotations.initMocks; public class DeviceManagementServiceImplTest { private static final Log log = LogFactory.getLog(DeviceManagementServiceImplTest.class); + private static final String TEST_DEVICE_IDENTIFIER = "TEST_DEVICE_IDENTIFIER"; private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE"; private static final String TEST_DEVICE_NAME = "TEST-DEVICE"; private static final String DEFAULT_USERNAME = "admin"; @@ -86,6 +109,7 @@ public class DeviceManagementServiceImplTest { private DeviceManagementService deviceManagementService; private DeviceAccessAuthorizationService deviceAccessAuthorizationService; private DeviceManagementProviderService deviceManagementProviderService; + private static Device demoDevice; @ObjectFactory public IObjectFactory getObjectFactory() { @@ -100,6 +124,7 @@ public class DeviceManagementServiceImplTest { .mock(DeviceManagementProviderServiceImpl.class, Mockito.RETURNS_MOCKS); this.deviceManagementService = new DeviceManagementServiceImpl(); this.deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class); + demoDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); } @Test(description = "Testing if the device is enrolled when the device is enrolled.") @@ -181,6 +206,103 @@ public class DeviceManagementServiceImplTest { Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); } + @Test(description = "Testing get devices by identifier with correct request.") + public void testGetDeviceByID() throws DeviceAccessAuthorizationException { + String ifModifiedSince = new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(new Date()); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")) + .toReturn(DEFAULT_USERNAME); + CarbonContext carbonContext = Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS); + DeviceAccessAuthorizationService deviceAccessAuthorizationService = + Mockito.mock(DeviceAccessAuthorizationService.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")) + .toReturn(deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(carbonContext); + Mockito.when(carbonContext.getTenantId()).thenReturn(-1234); + Mockito.when(carbonContext.getUsername()).thenReturn(DEFAULT_USERNAME); + Mockito.when(deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class), + Mockito.anyString())).thenReturn(true); + + Response response = this.deviceManagementService + .getDeviceByID(TEST_DEVICE_IDENTIFIER, ifModifiedSince,true); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + response = this.deviceManagementService + .getDeviceByID(TEST_DEVICE_IDENTIFIER, null,true); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + + } + + @Test(description = "Testing get devices by identifier when unauthorized user.") + public void testGetDeviceByIDWithErroneousUnauthorizedException() + throws DeviceAccessAuthorizationException { + String ifModifiedSince = new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(new Date()); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")) + .toReturn(DEFAULT_USERNAME); + CarbonContext carbonContext = Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS); + DeviceAccessAuthorizationService deviceAccessAuthorizationService = + Mockito.mock(DeviceAccessAuthorizationService.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")) + .toReturn(deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(carbonContext); + Mockito.when(carbonContext.getTenantId()).thenReturn(-1234); + Mockito.when(carbonContext.getUsername()).thenReturn(DEFAULT_USERNAME); + Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(false); + + Response response = this.deviceManagementService + .getDeviceByID(TEST_DEVICE_IDENTIFIER, ifModifiedSince,true); + Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode()); + + } + + @Test(description = "Testing get device when DeviceAccessAuthorizationService is not available", + expectedExceptions = ExceptionInInitializerError.class) + public void testGetDeviceByIDWithErroneousDeviceAccessAuthorizationService() + throws DeviceAccessAuthorizationException { + String ifModifiedSince = new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(new Date()); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")) + .toReturn(DEFAULT_USERNAME); + CarbonContext carbonContext = Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(carbonContext); + Mockito.when(carbonContext.getTenantId()).thenReturn(-1234); + Mockito.when(carbonContext.getUsername()).thenReturn(DEFAULT_USERNAME); + Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); + + this.deviceManagementService.getDeviceByID(TEST_DEVICE_IDENTIFIER, ifModifiedSince,true); + + } + + @Test(description = "Testing get device when DeviceManagementProviderService is not available", + expectedExceptions = NoClassDefFoundError.class) + public void testGetDeviceByIDWithErroneousDeviceManagementProviderService() + throws DeviceAccessAuthorizationException { + String ifModifiedSince = new SimpleDateFormat(DEFAULT_DATE_FORMAT).format(new Date()); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")) + .toReturn(DEFAULT_USERNAME); + CarbonContext carbonContext = Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS); + DeviceAccessAuthorizationService deviceAccessAuthorizationService = + Mockito.mock(DeviceAccessAuthorizationService.class, Mockito.RETURNS_MOCKS); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, + "getDeviceAccessAuthorizationService")) + .toReturn(deviceAccessAuthorizationService); + PowerMockito.stub(PowerMockito.method(CarbonContext.class, "getThreadLocalCarbonContext")) + .toReturn(carbonContext); + Mockito.when(carbonContext.getTenantId()).thenReturn(-1234); + Mockito.when(carbonContext.getUsername()).thenReturn(DEFAULT_USERNAME); + Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); + + this.deviceManagementService.getDeviceByID(TEST_DEVICE_IDENTIFIER, ifModifiedSince,true); + } + @Test(description = "Testing get devices when DeviceAccessAuthorizationService is not available") public void testGetDevicesWithErroneousDeviceAccessAuthorizationService() { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 93a254d2c7d..bdb7557ae49 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -15,6 +15,23 @@ * specific language governing permissions and limitations * under the License. */ +/* + * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.wso2.carbon.device.mgt.core.dao; @@ -128,6 +145,17 @@ public interface DeviceDAO { */ Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException; + + /** + * This method is used to retrieve a device of a given device-identifier and tenant-id. + * + * @param deviceIdentifier device id. + * @param tenantId tenant id. + * @return returns the device object. + * @throws DeviceManagementDAOException + */ + Device getDevice(String deviceIdentifier, int tenantId) throws DeviceManagementDAOException; + /** * This method is used to retrieve a device of a given device-identifier and owner and tenant-id. * @@ -152,6 +180,19 @@ public interface DeviceDAO { Device getDevice(DeviceIdentifier deviceIdentifier, Date ifModifiedSince, int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve a device of a given device-identifier and tenant-id which modified + * later than the ifModifiedSince param. + * + * @param deviceIdentifier device id. + * @param ifModifiedSince last modified time. + * @param tenantId tenant id. + * @return returns the device object. + * @throws DeviceManagementDAOException + */ + Device getDevice(String deviceIdentifier, Date ifModifiedSince, int tenantId) throws + DeviceManagementDAOException; + /** * This method is used to retrieve a device of a given device-identifier and owner and tenant-id which modified * later than the ifModifiedSince param. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 1e8a01e2442..30cd6d4dcd2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -1,19 +1,37 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * 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 + * 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 + * 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. + * 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. + * + */ +/* + * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.wso2.carbon.device.mgt.core.dao.impl; @@ -55,7 +73,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { String sql = "INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, " + "LAST_UPDATED_TIMESTAMP, TENANT_ID) " + "VALUES (?, ?, ?, ?, ?, ?)"; - stmt = conn.prepareStatement(sql, new String[] {"id"}); + stmt = conn.prepareStatement(sql, new String[]{"id"}); stmt.setString(1, device.getDescription()); stmt.setString(2, device.getName()); stmt.setInt(3, typeId); @@ -87,7 +105,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { String sql = "UPDATE DM_DEVICE SET NAME = ?, DESCRIPTION = ?, LAST_UPDATED_TIMESTAMP = ? " + "WHERE DEVICE_TYPE_ID = (SELECT ID FROM DM_DEVICE_TYPE WHERE NAME = ? AND (PROVIDER_TENANT_ID = ? OR SHARED_WITH_ALL_TENANTS = ?)) " + "AND DEVICE_IDENTIFICATION = ? AND TENANT_ID = ?"; - stmt = conn.prepareStatement(sql, new String[] {"id"}); + stmt = conn.prepareStatement(sql, new String[]{"id"}); stmt.setString(1, device.getName()); stmt.setString(2, device.getDescription()); stmt.setTimestamp(3, new Timestamp(new Date().getTime())); @@ -145,6 +163,53 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { return device; } + @Override + public Device getDevice(String deviceIdentifier, int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + Device device = null; + try { + conn = this.getConnection(); + String sql = "SELECT " + + "d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + + "FROM " + + "DM_ENROLMENT e," + + " (SELECT d.ID, d.DESCRIPTION, d.NAME, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION " + + "FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE " + + "t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 " + + "WHERE " + + "d1.ID = e.DEVICE_ID " + + "AND TENANT_ID = ? " + + "ORDER BY e.DATE_OF_LAST_UPDATE DESC, e.STATUS ASC"; + // Status adeed as an orderby clause to fix a bug : when an existing device is + // re-enrolled, earlier enrollment is marked as removed and a new enrollment is added. + // However, both enrollments share the same time stamp. When retrieving the device + // due to same timestamp, enrollment information is incorrect, intermittently. Hence + // status also should be taken into consideration when ordering. This should not present a + // problem for other status transitions, as there would be an intermediary removed + // state in between. + stmt = conn.prepareStatement(sql); + stmt.setString(1, deviceIdentifier); + stmt.setInt(2, tenantId); + stmt.setInt(3, tenantId); + rs = stmt.executeQuery(); + if (rs.next()) { + device = DeviceManagementDAOUtil.loadMatchingDevice(rs, false); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while listing device " + + "'" + deviceIdentifier + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return device; + } + @Override public Device getDevice(DeviceIdentifier deviceIdentifier, String owner, int tenantId) throws DeviceManagementDAOException { @@ -181,7 +246,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { @Override public Device getDevice(DeviceIdentifier deviceIdentifier, Date since, int tenantId) - throws DeviceManagementDAOException { + throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; @@ -189,11 +254,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + - "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_DETAIL dt " + - "WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " + - "AND dt.UPDATE_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC" ; + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_DETAIL dt " + + "WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " + + "AND dt.UPDATE_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); int paramIdx = 1; stmt.setString(paramIdx++, deviceIdentifier.getType()); @@ -207,7 +272,52 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while listing device for type " + - "'" + deviceIdentifier.getType() + "'", e); + "'" + deviceIdentifier.getType() + "'", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return device; + } + + @Override + public Device getDevice(String deviceIdentifier, Date since, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + Device device = null; + try { + conn = this.getConnection(); + String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + + "FROM" + + " DM_ENROLMENT e, " + + "(SELECT d.ID, d.DESCRIPTION, d.NAME, " + + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION " + + "FROM" + + " DM_DEVICE d, DM_DEVICE_TYPE t," + + " DM_DEVICE_DETAIL dt " + + "WHERE " + + "t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND" + + " dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?) d1 " + + "WHERE" + + " d1.ID = e.DEVICE_ID AND TENANT_ID = ? " + + "ORDER BY " + + "e.DATE_OF_LAST_UPDATE DESC"; + stmt = conn.prepareStatement(sql); + int paramIdx = 1; + stmt.setString(paramIdx++, deviceIdentifier); + stmt.setInt(paramIdx++, tenantId); + stmt.setLong(paramIdx++, since.getTime()); + stmt.setInt(paramIdx, tenantId); + rs = stmt.executeQuery(); + if (rs.next()) { + device = DeviceManagementDAOUtil.loadMatchingDevice(rs, false); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while listing device for id " + + "'" + deviceIdentifier + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -228,7 +338,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_DETAIL dt " + "WHERE t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ? AND dt.DEVICE_ID = d.ID " + - "AND dt.UPDATE_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ?" ; + "AND dt.UPDATE_TIMESTAMP > ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? AND e.OWNER = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceIdentifier.getType()); stmt.setString(2, deviceIdentifier.getId()); @@ -250,8 +360,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } @Override - public Device getDevice(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status status, int tenantId) throws - DeviceManagementDAOException { + public Device getDevice(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status status, int tenantId) + throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; @@ -259,11 +369,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + - "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + - "t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + - "AND TENANT_ID = ? AND e.STATUS = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + + "t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + + "AND TENANT_ID = ? AND e.STATUS = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceIdentifier.getType()); stmt.setString(2, deviceIdentifier.getId()); @@ -276,7 +386,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while listing devices for type " + - "'" + deviceIdentifier.getType() + "'", e); + "'" + deviceIdentifier.getType() + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -293,13 +403,13 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, e.TENANT_ID, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + - "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + - "t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? ) d1 WHERE d1.ID = e.DEVICE_ID ORDER BY e.DATE_OF_LAST_UPDATE DESC"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, deviceIdentifier.getType()); - stmt.setString(2, deviceIdentifier.getId()); + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + + "t.NAME = ? AND t.ID = d.DEVICE_TYPE_ID AND d.DEVICE_IDENTIFICATION = ? ) d1 WHERE d1.ID = e.DEVICE_ID ORDER BY e.DATE_OF_LAST_UPDATE DESC"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, deviceIdentifier.getType()); + stmt.setString(2, deviceIdentifier.getId()); rs = stmt.executeQuery(); if (rs.next()) { device = DeviceManagementDAOUtil.loadDevice(rs); @@ -323,11 +433,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + - "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + - "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + - "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + - "d.ID = ? AND t.ID = d.DEVICE_TYPE_ID AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + - "AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + + "t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE " + + "d.ID = ? AND t.ID = d.DEVICE_TYPE_ID AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID " + + "AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC"; stmt = conn.prepareStatement(sql); stmt.setInt(1, deviceId); stmt.setInt(2, tenantId); @@ -338,7 +448,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while retrieving device for id " + - "'" + deviceId + "'", e); + "'" + deviceId + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -421,11 +531,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," + - " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + - "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + - "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + - "e.TENANT_ID = ? AND LOWER(e.OWNER) = LOWER(?) ORDER BY e.DATE_OF_LAST_UPDATE DESC) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + - "AND t.ID = d.DEVICE_TYPE_ID"; + " e1.DATE_OF_ENROLMENT, d.DESCRIPTION, d.NAME AS DEVICE_NAME, d.DEVICE_IDENTIFICATION, t.NAME " + + "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + + "e.TENANT_ID = ? AND LOWER(e.OWNER) = LOWER(?) ORDER BY e.DATE_OF_LAST_UPDATE DESC) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + + "AND t.ID = d.DEVICE_TYPE_ID"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, username); @@ -497,8 +607,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT COUNT(d1.DEVICE_ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID FROM " + - "DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 WHERE " + - "d1.DEVICE_ID = e.DEVICE_ID AND LOWER(e.OWNER) = LOWER(?) AND TENANT_ID = ?"; + "DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 WHERE " + + "d1.DEVICE_ID = e.DEVICE_ID AND LOWER(e.OWNER) = LOWER(?) AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, username); @@ -580,7 +690,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { @Override public boolean setEnrolmentStatusInBulk(String deviceType, String status, - int tenantId, List devices) throws DeviceManagementDAOException { + int tenantId, List devices) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; try { @@ -625,8 +735,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT COUNT(d1.DEVICE_ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID FROM " + - "DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 WHERE " + - "d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; + "DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 WHERE " + + "d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setInt(2, tenantId); @@ -665,7 +775,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t"; + "t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t"; //Add query for last updated timestamp if (since != null) { @@ -739,7 +849,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + - "registered devices", e); + "registered devices", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -755,8 +865,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + - "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, type); stmt.setInt(2, tenantId); @@ -781,8 +891,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT COUNT(e1.DEVICE_ID) AS DEVICE_COUNT FROM DM_DEVICE d, (SELECT e.DEVICE_ID " + - "FROM DM_ENROLMENT e WHERE e.TENANT_ID = ? AND LOWER(e.OWNER) = LOWER(?)) " + - "e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID AND t.ID = d.DEVICE_TYPE_ID"; + "FROM DM_ENROLMENT e WHERE e.TENANT_ID = ? AND LOWER(e.OWNER) = LOWER(?)) " + + "e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID AND t.ID = d.DEVICE_TYPE_ID"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, username); @@ -793,7 +903,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + - username + "'", e); + username + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -808,8 +918,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + - "WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + + "WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceName + "%"); stmt.setInt(2, tenantId); @@ -821,7 +931,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the device count that matches " + - "'" + deviceName + "'", e); + "'" + deviceName + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -836,8 +946,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT COUNT(d.ID) AS DEVICE_COUNT FROM (SELECT e.DEVICE_ID FROM DM_ENROLMENT e WHERE " + - "TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE d.ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + "TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, " + + "DM_DEVICE_TYPE t WHERE d.ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, ownerShip); @@ -849,7 +959,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + - "'" + ownerShip + "'", e); + "'" + ownerShip + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } @@ -923,7 +1033,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { conn = this.getConnection(); String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS,DATE_OF_ENROLMENT, " + "DATE_OF_LAST_UPDATE, TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?)"; - stmt = conn.prepareStatement(sql, new String[] {"id"}); + stmt = conn.prepareStatement(sql, new String[]{"id"}); stmt.setInt(1, device.getId()); stmt.setString(2, device.getEnrolmentInfo().getOwner()); stmt.setString(3, device.getEnrolmentInfo().getOwnership().toString()); @@ -1044,10 +1154,10 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { try { conn = this.getConnection(); String sql = "SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " + - "DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID " + - "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " + - "AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + - "AND TENANT_ID = ? AND STATUS in ('ACTIVE','UNREACHABLE','INACTIVE')"; + "DATE_OF_LAST_UPDATE, TENANT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT d.ID " + + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " + + "AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + + "AND TENANT_ID = ? AND STATUS in ('ACTIVE','UNREACHABLE','INACTIVE')"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceId.getId()); stmt.setString(2, deviceId.getType()); @@ -1060,8 +1170,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { return enrolmentInfo; } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " + - "information of device '" + deviceId.getId() + "' of type : " - + deviceId.getType(), e); + "information of device '" + deviceId.getId() + "' of type : " + + deviceId.getType(), e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -1130,7 +1240,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { * * @param timestamp Timestamp in long, after which the devices have been updated. * @param tenantId Tenant id of the currently logged in user. - * @return A collection of devices that have been updated after the provided timestamp + * @return A collection of devices that have been updated after the provided timestamp * @throws DeviceManagementDAOException */ public List getDevices(long timestamp, int tenantId) throws DeviceManagementDAOException { @@ -1194,7 +1304,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { List geoClusters = new ArrayList<>(); try { conn = this.getConnection(); - String sql ="SELECT AVG(DEVICE_LOCATION.LATITUDE) AS LATITUDE,AVG(DEVICE_LOCATION.LONGITUDE) AS LONGITUDE," + + String sql = "SELECT AVG(DEVICE_LOCATION.LATITUDE) AS LATITUDE,AVG(DEVICE_LOCATION.LONGITUDE) AS LONGITUDE," + " MIN(DEVICE_LOCATION.LATITUDE) AS MIN_LATITUDE, MAX(DEVICE_LOCATION.LATITUDE) AS MAX_LATITUDE," + " MIN(DEVICE_LOCATION.LONGITUDE) AS MIN_LONGITUDE," + " MAX(DEVICE_LOCATION.LONGITUDE) AS MAX_LONGITUDE," + @@ -1217,7 +1327,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { stmt.setDouble(3, northEast.getLatitude()); stmt.setDouble(4, southWest.getLongitude()); stmt.setDouble(5, northEast.getLongitude()); - stmt.setDouble(6,tenantId); + stmt.setDouble(6, tenantId); if (deviceType != null && !deviceType.isEmpty()) { stmt.setString(7, deviceType); } @@ -1230,13 +1340,13 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { double min_longitude = rs.getDouble("MIN_LONGITUDE"); double max_longitude = rs.getDouble("MAX_LONGITUDE"); String device_identification = rs.getString("DEVICE_IDENTIFICATION"); - String device_type=rs.getString("TYPE"); + String device_type = rs.getString("TYPE"); String last_seen = rs.getString("LAST_UPDATED_TIMESTAMP"); long count = rs.getLong("COUNT"); String geohashPrefix = rs.getString("GEOHASH_PREFIX"); geoClusters.add(new GeoCluster(new GeoCoordinate(latitude, longitude), - new GeoCoordinate(min_latitude,min_longitude), new GeoCoordinate(max_latitude,max_longitude), - count, geohashPrefix,device_identification,device_type,last_seen)); + new GeoCoordinate(min_latitude, min_longitude), new GeoCoordinate(max_latitude, max_longitude), + count, geohashPrefix, device_identification, device_type, last_seen)); } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while retrieving information of " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 3fa92a1aed7..186b253de40 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -15,6 +15,24 @@ * specific language governing permissions and limitations * under the License. */ +/* + * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.device.mgt.core.service; import org.wso2.carbon.device.mgt.common.Device; @@ -189,6 +207,17 @@ public interface DeviceManagementProviderService { */ Device getDevice(DeviceIdentifier deviceId, boolean requireDeviceInfo) throws DeviceManagementException; + /** + * Returns the device of specified id. + * + * @param deviceId device Id + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return Device returns null when device is not available. + * @throws DeviceManagementException + */ + Device getDevice(String deviceId, boolean requireDeviceInfo) throws DeviceManagementException; + /** * Returns the device of specified id owned by user with given username. * @@ -224,6 +253,18 @@ public interface DeviceManagementProviderService { */ Device getDevice(DeviceIdentifier deviceId, Date since, boolean requireDeviceInfo) throws DeviceManagementException; + /** + * Returns the device of specified id. + * + * @param deviceId device Id + * @param since - Date value where the resource was last modified + * @param requireDeviceInfo - A boolean indicating whether the device-info (location, app-info etc) is also required + * along with the device data. + * @return Device returns null when device is not available. + * @throws DeviceManagementException + */ + Device getDevice(String deviceId, Date since, boolean requireDeviceInfo) throws DeviceManagementException; + /** * Returns the device of specified id and owned by user with given username. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index ecb7463be27..a890487f4ca 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -15,6 +15,23 @@ * specific language governing permissions and limitations * under the License. */ +/* + * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.wso2.carbon.device.mgt.core.service; import org.apache.commons.lang.StringUtils; @@ -813,6 +830,53 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return device; } + @Override + public Device getDevice(String deviceId, boolean requireDeviceInfo) throws DeviceManagementException { + if (deviceId == null) { + String message = "Received null device identifier for method getDevice"; + log.error(message); + throw new DeviceManagementException(message); + } + if (log.isDebugEnabled()) { + log.debug("Get device by device id :" + deviceId + " '" + + "' and requiredDeviceInfo: " + requireDeviceInfo); + } + int tenantId = this.getTenantId(); + Device device; + try { + DeviceManagementDAOFactory.openConnection(); + device = deviceDAO.getDevice(deviceId, tenantId); + if (device == null) { + String message = "No device is found upon the id '" + + deviceId + "'"; + if (log.isDebugEnabled()) { + log.debug(message); + } + return null; + } + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, device.getType()); + this.addDeviceToCache(deviceIdentifier, device); + } catch (DeviceManagementDAOException e) { + String message = "Error occurred while obtaining the device for '" + deviceId + "'"; + log.error(message, e); + throw new DeviceManagementException(message, e); + } catch (SQLException e) { + String message = "Error occurred while opening a connection to the data source"; + log.error(message); + throw new DeviceManagementException(message, e); + } catch (Exception e) { + String message = "Error occurred in getDevice: " + deviceId; + log.error(message, e); + throw new DeviceManagementException(message, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + if (requireDeviceInfo) { + device = this.getAllDeviceInfo(device); + } + return device; + } + @Override public Device getDevice(DeviceIdentifier deviceId, String owner, boolean requireDeviceInfo) throws DeviceManagementException { @@ -1072,6 +1136,47 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return device; } + @Override + public Device getDevice(String deviceId, Date since, boolean requireDeviceInfo) throws DeviceManagementException { + if (deviceId == null || since == null) { + String message = "Received incomplete data for getDevice"; + log.error(message); + throw new DeviceManagementException(message); + } + if (log.isDebugEnabled()) { + log.debug("Get device since '" + since.toString() + "' with identifier: " + deviceId + ""); + } + Device device; + try { + DeviceManagementDAOFactory.openConnection(); + device = deviceDAO.getDevice(deviceId, since, this.getTenantId()); + if (device == null) { + if (log.isDebugEnabled()) { + log.debug("No device is found upon the id '" + deviceId + "'"); + } + return null; + } + } catch (DeviceManagementDAOException e) { + String message = "Error occurred while obtaining the device for id '" + deviceId + "'"; + log.error(message, e); + throw new DeviceManagementException(message, e); + } catch (SQLException e) { + String message = "Error occurred while opening a connection to the data source"; + log.error(message, e); + throw new DeviceManagementException(message, e); + } catch (Exception e) { + String message = "Error occurred in getDevice for device: " + deviceId; + log.error(message, e); + throw new DeviceManagementException(message, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + if (requireDeviceInfo) { + device = this.getAllDeviceInfo(device); + } + return device; + } + @Override public Device getDevice(DeviceIdentifier deviceId, String owner, Date since, boolean requireDeviceInfo) throws DeviceManagementException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java index ffff69c6a51..98328cab30e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java @@ -1,18 +1,39 @@ /* -* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* Licensed 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. -*/ + * 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. + * + */ +/* + * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + package org.wso2.carbon.device.mgt.core.service; import org.apache.commons.logging.Log; @@ -72,6 +93,7 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes private static final String ALTERNATE_DEVICE_ID = "1128"; private DeviceManagementProviderService providerService; private static final String DEVICE_TYPE = "RANDOM_DEVICE_TYPE"; + private static final String DEVICE_OWNER = "admin"; private DeviceDetailsDAO deviceDetailsDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO(); DeviceManagementProviderService deviceMgtService; @@ -352,7 +374,6 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes Assert.assertTrue(device.getDeviceIdentifier().equalsIgnoreCase(DEVICE_ID)); } - @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) public void testGetDeviceWithInfo() throws DeviceManagementException { Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE) @@ -362,6 +383,52 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes } } + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetDeviceByID() throws DeviceManagementException { + Device device = deviceMgtService.getDevice(DEVICE_ID, true); + if (!isMock()) { + Assert.assertTrue(device.getDeviceIdentifier().equalsIgnoreCase(DEVICE_ID)); + } + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = + DeviceManagementException.class) + public void testGetDeviceByIDWithNullID() throws DeviceManagementException { + deviceMgtService.getDevice((String) null, true); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) + public void testGetDeviceByIDAndSinceDate() throws DeviceManagementException, DeviceDetailsMgtDAOException + , TransactionManagementException { + Device initialDevice = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE)); + addDeviceInformation(initialDevice); + Device device = deviceMgtService.getDevice(DEVICE_ID, yesterday(), true); + if (!isMock()) { + Assert.assertTrue(device != null); + } + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = + DeviceManagementException.class) + public void testGetDeviceByIDAndSinceDateWithNullID() throws DeviceManagementException, DeviceDetailsMgtDAOException + , TransactionManagementException { + Device initialDevice = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE)); + addDeviceInformation(initialDevice); + deviceMgtService.getDevice((String)null, yesterday(), true); + } + + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = + DeviceManagementException.class) + public void testGetDeviceByIDAndSinceDateWithNullDate() throws DeviceManagementException, + DeviceDetailsMgtDAOException, TransactionManagementException { + Device initialDevice = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, + DEVICE_TYPE)); + addDeviceInformation(initialDevice); + deviceMgtService.getDevice(DEVICE_ID, (Date)null, true); + } + @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) public void testGetDeviceTypeWithProps() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException { @@ -437,7 +504,7 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = DeviceManagementException.class) public void testDeviceByOwnerWithNullDeviceID() throws DeviceManagementException { - deviceMgtService.getDevice(null, "admin", true); + deviceMgtService.getDevice((DeviceIdentifier) null, "admin", true); } @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) @@ -498,7 +565,7 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = DeviceManagementException.class) public void testDeviceByDateWithNullDeviceID() throws DeviceManagementException { - deviceMgtService.getDevice(null, yesterday()); + deviceMgtService.getDevice((DeviceIdentifier) null, yesterday()); } private void addDeviceInformation(Device initialDevice) throws TransactionManagementException, DeviceDetailsMgtDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java index 05bd490a854..cd11cb9d33a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java @@ -155,9 +155,9 @@ public class DeviceAgentServiceTest { public void testEnrollExistingDevice() throws DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(demoDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(demoDevice); Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(device); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(device); Response response = this.deviceAgentService.enrollDevice(device); Assert.assertNotNull(response, "Response should not be null"); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), @@ -174,7 +174,7 @@ public class DeviceAgentServiceTest { EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo(); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); demoDevice.setEnrolmentInfo(enrolmentInfo); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(demoDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(demoDevice); Response response = this.deviceAgentService.enrollDevice(demoDevice); Assert.assertNotNull(response, "Response should not be null"); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), @@ -192,7 +192,7 @@ public class DeviceAgentServiceTest { EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); device.setEnrolmentInfo(enrolmentInfo); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(device); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(device); Mockito.when(this.deviceManagementProviderService.enrollDevice(Mockito.any())) .thenThrow(new DeviceManagementException()); Response response = this.deviceAgentService.enrollDevice(device); @@ -241,7 +241,7 @@ public class DeviceAgentServiceTest { public void testUpdateDeviceWithDeviceManagementException() throws DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenThrow(new + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenThrow(new DeviceManagementException()); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); @@ -265,7 +265,7 @@ public class DeviceAgentServiceTest { public void testUpdateDeviceWithNonExistingDevice() throws DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(null); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(null); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Assert.assertNotNull(response, "Response should not be null"); @@ -282,7 +282,7 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenThrow(new DeviceAccessAuthorizationException()); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); @@ -301,7 +301,7 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(false); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); @@ -322,7 +322,7 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false); @@ -344,7 +344,7 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())) @@ -366,7 +366,7 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true));