Get Device By ID API

4.x.x
Asanka Kumara 6 years ago committed by Charitha Goonetilleke
parent 76524b03ae
commit b863d2fa5e

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;
@ -143,11 +161,11 @@ import java.util.List;
permissions = {"/device-mgt/devices/owning-device/view"} permissions = {"/device-mgt/devices/owning-device/view"}
), ),
@Scope( @Scope(
name = "Change device status.", name = "Change device status.",
description = "Change device status.", description = "Change device status.",
key = "perm:devices:change-status", key = "perm:devices:change-status",
permissions = {"/device-mgt/devices/change-status"} permissions = {"/device-mgt/devices/change-status"}
), ),
} }
) )
@Path("/devices") @Path("/devices")
@ -165,10 +183,10 @@ public interface DeviceManagementService {
notes = "Provides details of all the devices enrolled with WSO2 IoT Server.", notes = "Provides details of all the devices enrolled with WSO2 IoT Server.",
tags = "Device Management", tags = "Device Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
}) })
} }
) )
@ApiResponses(value = { @ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.", @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.", value = "The device name. For example, Nexus devices can have names, suhc as shamu, bullhead or angler.",
required = false) required = false)
@Size(max = 45) @Size(max = 45)
String name, String name,
@ApiParam( @ApiParam(
name = "type", name = "type",
value = "The device type, such as ios, android, or windows.", value = "The device type, such as ios, android, or windows.",
required = false) required = false)
@QueryParam("type") @QueryParam("type")
@Size(max = 45) @Size(max = 45)
String type, String type,
@ApiParam( @ApiParam(
name = "user", name = "user",
value = "The username of the owner of the device.", value = "The username of the owner of the device.",
@ -248,14 +266,14 @@ public interface DeviceManagementService {
required = false) required = false)
@QueryParam("ownership") @QueryParam("ownership")
@Size(max = 45) @Size(max = 45)
String ownership, String ownership,
@ApiParam( @ApiParam(
name = "status", name = "status",
value = "Provide the device status details, such as active or inactive.", value = "Provide the device status details, such as active or inactive.",
required = false) required = false)
@QueryParam("status") @QueryParam("status")
@Size(max = 45) @Size(max = 45)
String status, String status,
@ApiParam( @ApiParam(
name = "groupId", name = "groupId",
value = "Id of the group which device belongs", value = "Id of the group which device belongs",
@ -269,7 +287,7 @@ public interface DeviceManagementService {
"Example: Mon, 05 Jan 2014 15:10:00 +0200", "Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false) required = false)
@QueryParam("since") @QueryParam("since")
String since, String since,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time.\n" + 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", "Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false) required = false)
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String timestamp, String timestamp,
@ApiParam( @ApiParam(
name = "requireDeviceInfo", name = "requireDeviceInfo",
value = "Boolean flag indicating whether to include device-info (location, application list etc) \n" + value = "Boolean flag indicating whether to include device-info (location, application list etc) \n" +
@ -291,14 +309,14 @@ public interface DeviceManagementService {
required = false, required = false,
defaultValue = "0") defaultValue = "0")
@QueryParam("offset") @QueryParam("offset")
int offset, int offset,
@ApiParam( @ApiParam(
name = "limit", name = "limit",
value = "Provide how many device details you require from the starting pagination index/offset.", value = "Provide how many device details you require from the starting pagination index/offset.",
required = false, required = false,
defaultValue = "5") defaultValue = "5")
@QueryParam("limit") @QueryParam("limit")
int limit); int limit);
@GET @GET
@ApiOperation( @ApiOperation(
@ -323,16 +341,16 @@ public interface DeviceManagementService {
@ResponseHeader( @ResponseHeader(
name = "ETag", name = "ETag",
description = "Entity Tag of the response resource.\n" + description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."), "Used by caches, or in conditional requests."),
@ResponseHeader( @ResponseHeader(
name = "Last-Modified", name = "Last-Modified",
description = "Date and time the resource was last modified.\n" + 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( @ApiResponse(
code = 304, code = 304,
message = "Not Modified. \n Empty body because the client already has the latest version of " + message = "Not Modified. \n Empty body because the client already has the latest version of " +
"the requested resource.\n"), "the requested resource.\n"),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "The incoming request has more than one selection criteria defined via the query parameters.", message = "The incoming request has more than one selection criteria defined via the query parameters.",
@ -383,9 +401,9 @@ public interface DeviceManagementService {
"the owner.", "the owner.",
tags = "Device Management", tags = "Device Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details") @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details")
}) })
} }
) )
@ApiResponses( @ApiResponses(
@ -446,16 +464,92 @@ public interface DeviceManagementService {
required = false) required = false)
@QueryParam("owner") @QueryParam("owner")
@Size(max = 100) @Size(max = 100)
String owner, String owner,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" + 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" + "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", "Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false) required = false)
@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(
@ -646,14 +739,14 @@ public interface DeviceManagementService {
required = true) required = true)
@PathParam("type") @PathParam("type")
@Size(max = 45) @Size(max = 45)
String type, String type,
@ApiParam( @ApiParam(
name = "id", name = "id",
value = "The device identifier of the device you want ot get details.", value = "The device identifier of the device you want ot get details.",
required = true) required = true)
@PathParam("id") @PathParam("id")
@Size(max = 45) @Size(max = 45)
String id, String id,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" + 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", "Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false) required = false)
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String ifModifiedSince); String ifModifiedSince);
//device rename request would looks like follows //device rename request would looks like follows
//POST devices/type/virtual_firealarm/id/us06ww93auzp/rename //POST devices/type/virtual_firealarm/id/us06ww93auzp/rename
@ -820,10 +913,10 @@ public interface DeviceManagementService {
" such as iOS, Android or Windows.", " such as iOS, Android or Windows.",
tags = "Device Management", tags = "Device Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:features") @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:features")
}) })
} }
) )
@ApiResponses( @ApiResponses(
value = { value = {
@ -880,7 +973,7 @@ public interface DeviceManagementService {
required = true) required = true)
@PathParam("type") @PathParam("type")
@Size(max = 45) @Size(max = 45)
String type, String type,
@ApiParam( @ApiParam(
name = "id", name = "id",
value = "The device identifier of the device.\n" + value = "The device identifier of the device.\n" +
@ -888,7 +981,7 @@ public interface DeviceManagementService {
required = true) required = true)
@PathParam("id") @PathParam("id")
@Size(max = 45) @Size(max = 45)
String id, String id,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" + 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", "Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false) required = false)
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String ifModifiedSince); String ifModifiedSince);
@POST @POST
@Path("/search-devices") @Path("/search-devices")
@ -908,9 +1001,9 @@ public interface DeviceManagementService {
notes = "Search for devices by filtering the search result through the specified search terms.", notes = "Search for devices by filtering the search result through the specified search terms.",
tags = "Device Management", tags = "Device Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:search") @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:search")
}) })
} }
) )
@ApiResponses( @ApiResponses(
@ -962,19 +1055,19 @@ public interface DeviceManagementService {
required = false, required = false,
defaultValue = "0") defaultValue = "0")
@QueryParam("offset") @QueryParam("offset")
int offset, int offset,
@ApiParam( @ApiParam(
name = "limit", name = "limit",
value = "Provide how many activity details you require from the starting pagination index/offset.", value = "Provide how many activity details you require from the starting pagination index/offset.",
required = false, required = false,
defaultValue = "5") defaultValue = "5")
@QueryParam("limit") @QueryParam("limit")
int limit, int limit,
@ApiParam( @ApiParam(
name = "searchContext", name = "searchContext",
value = "The properties to advanced search devices.", value = "The properties to advanced search devices.",
required = true) required = true)
SearchContext searchContext); SearchContext searchContext);
@GET @GET
@Path("/{type}/{id}/applications") @Path("/{type}/{id}/applications")
@ -985,11 +1078,11 @@ public interface DeviceManagementService {
notes = "Get the list of applications subscribed to by a device.", notes = "Get the list of applications subscribed to by a device.",
tags = "Device Management", tags = "Device Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:applications") @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:applications")
}) })
} }
) )
@ApiResponses( @ApiResponses(
value = { value = {
@ -1046,14 +1139,14 @@ public interface DeviceManagementService {
required = true) required = true)
@PathParam("type") @PathParam("type")
@Size(max = 45) @Size(max = 45)
String type, String type,
@ApiParam( @ApiParam(
name = "id", name = "id",
value = "The device identifier of the device.", value = "The device identifier of the device.",
required = true) required = true)
@PathParam("id") @PathParam("id")
@Size(max = 45) @Size(max = 45)
String id, String id,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" + 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", "Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false) required = false)
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String ifModifiedSince, String ifModifiedSince,
@ApiParam( @ApiParam(
name = "offset", name = "offset",
value = "The starting pagination index for the complete list of qualified items.", value = "The starting pagination index for the complete list of qualified items.",
required = false, required = false,
defaultValue = "0") defaultValue = "0")
@QueryParam("offset") @QueryParam("offset")
int offset, int offset,
@ApiParam( @ApiParam(
name = "limit", name = "limit",
value = "Provide how many application details you require from the starting pagination index/offset.", value = "Provide how many application details you require from the starting pagination index/offset.",
required = false, required = false,
defaultValue = "5") defaultValue = "5")
@QueryParam("limit") @QueryParam("limit")
int limit); int limit);
@GET @GET
@ -1087,10 +1180,10 @@ public interface DeviceManagementService {
notes = "Get the details of operations carried out on a selected device.", notes = "Get the details of operations carried out on a selected device.",
tags = "Device Management", tags = "Device Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:operations") @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:operations")
}) })
} }
) )
@ApiResponses( @ApiResponses(
value = { value = {
@ -1147,7 +1240,7 @@ public interface DeviceManagementService {
required = true) required = true)
@PathParam("type") @PathParam("type")
@Size(max = 45) @Size(max = 45)
String type, String type,
@ApiParam( @ApiParam(
name = "id", name = "id",
value = "The device identifier of the device you wish to get details.\n" + value = "The device identifier of the device you wish to get details.\n" +
@ -1155,7 +1248,7 @@ public interface DeviceManagementService {
required = true) required = true)
@PathParam("id") @PathParam("id")
@Size(max = 45) @Size(max = 45)
String id, String id,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" + 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", "Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false) required = false)
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String ifModifiedSince, String ifModifiedSince,
@ApiParam( @ApiParam(
name = "offset", name = "offset",
value = "The starting pagination index for the complete list of qualified items.", value = "The starting pagination index for the complete list of qualified items.",
required = false, required = false,
defaultValue = "0") defaultValue = "0")
@QueryParam("offset") @QueryParam("offset")
int offset, int offset,
@ApiParam( @ApiParam(
name = "limit", name = "limit",
value = "Provide how many activity details you require from the starting pagination index/offset.", value = "Provide how many activity details you require from the starting pagination index/offset.",
required = false, required = false,
defaultValue = "5") defaultValue = "5")
@QueryParam("limit") @QueryParam("limit")
int limit, int limit,
@ApiParam( @ApiParam(
name = "owner", name = "owner",
value = "Provides the owner of the required device.", 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.", "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", tags = "Device Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:effective-policy") @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:effective-policy")
}) })
} }
) )
@ApiResponses( @ApiResponses(
value = { value = {
@ -1257,14 +1350,14 @@ public interface DeviceManagementService {
required = true) required = true)
@PathParam("type") @PathParam("type")
@Size(max = 45) @Size(max = 45)
String type, String type,
@ApiParam( @ApiParam(
name = "id", name = "id",
value = "The device ID.", value = "The device ID.",
required = true) required = true)
@PathParam("id") @PathParam("id")
@Size(max = 45) @Size(max = 45)
String id, String id,
@ApiParam( @ApiParam(
name = "If-Modified-Since", name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" + 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", "Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false) required = false)
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String ifModifiedSince); String ifModifiedSince);
@GET @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.", "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", tags = "Device Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:compliance-data") @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:compliance-data")
}) })
} }
) )
@ApiResponses( @ApiResponses(
@ -1313,14 +1406,14 @@ public interface DeviceManagementService {
required = true) required = true)
@PathParam("type") @PathParam("type")
@Size(max = 45) @Size(max = 45)
String type, String type,
@ApiParam( @ApiParam(
name = "id", name = "id",
value = "Device Identifier", value = "Device Identifier",
required = true) required = true)
@PathParam("id") @PathParam("id")
@Size(max = 45) @Size(max = 45)
String id); String id);
@PUT @PUT
@Path("/{type}/{id}/changestatus") @Path("/{type}/{id}/changestatus")

