Change status query param to a array to accept multiple values

Status param was changed from string to an array. excludeStatus param was removed from api and api calls. New methods were added to the DAO to query data filtered from list of status
feature/appm-store/pbac
Yohan Avishke 5 years ago committed by Dharmakeerthi Lasantha
parent f11cb0d2b2
commit 16681acf55

@ -183,7 +183,8 @@ class GeoDashboard extends React.Component {
window.location.origin + window.location.origin +
config.serverConfig.invoker.uri + config.serverConfig.invoker.uri +
config.serverConfig.invoker.deviceMgt + config.serverConfig.invoker.deviceMgt +
'/devices?excludeStatus=REMOVED', '/devices?status=ACTIVE&status=INACTIVE&status=UNCLAIMED&status=UNREACHABLE&status=SUSPENDED&' +
'status=DISENROLLMENT_REQUESTED&status=BLOCKED&status=CREATED',
) )
.then(res => { .then(res => {
if (res.status === 200) { if (res.status === 200) {

@ -173,11 +173,10 @@ import java.util.Map;
@Path("/devices") @Path("/devices")
@Api(value = "Device Management", description = "This API carries all device management related operations " + @Api(value = "Device Management", description = "This API carries all device management related operations " +
"such as get all the available devices, etc.") "such as get all the available devices, etc.")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface DeviceManagementService { public interface DeviceManagementService {
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
@ -269,20 +268,12 @@ public interface DeviceManagementService {
@QueryParam("ownership") @QueryParam("ownership")
@Size(max = 45) @Size(max = 45)
String ownership, String ownership,
@ApiParam(
name = "excludeStatus",
value = "Provide the devices that excludes the given status",
required = false)
@QueryParam("excludeStatus")
@Size(max = 45)
String excludeStatus,
@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) List<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",
@ -328,6 +319,7 @@ public interface DeviceManagementService {
int limit); int limit);
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
@ -401,6 +393,7 @@ public interface DeviceManagementService {
int limit); int limit);
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}") @Path("/{type}/{id}")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -488,9 +481,9 @@ public interface DeviceManagementService {
String ifModifiedSince); String ifModifiedSince);
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{deviceType}/{deviceId}/location-history") @Path("/{deviceType}/{deviceId}/location-history")
@ApiOperation( @ApiOperation(
consumes = "application/json",
produces = "application/json", produces = "application/json",
httpMethod = "GET", httpMethod = "GET",
value = "Getting the Location Details of a Device", value = "Getting the Location Details of a Device",
@ -560,6 +553,7 @@ public interface DeviceManagementService {
@QueryParam("to") long to); @QueryParam("to") long to);
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/type/any/id/{id}") @Path("/type/any/id/{id}")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -636,6 +630,7 @@ public interface DeviceManagementService {
@PUT @PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}") @Path("/{type}/{id}")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -691,6 +686,7 @@ public interface DeviceManagementService {
@PathParam("id") String deviceId); @PathParam("id") String deviceId);
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/location") @Path("/{type}/{id}/location")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -767,6 +763,7 @@ public interface DeviceManagementService {
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/info") @Path("/{type}/{id}/info")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -844,6 +841,8 @@ public interface DeviceManagementService {
//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
@POST @POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/type/{device-type}/id/{device-id}/rename") @Path("/type/{device-type}/id/{device-id}/rename")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -919,11 +918,10 @@ public interface DeviceManagementService {
//device remove request would looks like follows //device remove request would looks like follows
//DELETE devices/type/virtual_firealarm/id/us06ww93auzp //DELETE devices/type/virtual_firealarm/id/us06ww93auzp
@DELETE @DELETE
@Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON)
@Path("/type/{device-type}/id/{device-id}") @Path("/type/{device-type}/id/{device-id}")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
consumes = MediaType.WILDCARD,
httpMethod = "DELETE", httpMethod = "DELETE",
value = "Remove the Device Specified by the Device ID", value = "Remove the Device Specified by the Device ID",
notes = "Returns the status of the deleted device operation and the details of the deleted device.", notes = "Returns the status of the deleted device operation and the details of the deleted device.",
@ -988,9 +986,9 @@ public interface DeviceManagementService {
String deviceId); String deviceId);
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/features") @Path("/{type}/{id}/features")
@ApiOperation( @ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
value = "Getting Feature Details of a Device", value = "Getting Feature Details of a Device",
@ -1078,6 +1076,8 @@ public interface DeviceManagementService {
String ifModifiedSince); String ifModifiedSince);
@POST @POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/search-devices") @Path("/search-devices")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1156,6 +1156,8 @@ public interface DeviceManagementService {
SearchContext searchContext); SearchContext searchContext);
@POST @POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/query-devices") @Path("/query-devices")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1234,6 +1236,7 @@ public interface DeviceManagementService {
PropertyMap map); PropertyMap map);
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/applications") @Path("/{type}/{id}/applications")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1336,6 +1339,7 @@ public interface DeviceManagementService {
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/operations") @Path("/{type}/{id}/operations")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1446,6 +1450,7 @@ public interface DeviceManagementService {
String ownership); String ownership);
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/effective-policy") @Path("/{type}/{id}/effective-policy")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1535,6 +1540,7 @@ public interface DeviceManagementService {
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{type}/{id}/compliance-data") @Path("{type}/{id}/compliance-data")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1582,6 +1588,8 @@ public interface DeviceManagementService {
String id); String id);
@PUT @PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/changestatus") @Path("/{type}/{id}/changestatus")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1656,6 +1664,8 @@ public interface DeviceManagementService {
EnrolmentInfo.Status newStatus); EnrolmentInfo.Status newStatus);
@POST @POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{type}/operations") @Path("/{type}/operations")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1713,6 +1723,7 @@ public interface DeviceManagementService {
@Valid OperationRequest operationRequest); @Valid OperationRequest operationRequest);
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/type/{type}/status/{status}/count") @Path("/type/{type}/status/{status}/count")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1781,6 +1792,7 @@ public interface DeviceManagementService {
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/type/{type}/status/{status}/ids") @Path("/type/{type}/status/{status}/ids")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1848,6 +1860,8 @@ public interface DeviceManagementService {
String status); String status);
@PUT @PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/type/{type}/status/{status}") @Path("/type/{type}/status/{status}")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1908,6 +1922,7 @@ public interface DeviceManagementService {
@Valid List<String> deviceList); @Valid List<String> deviceList);
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/compliance/{compliance-status}") @Path("/compliance/{compliance-status}")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -1975,6 +1990,7 @@ public interface DeviceManagementService {
int limit); int limit);
@GET @GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}/features") @Path("/{id}/features")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,

