Merge branch 'master' into 'master'

Get Device By ID API

See merge request entgra/carbon-device-mgt!85
revert-70aa11f8
Charitha Goonetilleke 6 years ago
commit b05ff6a92d

1
.gitignore vendored

@ -8,6 +8,7 @@ target
*.ipr *.ipr
.idea .idea
*.ids *.ids
.editorconfig
# Mac crap # Mac crap
.DS_Store .DS_Store

@ -16,6 +16,24 @@
* under the License. * 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; package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
@ -456,6 +474,82 @@ public interface DeviceManagementService {
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String ifModifiedSince); 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 @PUT
@Path("/{type}/{id}") @Path("/{type}/{id}")
@ApiOperation( @ApiOperation(
@ -587,7 +681,6 @@ public interface DeviceManagementService {
String ifModifiedSince); String ifModifiedSince);
@GET @GET
@Path("/{type}/{id}/info") @Path("/{type}/{id}/info")
@ApiOperation( @ApiOperation(

@ -16,6 +16,24 @@
* under the License. * 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; package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
@ -447,6 +465,77 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.OK).entity(device).build(); 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 @GET
@Path("/{type}/{id}/location") @Path("/{type}/{id}/location")
@Override @Override
@ -491,7 +580,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
deviceInfo = informationManager.getDeviceInfo(deviceIdentifier); deviceInfo = informationManager.getDeviceInfo(deviceIdentifier);
} catch (DeviceDetailsMgtException e) { } 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); log.error(msg, e);
return Response.serverError().entity( return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();

@ -154,9 +154,9 @@ public class DeviceAgentServiceTest {
public void testEnrollExistingDevice() throws DeviceManagementException { public void testEnrollExistingDevice() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .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); 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); Response response = this.deviceAgentService.enrollDevice(device);
Assert.assertNotNull(response, "Response should not be null"); Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
@ -173,7 +173,7 @@ public class DeviceAgentServiceTest {
EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo(); EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
demoDevice.setEnrolmentInfo(enrolmentInfo); 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); Response response = this.deviceAgentService.enrollDevice(demoDevice);
Assert.assertNotNull(response, "Response should not be null"); Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
@ -191,7 +191,7 @@ public class DeviceAgentServiceTest {
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
device.setEnrolmentInfo(enrolmentInfo); 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())) Mockito.when(this.deviceManagementProviderService.enrollDevice(Mockito.any()))
.thenThrow(new DeviceManagementException()); .thenThrow(new DeviceManagementException());
Response response = this.deviceAgentService.enrollDevice(device); Response response = this.deviceAgentService.enrollDevice(device);
@ -240,7 +240,7 @@ public class DeviceAgentServiceTest {
public void testUpdateDeviceWithDeviceManagementException() throws DeviceManagementException { public void testUpdateDeviceWithDeviceManagementException() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenThrow(new Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenThrow(new
DeviceManagementException()); DeviceManagementException());
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
@ -264,7 +264,7 @@ public class DeviceAgentServiceTest {
public void testUpdateDeviceWithNonExistingDevice() throws DeviceManagementException { public void testUpdateDeviceWithNonExistingDevice() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .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); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
Assert.assertNotNull(response, "Response should not be null"); Assert.assertNotNull(response, "Response should not be null");
@ -281,7 +281,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); 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))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenThrow(new DeviceAccessAuthorizationException()); .thenThrow(new DeviceAccessAuthorizationException());
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
@ -300,7 +300,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); 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))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(false); .thenReturn(false);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
@ -321,7 +321,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); 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))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true); .thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false);
@ -343,7 +343,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); 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))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true); .thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())) Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any()))
@ -365,7 +365,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); 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))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true); .thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true)); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true));