@ -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();
@ -681,8 +770,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
/** /**
* Change device status. * Change device status.
* *
* @param type Device type * @param type Device type
* @param id Device id * @param id Device id
* @param newsStatus Device new status * @param newsStatus Device new status
* @return {@link Response} object * @return {@link Response} object
*/ */
@ -766,7 +855,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
String date = new SimpleDateFormat(DATE_FORMAT_NOW).format(new Date()); String date = new SimpleDateFormat(DATE_FORMAT_NOW).format(new Date());
operation.setCreatedTimeStamp(date); operation.setCreatedTimeStamp(date);
Activity activity = DeviceMgtAPIUtils.getDeviceManagementService().addOperation(type, operation, Activity activity = DeviceMgtAPIUtils.getDeviceManagementService().addOperation(type, operation,
deviceIdentifiers); deviceIdentifiers);
return Response.status(Response.Status.CREATED).entity(activity).build(); return Response.status(Response.Status.CREATED).entity(activity).build();
} else { } else {
String message = "Only Command and Config operation is supported through this api"; String message = "Only Command and Config operation is supported through this api";

@ -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,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, * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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.jaxrs.service.impl; 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.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.

@ -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, * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* 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 {
@ -181,7 +246,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
@Override @Override
public Device getDevice(DeviceIdentifier deviceIdentifier, Date since, int tenantId) public Device getDevice(DeviceIdentifier deviceIdentifier, Date since, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -189,11 +254,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + 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, " + "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, " + "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());
@ -207,7 +272,52 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while listing device for type " + 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 { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs); 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, " + "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;
@ -259,11 +369,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + 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, " + "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, " + "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 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 " + "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"; "AND TENANT_ID = ? AND e.STATUS = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC";
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());
@ -276,7 +386,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while listing devices for type " + throw new DeviceManagementDAOException("Error occurred while listing devices for type " +
"'" + deviceIdentifier.getType() + "'", e); "'" + deviceIdentifier.getType() + "'", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs); DeviceManagementDAOUtil.cleanupResources(stmt, rs);
} }
@ -293,13 +403,13 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, e.TENANT_ID, " + 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, " + "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, " + "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 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"; "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 = conn.prepareStatement(sql);
stmt.setString(1, deviceIdentifier.getType()); stmt.setString(1, deviceIdentifier.getType());
stmt.setString(2, deviceIdentifier.getId()); stmt.setString(2, deviceIdentifier.getId());
rs = stmt.executeQuery(); rs = stmt.executeQuery();
if (rs.next()) { if (rs.next()) {
device = DeviceManagementDAOUtil.loadDevice(rs); device = DeviceManagementDAOUtil.loadDevice(rs);
@ -323,11 +433,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + 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, " + "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, " + "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 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 " + "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"; "AND TENANT_ID = ? ORDER BY e.DATE_OF_LAST_UPDATE DESC";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
@ -338,7 +448,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving device for id " + throw new DeviceManagementDAOException("Error occurred while retrieving device for id " +
"'" + deviceId + "'", e); "'" + deviceId + "'", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs); DeviceManagementDAOUtil.cleanupResources(stmt, rs);
} }
@ -421,11 +531,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT e1.OWNER, e1.OWNERSHIP, e1.ENROLMENT_ID, e1.DEVICE_ID, e1.STATUS, e1.DATE_OF_LAST_UPDATE," + 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 " + " 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, " + "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.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 " + "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"; "AND t.ID = d.DEVICE_TYPE_ID";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
stmt.setString(2, username); stmt.setString(2, username);
@ -497,8 +607,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT COUNT(d1.DEVICE_ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID FROM " + 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 " + "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 = ?"; "d1.DEVICE_ID = e.DEVICE_ID AND LOWER(e.OWNER) = LOWER(?) AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
stmt.setString(2, username); stmt.setString(2, username);
@ -580,7 +690,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
@Override @Override
public boolean setEnrolmentStatusInBulk(String deviceType, String status, public boolean setEnrolmentStatusInBulk(String deviceType, String status,
int tenantId, List<String> devices) throws DeviceManagementDAOException { int tenantId, List<String> devices) throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
@ -625,8 +735,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT COUNT(d1.DEVICE_ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID FROM " + 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 " + "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 = ?"; "d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
@ -665,7 +775,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, d.DEVICE_IDENTIFICATION, " + 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 //Add query for last updated timestamp
if (since != null) { if (since != null) {
@ -739,7 +849,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + throw new DeviceManagementDAOException("Error occurred while retrieving information of all " +
"registered devices", e); "registered devices", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs); DeviceManagementDAOUtil.cleanupResources(stmt, rs);
} }
@ -755,8 +865,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID FROM DM_DEVICE d, " + 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 = ? " + "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 = ?"; "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, type); stmt.setString(1, type);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
@ -781,8 +891,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT COUNT(e1.DEVICE_ID) AS DEVICE_COUNT FROM DM_DEVICE d, (SELECT e.DEVICE_ID " + 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(?)) " + "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"; "e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID AND t.ID = d.DEVICE_TYPE_ID";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
stmt.setString(2, username); stmt.setString(2, username);
@ -793,7 +903,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices belongs to '" +
username + "'", e); username + "'", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null); DeviceManagementDAOUtil.cleanupResources(stmt, null);
} }
@ -808,8 +918,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID FROM DM_DEVICE d, " + 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 " + "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 = ?"; "WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceName + "%"); stmt.setString(1, deviceName + "%");
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
@ -821,7 +931,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the device count that matches " + throw new DeviceManagementDAOException("Error occurred while fetching the device count that matches " +
"'" + deviceName + "'", e); "'" + deviceName + "'", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null); DeviceManagementDAOUtil.cleanupResources(stmt, null);
} }
@ -836,8 +946,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT COUNT(d.ID) AS DEVICE_COUNT FROM (SELECT e.DEVICE_ID FROM DM_ENROLMENT e WHERE " + 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, " + "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 = ?"; "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 = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
stmt.setString(2, ownerShip); stmt.setString(2, ownerShip);
@ -849,7 +959,7 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices that matches to ownership " +
"'" + ownerShip + "'", e); "'" + ownerShip + "'", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null); DeviceManagementDAOUtil.cleanupResources(stmt, 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());
@ -1044,10 +1154,10 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT ID AS ENROLMENT_ID, DEVICE_ID, OWNER, OWNERSHIP, STATUS, DATE_OF_ENROLMENT, " + 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 " + "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 " + "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 d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " +
"AND TENANT_ID = ? AND STATUS in ('ACTIVE','UNREACHABLE','INACTIVE')"; "AND TENANT_ID = ? AND STATUS in ('ACTIVE','UNREACHABLE','INACTIVE')";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceId.getId()); stmt.setString(1, deviceId.getId());
stmt.setString(2, deviceId.getType()); stmt.setString(2, deviceId.getType());
@ -1060,8 +1170,8 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
return enrolmentInfo; return enrolmentInfo;
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " + throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " +
"information of device '" + deviceId.getId() + "' of type : " "information of device '" + deviceId.getId() + "' of type : "
+ deviceId.getType(), e); + deviceId.getType(), e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs); 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 timestamp Timestamp in long, after which the devices have been updated.
* @param tenantId Tenant id of the currently logged in user. * @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 * @throws DeviceManagementDAOException
*/ */
public List<Device> getDevices(long timestamp, int tenantId) throws DeviceManagementDAOException { public List<Device> getDevices(long timestamp, int tenantId) throws DeviceManagementDAOException {
@ -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