@ -99,7 +99,6 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam; import javax.ws.rs.HeaderParam;
@ -107,7 +106,6 @@ import javax.ws.rs.POST;
import javax.ws.rs.PUT; import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue; import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
@ -119,8 +117,6 @@ import java.util.Date;
import java.util.List; import java.util.List;
@Path("/devices") @Path("/devices")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class DeviceManagementServiceImpl implements DeviceManagementService { public class DeviceManagementServiceImpl implements DeviceManagementService {
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
@ -155,8 +151,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@QueryParam("userPattern") String userPattern, @QueryParam("userPattern") String userPattern,
@QueryParam("role") String role, @QueryParam("role") String role,
@QueryParam("ownership") String ownership, @QueryParam("ownership") String ownership,
@QueryParam("status") String status, @QueryParam("status") List<String> status,
@QueryParam("excludeStatus") String excludeStatus,
@QueryParam("groupId") int groupId, @QueryParam("groupId") int groupId,
@QueryParam("since") String since, @QueryParam("since") String since,
@HeaderParam("If-Modified-Since") String ifModifiedSince, @HeaderParam("If-Modified-Since") String ifModifiedSince,
@ -175,11 +170,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
DeviceAccessAuthorizationService deviceAccessAuthorizationService = DeviceAccessAuthorizationService deviceAccessAuthorizationService =
DeviceMgtAPIUtils.getDeviceAccessAuthorizationService(); DeviceMgtAPIUtils.getDeviceAccessAuthorizationService();
if (deviceAccessAuthorizationService == null) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Device access authorization service is " +
"failed").build()).build();
}
PaginationRequest request = new PaginationRequest(offset, limit); PaginationRequest request = new PaginationRequest(offset, limit);
PaginationResult result; PaginationResult result;
DeviceList devices = new DeviceList(); DeviceList devices = new DeviceList();
@ -195,12 +185,17 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
request.setOwnership(ownership); request.setOwnership(ownership);
} }
if (status != null && !status.isEmpty()) { if (status != null && !status.isEmpty()) {
boolean isStatusEmpty = true;
for (String statusString : status){
if (StringUtils.isNotBlank(statusString)){
isStatusEmpty = false;
break;
}
}
if (!isStatusEmpty) {
RequestValidationUtil.validateStatus(status); RequestValidationUtil.validateStatus(status);
request.setStatus(status); request.setStatusList(status);
} }
if (excludeStatus != null && !excludeStatus.isEmpty()) {
RequestValidationUtil.validateStatus(excludeStatus);
request.setExcludeStatus(excludeStatus);
} }
// this is the user who initiates the request // this is the user who initiates the request
String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
@ -263,7 +258,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
+ "' user"; + "' user";
log.error(msg); log.error(msg);
return Response.status(Response.Status.UNAUTHORIZED).entity( return Response.status(Response.Status.UNAUTHORIZED).entity(
new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} }
} else { } else {
request.setOwner(authorizedUser); request.setOwner(authorizedUser);
@ -373,7 +368,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
} }
@DELETE @DELETE
@Consumes(MediaType.WILDCARD)
@Override @Override
@Path("/type/{device-type}/id/{device-id}") @Path("/type/{device-type}/id/{device-id}")
public Response deleteDevice(@PathParam("device-type") String deviceType, public Response deleteDevice(@PathParam("device-type") String deviceType,
@ -496,8 +490,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@Path("/{deviceType}/{deviceId}/location-history") @Path("/{deviceType}/{deviceId}/location-history")
@GET @GET
@Consumes("application/json")
@Produces("application/json")
public Response getDeviceLocationInfo(@PathParam("deviceType") String deviceType, public Response getDeviceLocationInfo(@PathParam("deviceType") String deviceType,
@PathParam("deviceId") String deviceId, @PathParam("deviceId") String deviceId,
@QueryParam("from") long from, @QueryParam("to") long to) { @QueryParam("from") long from, @QueryParam("to") long to) {
@ -515,12 +507,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(deviceType); deviceIdentifier.setType(deviceType);
if (deviceAccessAuthorizationService == null) {
errorMessage = "Device access authorization service is failed";
log.error(errorMessage);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()).build();
}
if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, authorizedUser)) { if (!deviceAccessAuthorizationService.isUserAuthorized(deviceIdentifier, authorizedUser)) {
String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" +
deviceId + "'"; deviceId + "'";

@ -74,8 +74,22 @@ public class ReportManagementServiceImpl implements ReportManagementService {
request.setOwnership(ownership); request.setOwnership(ownership);
} }
if (status != null && !status.isEmpty()) {
boolean isStatusEmpty = true;
for (String statusString : status){
if (StringUtils.isNotBlank(statusString)){
isStatusEmpty = false;
break;
}
}
if (!isStatusEmpty) {
RequestValidationUtil.validateStatus(status);
request.setStatusList(status);
}
}
result = DeviceMgtAPIUtils.getReportManagementService() result = DeviceMgtAPIUtils.getReportManagementService()
.getDevicesByDuration(request, status, fromDate, toDate); .getDevicesByDuration(request, fromDate, toDate);
if (result.getData().isEmpty()) { if (result.getData().isEmpty()) {
String msg = "No devices have enrolled between " + fromDate + " to " + toDate + String msg = "No devices have enrolled between " + fromDate + " to " + toDate +
" or doesn't match with" + " or doesn't match with" +

@ -19,6 +19,10 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; package org.wso2.carbon.device.mgt.jaxrs.service.impl.util;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;
import org.wso2.carbon.device.mgt.core.dao.impl.device.GenericDeviceDAOImpl;
import org.wso2.carbon.device.mgt.jaxrs.beans.Scope; import org.wso2.carbon.device.mgt.jaxrs.beans.Scope;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
@ -30,6 +34,8 @@ import java.util.List;
public class RequestValidationUtil { public class RequestValidationUtil {
private static final Log log = LogFactory.getLog(RequestValidationUtil.class);
/** /**
* Checks if multiple criteria are specified in a conditional request. * Checks if multiple criteria are specified in a conditional request.
* *
@ -95,12 +101,8 @@ public class RequestValidationUtil {
} }
} }
public static void validateStatus(String status) { public static void validateStatus(List<String> statusList) {
if (status == null) { for (String status : statusList) {
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(
"Enrollment status type cannot be null").build());
}
switch (status) { switch (status) {
case "ACTIVE": case "ACTIVE":
case "INACTIVE": case "INACTIVE":
@ -111,13 +113,16 @@ public class RequestValidationUtil {
case "REMOVED": case "REMOVED":
case "BLOCKED": case "BLOCKED":
case "CREATED": case "CREATED":
return; break;
default: default:
throw new InputValidationException( String msg = "Invalid enrollment status type: " + status + ". \nValid status types are " +
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Invalid enrollment status type " + "ACTIVE | INACTIVE | UNCLAIMED | UNREACHABLE | SUSPENDED | " +
"received. Valid status types are ACTIVE | INACTIVE | " + "DISENROLLMENT_REQUESTED | REMOVED | BLOCKED | CREATED";
"UNCLAIMED | UNREACHABLE | SUSPENDED | DISENROLLMENT_REQUESTED | REMOVED | " + log.error(msg);
"BLOCKED | CREATED").build()); throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST)
.setMessage(msg).build());
}
} }
} }

@ -80,7 +80,9 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import static org.mockito.MockitoAnnotations.initMocks; import static org.mockito.MockitoAnnotations.initMocks;
@ -102,8 +104,7 @@ public class DeviceManagementServiceImplTest {
private static final String TENANT_AWARE_USERNAME = "admin@carbon.super"; private static final String TENANT_AWARE_USERNAME = "admin@carbon.super";
private static final String DEFAULT_ROLE = "admin"; private static final String DEFAULT_ROLE = "admin";
private static final String DEFAULT_OWNERSHIP = "BYOD"; private static final String DEFAULT_OWNERSHIP = "BYOD";
private static final String DEFAULT_STATUS = "ACTIVE"; private static final List<String> DEFAULT_STATUS_LIST = new ArrayList<>();
private static final String DEFAULT_EXCLUDED_STATUS = "REMOVED";
private static final String DEFAULT_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; private static final String DEFAULT_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z";
private DeviceManagementService deviceManagementService; private DeviceManagementService deviceManagementService;
private DeviceAccessAuthorizationService deviceAccessAuthorizationService; private DeviceAccessAuthorizationService deviceAccessAuthorizationService;
@ -124,6 +125,8 @@ public class DeviceManagementServiceImplTest {
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); demoDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
DEFAULT_STATUS_LIST.add("ACTIVE");
DEFAULT_STATUS_LIST.add("REMOVED");
} }
@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.")
@ -172,7 +175,7 @@ public class DeviceManagementServiceImplTest {
.toReturn(this.deviceAccessAuthorizationService); .toReturn(this.deviceAccessAuthorizationService);
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5); DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} }
@ -191,19 +194,19 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5); DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5); DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5); DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, true, 10, 5); DEFAULT_STATUS_LIST, 1, null, null, true, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
} }
@ -280,7 +283,7 @@ public class DeviceManagementServiceImplTest {
Mockito.when(carbonContext.getUsername()).thenReturn(DEFAULT_USERNAME); Mockito.when(carbonContext.getUsername()).thenReturn(DEFAULT_USERNAME);
Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true);
this.deviceManagementService.getDeviceByID(TEST_DEVICE_IDENTIFIER, ifModifiedSince,true); this.deviceManagementService.getDeviceByID(TEST_DEVICE_IDENTIFIER, ifModifiedSince, true);
} }
@ -308,16 +311,16 @@ public class DeviceManagementServiceImplTest {
this.deviceManagementService.getDeviceByID(TEST_DEVICE_IDENTIFIER, ifModifiedSince,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() { expectedExceptions = NoClassDefFoundError.class)
public void testGetDevicesWithErroneousDeviceAccessAuthorizationService()
throws DeviceAccessAuthorizationException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true);
.toReturn(null); deviceManagementService.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null,
Response response = this.deviceManagementService DEFAULT_ROLE, DEFAULT_OWNERSHIP, DEFAULT_STATUS_LIST, 1,
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, null, false, 10, 5);
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} }
@Test(description = "Testing get devices when user is the device admin") @Test(description = "Testing get devices when user is the device admin")
@ -335,12 +338,12 @@ public class DeviceManagementServiceImplTest {
Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true);
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5); , DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5); , DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
} }
@ -361,8 +364,8 @@ public class DeviceManagementServiceImplTest {
.toReturn(Mockito.mock(RealmService.class, Mockito.RETURNS_MOCKS)); .toReturn(Mockito.mock(RealmService.class, Mockito.RETURNS_MOCKS));
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, DEFAULT_EXCLUDED_STATUS, .getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS, 0, null, null, false, 10, 5); DEFAULT_STATUS_LIST, 0, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode());
Mockito.reset(this.deviceAccessAuthorizationService); Mockito.reset(this.deviceAccessAuthorizationService);
} }
@ -383,15 +386,15 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 0, null, ifModifiedSince, false, 10, 5); DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 0, null, ifModifiedSince, true, 10, 5); DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, true, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 0, null, "ErrorModifiedSince", false, 10, 5); DEFAULT_STATUS_LIST, 0, null, "ErrorModifiedSince", false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} }
@ -411,15 +414,15 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 0, since, null, false, 10, 5); DEFAULT_STATUS_LIST, 0, since, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 0, since, null, true, 10, 5); DEFAULT_STATUS_LIST, 0, since, null, true, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 0, "ErrorSince", null, false, 10, 5); DEFAULT_STATUS_LIST, 0, "ErrorSince", null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} }
@ -441,7 +444,7 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5); DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Mockito.reset(this.deviceManagementProviderService); Mockito.reset(this.deviceManagementProviderService);
} }
@ -463,7 +466,7 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5); DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Mockito.reset(this.deviceAccessAuthorizationService); Mockito.reset(this.deviceAccessAuthorizationService);
} }

@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.common;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
@ -32,8 +33,7 @@ public class PaginationRequest {
private int groupId; private int groupId;
private String owner; private String owner;
private String ownerPattern; private String ownerPattern;
private String status; private List<String> statusList;
private String excludeStatus;
private String deviceType; private String deviceType;
private String deviceName; private String deviceName;
private String ownership; private String ownership;
@ -78,20 +78,12 @@ public class PaginationRequest {
this.owner = owner; this.owner = owner;
} }
public String getStatus() { public List<String> getStatusList() {
return status; return statusList;
} }
public void setStatus(String status) { public void setStatusList(List<String> statusList) {
this.status = status; this.statusList = statusList;
}
public String getExcludeStatus() {
return excludeStatus;
}
public void setExcludeStatus(String excludeStatus) {
this.excludeStatus = excludeStatus;
} }
public String getDeviceType() { public String getDeviceType() {
@ -164,7 +156,7 @@ public class PaginationRequest {
public String toString() { public String toString() {
return "Device type '" + this.deviceType + "' Device Name '" + this.deviceName + "' row count: " + this.rowCount return "Device type '" + this.deviceType + "' Device Name '" + this.deviceName + "' row count: " + this.rowCount
+ " Owner role '" + this.ownerRole + "' owner pattern '" + this.ownerPattern + "' ownership " + " Owner role '" + this.ownerRole + "' owner pattern '" + this.ownerPattern + "' ownership "
+ this.ownership + "' Status '" + this.status + "' owner '" + this.owner + "' groupId: " + this.groupId + this.ownership + "' Status '" + this.statusList + "' owner '" + this.owner + "' groupId: " + this.groupId
+ " start index: " + this.startIndex; + " start index: " + this.startIndex;
} }
} }

@ -39,7 +39,7 @@ public interface ReportManagementService {
* @throws {@Link DeviceManagementException} When error occurred while validating device list page size * @throws {@Link DeviceManagementException} When error occurred while validating device list page size
* @throws {@Link ReportManagementException} When failed to retrieve devices. * @throws {@Link ReportManagementException} When failed to retrieve devices.
*/ */
PaginationResult getDevicesByDuration(PaginationRequest request, List<String> statusList, String fromDate, String toDate) PaginationResult getDevicesByDuration(PaginationRequest request, String fromDate, String toDate)
throws ReportManagementException; throws ReportManagementException;
int getDevicesByDurationCount(List<String> statusList, String ownership, String fromDate, String toDate) int getDevicesByDurationCount(List<String> statusList, String ownership, String fromDate, String toDate)

@ -294,7 +294,6 @@ public interface DeviceDAO {
*/ */
List<Device> getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; List<Device> getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException;
/** /**
* This method is used to search for devices within a specific group. * This method is used to search for devices within a specific group.
* *
@ -553,7 +552,6 @@ public interface DeviceDAO {
* *
*/ */
List<Device> getDevicesByDuration(PaginationRequest request, List<Device> getDevicesByDuration(PaginationRequest request,
List<String> statusList,
int tenantId, int tenantId,
String fromDate, String fromDate,
String toDate) throws DeviceManagementDAOException; String toDate) throws DeviceManagementDAOException;

@ -80,12 +80,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
@Override @Override
public int addDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException { public int addDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
int deviceId = -1; int deviceId = -1;
try { try {
conn = this.getConnection(); Connection conn = this.getConnection();
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 (?, ?, ?, ?, ?, ?)";
@ -1008,9 +1007,6 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
@Override @Override
public int getDeviceCount(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { public int getDeviceCount(PaginationRequest request, int tenantId) throws DeviceManagementDAOException {
int deviceCount = 0; int deviceCount = 0;
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
String deviceType = request.getDeviceType(); String deviceType = request.getDeviceType();
boolean isDeviceTypeProvided = false; boolean isDeviceTypeProvided = false;
String deviceName = request.getDeviceName(); String deviceName = request.getDeviceName();
@ -1021,17 +1017,23 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
boolean isOwnerPatternProvided = false; boolean isOwnerPatternProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
boolean isOwnershipProvided = false; boolean isOwnershipProvided = false;
String status = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false; boolean isStatusProvided = false;
String excludeStatus = request.getExcludeStatus();
boolean isExcludeStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
try {
conn = this.getConnection();
String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t";
try {
Connection conn = getConnection();
String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT " +
"FROM DM_ENROLMENT e, " +
"(SELECT " +
"d.ID, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"DM_DEVICE d, " +
"DM_DEVICE_TYPE t";
//Add query for last updated timestamp //Add query for last updated timestamp
if (since != null) { if (since != null) {
sql = sql + " , DM_DEVICE_DETAIL dt"; sql = sql + " , DM_DEVICE_DETAIL dt";
@ -1046,19 +1048,15 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
sql = sql + " AND t.NAME = ?"; sql = sql + " AND t.NAME = ?";
isDeviceTypeProvided = true; isDeviceTypeProvided = true;
} }
if (deviceName != null && !deviceName.isEmpty()) { if (deviceName != null && !deviceName.isEmpty()) {
sql = sql + " AND d.NAME LIKE ?"; sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true; isDeviceNameProvided = true;
} }
sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?";
if (ownership != null && !ownership.isEmpty()) { if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
isOwnershipProvided = true; isOwnershipProvided = true;
} }
//Add the query for owner //Add the query for owner
if (owner != null && !owner.isEmpty()) { if (owner != null && !owner.isEmpty()) {
sql = sql + " AND e.OWNER = ?"; sql = sql + " AND e.OWNER = ?";
@ -1067,20 +1065,14 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
sql = sql + " AND e.OWNER LIKE ?"; sql = sql + " AND e.OWNER LIKE ?";
isOwnerPatternProvided = true; isOwnerPatternProvided = true;
} }
if (statusList != null && !statusList.isEmpty()) {
if (status != null && !status.isEmpty()) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?";
isStatusProvided = true; isStatusProvided = true;
} }
if (excludeStatus != null && !excludeStatus.isEmpty()) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
sql = sql + " AND e.STATUS != ?"; int paramIdx = 1;
isExcludeStatusProvided = true; stmt.setInt(paramIdx++, tenantId);
}
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
int paramIdx = 2;
if (isSinceProvided) { if (isSinceProvided) {
stmt.setLong(paramIdx++, since.getTime()); stmt.setLong(paramIdx++, since.getTime());
} }
@ -1090,7 +1082,6 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
if (isDeviceNameProvided) { if (isDeviceNameProvided) {
stmt.setString(paramIdx++, request.getDeviceName() + "%"); stmt.setString(paramIdx++, request.getDeviceName() + "%");
} }
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) { if (isOwnershipProvided) {
stmt.setString(paramIdx++, request.getOwnership()); stmt.setString(paramIdx++, request.getOwnership());
@ -1101,22 +1092,22 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
stmt.setString(paramIdx++, ownerPattern + "%"); stmt.setString(paramIdx++, ownerPattern + "%");
} }
if (isStatusProvided) { if (isStatusProvided) {
stmt.setString(paramIdx++, request.getStatus()); for (String status : statusList) {
stmt.setString(paramIdx++, status);
} }
if (isExcludeStatusProvided) {
stmt.setString(paramIdx++, excludeStatus);
} }
rs = stmt.executeQuery();
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) { if (rs.next()) {
deviceCount = rs.getInt("DEVICE_COUNT"); deviceCount = rs.getInt("DEVICE_COUNT");
} }
return deviceCount;
}
}
} 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 {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
} }
return deviceCount;
} }
@Override @Override
@ -2270,4 +2261,17 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
} }
return true; return true;
} }
protected String buildStatusQuery(List<String> statusList)
throws DeviceManagementDAOException {
if (statusList == null || statusList.isEmpty()) {
String msg = "SQL query build for status list failed. Status list cannot be empty or null";
log.error(msg);
throw new DeviceManagementDAOException(msg);
}
StringJoiner joiner = new StringJoiner(",", " AND e.STATUS IN(", ")");
statusList.stream().map(status -> "?").forEach(joiner::add);
return joiner.toString();
}
} }

