API endpoint to get all devices which are enrolled between two dates

feature/appm-store/pbac
Shamalka Navod 5 years ago committed by Milan Perera
parent 8e9d64038b
commit c5793bcf67

@ -0,0 +1,160 @@
/*
* Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Extension;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Info;
import io.swagger.annotations.ResponseHeader;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.mgt.common.exceptions.ReportManagementException;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@SwaggerDefinition(
info = @Info(
version = "1.0.0",
title = "",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name", value = "DeviceReportnManagement"),
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/reports"),
})
}
),
tags = {
@Tag(name = "device_management", description = "")
}
)
@Scopes(
scopes = {
@Scope(
name = "Getting Details of Registered Devices",
description = "Getting Details of Registered Devices",
key = "perm:devices:view",
permissions = {"/device-mgt/devices/owning-device/view"}
),
}
)
@Api(value = "Device Report Management", description = "Device report related operations can be found here.")
@Path("/reports")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface ReportManagementService {
@GET
@Path("/devices")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of Registered Devices",
notes = "Provides details of all the devices enrolled with WSO2 IoT Server.",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the list of devices.",
response = DeviceList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid device status type received. \n" +
"Valid status types are NEW | CHECKED",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n There are no devices.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. " +
"\n Server error occurred while fetching the device list.",
response = ErrorResponse.class)
})
Response getDevicesByDuration(
@ApiParam(
name = "status",
value = "Provide the device status details, such as active or inactive.")
@QueryParam("status") String status,
@ApiParam(
name = "ownership",
allowableValues = "BYOD, COPE",
value = "Provide the ownership status of the device. The following values can be assigned:\n" +
"- BYOD: Bring Your Own Device\n" +
"- COPE: Corporate-Owned, Personally-Enabled")
@QueryParam("ownership") String ownership,
@ApiParam(
name = "fromDate",
value = "Start date of the duration",
required = true)
@QueryParam("from") String fromDate,
@ApiParam(
name = "toDate",
value = "end date of the duration",
required = true)
@QueryParam("to") String toDate,
@ApiParam(
name = "offset",
value = "The starting pagination index for the complete list of qualified items.",
defaultValue = "0")
@QueryParam("offset")
int offset,
@ApiParam(
name = "limit",
value = "Provide how many device details you require from the starting pagination index/offset.",
defaultValue = "5")
@QueryParam("limit")
int limit) throws ReportManagementException;
}

@ -29,10 +29,8 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.NotificationList; import org.wso2.carbon.device.mgt.jaxrs.beans.NotificationList;
import org.wso2.carbon.device.mgt.jaxrs.service.api.NotificationManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.api.NotificationManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import javax.validation.constraints.Max;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;

@ -0,0 +1,98 @@
/*
* Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.exceptions.ReportManagementException;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.api.ReportManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* This is the service class for report generating operations
*/
@Path("/reports")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ReportManagementServiceImpl implements ReportManagementService {
private static final Log log = LogFactory.getLog(ReportManagementServiceImpl.class);
@GET
@Path("/devices")
@Override
public Response getDevicesByDuration(
@QueryParam("status") String status,
@QueryParam("ownership") String ownership,
@QueryParam("from") String fromDate,
@QueryParam("to") String toDate,
@DefaultValue("0")
@QueryParam("offset") int offset,
@DefaultValue("5")
@QueryParam("limit") int limit) {
try {
RequestValidationUtil.validatePaginationParameters(offset, limit);
PaginationRequest request = new PaginationRequest(offset, limit);
PaginationResult result;
DeviceList devices = new DeviceList();
if (!StringUtils.isBlank(status)) {
request.setStatus(status);
}
if (!StringUtils.isBlank(ownership)) {
request.setOwnership(ownership);
}
result = DeviceMgtAPIUtils.getReportManagementService()
.getDevicesByDuration(request, fromDate, toDate);
if (result.getData().isEmpty()) {
String msg = "No devices have enrolled between " + fromDate + " to " + toDate +
" or doesn't match with" +
" given parameters";
log.error(msg);
return Response.status(Response.Status.OK).entity(msg).build();
} else {
devices.setList((List<Device>) result.getData());
devices.setCount(result.getRecordsTotal());
return Response.status(Response.Status.OK).entity(devices).build();
}
} catch (ReportManagementException e) {
String msg = "Error occurred while retrieving device list";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
}

@ -46,6 +46,7 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.report.mgt.ReportManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
@ -431,6 +432,23 @@ public class DeviceMgtAPIUtils {
return notificationManagementService; return notificationManagementService;
} }
/**
* Method for initializing ReportManagementService
* @return ReportManagementServie Instance
*/
public static ReportManagementService getReportManagementService() {
ReportManagementService reportManagementService;
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
reportManagementService = (ReportManagementService) ctx.getOSGiService(
ReportManagementService.class, null);
if (reportManagementService == null) {
String msg = "Report Management service not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return reportManagementService;
}
public static DeviceInformationManager getDeviceInformationManagerService() { public static DeviceInformationManager getDeviceInformationManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceInformationManager deviceInformationManager = DeviceInformationManager deviceInformationManager =

@ -32,6 +32,7 @@
<ref bean="configurationManagementService"/> <ref bean="configurationManagementService"/>
<ref bean="activityProviderService"/> <ref bean="activityProviderService"/>
<ref bean="notificationManagementService"/> <ref bean="notificationManagementService"/>
<ref bean="reportManagementService"/>
<ref bean="policyManagementService"/> <ref bean="policyManagementService"/>
<ref bean="roleManagementService"/> <ref bean="roleManagementService"/>
<ref bean="userManagementService"/> <ref bean="userManagementService"/>
@ -78,6 +79,7 @@
<bean id="configurationManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.ConfigurationServiceImpl"/> <bean id="configurationManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.ConfigurationServiceImpl"/>
<bean id="activityProviderService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.ActivityProviderServiceImpl"/> <bean id="activityProviderService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.ActivityProviderServiceImpl"/>
<bean id="notificationManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.NotificationManagementServiceImpl"/> <bean id="notificationManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.NotificationManagementServiceImpl"/>
<bean id="reportManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.ReportManagementServiceImpl"/>
<bean id="policyManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.PolicyManagementServiceImpl"/> <bean id="policyManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.PolicyManagementServiceImpl"/>
<bean id="roleManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.RoleManagementServiceImpl"/> <bean id="roleManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.RoleManagementServiceImpl"/>
<bean id="userManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.UserManagementServiceImpl"/> <bean id="userManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.UserManagementServiceImpl"/>

@ -0,0 +1,59 @@
/*
* Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.exceptions;
/**
* This class is used for exception handling in report generating operations
*/
public class ReportManagementException extends Exception {
private static final long serialVersionUID = -409298183404045217L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public ReportManagementException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public ReportManagementException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public ReportManagementException(String msg) {
super(msg);
setErrorMessage(msg);
}
public ReportManagementException() {
super();
}
public ReportManagementException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,41 @@
/*
* Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.report.mgt;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.exceptions.ReportManagementException;
/**
* This is the service class for reports which connects with DAO layer
*/
public interface ReportManagementService {
/**
* This method is used to call the getDevicesByDuration method from DeviceDAO
*
* @param request Pagination Request to get a paginated result
* @param fromDate Start date to filter devices(YYYY-MM-DD)
* @param toDate End date to filter devices(YYYY-MM-DD)
* @return {@link PaginationResult}
* @throws {@Link DeviceManagementException} When error occurred while validating device list page size
* @throws {@Link ReportManagementException} When failed to retrieve devices.
*/
PaginationResult getDevicesByDuration(PaginationRequest request, String fromDate, String toDate)
throws ReportManagementException;
}

@ -534,4 +534,20 @@ public interface DeviceDAO {
boolean transferDevice(String deviceType, String deviceId, String owner, int destinationTenantId) boolean transferDevice(String deviceType, String deviceId, String owner, int destinationTenantId)
throws DeviceManagementDAOException, SQLException; throws DeviceManagementDAOException, SQLException;
/**
* This method is used to get a device list which enrolled within a specific time period
*
* @param request Pagination request to get paginated result
* @param tenantId ID of the current tenant
* @param fromDate Start date to filter devices(YYYY-MM-DD)
* @param toDate End date to filter devices(YYYY-MM-DD)
* @return returns a list of Device objects
* @throws {@Link DeviceManagementDAOException} If failed to retrieve devices
*
*/
List<Device> getDevicesByDuration(PaginationRequest request,
int tenantId,
String fromDate,
String toDate) throws DeviceManagementDAOException;
} }

@ -288,5 +288,4 @@ public class DeviceManagementDAOFactory {
} }
return dataSource; return dataSource;
} }
} }