@ -1,10 +1,28 @@
/* /*
* 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, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* you may obtain a copy of the License at * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
@ -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.search.mgt.impl.SearchManagerServiceImpl;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; 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.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.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.UUID; import java.util.UUID;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@ -75,6 +97,7 @@ import static org.mockito.MockitoAnnotations.initMocks;
public class DeviceManagementServiceImplTest { public class DeviceManagementServiceImplTest {
private static final Log log = LogFactory.getLog(DeviceManagementServiceImplTest.class); 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_TYPE = "TEST-DEVICE-TYPE";
private static final String TEST_DEVICE_NAME = "TEST-DEVICE"; private static final String TEST_DEVICE_NAME = "TEST-DEVICE";
private static final String DEFAULT_USERNAME = "admin"; private static final String DEFAULT_USERNAME = "admin";
@ -86,6 +109,7 @@ public class DeviceManagementServiceImplTest {
private DeviceManagementService deviceManagementService; private DeviceManagementService deviceManagementService;
private DeviceAccessAuthorizationService deviceAccessAuthorizationService; private DeviceAccessAuthorizationService deviceAccessAuthorizationService;
private DeviceManagementProviderService deviceManagementProviderService; private DeviceManagementProviderService deviceManagementProviderService;
private static Device demoDevice;
@ObjectFactory @ObjectFactory
public IObjectFactory getObjectFactory() { public IObjectFactory getObjectFactory() {
@ -100,6 +124,7 @@ public class DeviceManagementServiceImplTest {
.mock(DeviceManagementProviderServiceImpl.class, Mockito.RETURNS_MOCKS); .mock(DeviceManagementProviderServiceImpl.class, Mockito.RETURNS_MOCKS);
this.deviceManagementService = new DeviceManagementServiceImpl(); this.deviceManagementService = new DeviceManagementServiceImpl();
this.deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class); 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.") @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()); 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") @Test(description = "Testing get devices when DeviceAccessAuthorizationService is not available")
public void testGetDevicesWithErroneousDeviceAccessAuthorizationService() { public void testGetDevicesWithErroneousDeviceAccessAuthorizationService() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))

@ -15,6 +15,23 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * 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; package org.wso2.carbon.device.mgt.core.dao;
@ -128,6 +145,17 @@ public interface DeviceDAO {
*/ */
Device getDevice(DeviceIdentifier deviceIdentifier, int tenantId) throws DeviceManagementDAOException; 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. * 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 Device getDevice(DeviceIdentifier deviceIdentifier, Date ifModifiedSince, int tenantId) throws
DeviceManagementDAOException; 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 * 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. * later than the ifModifiedSince param.

