From 16681acf558da25ec1ce5b1a07361366d499db66 Mon Sep 17 00:00:00 2001 From: Yohan Avishke Date: Wed, 29 Jan 2020 12:22:35 +0000 Subject: [PATCH] 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 --- .../Geo/geo-dashboard/GeoDashboard.js | 3 +- .../service/api/DeviceManagementService.java | 46 +- .../impl/DeviceManagementServiceImpl.java | 40 +- .../impl/ReportManagementServiceImpl.java | 16 +- .../impl/util/RequestValidationUtil.java | 51 +- .../impl/DeviceManagementServiceImplTest.java | 63 +-- .../device/mgt/common/PaginationRequest.java | 22 +- .../report/mgt/ReportManagementService.java | 2 +- .../carbon/device/mgt/core/dao/DeviceDAO.java | 2 - .../core/dao/impl/AbstractDeviceDAOImpl.java | 120 ++--- .../dao/impl/device/GenericDeviceDAOImpl.java | 487 +++++++++--------- .../dao/impl/device/OracleDeviceDAOImpl.java | 380 +++++++------- .../impl/device/PostgreSQLDeviceDAOImpl.java | 369 +++++++------ .../impl/device/SQLServerDeviceDAOImpl.java | 376 ++++++++------ .../mgt/ReportManagementServiceImpl.java | 3 +- .../DeviceManagementProviderServiceImpl.java | 26 +- .../DeviceManagementProviderServiceTest.java | 10 +- 17 files changed, 1089 insertions(+), 927 deletions(-) diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/components/Geo/geo-dashboard/GeoDashboard.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/components/Geo/geo-dashboard/GeoDashboard.js index bf0ed0dcdd..11f2af12d9 100644 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/components/Geo/geo-dashboard/GeoDashboard.js +++ b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/components/Geo/geo-dashboard/GeoDashboard.js @@ -183,7 +183,8 @@ class GeoDashboard extends React.Component { window.location.origin + config.serverConfig.invoker.uri + 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 => { if (res.status === 200) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index d916e54fa9..be4cf349d2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -173,11 +173,10 @@ import java.util.Map; @Path("/devices") @Api(value = "Device Management", description = "This API carries all device management related operations " + "such as get all the available devices, etc.") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) public interface DeviceManagementService { @GET + @Produces(MediaType.APPLICATION_JSON) @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", @@ -269,20 +268,12 @@ public interface DeviceManagementService { @QueryParam("ownership") @Size(max = 45) String ownership, - @ApiParam( - name = "excludeStatus", - value = "Provide the devices that excludes the given status", - required = false) - @QueryParam("excludeStatus") - @Size(max = 45) - String excludeStatus, @ApiParam( name = "status", value = "Provide the device status details, such as active or inactive.", required = false) @QueryParam("status") - @Size(max = 45) - String status, + List status, @ApiParam( name = "groupId", value = "Id of the group which device belongs", @@ -328,6 +319,7 @@ public interface DeviceManagementService { int limit); @GET + @Produces(MediaType.APPLICATION_JSON) @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", @@ -401,6 +393,7 @@ public interface DeviceManagementService { int limit); @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/{type}/{id}") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -488,9 +481,9 @@ public interface DeviceManagementService { String ifModifiedSince); @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/{deviceType}/{deviceId}/location-history") @ApiOperation( - consumes = "application/json", produces = "application/json", httpMethod = "GET", value = "Getting the Location Details of a Device", @@ -560,6 +553,7 @@ public interface DeviceManagementService { @QueryParam("to") long to); @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/type/any/id/{id}") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -636,6 +630,7 @@ public interface DeviceManagementService { @PUT + @Produces(MediaType.APPLICATION_JSON) @Path("/{type}/{id}") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -691,6 +686,7 @@ public interface DeviceManagementService { @PathParam("id") String deviceId); @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/{type}/{id}/location") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -767,6 +763,7 @@ public interface DeviceManagementService { @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/{type}/{id}/info") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -844,6 +841,8 @@ public interface DeviceManagementService { //device rename request would looks like follows //POST devices/type/virtual_firealarm/id/us06ww93auzp/rename @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) @Path("/type/{device-type}/id/{device-id}/rename") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -919,11 +918,10 @@ public interface DeviceManagementService { //device remove request would looks like follows //DELETE devices/type/virtual_firealarm/id/us06ww93auzp @DELETE - @Consumes(MediaType.WILDCARD) + @Produces(MediaType.APPLICATION_JSON) @Path("/type/{device-type}/id/{device-id}") @ApiOperation( produces = MediaType.APPLICATION_JSON, - consumes = MediaType.WILDCARD, httpMethod = "DELETE", 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.", @@ -988,9 +986,9 @@ public interface DeviceManagementService { String deviceId); @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/{type}/{id}/features") @ApiOperation( - consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, httpMethod = "GET", value = "Getting Feature Details of a Device", @@ -1078,6 +1076,8 @@ public interface DeviceManagementService { String ifModifiedSince); @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) @Path("/search-devices") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1156,6 +1156,8 @@ public interface DeviceManagementService { SearchContext searchContext); @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) @Path("/query-devices") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1234,6 +1236,7 @@ public interface DeviceManagementService { PropertyMap map); @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/{type}/{id}/applications") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1336,6 +1339,7 @@ public interface DeviceManagementService { @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/{type}/{id}/operations") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1446,6 +1450,7 @@ public interface DeviceManagementService { String ownership); @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/{type}/{id}/effective-policy") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1535,6 +1540,7 @@ public interface DeviceManagementService { @GET + @Produces(MediaType.APPLICATION_JSON) @Path("{type}/{id}/compliance-data") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1582,6 +1588,8 @@ public interface DeviceManagementService { String id); @PUT + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) @Path("/{type}/{id}/changestatus") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1656,6 +1664,8 @@ public interface DeviceManagementService { EnrolmentInfo.Status newStatus); @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) @Path("/{type}/operations") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1713,6 +1723,7 @@ public interface DeviceManagementService { @Valid OperationRequest operationRequest); @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/type/{type}/status/{status}/count") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1781,6 +1792,7 @@ public interface DeviceManagementService { @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/type/{type}/status/{status}/ids") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1848,6 +1860,8 @@ public interface DeviceManagementService { String status); @PUT + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) @Path("/type/{type}/status/{status}") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1908,6 +1922,7 @@ public interface DeviceManagementService { @Valid List deviceList); @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/compliance/{compliance-status}") @ApiOperation( produces = MediaType.APPLICATION_JSON, @@ -1975,6 +1990,7 @@ public interface DeviceManagementService { int limit); @GET + @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/features") @ApiOperation( produces = MediaType.APPLICATION_JSON, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 10318be4ec..dbbff69e9f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -99,7 +99,6 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.validation.Valid; import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; @@ -107,7 +106,6 @@ import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.DefaultValue; import javax.ws.rs.core.MediaType; @@ -119,8 +117,6 @@ import java.util.Date; import java.util.List; @Path("/devices") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) public class DeviceManagementServiceImpl implements DeviceManagementService { 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("role") String role, @QueryParam("ownership") String ownership, - @QueryParam("status") String status, - @QueryParam("excludeStatus") String excludeStatus, + @QueryParam("status") List status, @QueryParam("groupId") int groupId, @QueryParam("since") String since, @HeaderParam("If-Modified-Since") String ifModifiedSince, @@ -175,11 +170,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); DeviceAccessAuthorizationService deviceAccessAuthorizationService = 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); PaginationResult result; DeviceList devices = new DeviceList(); @@ -195,12 +185,17 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { request.setOwnership(ownership); } if (status != null && !status.isEmpty()) { - RequestValidationUtil.validateStatus(status); - request.setStatus(status); - } - if (excludeStatus != null && !excludeStatus.isEmpty()) { - RequestValidationUtil.validateStatus(excludeStatus); - request.setExcludeStatus(excludeStatus); + boolean isStatusEmpty = true; + for (String statusString : status){ + if (StringUtils.isNotBlank(statusString)){ + isStatusEmpty = false; + break; + } + } + if (!isStatusEmpty) { + RequestValidationUtil.validateStatus(status); + request.setStatusList(status); + } } // this is the user who initiates the request String authorizedUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); @@ -263,7 +258,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { + "' user"; log.error(msg); return Response.status(Response.Status.UNAUTHORIZED).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(401l).setMessage(msg).build()).build(); + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } else { request.setOwner(authorizedUser); @@ -373,7 +368,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } @DELETE - @Consumes(MediaType.WILDCARD) @Override @Path("/type/{device-type}/id/{device-id}") public Response deleteDevice(@PathParam("device-type") String deviceType, @@ -496,8 +490,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @Path("/{deviceType}/{deviceId}/location-history") @GET - @Consumes("application/json") - @Produces("application/json") public Response getDeviceLocationInfo(@PathParam("deviceType") String deviceType, @PathParam("deviceId") String deviceId, @QueryParam("from") long from, @QueryParam("to") long to) { @@ -515,12 +507,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { deviceIdentifier.setId(deviceId); 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)) { String msg = "User '" + authorizedUser + "' is not authorized to retrieve the given device id '" + deviceId + "'"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ReportManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ReportManagementServiceImpl.java index d536ff83fb..4afdc7326b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ReportManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ReportManagementServiceImpl.java @@ -74,8 +74,22 @@ public class ReportManagementServiceImpl implements ReportManagementService { 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() - .getDevicesByDuration(request, status, fromDate, toDate); + .getDevicesByDuration(request, fromDate, toDate); if (result.getData().isEmpty()) { String msg = "No devices have enrolled between " + fromDate + " to " + toDate + " or doesn't match with" + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java index 3936341384..aa0616fcf4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java @@ -19,6 +19,10 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; 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.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; @@ -30,6 +34,8 @@ import java.util.List; public class RequestValidationUtil { + private static final Log log = LogFactory.getLog(RequestValidationUtil.class); + /** * Checks if multiple criteria are specified in a conditional request. * @@ -95,29 +101,28 @@ public class RequestValidationUtil { } } - public static void validateStatus(String status) { - if (status == null) { - throw new InputValidationException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage( - "Enrollment status type cannot be null").build()); - } - switch (status) { - case "ACTIVE": - case "INACTIVE": - case "UNCLAIMED": - case "UNREACHABLE": - case "SUSPENDED": - case "DISENROLLMENT_REQUESTED": - case "REMOVED": - case "BLOCKED": - case "CREATED": - return; - default: - throw new InputValidationException( - new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Invalid enrollment status type " + - "received. Valid status types are ACTIVE | INACTIVE | " + - "UNCLAIMED | UNREACHABLE | SUSPENDED | DISENROLLMENT_REQUESTED | REMOVED | " + - "BLOCKED | CREATED").build()); + public static void validateStatus(List statusList) { + for (String status : statusList) { + switch (status) { + case "ACTIVE": + case "INACTIVE": + case "UNCLAIMED": + case "UNREACHABLE": + case "SUSPENDED": + case "DISENROLLMENT_REQUESTED": + case "REMOVED": + case "BLOCKED": + case "CREATED": + break; + default: + String msg = "Invalid enrollment status type: " + status + ". \nValid status types are " + + "ACTIVE | INACTIVE | UNCLAIMED | UNREACHABLE | SUSPENDED | " + + "DISENROLLMENT_REQUESTED | REMOVED | BLOCKED | CREATED"; + log.error(msg); + throw new InputValidationException(new ErrorResponse.ErrorResponseBuilder() + .setCode(HttpStatus.SC_BAD_REQUEST) + .setMessage(msg).build()); + } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java index a040e16ba2..53a2b39d7b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java @@ -80,7 +80,9 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.ws.rs.core.Response; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; +import java.util.List; import java.util.UUID; 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 DEFAULT_ROLE = "admin"; private static final String DEFAULT_OWNERSHIP = "BYOD"; - private static final String DEFAULT_STATUS = "ACTIVE"; - private static final String DEFAULT_EXCLUDED_STATUS = "REMOVED"; + private static final List DEFAULT_STATUS_LIST = new ArrayList<>(); private static final String DEFAULT_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; private DeviceManagementService deviceManagementService; private DeviceAccessAuthorizationService deviceAccessAuthorizationService; @@ -124,6 +125,8 @@ public class DeviceManagementServiceImplTest { this.deviceManagementService = new DeviceManagementServiceImpl(); this.deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class); 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.") @@ -172,7 +175,7 @@ public class DeviceManagementServiceImplTest { .toReturn(this.deviceAccessAuthorizationService); Response response = this.deviceManagementService .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()); } @@ -191,19 +194,19 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .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()); response = this.deviceManagementService .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()); response = this.deviceManagementService .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()); response = this.deviceManagementService .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()); } @@ -280,7 +283,7 @@ public class DeviceManagementServiceImplTest { Mockito.when(carbonContext.getUsername()).thenReturn(DEFAULT_USERNAME); 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); } - @Test(description = "Testing get devices when DeviceAccessAuthorizationService is not available") - public void testGetDevicesWithErroneousDeviceAccessAuthorizationService() { + @Test(description = "Testing get devices when DeviceAccessAuthorizationService is not available", + expectedExceptions = NoClassDefFoundError.class) + public void testGetDevicesWithErroneousDeviceAccessAuthorizationService() + throws DeviceAccessAuthorizationException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")) - .toReturn(null); - Response response = this.deviceManagementService - .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5); - Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); + deviceManagementService.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, + DEFAULT_ROLE, DEFAULT_OWNERSHIP, DEFAULT_STATUS_LIST, 1, + null, null, false, 10, 5); } @Test(description = "Testing get devices when user is the device admin") @@ -335,12 +338,12 @@ public class DeviceManagementServiceImplTest { Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); Response response = this.deviceManagementService - .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5); + .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP + , DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); response = this.deviceManagementService - .getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP, - DEFAULT_EXCLUDED_STATUS, DEFAULT_STATUS, 1, null, null, false, 10, 5); + .getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP + , DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); } @@ -361,8 +364,8 @@ public class DeviceManagementServiceImplTest { .toReturn(Mockito.mock(RealmService.class, Mockito.RETURNS_MOCKS)); Response response = this.deviceManagementService - .getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, DEFAULT_EXCLUDED_STATUS, - DEFAULT_STATUS, 0, null, null, false, 10, 5); + .getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, + DEFAULT_STATUS_LIST, 0, null, null, false, 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode()); Mockito.reset(this.deviceAccessAuthorizationService); } @@ -383,15 +386,15 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .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()); response = this.deviceManagementService .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()); response = this.deviceManagementService .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()); } @@ -411,15 +414,15 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .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()); response = this.deviceManagementService .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()); response = this.deviceManagementService .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()); } @@ -441,7 +444,7 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .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()); Mockito.reset(this.deviceManagementProviderService); } @@ -463,7 +466,7 @@ public class DeviceManagementServiceImplTest { Response response = this.deviceManagementService .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()); Mockito.reset(this.deviceAccessAuthorizationService); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java index a7baf05ce8..4502400d60 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.common; import java.util.Date; import java.util.HashMap; +import java.util.List; import java.util.Map; /** @@ -32,8 +33,7 @@ public class PaginationRequest { private int groupId; private String owner; private String ownerPattern; - private String status; - private String excludeStatus; + private List statusList; private String deviceType; private String deviceName; private String ownership; @@ -78,20 +78,12 @@ public class PaginationRequest { this.owner = owner; } - public String getStatus() { - return status; + public List getStatusList() { + return statusList; } - public void setStatus(String status) { - this.status = status; - } - - public String getExcludeStatus() { - return excludeStatus; - } - - public void setExcludeStatus(String excludeStatus) { - this.excludeStatus = excludeStatus; + public void setStatusList(List statusList) { + this.statusList = statusList; } public String getDeviceType() { @@ -164,7 +156,7 @@ public class PaginationRequest { public String toString() { return "Device type '" + this.deviceType + "' Device Name '" + this.deviceName + "' row count: " + this.rowCount + " 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; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/report/mgt/ReportManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/report/mgt/ReportManagementService.java index 8546add79b..22330a98c7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/report/mgt/ReportManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/report/mgt/ReportManagementService.java @@ -39,7 +39,7 @@ public interface ReportManagementService { * @throws {@Link DeviceManagementException} When error occurred while validating device list page size * @throws {@Link ReportManagementException} When failed to retrieve devices. */ - PaginationResult getDevicesByDuration(PaginationRequest request, List statusList, String fromDate, String toDate) + PaginationResult getDevicesByDuration(PaginationRequest request, String fromDate, String toDate) throws ReportManagementException; int getDevicesByDurationCount(List statusList, String ownership, String fromDate, String toDate) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 95d7420eed..6758b273b4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -294,7 +294,6 @@ public interface DeviceDAO { */ List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; - /** * This method is used to search for devices within a specific group. * @@ -553,7 +552,6 @@ public interface DeviceDAO { * */ List getDevicesByDuration(PaginationRequest request, - List statusList, int tenantId, String fromDate, String toDate) throws DeviceManagementDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 30bd1d13c7..05baea121f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -80,12 +80,11 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { @Override public int addDevice(int typeId, Device device, int tenantId) throws DeviceManagementDAOException { - Connection conn; PreparedStatement stmt = null; ResultSet rs = null; int deviceId = -1; try { - conn = this.getConnection(); + Connection conn = this.getConnection(); String sql = "INSERT INTO DM_DEVICE(DESCRIPTION, NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, " + "LAST_UPDATED_TIMESTAMP, TENANT_ID) " + "VALUES (?, ?, ?, ?, ?, ?)"; @@ -1008,9 +1007,6 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { @Override public int getDeviceCount(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { int deviceCount = 0; - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; String deviceName = request.getDeviceName(); @@ -1021,17 +1017,23 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; - String status = request.getStatus(); + List statusList = request.getStatusList(); boolean isStatusProvided = false; - String excludeStatus = request.getExcludeStatus(); - boolean isExcludeStatusProvided = false; Date since = request.getSince(); 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 if (since != null) { sql = sql + " , DM_DEVICE_DETAIL dt"; @@ -1046,19 +1048,15 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { sql = sql + " AND t.NAME = ?"; isDeviceTypeProvided = true; } - if (deviceName != null && !deviceName.isEmpty()) { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; - if (ownership != null && !ownership.isEmpty()) { sql = sql + " AND e.OWNERSHIP = ?"; isOwnershipProvided = true; } - //Add the query for owner if (owner != null && !owner.isEmpty()) { sql = sql + " AND e.OWNER = ?"; @@ -1067,56 +1065,49 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { sql = sql + " AND e.OWNER LIKE ?"; isOwnerPatternProvided = true; } - - if (status != null && !status.isEmpty()) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); isStatusProvided = true; } - if (excludeStatus != null && !excludeStatus.isEmpty()) { - sql = sql + " AND e.STATUS != ?"; - isExcludeStatusProvided = true; - } - - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - int paramIdx = 2; - if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); - } - if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, request.getDeviceType()); - } - if (isDeviceNameProvided) { - stmt.setString(paramIdx++, request.getDeviceName() + "%"); - } + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, request.getDeviceType()); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, request.getDeviceName() + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, request.getOwnership()); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } - stmt.setInt(paramIdx++, tenantId); - if (isOwnershipProvided) { - stmt.setString(paramIdx++, request.getOwnership()); - } - if (isOwnerProvided) { - stmt.setString(paramIdx++, owner); - } else if (isOwnerPatternProvided) { - stmt.setString(paramIdx++, ownerPattern + "%"); - } - if (isStatusProvided) { - stmt.setString(paramIdx++, request.getStatus()); - } - if (isExcludeStatusProvided) { - stmt.setString(paramIdx++, excludeStatus); - } - rs = stmt.executeQuery(); - if (rs.next()) { - deviceCount = rs.getInt("DEVICE_COUNT"); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + deviceCount = rs.getInt("DEVICE_COUNT"); + } + return deviceCount; + } } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + - "registered devices", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); + "registered devices", e); } - return deviceCount; } @Override @@ -2270,4 +2261,17 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { } return true; } + + protected String buildStatusQuery(List 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(); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index ea1df72909..471929dc12 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -48,9 +48,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override public List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; List devices; String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; @@ -62,33 +59,42 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; - String status = request.getStatus(); + List statusList = request.getStatusList(); boolean isStatusProvided = false; - String excludeStatus = request.getExcludeStatus(); - boolean isExcludeStatusProvided = false; Date since = request.getSince(); 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 if (since != null) { sql = sql + ", DM_DEVICE_DETAIL dt"; isSinceProvided = true; } - sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; - //Add query for last updated timestamp if (isSinceProvided) { sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; } - //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -99,9 +105,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; - //Add the query for ownership if (ownership != null && !ownership.isEmpty()) { sql = sql + " AND e.OWNERSHIP = ?"; @@ -115,73 +119,62 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND e.OWNER LIKE ?"; isOwnerPatternProvided = true; } - //Add the query for status - if (status != null && !status.isEmpty()) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); isStatusProvided = true; } - //Add the query for exclude status - if (excludeStatus != null && !excludeStatus.isEmpty()) { - sql = sql + " AND e.STATUS != ?"; - isExcludeStatusProvided = true; - } - sql = sql + " LIMIT ?,?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - int paramIdx = 2; - if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); - } - if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, deviceType); - } - if (isDeviceNameProvided) { - stmt.setString(paramIdx++, deviceName + "%"); - } + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); - stmt.setInt(paramIdx++, tenantId); - if (isOwnershipProvided) { - stmt.setString(paramIdx++, ownership); - } - if (isOwnerProvided) { - stmt.setString(paramIdx++, owner); - } else if (isOwnerPatternProvided) { - stmt.setString(paramIdx++, ownerPattern + "%"); - } - if (isStatusProvided) { - stmt.setString(paramIdx++, status); - } - if (isExcludeStatusProvided) { - stmt.setString(paramIdx++, excludeStatus); - } - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx, request.getRowCount()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + - "registered devices", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } - return devices; } - @Override public List searchDevicesInGroup(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; List devices = null; - int groupId = request.getGroupId(); String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; @@ -193,52 +186,63 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; - String status = request.getStatus(); + List statusList = request.getStatusList(); boolean isStatusProvided = false; - String excludeStatus = request.getExcludeStatus(); - boolean isExcludeStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; try { - conn = this.getConnection(); - String sql = "SELECT d1.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 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 = ?"; - - + Connection conn = getConnection(); + String sql = "SELECT d1.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 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 if (deviceName != null && !deviceName.isEmpty()) { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") gd, DM_DEVICE_TYPE t"; - if (since != null) { sql = sql + ", DM_DEVICE_DETAIL dt"; isSinceProvided = true; } - sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; - //Add query for last updated timestamp if (isSinceProvided) { sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; } - //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; isDeviceTypeProvided = true; } - sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; - //Add the query for ownership if (ownership != null && !ownership.isEmpty()) { sql = sql + " AND e.OWNERSHIP = ?"; @@ -252,66 +256,57 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND e.OWNER LIKE ?"; isOwnerPatternProvided = true; } - //Add the query for status - if (status != null && !status.isEmpty()) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); isStatusProvided = true; } - //Add the query for exclude status - if (excludeStatus != null && !excludeStatus.isEmpty()) { - sql = sql + " AND e.STATUS != ?"; - isExcludeStatusProvided = true; - } - sql = sql + " LIMIT ?,?"; - stmt = conn.prepareStatement(sql); - - stmt.setInt(1, groupId); - stmt.setInt(2, tenantId); - - int paramIdx = 3; - if (isDeviceNameProvided) { - stmt.setString(paramIdx++, deviceName + "%"); - } - if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); - } - if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, deviceType); - } - - stmt.setInt(paramIdx++, tenantId); - if (isOwnershipProvided) { - stmt.setString(paramIdx++, ownership); - } - if (isOwnerProvided) { - stmt.setString(paramIdx++, owner); - } else if (isOwnerPatternProvided) { - stmt.setString(paramIdx++, ownerPattern + "%"); - } - if (isStatusProvided) { - stmt.setString(paramIdx++, status); - } - if (isExcludeStatusProvided) { - stmt.setString(paramIdx++, excludeStatus); - } - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx, request.getRowCount()); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, groupId); + stmt.setInt(paramIdx++, tenantId); + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving information of" + - " devices belonging to group : " + groupId, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); + String msg = "Error occurred while retrieving information of" + + " devices belonging to group : " + groupId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } - return devices; } @Override @@ -421,46 +416,81 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override public List getDevicesByStatus(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; List devices = new ArrayList<>(); + List statusList = request.getStatusList(); + try { - conn = this.getConnection(); - String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, 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 = ? AND STATUS = ?) 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 ?,?"; - 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(); + Connection conn = getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, " + + "d.DESCRIPTION, " + + "d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, " + + "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 = ? " + + "LIMIT ?,?"; - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + 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()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices that matches to status " + - "'" + request.getStatus() + "'"; + request.getStatusList().toString(); log.error(msg, e); throw new DeviceManagementDAOException(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, null); } - return devices; } @Override - public List getDevicesByDuration(PaginationRequest request, List statusList, int tenantId, + public List getDevicesByDuration(PaginationRequest request, int tenantId, String fromDate, String toDate) throws DeviceManagementDAOException { List devices; String ownership = request.getOwnership(); + List statusList = request.getStatusList(); boolean isStatusProvided = false; String sql = "SELECT " + @@ -479,20 +509,13 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_TYPE_ID = t.ID AND " + "e.TENANT_ID = ? AND " + "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; - - //Add the query for status - StringBuilder sqlBuilder = new StringBuilder(sql); - isStatusProvided = buildStatusQuery(statusList, sqlBuilder); - sql = sqlBuilder.toString(); - - if(statusList != null && !statusList.isEmpty()){ + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); isStatusProvided = true; } - if (ownership != null) { sql = sql + " AND e.OWNERSHIP = ?"; } - sql = sql + " LIMIT ?,?"; try (Connection conn = this.getConnection(); @@ -511,70 +534,74 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getRowCount()); + try (ResultSet rs = stmt.executeQuery()) { devices = new ArrayList<>(); while (rs.next()) { Device device = DeviceManagementDAOUtil.loadDevice(rs); devices.add(device); } + return devices; } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + - "registered devices under tenant id " + tenantId; + "registered devices under tenant id " + tenantId; log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } - return devices; } @Override - public int getDevicesByDurationCount(List statusList, String ownership, String fromDate, String toDate, int tenantId) throws DeviceManagementDAOException { + public int getDevicesByDurationCount( + List statusList, String ownership, String fromDate, String toDate, int tenantId) + throws DeviceManagementDAOException { int deviceCount = 0; - boolean isStatusProvided; - - String sql = "SELECT " + - "COUNT(d.ID) AS DEVICE_COUNT " + - "FROM DM_DEVICE AS d , DM_ENROLMENT AS e , DM_DEVICE_TYPE AS t " + - "WHERE d.ID = e.DEVICE_ID AND " + - "d.DEVICE_TYPE_ID = t.ID AND " + - "e.TENANT_ID = ? AND " + - "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; + boolean isStatusProvided = false; - //Add the query for status - StringBuilder sqlBuilder = new StringBuilder(sql); - isStatusProvided = buildStatusQuery(statusList, sqlBuilder); - sql = sqlBuilder.toString(); + String sql = "SELECT " + + "COUNT(d.ID) AS DEVICE_COUNT " + + "FROM DM_DEVICE AS d , " + + "DM_ENROLMENT AS e , " + + "DM_DEVICE_TYPE AS t " + + "WHERE d.ID = e.DEVICE_ID " + + "AND d.DEVICE_TYPE_ID = t.ID " + + "AND e.TENANT_ID = ? " + + "AND e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; + } + if (ownership != null) { + sql = sql + " AND e.OWNERSHIP = ?"; + } + try (Connection conn = this.getConnection(); + PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + stmt.setString(paramIdx++, fromDate); + stmt.setString(paramIdx++, toDate); + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } if (ownership != null) { - sql = sql + " AND e.OWNERSHIP = ?"; + stmt.setString(paramIdx, ownership); } - try (Connection conn = this.getConnection(); - PreparedStatement stmt = conn.prepareStatement(sql)) { - int paramIdx = 1; - stmt.setInt(paramIdx++, tenantId); - stmt.setString(paramIdx++, fromDate); - stmt.setString(paramIdx++, toDate); - if (isStatusProvided) { - for (String status : statusList) { - stmt.setString(paramIdx++, status); - } - } - if (ownership != null) { - stmt.setString(paramIdx++, ownership); - } - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - deviceCount = rs.getInt("DEVICE_COUNT"); - } + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + deviceCount = rs.getInt("DEVICE_COUNT"); } - } catch (SQLException e) { - String msg = "Error occurred while retrieving information of all " + - "registered devices under tenant id " + tenantId; - log.error(msg, e); - throw new DeviceManagementDAOException(msg, e); + return deviceCount; } - return deviceCount; + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all " + + "registered devices under tenant id " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } } @Override @@ -583,7 +610,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { throws DeviceManagementDAOException { List countList = new ArrayList<>(); String ownership = request.getOwnership(); - boolean isStatusProvided; + boolean isStatusProvided = false; String sql = "SELECT " + @@ -597,9 +624,10 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { "BETWEEN ? AND ? "; //Add the query for status - StringBuilder sqlBuilder = new StringBuilder(sql); - isStatusProvided = buildStatusQuery(statusList, sqlBuilder); - sql = sqlBuilder.toString(); + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; + } if (ownership != null) { sql = sql + " AND e.OWNERSHIP = ?"; @@ -644,23 +672,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { return countList; } - protected boolean buildStatusQuery(List 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. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index 718c187530..e864419d76 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -50,8 +50,6 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { public List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; List devices = null; String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; @@ -63,33 +61,42 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; - String status = request.getStatus(); + List statusList = request.getStatusList(); boolean isStatusProvided = false; - String excludeStatus = request.getExcludeStatus(); - boolean isExcludeStatusProvided = false; Date since = request.getSince(); 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 if (since != null) { sql = sql + ", DM_DEVICE_DETAIL dt"; isSinceProvided = true; } - sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; - //Add query for last updated timestamp if (isSinceProvided) { sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; } - //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -100,9 +107,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; - //Add the query for ownership if (ownership != null && !ownership.isEmpty()) { sql = sql + " AND e.OWNERSHIP = ?"; @@ -116,72 +121,63 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND e.OWNER LIKE ?"; isOwnerPatternProvided = true; } - //Add the query for status - if (status != null && !status.isEmpty()) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); 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"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - int paramIdx = 2; - if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); - } - if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, deviceType); - } - if (isDeviceNameProvided) { - stmt.setString(paramIdx++, deviceName + "%"); - } + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); - stmt.setInt(paramIdx++, tenantId); - if (isOwnershipProvided) { - stmt.setString(paramIdx++, ownership); - } - if (isOwnerProvided) { - stmt.setString(paramIdx++, owner); - } else if (isOwnerPatternProvided) { - stmt.setString(paramIdx++, ownerPattern + "%"); - } - if (isStatusProvided) { - stmt.setString(paramIdx++, status); - } - if (isExcludeStatusProvided) { - stmt.setString(paramIdx++, excludeStatus); - } - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx, request.getRowCount()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + - "registered devices", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } - return devices; } @Override public List searchDevicesInGroup(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; List devices = null; - int groupId = request.getGroupId(); String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; @@ -193,52 +189,64 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; - String status = request.getStatus(); + List statusList = request.getStatusList(); boolean isStatusProvided = false; - String excludeStatus = request.getExcludeStatus(); - boolean isExcludeStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; try { - conn = this.getConnection(); - String sql = "SELECT d1.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 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 = ?"; - - + conn = getConnection(); + String sql = "SELECT d1.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 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 if (deviceName != null && !deviceName.isEmpty()) { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") gd, DM_DEVICE_TYPE t"; - if (since != null) { sql = sql + ", DM_DEVICE_DETAIL dt"; isSinceProvided = true; } - sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; - //Add query for last updated timestamp if (isSinceProvided) { sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; } - //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; isDeviceTypeProvided = true; } - sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; - //Add the query for ownership if (ownership != null && !ownership.isEmpty()) { sql = sql + " AND e.OWNERSHIP = ?"; @@ -252,69 +260,59 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND e.OWNER LIKE ?"; isOwnerPatternProvided = true; } - //Add the query for status - if (status != null && !status.isEmpty()) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); 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"; - stmt = conn.prepareStatement(sql); - - stmt.setInt(1, groupId); - stmt.setInt(2, tenantId); - - int paramIdx = 3; - if (isDeviceNameProvided) { - stmt.setString(paramIdx++, deviceName + "%"); - } - if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); - } - if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, deviceType); - } - - stmt.setInt(paramIdx++, tenantId); - if (isOwnershipProvided) { - stmt.setString(paramIdx++, ownership); - } - if (isOwnerProvided) { - stmt.setString(paramIdx++, owner); - } else if (isOwnerPatternProvided) { - stmt.setString(paramIdx++, ownerPattern + "%"); - } - if (isStatusProvided) { - stmt.setString(paramIdx++, status); - } - if (isExcludeStatusProvided) { - stmt.setString(paramIdx++, excludeStatus); - } - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx, request.getRowCount()); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, groupId); + stmt.setInt(paramIdx++, tenantId); + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving information of" + - " devices belonging to group : " + groupId, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); + String msg = "Error occurred while retrieving information of" + + " devices belonging to group : " + groupId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } - return devices; } - @Override public List getDevicesOfUser(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { @@ -425,46 +423,80 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { public List getDevicesByStatus(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; - PreparedStatement stmt = null; List devices = new ArrayList<>(); + List statusList = request.getStatusList(); + try { - conn = this.getConnection(); - String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " - + "d.DEVICE_IDENTIFICATION, 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 = ? AND STATUS = ?) 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"; - 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(); + conn = getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, " + + "d.DESCRIPTION, " + + "d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, " + + "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 = ?" + + "LIMIT ?,?"; - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + 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()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices that matches to status " + - "'" + request.getStatus() + "'"; + request.getStatusList().toString(); log.error(msg, e); throw new DeviceManagementDAOException(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, null); } - return devices; } @Override - public List getDevicesByDuration(PaginationRequest request, List statusList, int tenantId, + public List getDevicesByDuration(PaginationRequest request, int tenantId, String fromDate, String toDate) throws DeviceManagementDAOException { List devices; - String deviceStatus = request.getStatus(); + List statusList = request.getStatusList(); + boolean isStatusProvided = false; String ownership = request.getOwnership(); String sql = "SELECT " + @@ -483,14 +515,13 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_TYPE_ID = t.ID AND " + "e.TENANT_ID = ? AND " + "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; - - if (deviceStatus != null) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; } if (ownership != null) { sql = sql + " AND e.OWNERSHIP = ?"; } - sql = sql + " ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (Connection conn = this.getConnection(); @@ -499,20 +530,24 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setInt(paramIdx++, tenantId); stmt.setString(paramIdx++, fromDate); stmt.setString(paramIdx++, toDate); - if (deviceStatus != null) { - stmt.setString(paramIdx++, deviceStatus); + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } } if (ownership != null) { stmt.setString(paramIdx++, ownership); } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getRowCount()); + try (ResultSet rs = stmt.executeQuery()) { devices = new ArrayList<>(); while (rs.next()) { Device device = DeviceManagementDAOUtil.loadDevice(rs); devices.add(device); } + return devices; } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + @@ -520,7 +555,6 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } - return devices; } @Override diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index 23068865fd..5df5f823bb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -49,8 +49,6 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { public List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; List devices = null; String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; @@ -62,20 +60,34 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; - String status = request.getStatus(); + List statusList = request.getStatusList(); boolean isStatusProvided = false; - String excludeStatus = request.getExcludeStatus(); - boolean isExcludeStatusProvided = false; Date since = request.getSince(); 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 if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -86,9 +98,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; - //Add the query for ownership if (ownership != null && !ownership.isEmpty()) { sql = sql + " AND e.OWNERSHIP = ?"; @@ -102,69 +112,60 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND e.OWNER LIKE ?"; isOwnerPatternProvided = true; } - //Add the query for status - if (status != null && !status.isEmpty()) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); isStatusProvided = true; } - //Add the query for exclude status - if (excludeStatus != null && !excludeStatus.isEmpty()) { - sql = sql + " AND e.STATUS != ?"; - isExcludeStatusProvided = true; - } - sql = sql + " LIMIT ? OFFSET ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - int paramIdx = 2; - if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, deviceType); - } - if (isDeviceNameProvided) { - stmt.setString(paramIdx++, deviceName + "%"); - } + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + stmt.setInt(paramIdx++, request.getRowCount()); + stmt.setInt(paramIdx, request.getStartIndex()); - stmt.setInt(paramIdx++, tenantId); - if (isOwnershipProvided) { - stmt.setString(paramIdx++, ownership); - } - if (isOwnerProvided) { - stmt.setString(paramIdx++, owner); - } else if (isOwnerPatternProvided) { - stmt.setString(paramIdx++, ownerPattern + "%"); - } - if (isStatusProvided) { - stmt.setString(paramIdx++, status); - } - if (isExcludeStatusProvided) { - stmt.setString(paramIdx++, excludeStatus); - } - stmt.setInt(paramIdx++, request.getRowCount()); - stmt.setInt(paramIdx, request.getStartIndex()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + - "registered devices", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } - return devices; } @Override public List searchDevicesInGroup(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; List devices = null; - int groupId = request.getGroupId(); String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; @@ -176,52 +177,63 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; - String status = request.getStatus(); + List statusList = request.getStatusList(); boolean isStatusProvided = false; - String excludeStatus = request.getExcludeStatus(); - boolean isExcludeStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; try { - conn = this.getConnection(); - String sql = "SELECT d1.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 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 = ?"; - - + conn = getConnection(); + String sql = "SELECT d1.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 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 if (deviceName != null && !deviceName.isEmpty()) { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") gd, DM_DEVICE_TYPE t"; - if (since != null) { sql = sql + ", DM_DEVICE_DETAIL dt"; isSinceProvided = true; } - sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; - //Add query for last updated timestamp if (isSinceProvided) { sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; } - //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; isDeviceTypeProvided = true; } - sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; - //Add the query for ownership if (ownership != null && !ownership.isEmpty()) { sql = sql + " AND e.OWNERSHIP = ?"; @@ -235,66 +247,57 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND e.OWNER LIKE ?"; isOwnerPatternProvided = true; } - //Add the query for status - if (status != null && !status.isEmpty()) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); isStatusProvided = true; } - //Add the query for exclude status - if (excludeStatus != null && !excludeStatus.isEmpty()) { - sql = sql + " AND e.STATUS != ?"; - isExcludeStatusProvided = true; - } - sql = sql + " LIMIT ? OFFSET ?"; - stmt = conn.prepareStatement(sql); - - stmt.setInt(1, groupId); - stmt.setInt(2, tenantId); - - int paramIdx = 3; - if (isDeviceNameProvided) { - stmt.setString(paramIdx++, deviceName + "%"); - } - if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); - } - if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, deviceType); - } - - stmt.setInt(paramIdx++, tenantId); - if (isOwnershipProvided) { - stmt.setString(paramIdx++, ownership); - } - if (isOwnerProvided) { - stmt.setString(paramIdx++, owner); - } else if (isOwnerPatternProvided) { - stmt.setString(paramIdx++, ownerPattern + "%"); - } - if (isStatusProvided) { - stmt.setString(paramIdx++, status); - } - if (isExcludeStatusProvided) { - stmt.setString(paramIdx++, excludeStatus); - } - stmt.setInt(paramIdx, request.getRowCount()); - stmt.setInt(paramIdx++, request.getStartIndex()); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, groupId); + stmt.setInt(paramIdx++, tenantId); + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + stmt.setInt(paramIdx++, request.getRowCount()); + stmt.setInt(paramIdx, request.getStartIndex()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving information of" + - " devices belonging to group : " + groupId, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); + String msg = "Error occurred while retrieving information of" + + " devices belonging to group : " + groupId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } - return devices; } @Override @@ -405,45 +408,79 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { public List getDevicesByStatus(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; - PreparedStatement stmt = null; List devices = new ArrayList<>(); + List statusList = request.getStatusList(); + try { - conn = this.getConnection(); - String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, 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 = ? AND STATUS = ?) 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 ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setString(2, request.getStatus()); - stmt.setInt(3, tenantId); - stmt.setInt(4, request.getRowCount()); - stmt.setInt(5, request.getStartIndex()); - ResultSet rs = stmt.executeQuery(); + conn = getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, " + + "d.DESCRIPTION, " + + "d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, " + + "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 = ? " + + "LIMIT ? OFFSET ?"; - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + 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()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices that matches to status " + - "'" + request.getStatus() + "'"; + request.getStatusList().toString(); log.error(msg, e); throw new DeviceManagementDAOException(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, null); } - return devices; } @Override - public List getDevicesByDuration(PaginationRequest request, List statusList, int tenantId, + public List getDevicesByDuration(PaginationRequest request, int tenantId, String fromDate, String toDate) throws DeviceManagementDAOException { List devices; - String deviceStatus = request.getStatus(); + List statusList = request.getStatusList(); + boolean isStatusProvided = false; String ownership = request.getOwnership(); String sql = "SELECT " + @@ -462,14 +499,13 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_TYPE_ID = t.ID AND " + "e.TENANT_ID = ? AND " + "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; - - if (deviceStatus != null) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; } if (ownership != null) { sql = sql + " AND e.OWNERSHIP = ?"; } - sql = sql + " LIMIT ? OFFSET ?"; try (Connection conn = this.getConnection(); @@ -478,20 +514,24 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setInt(paramIdx++, tenantId); stmt.setString(paramIdx++, fromDate); stmt.setString(paramIdx++, toDate); - if (deviceStatus != null) { - stmt.setString(paramIdx++, deviceStatus); + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } } if (ownership != null) { stmt.setString(paramIdx++, ownership); } stmt.setInt(paramIdx++, request.getRowCount()); stmt.setInt(paramIdx, request.getStartIndex()); + try (ResultSet rs = stmt.executeQuery()) { devices = new ArrayList<>(); while (rs.next()) { Device device = DeviceManagementDAOUtil.loadDevice(rs); devices.add(device); } + return devices; } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + @@ -499,7 +539,6 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } - return devices; } @Override diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 0df8ec959c..299917edd2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -51,8 +51,6 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { public List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; List devices = null; String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; @@ -64,33 +62,41 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; - String status = request.getStatus(); + List statusList = request.getStatusList(); boolean isStatusProvided = false; - String excludeStatus = request.getExcludeStatus(); - boolean isExcludeStatusProvided = false; Date since = request.getSince(); 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 " + + 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 if (since != null) { sql = sql + ", DM_DEVICE_DETAIL dt"; isSinceProvided = true; } - sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; - //Add query for last updated timestamp if (isSinceProvided) { sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; } - //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; @@ -101,9 +107,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; - //Add the query for ownership if (ownership != null && !ownership.isEmpty()) { sql = sql + " AND e.OWNERSHIP = ?"; @@ -117,72 +121,63 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND e.OWNER LIKE ?"; isOwnerPatternProvided = true; } - //Add the query for status - if (status != null && !status.isEmpty()) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); 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"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - int paramIdx = 2; - if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); - } - if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, deviceType); - } - if (isDeviceNameProvided) { - stmt.setString(paramIdx++, deviceName + "%"); - } + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); - stmt.setInt(paramIdx++, tenantId); - if (isOwnershipProvided) { - stmt.setString(paramIdx++, ownership); - } - if (isOwnerProvided) { - stmt.setString(paramIdx++, owner); - } else if (isOwnerPatternProvided) { - stmt.setString(paramIdx++, ownerPattern + "%"); - } - if (isStatusProvided) { - stmt.setString(paramIdx++, status); - } - if (isExcludeStatusProvided) { - stmt.setString(paramIdx++, excludeStatus); - } - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx, request.getRowCount()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving information of all " + - "registered devices", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } - return devices; } @Override public List searchDevicesInGroup(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; List devices = null; - int groupId = request.getGroupId(); String deviceType = request.getDeviceType(); boolean isDeviceTypeProvided = false; @@ -194,52 +189,63 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnerPatternProvided = false; String ownership = request.getOwnership(); boolean isOwnershipProvided = false; - String status = request.getStatus(); + List statusList = request.getStatusList(); boolean isStatusProvided = false; - String excludeStatus = request.getExcludeStatus(); - boolean isExcludeStatusProvided = false; Date since = request.getSince(); boolean isSinceProvided = false; try { - conn = this.getConnection(); - String sql = "SELECT d1.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 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 = ?"; - - + conn = getConnection(); + String sql = "SELECT d1.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 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 if (deviceName != null && !deviceName.isEmpty()) { sql = sql + " AND d.NAME LIKE ?"; isDeviceNameProvided = true; } - sql = sql + ") gd, DM_DEVICE_TYPE t"; - if (since != null) { sql = sql + ", DM_DEVICE_DETAIL dt"; isSinceProvided = true; } - sql = sql + " WHERE gd.DEVICE_TYPE_ID = t.ID"; - //Add query for last updated timestamp if (isSinceProvided) { sql = sql + " AND dt.DEVICE_ID = gd.DEVICE_ID AND dt.UPDATE_TIMESTAMP > ?"; } - //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; isDeviceTypeProvided = true; } - sql = sql + " ) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? "; - //Add the query for ownership if (ownership != null && !ownership.isEmpty()) { sql = sql + " AND e.OWNERSHIP = ?"; @@ -253,66 +259,57 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { sql = sql + " AND e.OWNER LIKE ?"; isOwnerPatternProvided = true; } - //Add the query for status - if (status != null && !status.isEmpty()) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); 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"; - stmt = conn.prepareStatement(sql); - - stmt.setInt(1, groupId); - stmt.setInt(2, tenantId); - - int paramIdx = 3; - if (isDeviceNameProvided) { - stmt.setString(paramIdx++, deviceName + "%"); - } - if (isSinceProvided) { - stmt.setLong(paramIdx++, since.getTime()); - } - if (isDeviceTypeProvided) { - stmt.setString(paramIdx++, deviceType); - } - - stmt.setInt(paramIdx++, tenantId); - if (isOwnershipProvided) { - stmt.setString(paramIdx++, ownership); - } - if (isOwnerProvided) { - stmt.setString(paramIdx++, owner); - } else if (isOwnerPatternProvided) { - stmt.setString(paramIdx++, ownerPattern + "%"); - } - if (isStatusProvided) { - stmt.setString(paramIdx++, status); - } - if (isExcludeStatusProvided) { - stmt.setString(paramIdx++, excludeStatus); - } - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx, request.getRowCount()); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, groupId); + stmt.setInt(paramIdx++, tenantId); + if (isDeviceNameProvided) { + stmt.setString(paramIdx++, deviceName + "%"); + } + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } + if (isDeviceTypeProvided) { + stmt.setString(paramIdx++, deviceType); + } + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } else if (isOwnerPatternProvided) { + stmt.setString(paramIdx++, ownerPattern + "%"); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); - rs = stmt.executeQuery(); - devices = new ArrayList<>(); - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while retrieving information of" + - " devices belonging to group : " + groupId, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); + String msg = "Error occurred while retrieving information of" + + " devices belonging to group : " + groupId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); } - return devices; } @Override @@ -425,38 +422,72 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { public List getDevicesByStatus(PaginationRequest request, int tenantId) throws DeviceManagementDAOException { Connection conn; - PreparedStatement stmt = null; List devices = new ArrayList<>(); + List statusList = request.getStatusList(); + try { - conn = this.getConnection(); - String sql = "SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME AS DEVICE_NAME, t.NAME AS DEVICE_TYPE, " + - "d.DEVICE_IDENTIFICATION, 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 = ? AND STATUS = ?) 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"; - 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(); + conn = getConnection(); + String sql = "SELECT d.ID AS DEVICE_ID, " + + "d.DESCRIPTION, " + + "d.NAME AS DEVICE_NAME, " + + "t.NAME AS DEVICE_TYPE, " + + "d.DEVICE_IDENTIFICATION, " + + "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"; - while (rs.next()) { - Device device = DeviceManagementDAOUtil.loadDevice(rs); - devices.add(device); + 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()) { + Device device = DeviceManagementDAOUtil.loadDevice(rs); + devices.add(device); + } + return devices; + } } } catch (SQLException e) { String msg = "Error occurred while fetching the list of devices that matches to status " + - "'" + request.getStatus() + "'"; + request.getStatusList().toString(); log.error(msg, e); throw new DeviceManagementDAOException(msg, e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, null); } - return devices; } /** @@ -604,11 +635,12 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getDevicesByDuration(PaginationRequest request, List statusList, int tenantId, + public List getDevicesByDuration(PaginationRequest request, int tenantId, String fromDate, String toDate) throws DeviceManagementDAOException { List devices; - String deviceStatus = request.getStatus(); + List statusList = request.getStatusList(); + boolean isStatusProvided = false; String ownership = request.getOwnership(); String sql = "SELECT " + @@ -627,14 +659,13 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "d.DEVICE_TYPE_ID = t.ID AND " + "e.TENANT_ID = ? AND " + "e.DATE_OF_ENROLMENT BETWEEN ? AND ?"; - - if (deviceStatus != null) { - sql = sql + " AND e.STATUS = ?"; + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; } if (ownership != null) { sql = sql + " AND e.OWNERSHIP = ?"; } - sql = sql + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; try (Connection conn = this.getConnection(); @@ -643,20 +674,24 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt.setInt(paramIdx++, tenantId); stmt.setString(paramIdx++, fromDate); stmt.setString(paramIdx++, toDate); - if (deviceStatus != null) { - stmt.setString(paramIdx++, deviceStatus); + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } } if (ownership != null) { stmt.setString(paramIdx++, ownership); } stmt.setInt(paramIdx++, request.getStartIndex()); stmt.setInt(paramIdx, request.getRowCount()); + try (ResultSet rs = stmt.executeQuery()) { devices = new ArrayList<>(); while (rs.next()) { Device device = DeviceManagementDAOUtil.loadDevice(rs); devices.add(device); } + return devices; } } catch (SQLException e) { String msg = "Error occurred while retrieving information of all " + @@ -664,7 +699,6 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { log.error(msg, e); throw new DeviceManagementDAOException(msg, e); } - return devices; } @Override diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/report/mgt/ReportManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/report/mgt/ReportManagementServiceImpl.java index 51c0ec6929..4ed96a5bbf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/report/mgt/ReportManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/report/mgt/ReportManagementServiceImpl.java @@ -57,7 +57,7 @@ public class ReportManagementServiceImpl implements ReportManagementService { } @Override - public PaginationResult getDevicesByDuration(PaginationRequest request, List statusList, String fromDate, + public PaginationResult getDevicesByDuration(PaginationRequest request, String fromDate, String toDate) throws ReportManagementException { PaginationResult paginationResult = new PaginationResult(); @@ -72,7 +72,6 @@ public class ReportManagementServiceImpl implements ReportManagementService { DeviceManagementDAOFactory.openConnection(); List devices = deviceDAO.getDevicesByDuration( request, - statusList, DeviceManagementDAOUtil.getTenantId(), fromDate, toDate diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 01948680e5..c74d7b2ca9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -2528,10 +2528,31 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.debug("Get devices by status " + request.toString() + " and requiredDeviceInfo: " + requireDeviceInfo); } + List 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(); List allDevices; int tenantId = this.getTenantId(); - String status = request.getStatus(); request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); @@ -2540,7 +2561,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv result.setRecordsTotal(deviceCount); result.setRecordsFiltered(deviceCount); } 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); throw new DeviceManagementException(msg, e); } catch (SQLException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java index 4bd90ecd4a..5e7d70680c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceTest.java @@ -78,7 +78,9 @@ import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import java.io.InputStream; import java.lang.reflect.Field; import java.sql.Timestamp; +import java.util.ArrayList; import java.util.Calendar; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -676,7 +678,8 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes public void testGetAllDevicesByStatus() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException { PaginationRequest request = new PaginationRequest(0, 100); - request.setStatus(EnrolmentInfo.Status.ACTIVE.toString()); + List statusList = new ArrayList<>(Collections.singletonList("ACTIVE")); + request.setStatusList(statusList); MockDataSource dataSource = setDatasourceForGetDevice(); if (dataSource != null) { setMockDeviceCount(dataSource.getConnection(0)); @@ -842,7 +845,8 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes public void testGetDeviesByStatus() throws DeviceManagementException, NoSuchFieldException, IllegalAccessException { PaginationRequest request = new PaginationRequest(0, 100); - request.setStatus("ACTIVE"); + List statusList = new ArrayList<>(Collections.singletonList("ACTIVE")); + request.setStatusList(statusList); MockDataSource dataSource = setDatasourceForGetDevice(); if (dataSource != null) { setMockDeviceCount(dataSource.getConnection(0)); @@ -917,4 +921,4 @@ public class DeviceManagementProviderServiceTest extends BaseDeviceManagementTes cal.add(Calendar.DATE, -1); return cal.getTime(); } -} \ No newline at end of file +}