@ -18,6 +18,8 @@
package org.wso2.carbon.device.mgt.core.dao.impl.device; package org.wso2.carbon.device.mgt.core.dao.impl.device;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
@ -25,7 +27,10 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import java.sql.*; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -35,13 +40,15 @@ import java.util.List;
*/ */
public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
private static final Log log = LogFactory.getLog(GenericDeviceDAOImpl.class);
@Override @Override
public List<Device> getDevices(PaginationRequest request, int tenantId) public List<Device> getDevices(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
List<Device> devices = null; List<Device> devices;
String deviceType = request.getDeviceType(); String deviceType = request.getDeviceType();
boolean isDeviceTypeProvided = false; boolean isDeviceTypeProvided = false;
String deviceName = request.getDeviceName(); String deviceName = request.getDeviceName();
@ -423,6 +430,70 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices; return devices;
} }
@Override
public List<Device> getDevicesByDuration(PaginationRequest request, int tenantId,
String fromDate, String toDate)
throws DeviceManagementDAOException {
List<Device> devices;
String deviceStatus = request.getStatus();
String ownership = request.getOwnership();
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 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 (deviceStatus != null) {
sql = sql + " AND e.STATUS = ?";
}
if (ownership != null) {
sql = sql + " AND e.OWNERSHIP = ?";
}
sql = sql + " LIMIT ?,?";
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 (deviceStatus != null) {
stmt.setString(paramIdx++, deviceStatus);
}
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);
}
}
} 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 devices;
}
/** /**
* Get the list of devices that matches with the given device name and (or) device type. * Get the list of devices that matches with the given device name and (or) device type.
* *

@ -18,6 +18,8 @@
package org.wso2.carbon.device.mgt.core.dao.impl.device; package org.wso2.carbon.device.mgt.core.dao.impl.device;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
@ -41,6 +43,8 @@ import java.util.List;
*/ */
public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
private static final Log log = LogFactory.getLog(OracleDeviceDAOImpl.class);
@Override @Override
public List<Device> getDevices(PaginationRequest request, int tenantId) public List<Device> getDevices(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
@ -432,6 +436,70 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices; return devices;
} }
@Override
public List<Device> getDevicesByDuration(PaginationRequest request, int tenantId,
String fromDate, String toDate)
throws DeviceManagementDAOException {
List<Device> devices;
String deviceStatus = request.getStatus();
String ownership = request.getOwnership();
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 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 (deviceStatus != null) {
sql = sql + " AND e.STATUS = ?";
}
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();
PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
stmt.setString(paramIdx++, fromDate);
stmt.setString(paramIdx++, toDate);
if (deviceStatus != null) {
stmt.setString(paramIdx++, deviceStatus);
}
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);
}
}
} 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 devices;
}
/** /**
* Get the list of devices that matches with the given device name and (or) device type. * Get the list of devices that matches with the given device name and (or) device type.
* *
@ -488,6 +556,9 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
devices.add(device); devices.add(device);
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices";
log.error(msg, e);
throw new DeviceManagementDAOException("Error occurred while fetching the list of devices corresponding" + throw new DeviceManagementDAOException("Error occurred while fetching the list of devices corresponding" +
"to the mentioned filtering criteria", e); "to the mentioned filtering criteria", e);
} finally { } finally {

@ -18,6 +18,8 @@
package org.wso2.carbon.device.mgt.core.dao.impl.device; package org.wso2.carbon.device.mgt.core.dao.impl.device;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
@ -38,6 +40,8 @@ import java.util.List;
*/ */
public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
private static final Log log = LogFactory.getLog(PostgreSQLDeviceDAOImpl.class);
@Override @Override
public List<Device> getDevices(PaginationRequest request, int tenantId) public List<Device> getDevices(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
@ -409,6 +413,70 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
return devices; return devices;
} }
@Override
public List<Device> getDevicesByDuration(PaginationRequest request, int tenantId,
String fromDate, String toDate)
throws DeviceManagementDAOException {
List<Device> devices;
String deviceStatus = request.getStatus();
String ownership = request.getOwnership();
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 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 (deviceStatus != null) {
sql = sql + " AND e.STATUS = ?";
}
if (ownership != null) {
sql = sql + " AND e.OWNERSHIP = ?";
}
sql = sql + " LIMIT ? OFFSET ?";
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 (deviceStatus != null) {
stmt.setString(paramIdx++, deviceStatus);
}
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);
}
}
} 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 devices;
}
/** /**
* Get the list of devices that matches with the given device name and (or) device type. * Get the list of devices that matches with the given device name and (or) device type.
* *

@ -18,6 +18,8 @@
package org.wso2.carbon.device.mgt.core.dao.impl.device; package org.wso2.carbon.device.mgt.core.dao.impl.device;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
@ -38,6 +40,8 @@ import java.util.List;
*/ */
public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
private static final Log log = LogFactory.getLog(SQLServerDeviceDAOImpl.class);
@Override @Override
public List<Device> getDevices(PaginationRequest request, int tenantId) public List<Device> getDevices(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
@ -496,4 +500,68 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
private Connection getConnection() throws SQLException { private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection(); return DeviceManagementDAOFactory.getConnection();
} }
@Override
public List<Device> getDevicesByDuration(PaginationRequest request, int tenantId,
String fromDate, String toDate)
throws DeviceManagementDAOException {
List<Device> devices;
String deviceStatus = request.getStatus();
String ownership = request.getOwnership();
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 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 (deviceStatus != null) {
sql = sql + " AND e.STATUS = ?";
}
if (ownership != null) {
sql = sql + " AND e.OWNERSHIP = ?";
}
sql = sql + " LIMIT ?,?";
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 (deviceStatus != null) {
stmt.setString(paramIdx++, deviceStatus);
}
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);
}
}
} 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 devices;
}
} }