@ -48,9 +48,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
@Override @Override
public List<Device> getDevices(PaginationRequest request, int tenantId) public List<Device> getDevices(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> devices; List<Device> devices;
String deviceType = request.getDeviceType(); String deviceType = request.getDeviceType();
boolean isDeviceTypeProvided = false; boolean isDeviceTypeProvided = false;
@ -62,33 +59,42 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isOwnerPatternProvided = false; boolean isOwnerPatternProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
boolean isOwnershipProvided = false; boolean isOwnershipProvided = false;
String status = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false; boolean isStatusProvided = false;
String excludeStatus = request.getExcludeStatus();
boolean isExcludeStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
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, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t ";
try {
Connection conn = 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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t ";
//Add the query to filter active devices on timestamp //Add the query to filter active devices on timestamp
if (since != null) { if (since != null) {
sql = sql + ", DM_DEVICE_DETAIL dt"; sql = sql + ", DM_DEVICE_DETAIL dt";
isSinceProvided = true; isSinceProvided = true;
} }
sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
//Add query for last updated timestamp //Add query for last updated timestamp
if (isSinceProvided) { if (isSinceProvided) {
sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?";
} }
//Add the query for device-type //Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) { if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?"; sql = sql + " AND t.NAME = ?";
@ -99,9 +105,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND d.NAME LIKE ?"; sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true; isDeviceNameProvided = true;
} }
sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?";
//Add the query for ownership //Add the query for ownership
if (ownership != null && !ownership.isEmpty()) { if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
@ -115,22 +119,15 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND e.OWNER LIKE ?"; sql = sql + " AND e.OWNER LIKE ?";
isOwnerPatternProvided = true; isOwnerPatternProvided = true;
} }
//Add the query for status if (statusList != null && !statusList.isEmpty()) {
if (status != null && !status.isEmpty()) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?";
isStatusProvided = true; isStatusProvided = true;
} }
//Add the query for exclude status
if (excludeStatus != null && !excludeStatus.isEmpty()) {
sql = sql + " AND e.STATUS != ?";
isExcludeStatusProvided = true;
}
sql = sql + " LIMIT ?,?"; sql = sql + " LIMIT ?,?";
stmt = conn.prepareStatement(sql); try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, tenantId); int paramIdx = 1;
int paramIdx = 2; stmt.setInt(paramIdx++, tenantId);
if (isSinceProvided) { if (isSinceProvided) {
stmt.setLong(paramIdx++, since.getTime()); stmt.setLong(paramIdx++, since.getTime());
} }
@ -140,7 +137,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (isDeviceNameProvided) { if (isDeviceNameProvided) {
stmt.setString(paramIdx++, deviceName + "%"); stmt.setString(paramIdx++, deviceName + "%");
} }
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) { if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx++, ownership);
@ -151,37 +147,34 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(paramIdx++, ownerPattern + "%"); stmt.setString(paramIdx++, ownerPattern + "%");
} }
if (isStatusProvided) { if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status); stmt.setString(paramIdx++, status);
} }
if (isExcludeStatusProvided) {
stmt.setString(paramIdx++, excludeStatus);
} }
stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount()); stmt.setInt(paramIdx, request.getRowCount());
rs = stmt.executeQuery();
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + String msg = "Error occurred while retrieving information of all " +
"registered devices", e); "registered devices";
} finally { log.error(msg, e);
DeviceManagementDAOUtil.cleanupResources(stmt, rs); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override
public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId) public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> devices = null; List<Device> devices = null;
int groupId = request.getGroupId(); int groupId = request.getGroupId();
String deviceType = request.getDeviceType(); String deviceType = request.getDeviceType();
boolean isDeviceTypeProvided = false; boolean isDeviceTypeProvided = false;
@ -193,52 +186,63 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isOwnerPatternProvided = false; boolean isOwnerPatternProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
boolean isOwnershipProvided = false; boolean isOwnershipProvided = false;
String status = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false; boolean isStatusProvided = false;
String excludeStatus = request.getExcludeStatus();
boolean isExcludeStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
try { try {
conn = this.getConnection(); Connection conn = getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + String sql = "SELECT d1.DEVICE_ID, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "d1.DESCRIPTION, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + "d1.NAME AS DEVICE_NAME, " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "d1.DEVICE_TYPE, " +
"FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID " + "d1.DEVICE_IDENTIFICATION, " +
"FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 WHERE" + "e.OWNER, " +
" d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?"; "e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
//Add the query for device-name //Add the query for device-name
if (deviceName != null && !deviceName.isEmpty()) { if (deviceName != null && !deviceName.isEmpty()) {
sql = sql + " AND d.NAME LIKE ?"; sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true; isDeviceNameProvided = true;
} }
sql = sql + ") gd, DM_DEVICE_TYPE t"; sql = sql + ") gd, DM_DEVICE_TYPE t";
if (since != null) { if (since != null) {
sql = sql + ", DM_DEVICE_DETAIL dt"; sql = sql + ", DM_DEVICE_DETAIL dt";
isSinceProvided = true; isSinceProvided = true;
} }
sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID";
//Add query for last updated timestamp //Add query for last updated timestamp
if (isSinceProvided) { if (isSinceProvided) {
sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?";
} }
//Add the query for device-type //Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) { if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?"; sql = sql + " AND t.NAME = ?";
isDeviceTypeProvided = true; isDeviceTypeProvided = true;
} }
sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ";
//Add the query for ownership //Add the query for ownership
if (ownership != null && !ownership.isEmpty()) { if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
@ -252,25 +256,16 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND e.OWNER LIKE ?"; sql = sql + " AND e.OWNER LIKE ?";
isOwnerPatternProvided = true; isOwnerPatternProvided = true;
} }
//Add the query for status if (statusList != null && !statusList.isEmpty()) {
if (status != null && !status.isEmpty()) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?";
isStatusProvided = true; isStatusProvided = true;
} }
//Add the query for exclude status
if (excludeStatus != null && !excludeStatus.isEmpty()) {
sql = sql + " AND e.STATUS != ?";
isExcludeStatusProvided = true;
}
sql = sql + " LIMIT ?,?"; sql = sql + " LIMIT ?,?";
stmt = conn.prepareStatement(sql); try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(1, groupId); stmt.setInt(paramIdx++, groupId);
stmt.setInt(2, tenantId); stmt.setInt(paramIdx++, tenantId);
int paramIdx = 3;
if (isDeviceNameProvided) { if (isDeviceNameProvided) {
stmt.setString(paramIdx++, deviceName + "%"); stmt.setString(paramIdx++, deviceName + "%");
} }
@ -280,7 +275,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (isDeviceTypeProvided) { if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType); stmt.setString(paramIdx++, deviceType);
} }
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) { if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx++, ownership);
@ -291,27 +285,28 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(paramIdx++, ownerPattern + "%"); stmt.setString(paramIdx++, ownerPattern + "%");
} }
if (isStatusProvided) { if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status); stmt.setString(paramIdx++, status);
} }
if (isExcludeStatusProvided) {
stmt.setString(paramIdx++, excludeStatus);
} }
stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount()); stmt.setInt(paramIdx, request.getRowCount());
rs = stmt.executeQuery(); try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of" + String msg = "Error occurred while retrieving information of" +
" devices belonging to group : " + groupId, e); " devices belonging to group : " + groupId;
} finally { log.error(msg, e);
DeviceManagementDAOUtil.cleanupResources(stmt, rs); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override
@ -421,46 +416,81 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
@Override @Override
public List<Device> getDevicesByStatus(PaginationRequest request, int tenantId) public List<Device> getDevicesByStatus(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
List<String> statusList = request.getStatusList();
try { try {
conn = this.getConnection(); Connection conn = getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + String sql = "SELECT d.ID AS DEVICE_ID, " +
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "d.DESCRIPTION, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + "d.NAME AS DEVICE_NAME, " +
"e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + "t.NAME AS DEVICE_TYPE, " +
"WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + "d.DEVICE_IDENTIFICATION, " +
"WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ?,?"; "e.OWNER, " +
stmt = conn.prepareStatement(sql); "e.OWNERSHIP, " +
stmt.setInt(1, tenantId); "e.STATUS, " +
stmt.setString(2, request.getStatus()); "e.DATE_OF_LAST_UPDATE, " +
stmt.setInt(3, tenantId); "e.DATE_OF_ENROLMENT, " +
stmt.setInt(4, request.getStartIndex()); "e.ID AS ENROLMENT_ID " +
stmt.setInt(5, request.getRowCount()); "FROM " +
ResultSet rs = stmt.executeQuery(); "(SELECT e.ID, " +
"e.DEVICE_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
if (statusList == null || statusList.isEmpty()) {
String msg = "Error occurred while fetching the list of devices. Status List can't " +
"be null or empty";
log.error(msg);
throw new DeviceManagementDAOException(msg);
}
sql += buildStatusQuery(statusList);
sql += ") e, " +
"DM_DEVICE d, " +
"DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID " +
"AND d.TENANT_ID = ? " +
"LIMIT ?,?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
for (String status : statusList) {
stmt.setString(paramIdx++, status);
}
stmt.setInt(paramIdx++, tenantId);
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount());
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices that matches to status " + String msg = "Error occurred while fetching the list of devices that matches to status " +
"'" + request.getStatus() + "'"; request.getStatusList().toString();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementDAOException(msg, e); throw new DeviceManagementDAOException(msg, e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
} }
return devices;
} }
@Override @Override
public List<Device> getDevicesByDuration(PaginationRequest request, List<String> statusList, int tenantId, public List<Device> getDevicesByDuration(PaginationRequest request, int tenantId,
String fromDate, String toDate) String fromDate, String toDate)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
List<Device> devices; List<Device> devices;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
List<String> statusList = request.getStatusList();
boolean isStatusProvided = false; boolean isStatusProvided = false;
String sql = "SELECT " + String sql = "SELECT " +
@ -479,20 +509,13 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DEVICE_TYPE_ID = t.ID AND " + "d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " + "e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; "e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
if (statusList != null && !statusList.isEmpty()) {
//Add the query for status sql += buildStatusQuery(statusList);
StringBuilder sqlBuilder = new StringBuilder(sql);
isStatusProvided = buildStatusQuery(statusList, sqlBuilder);
sql = sqlBuilder.toString();
if(statusList != null && !statusList.isEmpty()){
isStatusProvided = true; isStatusProvided = true;
} }
if (ownership != null) { if (ownership != null) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
} }
sql = sql + " LIMIT ?,?"; sql = sql + " LIMIT ?,?";
try (Connection conn = this.getConnection(); try (Connection conn = this.getConnection();
@ -511,12 +534,14 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount()); stmt.setInt(paramIdx, request.getRowCount());
try (ResultSet rs = stmt.executeQuery()) { try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " + String msg = "Error occurred while retrieving information of all " +
@ -524,27 +549,28 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementDAOException(msg, e); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override
public int getDevicesByDurationCount(List<String> statusList, String ownership, String fromDate, String toDate, int tenantId) throws DeviceManagementDAOException { public int getDevicesByDurationCount(
List<String> statusList, String ownership, String fromDate, String toDate, int tenantId)
throws DeviceManagementDAOException {
int deviceCount = 0; int deviceCount = 0;
boolean isStatusProvided; boolean isStatusProvided = false;
String sql = "SELECT " + String sql = "SELECT " +
"COUNT(d.ID) AS DEVICE_COUNT " + "COUNT(d.ID) AS DEVICE_COUNT " +
"FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " + "FROM DM_DEVICE AS d , " +
"WHERE d.ID = e.DEVICE_ID AND " + "DM_ENROLMENT AS e , " +
"d.DEVICE_TYPE_ID = t.ID AND " + "DM_DEVICE_TYPE AS t " +
"e.TENANT_ID = ? AND " + "WHERE d.ID = e.DEVICE_ID " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; "AND d.DEVICE_TYPE_ID = t.ID " +
"AND e.TENANT_ID = ? " +
//Add the query for status "AND e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
StringBuilder sqlBuilder = new StringBuilder(sql); if (statusList != null && !statusList.isEmpty()) {
isStatusProvided = buildStatusQuery(statusList, sqlBuilder); sql += buildStatusQuery(statusList);
sql = sqlBuilder.toString(); isStatusProvided = true;
}
if (ownership != null) { if (ownership != null) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
} }
@ -561,12 +587,14 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
} }
if (ownership != null) { if (ownership != null) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx, ownership);
} }
try (ResultSet rs = stmt.executeQuery()) { try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) { if (rs.next()) {
deviceCount = rs.getInt("DEVICE_COUNT"); deviceCount = rs.getInt("DEVICE_COUNT");
} }
return deviceCount;
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " + String msg = "Error occurred while retrieving information of all " +
@ -574,7 +602,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementDAOException(msg, e); throw new DeviceManagementDAOException(msg, e);
} }
return deviceCount;
} }
@Override @Override
@ -583,7 +610,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
List<Count> countList = new ArrayList<>(); List<Count> countList = new ArrayList<>();
String ownership = request.getOwnership(); String ownership = request.getOwnership();
boolean isStatusProvided; boolean isStatusProvided = false;
String sql = String sql =
"SELECT " + "SELECT " +
@ -597,9 +624,10 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"BETWEEN ? AND ? "; "BETWEEN ? AND ? ";
//Add the query for status //Add the query for status
StringBuilder sqlBuilder = new StringBuilder(sql); if (statusList != null && !statusList.isEmpty()) {
isStatusProvided = buildStatusQuery(statusList, sqlBuilder); sql += buildStatusQuery(statusList);
sql = sqlBuilder.toString(); isStatusProvided = true;
}
if (ownership != null) { if (ownership != null) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
@ -644,23 +672,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
return countList; return countList;
} }
protected boolean buildStatusQuery(List<String> statusList, StringBuilder sqlBuilder) {
if (statusList != null && !statusList.isEmpty() && !statusList.get(0).isEmpty()) {
sqlBuilder.append(" AND e.STATUS IN(");
for (int i = 0; i < statusList.size(); i++) {
sqlBuilder.append("?");
if (i != statusList.size() - 1) {
sqlBuilder.append(",");
}
}
sqlBuilder.append(")");
return true;
}else {
return false;
}
}
/** /**
* Get the list of devices that matches with the given device name and (or) device type. * Get the list of devices that matches with the given device name and (or) device type.
* *

@ -50,8 +50,6 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
public List<Device> getDevices(PaginationRequest request, int tenantId) public List<Device> getDevices(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> devices = null; List<Device> devices = null;
String deviceType = request.getDeviceType(); String deviceType = request.getDeviceType();
boolean isDeviceTypeProvided = false; boolean isDeviceTypeProvided = false;
@ -63,33 +61,42 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isOwnerPatternProvided = false; boolean isOwnerPatternProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
boolean isOwnershipProvided = false; boolean isOwnershipProvided = false;
String status = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false; boolean isStatusProvided = false;
String excludeStatus = request.getExcludeStatus();
boolean isExcludeStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
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, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "FROM DM_DEVICE d, DM_DEVICE_TYPE t ";
try {
conn = 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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t ";
//Add the query to filter active devices on timestamp //Add the query to filter active devices on timestamp
if (since != null) { if (since != null) {
sql = sql + ", DM_DEVICE_DETAIL dt"; sql = sql + ", DM_DEVICE_DETAIL dt";
isSinceProvided = true; isSinceProvided = true;
} }
sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
//Add query for last updated timestamp //Add query for last updated timestamp
if (isSinceProvided) { if (isSinceProvided) {
sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?";
} }
//Add the query for device-type //Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) { if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?"; sql = sql + " AND t.NAME = ?";
@ -100,9 +107,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND d.NAME LIKE ?"; sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true; isDeviceNameProvided = true;
} }
sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?";
//Add the query for ownership //Add the query for ownership
if (ownership != null && !ownership.isEmpty()) { if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
@ -116,22 +121,15 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND e.OWNER LIKE ?"; sql = sql + " AND e.OWNER LIKE ?";
isOwnerPatternProvided = true; isOwnerPatternProvided = true;
} }
//Add the query for status if (statusList != null && !statusList.isEmpty()) {
if (status != null && !status.isEmpty()) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?";
isStatusProvided = true; isStatusProvided = true;
} }
//Add the query for exclude status
if (excludeStatus != null && !excludeStatus.isEmpty()) {
sql = sql + " AND e.STATUS != ?";
isExcludeStatusProvided = true;
}
sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql); try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, tenantId); int paramIdx = 1;
int paramIdx = 2; stmt.setInt(paramIdx++, tenantId);
if (isSinceProvided) { if (isSinceProvided) {
stmt.setLong(paramIdx++, since.getTime()); stmt.setLong(paramIdx++, since.getTime());
} }
@ -141,7 +139,6 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (isDeviceNameProvided) { if (isDeviceNameProvided) {
stmt.setString(paramIdx++, deviceName + "%"); stmt.setString(paramIdx++, deviceName + "%");
} }
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) { if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx++, ownership);
@ -152,36 +149,35 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(paramIdx++, ownerPattern + "%"); stmt.setString(paramIdx++, ownerPattern + "%");
} }
if (isStatusProvided) { if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status); stmt.setString(paramIdx++, status);
} }
if (isExcludeStatusProvided) {
stmt.setString(paramIdx++, excludeStatus);
} }
stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount()); stmt.setInt(paramIdx, request.getRowCount());
rs = stmt.executeQuery();
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + String msg = "Error occurred while retrieving information of all " +
"registered devices", e); "registered devices";
} finally { log.error(msg, e);
DeviceManagementDAOUtil.cleanupResources(stmt, rs); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override
public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId) public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> devices = null; List<Device> devices = null;
int groupId = request.getGroupId(); int groupId = request.getGroupId();
String deviceType = request.getDeviceType(); String deviceType = request.getDeviceType();
boolean isDeviceTypeProvided = false; boolean isDeviceTypeProvided = false;
@ -193,52 +189,64 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isOwnerPatternProvided = false; boolean isOwnerPatternProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
boolean isOwnershipProvided = false; boolean isOwnershipProvided = false;
String status = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false; boolean isStatusProvided = false;
String excludeStatus = request.getExcludeStatus();
boolean isExcludeStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
try { try {
conn = this.getConnection(); conn = getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + String sql = "SELECT d1.DEVICE_ID, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "d1.DESCRIPTION, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + "d1.NAME AS DEVICE_NAME, " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "d1.DEVICE_TYPE, " +
"FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID " + "d1.DEVICE_IDENTIFICATION, " +
"FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 WHERE" + "e.OWNER, " +
" d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?"; "e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE " +
"d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
//Add the query for device-name //Add the query for device-name
if (deviceName != null && !deviceName.isEmpty()) { if (deviceName != null && !deviceName.isEmpty()) {
sql = sql + " AND d.NAME LIKE ?"; sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true; isDeviceNameProvided = true;
} }
sql = sql + ") gd, DM_DEVICE_TYPE t"; sql = sql + ") gd, DM_DEVICE_TYPE t";
if (since != null) { if (since != null) {
sql = sql + ", DM_DEVICE_DETAIL dt"; sql = sql + ", DM_DEVICE_DETAIL dt";
isSinceProvided = true; isSinceProvided = true;
} }
sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID";
//Add query for last updated timestamp //Add query for last updated timestamp
if (isSinceProvided) { if (isSinceProvided) {
sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?";
} }
//Add the query for device-type //Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) { if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?"; sql = sql + " AND t.NAME = ?";
isDeviceTypeProvided = true; isDeviceTypeProvided = true;
} }
sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ";
//Add the query for ownership //Add the query for ownership
if (ownership != null && !ownership.isEmpty()) { if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
@ -252,25 +260,16 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND e.OWNER LIKE ?"; sql = sql + " AND e.OWNER LIKE ?";
isOwnerPatternProvided = true; isOwnerPatternProvided = true;
} }
//Add the query for status if (statusList != null && !statusList.isEmpty()) {
if (status != null && !status.isEmpty()) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?";
isStatusProvided = true; isStatusProvided = true;
} }
//Add the query for exclude status
if (excludeStatus != null && !excludeStatus.isEmpty()) {
sql = sql + " AND e.STATUS != ?";
isExcludeStatusProvided = true;
}
sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql); try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(1, groupId); stmt.setInt(paramIdx++, groupId);
stmt.setInt(2, tenantId); stmt.setInt(paramIdx++, tenantId);
int paramIdx = 3;
if (isDeviceNameProvided) { if (isDeviceNameProvided) {
stmt.setString(paramIdx++, deviceName + "%"); stmt.setString(paramIdx++, deviceName + "%");
} }
@ -280,7 +279,6 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (isDeviceTypeProvided) { if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType); stmt.setString(paramIdx++, deviceType);
} }
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) { if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx++, ownership);
@ -291,30 +289,30 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(paramIdx++, ownerPattern + "%"); stmt.setString(paramIdx++, ownerPattern + "%");
} }
if (isStatusProvided) { if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status); stmt.setString(paramIdx++, status);
} }
if (isExcludeStatusProvided) {
stmt.setString(paramIdx++, excludeStatus);
} }
stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount()); stmt.setInt(paramIdx, request.getRowCount());
rs = stmt.executeQuery(); try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of" + String msg = "Error occurred while retrieving information of" +
" devices belonging to group : " + groupId, e); " devices belonging to group : " + groupId;
} finally { log.error(msg, e);
DeviceManagementDAOUtil.cleanupResources(stmt, rs); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override
public List<Device> getDevicesOfUser(PaginationRequest request, int tenantId) public List<Device> getDevicesOfUser(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
@ -425,46 +423,80 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
public List<Device> getDevicesByStatus(PaginationRequest request, int tenantId) public List<Device> getDevicesByStatus(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null;
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
List<String> statusList = request.getStatusList();
try { try {
conn = this.getConnection(); conn = getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " String sql = "SELECT d.ID AS DEVICE_ID, " +
+ "d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " "d.DESCRIPTION, " +
+ "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " "d.NAME AS DEVICE_NAME, " +
+ "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " "t.NAME AS DEVICE_TYPE, " +
+ "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " "d.DEVICE_IDENTIFICATION, " +
+ "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " "e.OWNER, " +
+ "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; "e.OWNERSHIP, " +
stmt = conn.prepareStatement(sql); "e.STATUS, " +
stmt.setInt(1, tenantId); "e.DATE_OF_LAST_UPDATE, " +
stmt.setString(2, request.getStatus()); "e.DATE_OF_ENROLMENT, " +
stmt.setInt(3, tenantId); "e.ID AS ENROLMENT_ID " +
stmt.setInt(4, request.getStartIndex()); "FROM (SELECT e.ID, " +
stmt.setInt(5, request.getRowCount()); "e.DEVICE_ID, " +
ResultSet rs = stmt.executeQuery(); "e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
if (statusList == null || statusList.isEmpty()) {
String msg = "Error occurred while fetching the list of devices. Status List can't " +
"be null or empty";
log.error(msg);
throw new DeviceManagementDAOException(msg);
}
sql += buildStatusQuery(statusList);
sql += ") e," +
"DM_DEVICE d," +
"DM_DEVICE_TYPE t" +
"WHERE DEVICE_ID = e.DEVICE_ID" +
"AND d.DEVICE_TYPE_ID = t.ID" +
"AND d.TENANT_ID = ?" +
"LIMIT ?,?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
for (String status : statusList) {
stmt.setString(paramIdx++, status);
}
stmt.setInt(paramIdx++, tenantId);
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount());
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices that matches to status " + String msg = "Error occurred while fetching the list of devices that matches to status " +
"'" + request.getStatus() + "'"; request.getStatusList().toString();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementDAOException(msg, e); throw new DeviceManagementDAOException(msg, e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
} }
return devices;
} }
@Override @Override
public List<Device> getDevicesByDuration(PaginationRequest request, List<String> statusList, int tenantId, public List<Device> getDevicesByDuration(PaginationRequest request, int tenantId,
String fromDate, String toDate) String fromDate, String toDate)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
List<Device> devices; List<Device> devices;
String deviceStatus = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
String sql = "SELECT " + String sql = "SELECT " +
@ -483,14 +515,13 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DEVICE_TYPE_ID = t.ID AND " + "d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " + "e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; "e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
if (statusList != null && !statusList.isEmpty()) {
if (deviceStatus != null) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?"; isStatusProvided = true;
} }
if (ownership != null) { if (ownership != null) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
} }
sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
try (Connection conn = this.getConnection(); try (Connection conn = this.getConnection();
@ -499,20 +530,24 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
stmt.setString(paramIdx++, fromDate); stmt.setString(paramIdx++, fromDate);
stmt.setString(paramIdx++, toDate); stmt.setString(paramIdx++, toDate);
if (deviceStatus != null) { if (isStatusProvided) {
stmt.setString(paramIdx++, deviceStatus); for (String status : statusList) {
stmt.setString(paramIdx++, status);
}
} }
if (ownership != null) { if (ownership != null) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx++, ownership);
} }
stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount()); stmt.setInt(paramIdx, request.getRowCount());
try (ResultSet rs = stmt.executeQuery()) { try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " + String msg = "Error occurred while retrieving information of all " +
@ -520,7 +555,6 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementDAOException(msg, e); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override

@ -49,8 +49,6 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
public List<Device> getDevices(PaginationRequest request, int tenantId) public List<Device> getDevices(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> devices = null; List<Device> devices = null;
String deviceType = request.getDeviceType(); String deviceType = request.getDeviceType();
boolean isDeviceTypeProvided = false; boolean isDeviceTypeProvided = false;
@ -62,20 +60,34 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isOwnerPatternProvided = false; boolean isOwnerPatternProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
boolean isOwnershipProvided = false; boolean isOwnershipProvided = false;
String status = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false; boolean isStatusProvided = false;
String excludeStatus = request.getExcludeStatus();
boolean isExcludeStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
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, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
try {
conn = 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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t " +
"WHERE DEVICE_TYPE_ID = t.ID " +
"AND d.TENANT_ID = ?";
//Add the query for device-type //Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) { if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?"; sql = sql + " AND t.NAME = ?";
@ -86,9 +98,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND d.NAME LIKE ?"; sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true; isDeviceNameProvided = true;
} }
sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?";
//Add the query for ownership //Add the query for ownership
if (ownership != null && !ownership.isEmpty()) { if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
@ -102,29 +112,21 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND e.OWNER LIKE ?"; sql = sql + " AND e.OWNER LIKE ?";
isOwnerPatternProvided = true; isOwnerPatternProvided = true;
} }
//Add the query for status if (statusList != null && !statusList.isEmpty()) {
if (status != null && !status.isEmpty()) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?";
isStatusProvided = true; isStatusProvided = true;
} }
//Add the query for exclude status
if (excludeStatus != null && !excludeStatus.isEmpty()) {
sql = sql + " AND e.STATUS != ?";
isExcludeStatusProvided = true;
}
sql = sql + " LIMIT ? OFFSET ?"; sql = sql + " LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql); try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, tenantId); int paramIdx = 1;
int paramIdx = 2; stmt.setInt(paramIdx++, tenantId);
if (isDeviceTypeProvided) { if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType); stmt.setString(paramIdx++, deviceType);
} }
if (isDeviceNameProvided) { if (isDeviceNameProvided) {
stmt.setString(paramIdx++, deviceName + "%"); stmt.setString(paramIdx++, deviceName + "%");
} }
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) { if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx++, ownership);
@ -135,36 +137,35 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(paramIdx++, ownerPattern + "%"); stmt.setString(paramIdx++, ownerPattern + "%");
} }
if (isStatusProvided) { if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status); stmt.setString(paramIdx++, status);
} }
if (isExcludeStatusProvided) {
stmt.setString(paramIdx++, excludeStatus);
} }
stmt.setInt(paramIdx++, request.getRowCount()); stmt.setInt(paramIdx++, request.getRowCount());
stmt.setInt(paramIdx, request.getStartIndex()); stmt.setInt(paramIdx, request.getStartIndex());
rs = stmt.executeQuery();
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + String msg = "Error occurred while retrieving information of all " +
"registered devices", e); "registered devices";
} finally { log.error(msg, e);
DeviceManagementDAOUtil.cleanupResources(stmt, rs); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override
public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId) public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> devices = null; List<Device> devices = null;
int groupId = request.getGroupId(); int groupId = request.getGroupId();
String deviceType = request.getDeviceType(); String deviceType = request.getDeviceType();
boolean isDeviceTypeProvided = false; boolean isDeviceTypeProvided = false;
@ -176,52 +177,63 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isOwnerPatternProvided = false; boolean isOwnerPatternProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
boolean isOwnershipProvided = false; boolean isOwnershipProvided = false;
String status = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false; boolean isStatusProvided = false;
String excludeStatus = request.getExcludeStatus();
boolean isExcludeStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
try { try {
conn = this.getConnection(); conn = getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + String sql = "SELECT d1.DEVICE_ID, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "d1.DESCRIPTION, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + "d1.NAME AS DEVICE_NAME, " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "d1.DEVICE_TYPE, " +
"FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID " + "d1.DEVICE_IDENTIFICATION, " +
"FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 WHERE" + "e.OWNER, " +
" d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?"; "e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
//Add the query for device-name //Add the query for device-name
if (deviceName != null && !deviceName.isEmpty()) { if (deviceName != null && !deviceName.isEmpty()) {
sql = sql + " AND d.NAME LIKE ?"; sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true; isDeviceNameProvided = true;
} }
sql = sql + ") gd, DM_DEVICE_TYPE t"; sql = sql + ") gd, DM_DEVICE_TYPE t";
if (since != null) { if (since != null) {
sql = sql + ", DM_DEVICE_DETAIL dt"; sql = sql + ", DM_DEVICE_DETAIL dt";
isSinceProvided = true; isSinceProvided = true;
} }
sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID";
//Add query for last updated timestamp //Add query for last updated timestamp
if (isSinceProvided) { if (isSinceProvided) {
sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?";
} }
//Add the query for device-type //Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) { if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?"; sql = sql + " AND t.NAME = ?";
isDeviceTypeProvided = true; isDeviceTypeProvided = true;
} }
sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ";
//Add the query for ownership //Add the query for ownership
if (ownership != null && !ownership.isEmpty()) { if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
@ -235,25 +247,16 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND e.OWNER LIKE ?"; sql = sql + " AND e.OWNER LIKE ?";
isOwnerPatternProvided = true; isOwnerPatternProvided = true;
} }
//Add the query for status if (statusList != null && !statusList.isEmpty()) {
if (status != null && !status.isEmpty()) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?";
isStatusProvided = true; isStatusProvided = true;
} }
//Add the query for exclude status
if (excludeStatus != null && !excludeStatus.isEmpty()) {
sql = sql + " AND e.STATUS != ?";
isExcludeStatusProvided = true;
}
sql = sql + " LIMIT ? OFFSET ?"; sql = sql + " LIMIT ? OFFSET ?";
stmt = conn.prepareStatement(sql); try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(1, groupId); stmt.setInt(paramIdx++, groupId);
stmt.setInt(2, tenantId); stmt.setInt(paramIdx++, tenantId);
int paramIdx = 3;
if (isDeviceNameProvided) { if (isDeviceNameProvided) {
stmt.setString(paramIdx++, deviceName + "%"); stmt.setString(paramIdx++, deviceName + "%");
} }
@ -263,7 +266,6 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (isDeviceTypeProvided) { if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType); stmt.setString(paramIdx++, deviceType);
} }
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) { if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx++, ownership);
@ -274,27 +276,28 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(paramIdx++, ownerPattern + "%"); stmt.setString(paramIdx++, ownerPattern + "%");
} }
if (isStatusProvided) { if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status); stmt.setString(paramIdx++, status);
} }
if (isExcludeStatusProvided) {
stmt.setString(paramIdx++, excludeStatus);
} }
stmt.setInt(paramIdx, request.getRowCount()); stmt.setInt(paramIdx++, request.getRowCount());
stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getStartIndex());
rs = stmt.executeQuery(); try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of" + String msg = "Error occurred while retrieving information of" +
" devices belonging to group : " + groupId, e); " devices belonging to group : " + groupId;
} finally { log.error(msg, e);
DeviceManagementDAOUtil.cleanupResources(stmt, rs); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override
@ -405,45 +408,79 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
public List<Device> getDevicesByStatus(PaginationRequest request, int tenantId) public List<Device> getDevicesByStatus(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null;
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
List<String> statusList = request.getStatusList();
try { try {
conn = this.getConnection(); conn = getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + String sql = "SELECT d.ID AS DEVICE_ID, " +
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "d.DESCRIPTION, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + "d.NAME AS DEVICE_NAME, " +
"e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + "t.NAME AS DEVICE_TYPE, " +
"WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + "d.DEVICE_IDENTIFICATION, " +
"WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? LIMIT ? OFFSET ?"; "e.OWNER, " +
stmt = conn.prepareStatement(sql); "e.OWNERSHIP, " +
stmt.setInt(1, tenantId); "e.STATUS, " +
stmt.setString(2, request.getStatus()); "e.DATE_OF_LAST_UPDATE, " +
stmt.setInt(3, tenantId); "e.DATE_OF_ENROLMENT, " +
stmt.setInt(4, request.getRowCount()); "e.ID AS ENROLMENT_ID " +
stmt.setInt(5, request.getStartIndex()); "FROM " +
ResultSet rs = stmt.executeQuery(); "(SELECT e.ID, " +
"e.DEVICE_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
if (statusList == null || statusList.isEmpty()) {
String msg = "Error occurred while fetching the list of devices. Status List can't " +
"be null or empty";
log.error(msg);
throw new DeviceManagementDAOException(msg);
}
sql += buildStatusQuery(statusList);
sql += ") e, " +
"DM_DEVICE d, DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? " +
"LIMIT ? OFFSET ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
for (String status : statusList) {
stmt.setString(paramIdx++, status);
}
stmt.setInt(paramIdx++, tenantId);
stmt.setInt(paramIdx++, request.getRowCount());
stmt.setInt(paramIdx, request.getStartIndex());
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices that matches to status " + String msg = "Error occurred while fetching the list of devices that matches to status " +
"'" + request.getStatus() + "'"; request.getStatusList().toString();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementDAOException(msg, e); throw new DeviceManagementDAOException(msg, e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
} }
return devices;
} }
@Override @Override
public List<Device> getDevicesByDuration(PaginationRequest request, List<String> statusList, int tenantId, public List<Device> getDevicesByDuration(PaginationRequest request, int tenantId,
String fromDate, String toDate) String fromDate, String toDate)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
List<Device> devices; List<Device> devices;
String deviceStatus = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
String sql = "SELECT " + String sql = "SELECT " +
@ -462,14 +499,13 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DEVICE_TYPE_ID = t.ID AND " + "d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " + "e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; "e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
if (statusList != null && !statusList.isEmpty()) {
if (deviceStatus != null) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?"; isStatusProvided = true;
} }
if (ownership != null) { if (ownership != null) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
} }
sql = sql + " LIMIT ? OFFSET ?"; sql = sql + " LIMIT ? OFFSET ?";
try (Connection conn = this.getConnection(); try (Connection conn = this.getConnection();
@ -478,20 +514,24 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
stmt.setString(paramIdx++, fromDate); stmt.setString(paramIdx++, fromDate);
stmt.setString(paramIdx++, toDate); stmt.setString(paramIdx++, toDate);
if (deviceStatus != null) { if (isStatusProvided) {
stmt.setString(paramIdx++, deviceStatus); for (String status : statusList) {
stmt.setString(paramIdx++, status);
}
} }
if (ownership != null) { if (ownership != null) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx++, ownership);
} }
stmt.setInt(paramIdx++, request.getRowCount()); stmt.setInt(paramIdx++, request.getRowCount());
stmt.setInt(paramIdx, request.getStartIndex()); stmt.setInt(paramIdx, request.getStartIndex());
try (ResultSet rs = stmt.executeQuery()) { try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " + String msg = "Error occurred while retrieving information of all " +
@ -499,7 +539,6 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementDAOException(msg, e); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override

@ -51,8 +51,6 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
public List<Device> getDevices(PaginationRequest request, int tenantId) public List<Device> getDevices(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> devices = null; List<Device> devices = null;
String deviceType = request.getDeviceType(); String deviceType = request.getDeviceType();
boolean isDeviceTypeProvided = false; boolean isDeviceTypeProvided = false;
@ -64,33 +62,41 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isOwnerPatternProvided = false; boolean isOwnerPatternProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
boolean isOwnershipProvided = false; boolean isOwnershipProvided = false;
String status = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false; boolean isStatusProvided = false;
String excludeStatus = request.getExcludeStatus();
boolean isExcludeStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
try { try {
conn = this.getConnection(); conn = 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.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "d1.DESCRIPTION, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + "d1.NAME AS DEVICE_NAME, " +
"d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "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, " +
"d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM DM_DEVICE d, DM_DEVICE_TYPE t "; "FROM DM_DEVICE d, DM_DEVICE_TYPE t ";
//Add the query to filter active devices on timestamp //Add the query to filter active devices on timestamp
if (since != null) { if (since != null) {
sql = sql + ", DM_DEVICE_DETAIL dt"; sql = sql + ", DM_DEVICE_DETAIL dt";
isSinceProvided = true; isSinceProvided = true;
} }
sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
//Add query for last updated timestamp //Add query for last updated timestamp
if (isSinceProvided) { if (isSinceProvided) {
sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?";
} }
//Add the query for device-type //Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) { if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?"; sql = sql + " AND t.NAME = ?";
@ -101,9 +107,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND d.NAME LIKE ?"; sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true; isDeviceNameProvided = true;
} }
sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?";
//Add the query for ownership //Add the query for ownership
if (ownership != null && !ownership.isEmpty()) { if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
@ -117,22 +121,15 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND e.OWNER LIKE ?"; sql = sql + " AND e.OWNER LIKE ?";
isOwnerPatternProvided = true; isOwnerPatternProvided = true;
} }
//Add the query for status if (statusList != null && !statusList.isEmpty()) {
if (status != null && !status.isEmpty()) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?";
isStatusProvided = true; isStatusProvided = true;
} }
//Add the query for exclude status
if (excludeStatus != null && !excludeStatus.isEmpty()) {
sql = sql + " AND e.STATUS != ?";
isExcludeStatusProvided = true;
}
sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql); try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, tenantId); int paramIdx = 1;
int paramIdx = 2; stmt.setInt(paramIdx++, tenantId);
if (isSinceProvided) { if (isSinceProvided) {
stmt.setLong(paramIdx++, since.getTime()); stmt.setLong(paramIdx++, since.getTime());
} }
@ -142,7 +139,6 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (isDeviceNameProvided) { if (isDeviceNameProvided) {
stmt.setString(paramIdx++, deviceName + "%"); stmt.setString(paramIdx++, deviceName + "%");
} }
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) { if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx++, ownership);
@ -153,36 +149,35 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(paramIdx++, ownerPattern + "%"); stmt.setString(paramIdx++, ownerPattern + "%");
} }
if (isStatusProvided) { if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status); stmt.setString(paramIdx++, status);
} }
if (isExcludeStatusProvided) {
stmt.setString(paramIdx++, excludeStatus);
} }
stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount()); stmt.setInt(paramIdx, request.getRowCount());
rs = stmt.executeQuery();
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + String msg = "Error occurred while retrieving information of all " +
"registered devices", e); "registered devices";
} finally { log.error(msg, e);
DeviceManagementDAOUtil.cleanupResources(stmt, rs); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override
public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId) public List<Device> searchDevicesInGroup(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> devices = null; List<Device> devices = null;
int groupId = request.getGroupId(); int groupId = request.getGroupId();
String deviceType = request.getDeviceType(); String deviceType = request.getDeviceType();
boolean isDeviceTypeProvided = false; boolean isDeviceTypeProvided = false;
@ -194,52 +189,63 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isOwnerPatternProvided = false; boolean isOwnerPatternProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
boolean isOwnershipProvided = false; boolean isOwnershipProvided = false;
String status = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false; boolean isStatusProvided = false;
String excludeStatus = request.getExcludeStatus();
boolean isExcludeStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
try { try {
conn = this.getConnection(); conn = getConnection();
String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + String sql = "SELECT d1.DEVICE_ID, " +
"d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "d1.DESCRIPTION, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, " + "d1.NAME AS DEVICE_NAME, " +
"(SELECT gd.DEVICE_ID, gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + "d1.DEVICE_TYPE, " +
"FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.DEVICE_TYPE_ID " + "d1.DEVICE_IDENTIFICATION, " +
"FROM DM_DEVICE d, (SELECT dgm.DEVICE_ID FROM DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ?) dgm1 WHERE" + "e.OWNER, " +
" d.ID = dgm1.DEVICE_ID AND d.TENANT_ID = ?"; "e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT gd.DEVICE_ID, " +
"gd.DESCRIPTION, " +
"gd.NAME, " +
"gd.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " +
"FROM " +
"(SELECT d.ID AS DEVICE_ID, " +
"d.DESCRIPTION, " +
"d.NAME, " +
"d.DEVICE_IDENTIFICATION, " +
"d.DEVICE_TYPE_ID " +
"FROM DM_DEVICE d, " +
"(SELECT dgm.DEVICE_ID " +
"FROM DM_DEVICE_GROUP_MAP dgm " +
"WHERE dgm.GROUP_ID = ?) dgm1 " +
"WHERE d.ID = dgm1.DEVICE_ID " +
"AND d.TENANT_ID = ?";
//Add the query for device-name //Add the query for device-name
if (deviceName != null && !deviceName.isEmpty()) { if (deviceName != null && !deviceName.isEmpty()) {
sql = sql + " AND d.NAME LIKE ?"; sql = sql + " AND d.NAME LIKE ?";
isDeviceNameProvided = true; isDeviceNameProvided = true;
} }
sql = sql + ") gd, DM_DEVICE_TYPE t"; sql = sql + ") gd, DM_DEVICE_TYPE t";
if (since != null) { if (since != null) {
sql = sql + ", DM_DEVICE_DETAIL dt"; sql = sql + ", DM_DEVICE_DETAIL dt";
isSinceProvided = true; isSinceProvided = true;
} }
sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID";
//Add query for last updated timestamp //Add query for last updated timestamp
if (isSinceProvided) { if (isSinceProvided) {
sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?";
} }
//Add the query for device-type //Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) { if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?"; sql = sql + " AND t.NAME = ?";
isDeviceTypeProvided = true; isDeviceTypeProvided = true;
} }
sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ";
//Add the query for ownership //Add the query for ownership
if (ownership != null && !ownership.isEmpty()) { if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
@ -253,25 +259,16 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
sql = sql + " AND e.OWNER LIKE ?"; sql = sql + " AND e.OWNER LIKE ?";
isOwnerPatternProvided = true; isOwnerPatternProvided = true;
} }
//Add the query for status if (statusList != null && !statusList.isEmpty()) {
if (status != null && !status.isEmpty()) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?";
isStatusProvided = true; isStatusProvided = true;
} }
//Add the query for exclude status
if (excludeStatus != null && !excludeStatus.isEmpty()) {
sql = sql + " AND e.STATUS != ?";
isExcludeStatusProvided = true;
}
sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql); try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(1, groupId); stmt.setInt(paramIdx++, groupId);
stmt.setInt(2, tenantId); stmt.setInt(paramIdx++, tenantId);
int paramIdx = 3;
if (isDeviceNameProvided) { if (isDeviceNameProvided) {
stmt.setString(paramIdx++, deviceName + "%"); stmt.setString(paramIdx++, deviceName + "%");
} }
@ -281,7 +278,6 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
if (isDeviceTypeProvided) { if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType); stmt.setString(paramIdx++, deviceType);
} }
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) { if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx++, ownership);
@ -292,27 +288,28 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setString(paramIdx++, ownerPattern + "%"); stmt.setString(paramIdx++, ownerPattern + "%");
} }
if (isStatusProvided) { if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status); stmt.setString(paramIdx++, status);
} }
if (isExcludeStatusProvided) {
stmt.setString(paramIdx++, excludeStatus);
} }
stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount()); stmt.setInt(paramIdx, request.getRowCount());
rs = stmt.executeQuery(); try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of" + String msg = "Error occurred while retrieving information of" +
" devices belonging to group : " + groupId, e); " devices belonging to group : " + groupId;
} finally { log.error(msg, e);
DeviceManagementDAOUtil.cleanupResources(stmt, rs); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override
@ -425,38 +422,72 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
public List<Device> getDevicesByStatus(PaginationRequest request, int tenantId) public List<Device> getDevicesByStatus(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null;
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
List<String> statusList = request.getStatusList();
try { try {
conn = this.getConnection(); conn = getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + String sql = "SELECT d.ID AS DEVICE_ID, " +
"d.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "d.DESCRIPTION, " +
"e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + "d.NAME AS DEVICE_NAME, " +
"e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + "t.NAME AS DEVICE_TYPE, " +
"WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + "d.DEVICE_IDENTIFICATION, " +
"WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " + "e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
"e.ID AS ENROLMENT_ID " +
"FROM " +
"(SELECT e.ID, " +
"e.DEVICE_ID, " +
"e.OWNER, " +
"e.OWNERSHIP, " +
"e.STATUS, " +
"e.DATE_OF_ENROLMENT, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e " +
"WHERE TENANT_ID = ?";
if (statusList == null || statusList.isEmpty()) {
String msg = "Error occurred while fetching the list of devices. Status List can't " +
"be null or empty";
log.error(msg);
throw new DeviceManagementDAOException(msg);
}
sql += buildStatusQuery(statusList);
sql += ") e, " +
"DM_DEVICE d, " +
"DM_DEVICE_TYPE t " +
"WHERE DEVICE_ID = e.DEVICE_ID " +
"AND d.DEVICE_TYPE_ID = t.ID " +
"AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " +
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, request.getStatus());
stmt.setInt(3, tenantId);
stmt.setInt(4, request.getStartIndex());
stmt.setInt(5, request.getRowCount());
ResultSet rs = stmt.executeQuery();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
for (String status : statusList) {
stmt.setString(paramIdx++, status);
}
stmt.setInt(paramIdx++, tenantId);
stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount());
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
}
}
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while fetching the list of devices that matches to status " + String msg = "Error occurred while fetching the list of devices that matches to status " +
"'" + request.getStatus() + "'"; request.getStatusList().toString();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementDAOException(msg, e); throw new DeviceManagementDAOException(msg, e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
} }
return devices;
} }
/** /**
@ -604,11 +635,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
@Override @Override
public List<Device> getDevicesByDuration(PaginationRequest request, List<String> statusList, int tenantId, public List<Device> getDevicesByDuration(PaginationRequest request, int tenantId,
String fromDate, String toDate) String fromDate, String toDate)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
List<Device> devices; List<Device> devices;
String deviceStatus = request.getStatus(); List<String> statusList = request.getStatusList();
boolean isStatusProvided = false;
String ownership = request.getOwnership(); String ownership = request.getOwnership();
String sql = "SELECT " + String sql = "SELECT " +
@ -627,14 +659,13 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DEVICE_TYPE_ID = t.ID AND " + "d.DEVICE_TYPE_ID = t.ID AND " +
"e.TENANT_ID = ? AND " + "e.TENANT_ID = ? AND " +
"e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; "e.DATE_OF_ENROLMENT BETWEEN ? AND ?";
if (statusList != null && !statusList.isEmpty()) {
if (deviceStatus != null) { sql += buildStatusQuery(statusList);
sql = sql + " AND e.STATUS = ?"; isStatusProvided = true;
} }
if (ownership != null) { if (ownership != null) {
sql = sql + " AND e.OWNERSHIP = ?"; sql = sql + " AND e.OWNERSHIP = ?";
} }
sql = sql + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; sql = sql + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
try (Connection conn = this.getConnection(); try (Connection conn = this.getConnection();
@ -643,20 +674,24 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
stmt.setString(paramIdx++, fromDate); stmt.setString(paramIdx++, fromDate);
stmt.setString(paramIdx++, toDate); stmt.setString(paramIdx++, toDate);
if (deviceStatus != null) { if (isStatusProvided) {
stmt.setString(paramIdx++, deviceStatus); for (String status : statusList) {
stmt.setString(paramIdx++, status);
}
} }
if (ownership != null) { if (ownership != null) {
stmt.setString(paramIdx++, ownership); stmt.setString(paramIdx++, ownership);
} }
stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx++, request.getStartIndex());
stmt.setInt(paramIdx, request.getRowCount()); stmt.setInt(paramIdx, request.getRowCount());
try (ResultSet rs = stmt.executeQuery()) { try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>(); devices = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDevice(rs); Device device = DeviceManagementDAOUtil.loadDevice(rs);
devices.add(device); devices.add(device);
} }
return devices;
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " + String msg = "Error occurred while retrieving information of all " +
@ -664,7 +699,6 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementDAOException(msg, e); throw new DeviceManagementDAOException(msg, e);
} }
return devices;
} }
@Override @Override

@ -57,7 +57,7 @@ public class ReportManagementServiceImpl implements ReportManagementService {
} }
@Override @Override
public PaginationResult getDevicesByDuration(PaginationRequest request, List<String> statusList, String fromDate, public PaginationResult getDevicesByDuration(PaginationRequest request, String fromDate,
String toDate) String toDate)
throws ReportManagementException { throws ReportManagementException {
PaginationResult paginationResult = new PaginationResult(); PaginationResult paginationResult = new PaginationResult();
@ -72,7 +72,6 @@ public class ReportManagementServiceImpl implements ReportManagementService {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
List<Device> devices = deviceDAO.getDevicesByDuration( List<Device> devices = deviceDAO.getDevicesByDuration(
request, request,
statusList,
DeviceManagementDAOUtil.getTenantId(), DeviceManagementDAOUtil.getTenantId(),
fromDate, fromDate,
toDate toDate

@ -2528,10 +2528,31 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
log.debug("Get devices by status " + request.toString() + " and requiredDeviceInfo: " log.debug("Get devices by status " + request.toString() + " and requiredDeviceInfo: "
+ requireDeviceInfo); + requireDeviceInfo);
} }
List<String> statusList = request.getStatusList();
if (statusList == null || statusList.isEmpty()) {
String msg = "Invalid enrollment status type received. Status can't be null or empty" +
"Valid status types are ACTIVE | INACTIVE | UNCLAIMED | UNREACHABLE " +
"| SUSPENDED | DISENROLLMENT_REQUESTED | REMOVED | BLOCKED | CREATED";
log.error(msg);
throw new DeviceManagementException(msg);
}
if (statusList.size() > 1) {
String msg = "Invalid enrollment status received. Devices can only be filtered by one " +
"type of status, more than one are not allowed";
log.error(msg);
throw new DeviceManagementException(msg);
}
String status = statusList.get(0);
if (StringUtils.isBlank(status)){
String msg = "Invalid enrollment status type received. Status can't be null or empty" +
"Valid status types are ACTIVE | INACTIVE | UNCLAIMED | UNREACHABLE " +
"| SUSPENDED | DISENROLLMENT_REQUESTED | REMOVED | BLOCKED | CREATED";
log.error(msg);
throw new DeviceManagementException(msg);
}
PaginationResult result = new PaginationResult(); PaginationResult result = new PaginationResult();
List<Device> allDevices; List<Device> allDevices;
int tenantId = this.getTenantId(); int tenantId = this.getTenantId();
String status = request.getStatus();
request = DeviceManagerUtil.validateDeviceListPageSize(request); request = DeviceManagerUtil.validateDeviceListPageSize(request);
try { try {
DeviceManagementDAOFactory.openConnection(); DeviceManagementDAOFactory.openConnection();
@ -2540,7 +2561,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
result.setRecordsTotal(deviceCount); result.setRecordsTotal(deviceCount);
result.setRecordsFiltered(deviceCount); result.setRecordsFiltered(deviceCount);
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
String msg = "Error occurred while fetching the list of devices that matches to status: '" + status + "'"; String msg = "Error occurred while fetching the list of devices that matches to status: " +
status;
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} catch (SQLException e) { } catch (SQLException e) {

@ -78,7 +78,9 @@ import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.io.InputStream; import java.io.InputStream;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -676,7 +678,8 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
public void testGetAllDevicesByStatus() throws DeviceManagementException, NoSuchFieldException, public void testGetAllDevicesByStatus() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException { IllegalAccessException {
PaginationRequest request = new PaginationRequest(0, 100); PaginationRequest request = new PaginationRequest(0, 100);
request.setStatus(EnrolmentInfo.Status.ACTIVE.toString()); List<String> statusList = new ArrayList<>(Collections.singletonList("ACTIVE"));
request.setStatusList(statusList);
MockDataSource dataSource = setDatasourceForGetDevice(); MockDataSource dataSource = setDatasourceForGetDevice();
if (dataSource != null) { if (dataSource != null) {
setMockDeviceCount(dataSource.getConnection(0)); setMockDeviceCount(dataSource.getConnection(0));
@ -842,7 +845,8 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes
public void testGetDeviesByStatus() throws DeviceManagementException, NoSuchFieldException, public void testGetDeviesByStatus() throws DeviceManagementException, NoSuchFieldException,
IllegalAccessException { IllegalAccessException {
PaginationRequest request = new PaginationRequest(0, 100); PaginationRequest request = new PaginationRequest(0, 100);
request.setStatus("ACTIVE"); List<String> statusList = new ArrayList<>(Collections.singletonList("ACTIVE"));
request.setStatusList(statusList);
MockDataSource dataSource = setDatasourceForGetDevice(); MockDataSource dataSource = setDatasourceForGetDevice();
if (dataSource != null) { if (dataSource != null) {
setMockDeviceCount(dataSource.getConnection(0)); setMockDeviceCount(dataSource.getConnection(0));

Loading…
Cancel
Save