@ -14,6 +14,24 @@
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * 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; 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, " + String sql = "INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, " +
"LAST_UPDATED_TIMESTAMP, TENANT_ID) " + "LAST_UPDATED_TIMESTAMP, TENANT_ID) " +
"VALUES (?, ?, ?, ?, ?, ?)"; "VALUES (?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, new String[] {"id"}); stmt = conn.prepareStatement(sql, new String[]{"id"});
stmt.setString(1, device.getDescription()); stmt.setString(1, device.getDescription());
stmt.setString(2, device.getName()); stmt.setString(2, device.getName());
stmt.setInt(3, typeId); 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 = ? " + 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 = ?)) " + "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 = ?"; "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(1, device.getName());
stmt.setString(2, device.getDescription()); stmt.setString(2, device.getDescription());
stmt.setTimestamp(3, new Timestamp(new Date().getTime())); stmt.setTimestamp(3, new Timestamp(new Date().getTime()));
@ -145,6 +163,53 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
return device; 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 @Override
public Device getDevice(DeviceIdentifier deviceIdentifier, String owner, int tenantId) public Device getDevice(DeviceIdentifier deviceIdentifier, String owner, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
@ -193,7 +258,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, " + "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 " + "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 " + "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" ; "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); stmt = conn.prepareStatement(sql);
int paramIdx = 1; int paramIdx = 1;
stmt.setString(paramIdx++, deviceIdentifier.getType()); stmt.setString(paramIdx++, deviceIdentifier.getType());
@ -214,6 +279,51 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
return device; 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);
}
return device;
}
@Override @Override
public Device getDevice(DeviceIdentifier deviceIdentifier, String owner, Date since, int tenantId) public Device getDevice(DeviceIdentifier deviceIdentifier, String owner, Date since, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
@ -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, " + "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 " + "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 " + "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 = conn.prepareStatement(sql);
stmt.setString(1, deviceIdentifier.getType()); stmt.setString(1, deviceIdentifier.getType());
stmt.setString(2, deviceIdentifier.getId()); stmt.setString(2, deviceIdentifier.getId());
@ -250,8 +360,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
@Override @Override
public Device getDevice(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status status, int tenantId) throws public Device getDevice(DeviceIdentifier deviceIdentifier, EnrolmentInfo.Status status, int tenantId)
DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -923,7 +1033,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
conn = this.getConnection(); conn = this.getConnection();
String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS,DATE_OF_ENROLMENT, " + String sql = "INSERT INTO DM_ENROLMENT(DEVICE_ID, OWNER, OWNERSHIP, STATUS,DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, TENANT_ID) VALUES(?, ?, ?, ?, ?, ?, ?)"; "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.setInt(1, device.getId());
stmt.setString(2, device.getEnrolmentInfo().getOwner()); stmt.setString(2, device.getEnrolmentInfo().getOwner());
stmt.setString(3, device.getEnrolmentInfo().getOwnership().toString()); stmt.setString(3, device.getEnrolmentInfo().getOwnership().toString());
@ -1194,7 +1304,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
List<GeoCluster> geoClusters = new ArrayList<>(); List<GeoCluster> geoClusters = new ArrayList<>();
try { try {
conn = this.getConnection(); 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.LATITUDE) AS MIN_LATITUDE, MAX(DEVICE_LOCATION.LATITUDE) AS MAX_LATITUDE," +
" MIN(DEVICE_LOCATION.LONGITUDE) AS MIN_LONGITUDE," + " MIN(DEVICE_LOCATION.LONGITUDE) AS MIN_LONGITUDE," +
" MAX(DEVICE_LOCATION.LONGITUDE) AS MAX_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(3, northEast.getLatitude());
stmt.setDouble(4, southWest.getLongitude()); stmt.setDouble(4, southWest.getLongitude());
stmt.setDouble(5, northEast.getLongitude()); stmt.setDouble(5, northEast.getLongitude());
stmt.setDouble(6,tenantId); stmt.setDouble(6, tenantId);
if (deviceType != null && !deviceType.isEmpty()) { if (deviceType != null && !deviceType.isEmpty()) {
stmt.setString(7, deviceType); stmt.setString(7, deviceType);
} }
@ -1230,13 +1340,13 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
double min_longitude = rs.getDouble("MIN_LONGITUDE"); double min_longitude = rs.getDouble("MIN_LONGITUDE");
double max_longitude = rs.getDouble("MAX_LONGITUDE"); double max_longitude = rs.getDouble("MAX_LONGITUDE");
String device_identification = rs.getString("DEVICE_IDENTIFICATION"); 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"); String last_seen = rs.getString("LAST_UPDATED_TIMESTAMP");
long count = rs.getLong("COUNT"); long count = rs.getLong("COUNT");
String geohashPrefix = rs.getString("GEOHASH_PREFIX"); String geohashPrefix = rs.getString("GEOHASH_PREFIX");
geoClusters.add(new GeoCluster(new GeoCoordinate(latitude, longitude), geoClusters.add(new GeoCluster(new GeoCoordinate(latitude, longitude),
new GeoCoordinate(min_latitude,min_longitude), new GeoCoordinate(max_latitude,max_longitude), new GeoCoordinate(min_latitude, min_longitude), new GeoCoordinate(max_latitude, max_longitude),
count, geohashPrefix,device_identification,device_type,last_seen)); count, geohashPrefix, device_identification, device_type, last_seen));
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of " + throw new DeviceManagementDAOException("Error occurred while retrieving information of " +

@ -15,6 +15,24 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * 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; package org.wso2.carbon.device.mgt.core.service;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
@ -189,6 +207,17 @@ public interface DeviceManagementProviderService {
*/ */
Device getDevice(DeviceIdentifier deviceId, boolean requireDeviceInfo) throws DeviceManagementException; 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. * 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; 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. * Returns the device of specified id and owned by user with given username.
* *

@ -15,6 +15,23 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * 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; package org.wso2.carbon.device.mgt.core.service;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
@ -813,6 +830,53 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return device; 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 @Override
public Device getDevice(DeviceIdentifier deviceId, String owner, boolean requireDeviceInfo) public Device getDevice(DeviceIdentifier deviceId, String owner, boolean requireDeviceInfo)
throws DeviceManagementException { throws DeviceManagementException {
@ -1072,6 +1136,47 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return device; 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 @Override
public Device getDevice(DeviceIdentifier deviceId, String owner, Date since, boolean requireDeviceInfo) public Device getDevice(DeviceIdentifier deviceId, String owner, Date since, boolean requireDeviceInfo)
throws DeviceManagementException { throws DeviceManagementException {

@ -1,18 +1,39 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * WSO2 Inc. licenses this file to you under the Apache License,
* you may not use this file except in compliance with the License. * Version 2.0 (the "License"); you may not use this file except
* You may obtain a copy of the License at * 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, * Unless required by applicable law or agreed to in writing,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * software distributed under the License is distributed on an
* See the License for the specific language governing permissions and * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* limitations under the License. * 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; package org.wso2.carbon.device.mgt.core.service;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -72,6 +93,7 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
private static final String ALTERNATE_DEVICE_ID = "1128"; private static final String ALTERNATE_DEVICE_ID = "1128";
private DeviceManagementProviderService providerService; private DeviceManagementProviderService providerService;
private static final String DEVICE_TYPE = "RANDOM_DEVICE_TYPE"; private static final String DEVICE_TYPE = "RANDOM_DEVICE_TYPE";
private static final String DEVICE_OWNER = "admin";
private DeviceDetailsDAO deviceDetailsDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO(); private DeviceDetailsDAO deviceDetailsDAO = DeviceManagementDAOFactory.getDeviceDetailsDAO();
DeviceManagementProviderService deviceMgtService; DeviceManagementProviderService deviceMgtService;
@ -352,7 +374,6 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
Assert.assertTrue(device.getDeviceIdentifier().equalsIgnoreCase(DEVICE_ID)); Assert.assertTrue(device.getDeviceIdentifier().equalsIgnoreCase(DEVICE_ID));
} }
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviceWithInfo() throws DeviceManagementException { public void testGetDeviceWithInfo() throws DeviceManagementException {
Device device = deviceMgtService.getDevice(new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE) 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"}) @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
public void testGetDeviceTypeWithProps() throws DeviceManagementException, NoSuchFieldException, public void testGetDeviceTypeWithProps() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException { IllegalAccessException {
@ -437,7 +504,7 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions =
DeviceManagementException.class) DeviceManagementException.class)
public void testDeviceByOwnerWithNullDeviceID() throws DeviceManagementException { public void testDeviceByOwnerWithNullDeviceID() throws DeviceManagementException {
deviceMgtService.getDevice(null, "admin", true); deviceMgtService.getDevice((DeviceIdentifier) null, "admin", true);
} }
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}) @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"})
@ -498,7 +565,7 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
@Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions = @Test(dependsOnMethods = {"testSuccessfulDeviceEnrollment"}, expectedExceptions =
DeviceManagementException.class) DeviceManagementException.class)
public void testDeviceByDateWithNullDeviceID() throws DeviceManagementException { public void testDeviceByDateWithNullDeviceID() throws DeviceManagementException {
deviceMgtService.getDevice(null, yesterday()); deviceMgtService.getDevice((DeviceIdentifier) null, yesterday());
} }
private void addDeviceInformation(Device initialDevice) throws TransactionManagementException, DeviceDetailsMgtDAOException { private void addDeviceInformation(Device initialDevice) throws TransactionManagementException, DeviceDetailsMgtDAOException {

@ -155,9 +155,9 @@ public class DeviceAgentServiceTest {
public void testEnrollExistingDevice() throws DeviceManagementException { public void testEnrollExistingDevice() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .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); 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); Response response = this.deviceAgentService.enrollDevice(device);
Assert.assertNotNull(response, "Response should not be null"); Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
@ -174,7 +174,7 @@ public class DeviceAgentServiceTest {
EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo(); EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
demoDevice.setEnrolmentInfo(enrolmentInfo); 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); Response response = this.deviceAgentService.enrollDevice(demoDevice);
Assert.assertNotNull(response, "Response should not be null"); Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
@ -192,7 +192,7 @@ public class DeviceAgentServiceTest {
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
device.setEnrolmentInfo(enrolmentInfo); 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())) Mockito.when(this.deviceManagementProviderService.enrollDevice(Mockito.any()))
.thenThrow(new DeviceManagementException()); .thenThrow(new DeviceManagementException());
Response response = this.deviceAgentService.enrollDevice(device); Response response = this.deviceAgentService.enrollDevice(device);
@ -241,7 +241,7 @@ public class DeviceAgentServiceTest {
public void testUpdateDeviceWithDeviceManagementException() throws DeviceManagementException { public void testUpdateDeviceWithDeviceManagementException() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any())).thenThrow(new Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenThrow(new
DeviceManagementException()); DeviceManagementException());
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
@ -265,7 +265,7 @@ public class DeviceAgentServiceTest {
public void testUpdateDeviceWithNonExistingDevice() throws DeviceManagementException { public void testUpdateDeviceWithNonExistingDevice() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .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); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
Assert.assertNotNull(response, "Response should not be null"); Assert.assertNotNull(response, "Response should not be null");
@ -282,7 +282,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); 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))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenThrow(new DeviceAccessAuthorizationException()); .thenThrow(new DeviceAccessAuthorizationException());
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
@ -301,7 +301,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); 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))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(false); .thenReturn(false);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
@ -322,7 +322,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); 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))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true); .thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false);
@ -344,7 +344,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); 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))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true); .thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())) Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any()))
@ -366,7 +366,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); 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))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true); .thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true)); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true));

Loading…
Cancel
Save