@ -245,5 +245,4 @@ public final class DeviceManagementDAOUtil {
deviceInfo.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP"))); deviceInfo.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP")));
return deviceInfo; return deviceInfo;
} }
} }

@ -31,6 +31,7 @@ import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagement
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
import org.wso2.carbon.device.mgt.common.report.mgt.ReportManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService; import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
@ -55,6 +56,7 @@ import org.wso2.carbon.device.mgt.core.privacy.PrivacyComplianceProvider;
import org.wso2.carbon.device.mgt.core.privacy.impl.PrivacyComplianceProviderImpl; import org.wso2.carbon.device.mgt.core.privacy.impl.PrivacyComplianceProviderImpl;
import org.wso2.carbon.device.mgt.core.push.notification.mgt.PushNotificationProviderRepository; import org.wso2.carbon.device.mgt.core.push.notification.mgt.PushNotificationProviderRepository;
import org.wso2.carbon.device.mgt.core.push.notification.mgt.task.PushNotificationSchedulerTask; import org.wso2.carbon.device.mgt.core.push.notification.mgt.task.PushNotificationSchedulerTask;
import org.wso2.carbon.device.mgt.core.report.mgt.ReportManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
@ -295,6 +297,10 @@ public class DeviceManagementServiceComponent {
= new NotificationManagementServiceImpl(); = new NotificationManagementServiceImpl();
bundleContext.registerService(NotificationManagementService.class.getName(), notificationManagementService, null); bundleContext.registerService(NotificationManagementService.class.getName(), notificationManagementService, null);
/* Registering Report Service */
ReportManagementService reportManagementService = new ReportManagementServiceImpl();
bundleContext.registerService(ReportManagementService.class.getName(), reportManagementService, null);
/* Registering DeviceAccessAuthorization Service */ /* Registering DeviceAccessAuthorization Service */
DeviceAccessAuthorizationService deviceAccessAuthorizationService = new DeviceAccessAuthorizationServiceImpl(); DeviceAccessAuthorizationService deviceAccessAuthorizationService = new DeviceAccessAuthorizationServiceImpl();
DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(deviceAccessAuthorizationService); DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(deviceAccessAuthorizationService);

@ -0,0 +1,88 @@
/*
* Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.report.mgt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.exceptions.ReportManagementException;
import org.wso2.carbon.device.mgt.common.report.mgt.ReportManagementService;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import java.sql.SQLException;
import java.util.List;
/**
* This is the service class for reports which calls dao classes and its method which are used for
* report generation tasks.
*/
public class ReportManagementServiceImpl implements ReportManagementService {
private static final Log log = LogFactory.getLog(ReportManagementServiceImpl.class);
private DeviceDAO deviceDAO;
public ReportManagementServiceImpl() {
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
}
@Override
public PaginationResult getDevicesByDuration(PaginationRequest request, String fromDate,
String toDate)
throws ReportManagementException {
PaginationResult paginationResult = new PaginationResult();
try {
request = DeviceManagerUtil.validateDeviceListPageSize(request);
} catch (DeviceManagementException e) {
String msg = "Error occurred while validating device list page size";
log.error(msg, e);
throw new ReportManagementException(msg, e);
}
try {
DeviceManagementDAOFactory.openConnection();
List<Device> devices = deviceDAO.getDevicesByDuration(
request,
DeviceManagementDAOUtil.getTenantId(),
fromDate,
toDate
);
paginationResult.setData(devices);
//TODO: Should change the following code to a seperate count method from deviceDAO to get the count
paginationResult.setRecordsTotal(devices.size());
return paginationResult;
} catch (SQLException e) {
String msg = "Error occurred while opening a connection " +
"to the data source";
log.error(msg, e);
throw new ReportManagementException(msg, e);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving Tenant ID";
log.error(msg, e);
throw new ReportManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
}
Loading…
Cancel
Save