Improve billing feature

Co-authored-by: Oshani Silva <oshani@entgra.io>
Co-committed-by: Oshani Silva <oshani@entgra.io>
master
Oshani Silva 2 years ago committed by Lasantha Dharmakeerthi
parent ad111a3999
commit a93f534e06

@ -35,8 +35,11 @@ public class DeviceList extends BasePaginatedResult {
@ApiModelProperty(name = "message", value = "Send information text to the billing UI", required = false) @ApiModelProperty(name = "message", value = "Send information text to the billing UI", required = false)
private String message; private String message;
@ApiModelProperty(name = "billedDateIsValid", value = "Check if user entered date is valid", required = false) @ApiModelProperty(name = "deviceCount", value = "Total count of all devices per tenant", required = false)
private boolean billedDateIsValid; private double deviceCount;
@ApiModelProperty(name = "billPeriod", value = "Billed period", required = false)
private String billPeriod;
@ApiModelProperty(value = "List of devices returned") @ApiModelProperty(value = "List of devices returned")
@JsonProperty("devices") @JsonProperty("devices")
@ -48,12 +51,20 @@ public class DeviceList extends BasePaginatedResult {
this.devices = devices; this.devices = devices;
} }
public boolean isBilledDateIsValid() { public String getBillPeriod() {
return billedDateIsValid; return billPeriod;
}
public void setBillPeriod(String billPeriod) {
this.billPeriod = billPeriod;
}
public double getDeviceCount() {
return deviceCount;
} }
public void setBilledDateIsValid(boolean billedDateIsValid) { public void setDeviceCount(double deviceCount) {
this.billedDateIsValid = billedDateIsValid; this.deviceCount = deviceCount;
} }
public String getMessage() { public String getMessage() {

@ -344,179 +344,6 @@ public interface DeviceManagementService {
@QueryParam("limit") @QueryParam("limit")
int limit); int limit);
@GET
@Path("/billing")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Cost details of devices in a tenant",
notes = "Provides individual cost and total cost of all devices per tenant.",
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 = 304,
message = "Not Modified. \n Empty body because the client already has the latest version of " +
"the requested resource.\n"),
@ApiResponse(
code = 400,
message = "The incoming request has more than one selection criteria defined via the query parameters.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "The search criteria did not match any device registered with the server.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the device list.",
response = ErrorResponse.class)
})
Response getDevicesBilling(
@ApiParam(
name = "tenantDomain",
value = "The tenant domain.",
required = false)
@QueryParam("tenantDomain")
String tenantDomain,
@ApiParam(
name = "startDate",
value = "The start date.",
required = false)
@QueryParam("startDate")
Timestamp startDate,
@ApiParam(
name = "endDate",
value = "The end date.",
required = false)
@QueryParam("endDate")
Timestamp endDate,
@ApiParam(
name = "generateBill",
value = "The generate bill boolean.",
required = false)
@QueryParam("generateBill")
boolean generateBill,
@ApiParam(
name = "offset",
value = "The starting pagination index for the complete list of qualified items.",
required = false,
defaultValue = "0")
@QueryParam("offset")
int offset,
@ApiParam(
name = "limit",
value = "Provide how many device details you require from the starting pagination index/offset.",
required = false,
defaultValue = "10")
@QueryParam("limit")
int limit);
@GET
@Path("/billing/file")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Cost details of devices in a tenant",
notes = "Provides individual cost and total cost of all devices per tenant.",
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 = "Content-Disposition",
description = "The content disposition of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client already has the latest version of " +
"the requested resource.\n"),
@ApiResponse(
code = 400,
message = "The incoming request has more than one selection criteria defined via the query parameters.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "The search criteria did not match any device registered with the server.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the device list.",
response = ErrorResponse.class)
})
Response exportBilling(
@ApiParam(
name = "tenantDomain",
value = "The tenant domain.",
required = false)
@QueryParam("tenantDomain")
String tenantDomain,
@ApiParam(
name = "startDate",
value = "The start date.",
required = false)
@QueryParam("startDate")
Timestamp startDate,
@ApiParam(
name = "endDate",
value = "The end date.",
required = false)
@QueryParam("endDate")
Timestamp endDate,
@ApiParam(
name = "generateBill",
value = "The generate bill boolean.",
required = false)
@QueryParam("generateBill")
boolean generateBill);
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ApiOperation( @ApiOperation(

@ -65,6 +65,7 @@ import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.sql.Timestamp;
import java.util.List; import java.util.List;
@SwaggerDefinition( @SwaggerDefinition(
@ -110,7 +111,14 @@ import java.util.List;
key = "perm:devices:permanent-delete", key = "perm:devices:permanent-delete",
roles = {"Internal/devicemgt-admin"}, roles = {"Internal/devicemgt-admin"},
permissions = {"/device-mgt/admin/devices/permanent-delete"} permissions = {"/device-mgt/admin/devices/permanent-delete"}
) ),
@Scope(
name = "Get Usage of Devices",
description = "Get Usage of Devices",
key = "perm:admin:usage:view",
roles = {"Internal/devicemgt-admin"},
permissions = {"/device-mgt/admin/devices/usage/view"}
),
} }
) )
public interface DeviceManagementAdminService { public interface DeviceManagementAdminService {
@ -423,4 +431,78 @@ public interface DeviceManagementAdminService {
List<String> actions List<String> actions
); );
@GET
@Path("/billing")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Cost details of devices in a tenant",
notes = "Provides individual cost and total cost of all devices per tenant.",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:usage: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 = "Content-Disposition",
description = "The content disposition of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client already has the latest version of " +
"the requested resource.\n"),
@ApiResponse(
code = 400,
message = "The incoming request has more than one selection criteria defined via the query parameters.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "The search criteria did not match any device registered with the server.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the device list.",
response = ErrorResponse.class)
})
Response getBilling(
@ApiParam(
name = "tenantDomain",
value = "The tenant domain.",
required = false)
@QueryParam("tenantDomain")
String tenantDomain,
@ApiParam(
name = "startDate",
value = "The start date.",
required = false)
@QueryParam("startDate")
Timestamp startDate,
@ApiParam(
name = "endDate",
value = "The end date.",
required = false)
@QueryParam("endDate")
Timestamp endDate);
} }

@ -355,105 +355,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
} }
} }
@GET
@Override
@Path("/billing")
public Response getDevicesBilling(
@QueryParam("tenantDomain") String tenantDomain,
@QueryParam("startDate") Timestamp startDate,
@QueryParam("endDate") Timestamp endDate,
@QueryParam("generateBill") boolean generateBill,
@QueryParam("offset") int offset,
@DefaultValue("10")
@QueryParam("limit") int limit) {
try {
RequestValidationUtil.validatePaginationParameters(offset, limit);
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
PaginationRequest request = new PaginationRequest(offset, limit);
PaginationResult result;
DeviceList devices = new DeviceList();
int tenantId = 0;
RealmService realmService = DeviceMgtAPIUtils.getRealmService();
if (!tenantDomain.isEmpty()) {
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
} else {
tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
}
try {
result = dms.getAllDevicesBillings(request, tenantId, tenantDomain, startDate, endDate, generateBill);
} catch (Exception exception) {
String msg = "Error occurred when trying to retrieve billing data";
log.error(msg, exception);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
int resultCount = result.getRecordsTotal();
if (resultCount == 0) {
Response.status(Response.Status.OK).entity(devices).build();
}
devices.setList((List<Device>) result.getData());
devices.setBilledDateIsValid(result.isBilledDateIsValid());
devices.setMessage(result.getMessage());
devices.setCount(result.getRecordsTotal());
devices.setTotalCost(result.getTotalCost());
return Response.status(Response.Status.OK).entity(devices).build();
} catch (Exception e) {
String msg = "Error occurred while retrieving billing data";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@GET
@Override
@Path("/billing/file")
public Response exportBilling(
@QueryParam("tenantDomain") String tenantDomain,
@QueryParam("startDate") Timestamp startDate,
@QueryParam("endDate") Timestamp endDate,
@QueryParam("generateBill") boolean generateBill) {
try {
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
PaginationResult result;
int tenantId = 0;
RealmService realmService = DeviceMgtAPIUtils.getRealmService();
DeviceList devices = new DeviceList();
if (!tenantDomain.isEmpty()) {
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
} else {
tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
}
try {
result = dms.createBillingFile(tenantId, tenantDomain, startDate, endDate, generateBill);
} catch (Exception exception) {
String msg = "Error occurred when trying to retrieve billing data without pagination";
log.error(msg, exception);
return null;
}
devices.setList((List<Device>) result.getData());
devices.setBilledDateIsValid(result.isBilledDateIsValid());
devices.setMessage(result.getMessage());
devices.setCount(result.getRecordsTotal());
devices.setTotalCost(result.getTotalCost());
return Response.status(Response.Status.OK).entity(devices).build();
} catch (Exception e) {
String msg = "Error occurred while retrieving billing data without pagination";
log.error(msg, e);
return null;
}
}
@GET @GET
@Override @Override
@Path("/user-devices") @Path("/user-devices")

@ -52,12 +52,15 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.exceptions.UserNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.UserNotFoundException;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; 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.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService;
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.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
@ -71,6 +74,7 @@ import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.sql.Timestamp;
import java.util.List; import java.util.List;
@Path("/admin/devices") @Path("/admin/devices")
@ -147,7 +151,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
@Path("/device-owner") @Path("/device-owner")
public Response updateEnrollOwner( public Response updateEnrollOwner(
@QueryParam("owner") String owner, @QueryParam("owner") String owner,
List<String> deviceIdentifiers){ List<String> deviceIdentifiers) {
try { try {
if (DeviceMgtAPIUtils.getDeviceManagementService().updateEnrollment(owner, true, deviceIdentifiers)) { if (DeviceMgtAPIUtils.getDeviceManagementService().updateEnrollment(owner, true, deviceIdentifiers)) {
String msg = "Device owner is updated successfully."; String msg = "Device owner is updated successfully.";
@ -190,8 +194,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} } catch (InvalidDeviceException e) {
catch (InvalidDeviceException e) {
String msg = "Found Invalid devices"; String msg = "Found Invalid devices";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity( return Response.status(Response.Status.BAD_REQUEST).entity(
@ -205,7 +208,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
public Response triggerCorrectiveActions( public Response triggerCorrectiveActions(
@PathParam("deviceId") String deviceIdentifier, @PathParam("deviceId") String deviceIdentifier,
@PathParam("featureCode") String featureCode, @PathParam("featureCode") String featureCode,
List<String> actions){ List<String> actions) {
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
PlatformConfigurationManagementService platformConfigurationManagementService = DeviceMgtAPIUtils PlatformConfigurationManagementService platformConfigurationManagementService = DeviceMgtAPIUtils
.getPlatformConfigurationManagementService(); .getPlatformConfigurationManagementService();
@ -233,4 +236,51 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
} }
return Response.status(Response.Status.OK).entity("Triggered action successfully").build(); return Response.status(Response.Status.OK).entity("Triggered action successfully").build();
} }
@GET
@Override
@Path("/billing")
public Response getBilling(
@QueryParam("tenantDomain") String tenantDomain,
@QueryParam("startDate") Timestamp startDate,
@QueryParam("endDate") Timestamp endDate) {
try {
PaginationResult result;
int tenantId = 0;
RealmService realmService = DeviceMgtAPIUtils.getRealmService();
int tenantIdContext = CarbonContext.getThreadLocalCarbonContext().getTenantId();
if (!tenantDomain.isEmpty()) {
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
}
if (tenantIdContext != MultitenantConstants.SUPER_TENANT_ID && tenantIdContext != tenantId) {
String msg = "Current logged in user is not authorized to access billing details of other tenants";
log.error(msg);
return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build();
} else {
DeviceList devices = new DeviceList();
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
result = dms.createBillingFile(tenantId, tenantDomain, startDate, endDate);
devices.setList((List<Device>) result.getData());
devices.setDeviceCount(result.getTotalDeviceCount());
devices.setMessage(result.getMessage());
devices.setTotalCost(result.getTotalCost());
devices.setBillPeriod(startDate.toString() + " - " + endDate.toString());
return Response.status(Response.Status.OK).entity(devices).build();
}
} catch (BadRequestException e) {
String msg = "Bad request, can't proceed. Hence verify the request and re-try";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving billing data";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (UserStoreException e) {
String msg = "Error occurred while processing tenant configuration.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
} }

@ -0,0 +1,123 @@
/*
* Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.List;
@ApiModel(value = "BillingResponse", description = "This class carries all information related to a billing response.")
public class BillingResponse implements Serializable {
private static final long serialVersionUID = 1998101711L;
@ApiModelProperty(name = "year", value = "Year of the billed period",
required = false)
private String year;
@ApiModelProperty(name = "totalCostPerYear", value = "Bill for a period of year", required = false)
private double totalCostPerYear;
@ApiModelProperty(name = "devices", value = "Billed list of devices per year", required = false)
private List<Device> device;
@ApiModelProperty(name = "billPeriod", value = "Billed period", required = false)
private String billPeriod;
@ApiModelProperty(name = "startDate", value = "Start Date of period", required = false)
private String startDate;
@ApiModelProperty(name = "endDate", value = "End Date of period", required = false)
private String endDate;
@ApiModelProperty(name = "deviceCount", value = "Device count for a billing period",
required = false)
private int deviceCount;
public BillingResponse() {
}
public BillingResponse(String year, double totalCostPerYear, List<Device> device, String billPeriod, String startDate, String endDate, int deviceCount) {
this.year = year;
this.totalCostPerYear = totalCostPerYear;
this.device = device;
this.billPeriod = billPeriod;
this.startDate = startDate;
this.endDate = endDate;
this.deviceCount = deviceCount;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public double getTotalCostPerYear() {
return totalCostPerYear;
}
public void setTotalCostPerYear(double totalCostPerYear) {
this.totalCostPerYear = totalCostPerYear;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public List<Device> getDevice() {
return device;
}
public void setDevice(List<Device> device) {
this.device = device;
}
public String getBillPeriod() {
return billPeriod;
}
public void setBillPeriod(String billPeriod) {
this.billPeriod = billPeriod;
}
public int getDeviceCount() {
return deviceCount;
}
public void setDeviceCount(int deviceCount) {
this.deviceCount = deviceCount;
}
}

@ -47,18 +47,29 @@ public class PaginationResult implements Serializable {
@ApiModelProperty(name = "totalCost", value = "Total cost of all devices per tenant", required = false) @ApiModelProperty(name = "totalCost", value = "Total cost of all devices per tenant", required = false)
private double totalCost; private double totalCost;
@ApiModelProperty(name = "billedDateIsValid", value = "Check if user entered date is valid", required = false) @ApiModelProperty(name = "totalDeviceCount", value = "Total count of all devices per tenant", required = false)
private boolean billedDateIsValid; private double totalDeviceCount;
@ApiModelProperty(name = "billPeriod", value = "Billed period", required = false)
private String billPeriod;
@ApiModelProperty(name = "message", value = "Send information text to the billing UI", required = false) @ApiModelProperty(name = "message", value = "Send information text to the billing UI", required = false)
private String message; private String message;
public boolean isBilledDateIsValid() { public String getBillPeriod() {
return billedDateIsValid; return billPeriod;
}
public void setBillPeriod(String billPeriod) {
this.billPeriod = billPeriod;
}
public double getTotalDeviceCount() {
return totalDeviceCount;
} }
public void setBilledDateIsValid(boolean billedDateIsValid) { public void setTotalDeviceCount(double totalDeviceCount) {
this.billedDateIsValid = billedDateIsValid; this.totalDeviceCount = totalDeviceCount;
} }
public String getMessage() { public String getMessage() {

@ -44,6 +44,7 @@ public final class DeviceManagementConstants {
public static final String DEVICE_CACHE = "DEVICE_CACHE"; public static final String DEVICE_CACHE = "DEVICE_CACHE";
public static final String API_RESOURCE_PERMISSION_CACHE = "API_RESOURCE_CACHE_CACHE"; public static final String API_RESOURCE_PERMISSION_CACHE = "API_RESOURCE_CACHE_CACHE";
public static final String GEOFENCE_CACHE = "GEOFENCE_CACHE"; public static final String GEOFENCE_CACHE = "GEOFENCE_CACHE";
public static final String BILLING_CACHE = "BILLING_CACHE";
public static final String META_KEY = "PER_DEVICE_COST"; public static final String META_KEY = "PER_DEVICE_COST";
public static final String ACTIVE_STATUS = "ACTIVE"; public static final String ACTIVE_STATUS = "ACTIVE";
public static final String ENROLLMENT_NOTIFICATION_API_ENDPOINT = "/api/device-mgt/enrollment-notification"; public static final String ENROLLMENT_NOTIFICATION_API_ENDPOINT = "/api/device-mgt/enrollment-notification";

@ -0,0 +1,79 @@
/*
* Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.cache;
import java.sql.Timestamp;
import java.util.Objects;
public class BillingCacheKey {
private String tenantDomain;
private Timestamp startDate;
private Timestamp endDate;
private volatile int hashCode;
public String getTenantDomain() {
return tenantDomain;
}
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
public Timestamp getStartDate() {
return startDate;
}
public void setStartDate(Timestamp startDate) {
this.startDate = startDate;
}
public Timestamp getEndDate() {
return endDate;
}
public void setEndDate(Timestamp endDate) {
this.endDate = endDate;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!BillingCacheKey.class.isAssignableFrom(obj.getClass())) {
return false;
}
final BillingCacheKey other = (BillingCacheKey) obj;
String thisId = this.tenantDomain + "_" + this.startDate + "_" + this.endDate;
String otherId = other.tenantDomain + "_" + other.startDate + "_" + this.endDate;
if (!thisId.equals(otherId)) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (hashCode == 0) {
hashCode = Objects.hash(tenantDomain, startDate, endDate);
}
return hashCode;
}
}

@ -0,0 +1,73 @@
/*
* Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.cache;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import java.sql.Timestamp;
import java.util.List;
public interface BillingCacheManager {
/**
* Adds a given billing object to the billing-cache.
* @param startDate - startDate of the billing period.
* @param endDate - endDate of the billing period.
* @param paginationResult - PaginationResult object to be added.
* @param tenantDomain - Owning tenant of the billing.
*
*/
void addBillingToCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException;
/**
* Removes a billing object from billing-cache.
* @param startDate - startDate of the billing period.
* @param endDate - endDate of the billing period.
* @param tenantDomain - Owning tenant of the billing.
*
*/
void removeBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException;
/**
* Removes a list of devices from billing-cache.
* @param billingList - List of Cache-Keys of the billing objects to be removed.
*
*/
void removeBillingsFromCache(List<BillingCacheKey> billingList) throws DeviceManagementException;
/**
* Updates a given billing object in the billing-cache.
* @param startDate - startDate of the billing period.
* @param endDate - endDate of the billing period.
* @param paginationResult - PaginationResult object to be updated.
* @param tenantDomain - Owning tenant of the billing.
*
*/
void updateBillingInCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException;
/**
* Fetches a billing object from billing-cache.
* @param startDate - startDate of the billing period.
* @param endDate - endDate of the billing period.
* @param tenantDomain - Owning tenant of the billing.
* @return Device object
*
*/
PaginationResult getBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate);
}

@ -0,0 +1,135 @@
/*
* Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.cache.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.cache.BillingCacheKey;
import org.wso2.carbon.device.mgt.core.cache.BillingCacheManager;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import javax.cache.Cache;
import java.sql.Timestamp;
import java.util.List;
/**
* Implementation of BillingCacheManager.
*/
public class BillingCacheManagerImpl implements BillingCacheManager {
private static final Log log = LogFactory.getLog(BillingCacheManagerImpl.class);
private static BillingCacheManagerImpl billingCacheManager;
private BillingCacheManagerImpl() {
}
public static BillingCacheManagerImpl getInstance() {
if (billingCacheManager == null) {
synchronized (BillingCacheManagerImpl.class) {
if (billingCacheManager == null) {
billingCacheManager = new BillingCacheManagerImpl();
}
}
}
return billingCacheManager;
}
@Override
public void addBillingToCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException {
Cache<BillingCacheKey, PaginationResult> lCache = DeviceManagerUtil.getBillingCache();
if (lCache != null) {
BillingCacheKey cacheKey = getCacheKey(tenantDomain, startDate, endDate);
if (lCache.containsKey(cacheKey)) {
this.updateBillingInCache(paginationResult, tenantDomain, startDate, endDate);
} else {
lCache.put(cacheKey, paginationResult);
}
}
}
@Override
public void removeBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException {
Cache<BillingCacheKey, PaginationResult> lCache = DeviceManagerUtil.getBillingCache();
if (lCache != null) {
BillingCacheKey cacheKey = getCacheKey(tenantDomain, startDate, endDate);
if (lCache.containsKey(cacheKey)) {
lCache.remove(cacheKey);
}
} else {
String msg = "Failed to remove selected billing from cache";
log.error(msg);
throw new DeviceManagementException(msg);
}
}
@Override
public void removeBillingsFromCache(List<BillingCacheKey> billingList) throws DeviceManagementException {
Cache<BillingCacheKey, PaginationResult> lCache = DeviceManagerUtil.getBillingCache();
if (lCache != null) {
for (BillingCacheKey cacheKey : billingList) {
if (lCache.containsKey(cacheKey)) {
lCache.remove(cacheKey);
}
}
} else {
String msg = "Failed to remove billing from cache";
log.error(msg);
throw new DeviceManagementException(msg);
}
}
@Override
public void updateBillingInCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException {
Cache<BillingCacheKey, PaginationResult> lCache = DeviceManagerUtil.getBillingCache();
if (lCache != null) {
BillingCacheKey cacheKey = getCacheKey(tenantDomain, startDate, endDate);
if (lCache.containsKey(cacheKey)) {
lCache.replace(cacheKey, paginationResult);
}
} else {
String msg = "Failed to update billing cache";
log.error(msg);
throw new DeviceManagementException(msg);
}
}
// TODO remove null check from here and do cache enable check in the methods calling this
@Override
public PaginationResult getBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate) {
Cache<BillingCacheKey, PaginationResult> lCache = DeviceManagerUtil.getBillingCache();
if (lCache != null) {
return lCache.get(getCacheKey(tenantDomain, startDate, endDate));
}
return null;
}
/**
* This method generates the billing CacheKey and returns it.
*/
private BillingCacheKey getCacheKey(String tenantDomain, Timestamp startDate, Timestamp endDate) {
BillingCacheKey billingCacheKey = new BillingCacheKey();
billingCacheKey.setTenantDomain(tenantDomain);
billingCacheKey.setStartDate(startDate);
billingCacheKey.setEndDate(endDate);
return billingCacheKey;
}
}

@ -21,6 +21,7 @@ import org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotif
import org.wso2.carbon.device.mgt.common.roles.config.DefaultRoles; import org.wso2.carbon.device.mgt.common.roles.config.DefaultRoles;
import org.wso2.carbon.device.mgt.core.config.analytics.OperationAnalyticsConfiguration; import org.wso2.carbon.device.mgt.core.config.analytics.OperationAnalyticsConfiguration;
import org.wso2.carbon.device.mgt.core.config.archival.ArchivalConfiguration; import org.wso2.carbon.device.mgt.core.config.archival.ArchivalConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.BillingCacheConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.CertificateCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.CertificateCacheConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.GeoFenceCacheConfiguration; import org.wso2.carbon.device.mgt.core.config.cache.GeoFenceCacheConfiguration;
@ -58,6 +59,7 @@ public final class DeviceManagementConfig {
private DeviceStatusTaskConfig deviceStatusTaskConfig; private DeviceStatusTaskConfig deviceStatusTaskConfig;
private DeviceCacheConfiguration deviceCacheConfiguration; private DeviceCacheConfiguration deviceCacheConfiguration;
private GeoFenceCacheConfiguration geoFenceCacheConfiguration; private GeoFenceCacheConfiguration geoFenceCacheConfiguration;
private BillingCacheConfiguration billingCacheConfiguration;
private EventOperationTaskConfiguration eventOperationTaskConfiguration; private EventOperationTaskConfiguration eventOperationTaskConfiguration;
private CertificateCacheConfiguration certificateCacheConfiguration; private CertificateCacheConfiguration certificateCacheConfiguration;
private OperationAnalyticsConfiguration operationAnalyticsConfiguration; private OperationAnalyticsConfiguration operationAnalyticsConfiguration;
@ -169,6 +171,15 @@ public final class DeviceManagementConfig {
this.geoFenceCacheConfiguration = geoFenceCacheConfiguration; this.geoFenceCacheConfiguration = geoFenceCacheConfiguration;
} }
@XmlElement(name = "BillingCacheConfiguration", required = true)
public BillingCacheConfiguration getBillingCacheConfiguration() {
return billingCacheConfiguration;
}
public void setBillingCacheConfiguration(BillingCacheConfiguration billingCacheConfiguration) {
this.billingCacheConfiguration = billingCacheConfiguration;
}
@XmlElement(name = "EventOperationTaskConfiguration", required = true) @XmlElement(name = "EventOperationTaskConfiguration", required = true)
public EventOperationTaskConfiguration getEventOperationTaskConfiguration() { public EventOperationTaskConfiguration getEventOperationTaskConfiguration() {
return eventOperationTaskConfiguration; return eventOperationTaskConfiguration;

@ -0,0 +1,56 @@
/*
* Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.config.cache;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "BillingCacheConfiguration")
public class BillingCacheConfiguration {
private boolean isEnabled;
private int expiryTime;
private long capacity;
@XmlElement(name = "Enable", required = true)
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean enabled) {
isEnabled = enabled;
}
@XmlElement(name = "ExpiryTime", required = true)
public int getExpiryTime() {
return expiryTime;
}
public void setExpiryTime(int expiryTime) {
this.expiryTime = expiryTime;
}
@XmlElement(name = "Capacity", required = true)
public long getCapacity() {
return capacity;
}
public void setCapacity(long capacity) {
this.capacity = capacity;
}
}

@ -1,13 +0,0 @@
package org.wso2.carbon.device.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.Billing;
import java.sql.Timestamp;
import java.util.List;
public interface BillingDAO {
void addBilling(int deviceId, int tenantId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException;
List<Billing> getBilling(int deviceId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException;
}

@ -293,6 +293,50 @@ public interface DeviceDAO {
*/ */
List<Device> getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; List<Device> getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve the not removed device list in a year of a given tenant without pagination.
*
* @param tenantId tenant id.
* @param startDate start date of usage period.
* @param endDate end date of usage period.
* @return returns a list of not removed devices enrolled in that year.
* @throws DeviceManagementDAOException
*/
List<Device> getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException;
/**
* This method is used to retrieve the removed device list in a year of a given tenant without pagination.
*
* @param tenantId tenant id.
* @param startDate start date of usage period.
* @param endDate end date of usage period.
* @return returns a list of removed devices enrolled in that year.
* @throws DeviceManagementDAOException
*/
List<Device> getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException;
/**
* This method is used to retrieve the not removed device list in the prior year of a given tenant without pagination.
*
* @param tenantId tenant id.
* @param startDate start date of usage period.
* @param endDate end date of usage period.
* @return returns a list of not removed devices enrolled prior to that year.
* @throws DeviceManagementDAOException
*/
List<Device> getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException;
/**
* This method is used to retrieve the removed device list in the prior year of a given tenant without pagination.
*
* @param tenantId tenant id.
* @param startDate start date of usage period.
* @param endDate end date of usage period.
* @return returns a list of removed devices enrolled prior to that year.
* @throws DeviceManagementDAOException
*/
List<Device> getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException;
/** /**
* This method is used to retrieve the devices of a given tenant without pagination. * This method is used to retrieve the devices of a given tenant without pagination.
* @param tenantId tenant id. * @param tenantId tenant id.

@ -125,11 +125,6 @@ public class DeviceManagementDAOFactory {
return new EnrollmentDAOImpl(); return new EnrollmentDAOImpl();
} }
public static BillingDAO getBillingDAO() {
return new BillingDAOImpl();
}
public static TrackerDAO getTrackerDAO() { public static TrackerDAO getTrackerDAO() {
if (databaseEngine != null) { if (databaseEngine != null) {
switch (databaseEngine) { switch (databaseEngine) {

@ -33,8 +33,6 @@ public interface EnrollmentDAO {
boolean updateEnrollmentStatus(List<EnrolmentInfo> enrolmentInfos) throws DeviceManagementDAOException; boolean updateEnrollmentStatus(List<EnrolmentInfo> enrolmentInfos) throws DeviceManagementDAOException;
boolean updateEnrollmentLastBilledDate(EnrolmentInfo enrolmentInfos, Timestamp lastBilledDate, int tenantId) throws DeviceManagementDAOException;
int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException; int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException;
@Deprecated @Deprecated

@ -1,71 +0,0 @@
package org.wso2.carbon.device.mgt.core.dao.impl;
import org.wso2.carbon.device.mgt.common.Billing;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.core.dao.BillingDAO;
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 java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BillingDAOImpl implements BillingDAO {
@Override
public void addBilling(int deviceId, int tenantId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getConnection();
String sql = "INSERT INTO DM_BILLING(DEVICE_ID, TENANT_ID, BILLING_START, BILLING_END) VALUES(?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, new String[] {"invoice_id"});
stmt.setInt(1, deviceId);
stmt.setInt(2,tenantId);
stmt.setTimestamp(3, billingStart);
stmt.setTimestamp(4, billingEnd);
stmt.execute();
} catch (SQLException e) {
e.printStackTrace();
throw new DeviceManagementDAOException("Error occurred while adding billing period", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public List<Billing> getBilling(int deviceId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException {
List<Billing> billings = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
EnrolmentInfo.Status status = null;
try {
conn = this.getConnection();
String sql;
sql = "SELECT * FROM DM_BILLING WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
rs = stmt.executeQuery();
while (rs.next()) {
Billing bill = new Billing(rs.getInt("INVOICE_ID"), rs.getInt("DEVICE_ID"),rs.getInt("TENANT_ID"),
(rs.getTimestamp("BILLING_START").getTime()), (rs.getTimestamp("BILLING_END").getTime()));
billings.add(bill);
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred getting billing periods", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return billings;
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}
}

@ -25,13 +25,7 @@ public class DeviceStatusDAOImpl implements DeviceStatusDAO {
conn = this.getConnection(); conn = this.getConnection();
// either we list all status values for the device using the device id or only get status values for the given enrolment id // either we list all status values for the device using the device id or only get status values for the given enrolment id
String idType = isDeviceId ? "DEVICE_ID" : "ENROLMENT_ID"; String idType = isDeviceId ? "DEVICE_ID" : "ENROLMENT_ID";
String sql; String sql = "SELECT ENROLMENT_ID, DEVICE_ID, UPDATE_TIME, STATUS, CHANGED_BY FROM DM_DEVICE_STATUS WHERE " + idType + " = ?";
if (billingStatus) {
sql = "SELECT ENROLMENT_ID, DEVICE_ID, UPDATE_TIME, STATUS, CHANGED_BY FROM DM_DEVICE_STATUS WHERE STATUS IN ('ACTIVE','REMOVED') AND " + idType + " = ?";
} else {
sql = "SELECT ENROLMENT_ID, DEVICE_ID, UPDATE_TIME, STATUS, CHANGED_BY FROM DM_DEVICE_STATUS WHERE " + idType + " = ?";
}
// filter the data based on a date range if specified // filter the data based on a date range if specified
if (fromDate != null){ if (fromDate != null){
@ -41,6 +35,10 @@ public class DeviceStatusDAOImpl implements DeviceStatusDAO {
sql += " AND UPDATE_TIME <= ?"; sql += " AND UPDATE_TIME <= ?";
} }
if (billingStatus) {
sql += " ORDER BY UPDATE_TIME DESC";
}
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
int i = 1; int i = 1;

@ -144,28 +144,6 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
return status; return status;
} }
@Override
public boolean updateEnrollmentLastBilledDate(EnrolmentInfo enrolmentInfo, Timestamp lastBilledDate, int tenantId) throws DeviceManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getConnection();
String sql = "UPDATE DM_ENROLMENT SET LAST_BILLED_DATE = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setLong(1, lastBilledDate.getTime());
stmt.setInt(2, enrolmentInfo.getId());
stmt.setInt(3, tenantId);
stmt.executeUpdate();
return true;
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while updating enrolment last billed date.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override @Override
public int removeEnrollment(int deviceId, String currentOwner, public int removeEnrollment(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException { int tenantId) throws DeviceManagementDAOException {

@ -84,7 +84,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"e.IS_TRANSFERRED, " + "e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " + "e.DATE_OF_ENROLMENT, " +
"e.LAST_BILLED_DATE, " +
"e.ID AS ENROLMENT_ID " + "e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " + "FROM DM_ENROLMENT e, " +
"(SELECT d.ID, " + "(SELECT d.ID, " +
@ -188,6 +187,169 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
} }
@Override
public List<Device> getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
List<Device> devices = new ArrayList<>();
try {
Connection conn = getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, " +
"DEVICE_IDENTIFICATION, " +
"DESCRIPTION, " +
"NAME, " +
"DATE_OF_ENROLMENT, " +
"STATUS, " +
"DATE_OF_LAST_UPDATE, " +
"TIMESTAMPDIFF(DAY, ?, DATE_OF_ENROLMENT) as DAYS_SINCE_ENROLLED " +
"FROM DM_DEVICE d, DM_ENROLMENT e " +
"WHERE " +
"e.TENANT_ID=? AND " +
"d.ID=e.DEVICE_ID AND " +
"STATUS !='REMOVED' AND " +
"(" +
"DATE_OF_ENROLMENT BETWEEN ? AND ? " +
")";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, String.valueOf(endDate));
stmt.setInt(2, tenantId);
stmt.setString(3, String.valueOf(startDate));
stmt.setString(4, String.valueOf(endDate));
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs));
}
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of NonRemovedYearly device billing ", e);
}
return devices;
}
@Override
public List<Device> getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
Connection conn;
List<Device> devices = new ArrayList<>();
try {
conn = this.getConnection();
String sql = "select d.ID AS DEVICE_ID, " +
"DEVICE_IDENTIFICATION, " +
"DESCRIPTION, " +
"NAME, " +
"DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, " +
"STATUS, " +
"TIMESTAMPDIFF(DAY, DATE_OF_LAST_UPDATE, DATE_OF_ENROLMENT) AS DAYS_USED " +
"from DM_DEVICE d, DM_ENROLMENT e " +
"where " +
"e.TENANT_ID=? and d.ID=e.DEVICE_ID and " +
"STATUS ='REMOVED' and " +
"(" +
"DATE_OF_ENROLMENT between ? and ? " +
") and " +
"(" +
"DATE_OF_LAST_UPDATE >= ? " +
")";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, tenantId);
stmt.setString(2, String.valueOf(startDate));
stmt.setString(3, String.valueOf(endDate));
stmt.setString(4, String.valueOf(startDate));
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs));
}
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of RemovedYearly device billing ", e);
}
return devices;
}
@Override
public List<Device> getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
Connection conn;
List<Device> devices = new ArrayList<>();
try {
conn = this.getConnection();
String sql = "select d.ID AS DEVICE_ID, " +
"DEVICE_IDENTIFICATION, " +
"DESCRIPTION, " +
"NAME, " +
"DATE_OF_ENROLMENT, " +
"STATUS, " +
"DATE_OF_LAST_UPDATE, " +
"TIMESTAMPDIFF(DAY, ?, ?) as DAYS_SINCE_ENROLLED " +
"from DM_DEVICE d, DM_ENROLMENT e " +
"where " +
"e.TENANT_ID=? and " +
"d.ID=e.DEVICE_ID and " +
"STATUS !='REMOVED' and " +
"(" +
"DATE_OF_ENROLMENT < ? " +
")";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, String.valueOf(endDate));
stmt.setString(2, String.valueOf(startDate));
stmt.setInt(3, tenantId);
stmt.setString(4, String.valueOf(startDate));
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs));
}
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of NonRemovedPriorYears device billing ", e);
}
return devices;
}
@Override
public List<Device> getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
Connection conn;
List<Device> devices = new ArrayList<>();
try {
conn = this.getConnection();
String sql = "select d.ID AS DEVICE_ID, " +
"DEVICE_IDENTIFICATION, " +
"DESCRIPTION, " +
"NAME, " +
"DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, " +
"STATUS, " +
"TIMESTAMPDIFF(DAY, DATE_OF_LAST_UPDATE, ?) AS DAYS_USED " +
"from DM_DEVICE d, DM_ENROLMENT e " +
"where " +
"e.TENANT_ID=? and d.ID=e.DEVICE_ID and " +
"STATUS ='REMOVED' and " +
"(" +
"DATE_OF_ENROLMENT < ? " +
") and " +
"(" +
"DATE_OF_LAST_UPDATE >= ? " +
")";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, String.valueOf(startDate));
stmt.setInt(2, tenantId);
stmt.setString(3, String.valueOf(startDate));
stmt.setString(4, String.valueOf(startDate));
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs));
}
}
} catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while fetching the list of RemovedPriorYears device billing ", e);
}
return devices;
}
//Return only not removed id list //Return only not removed id list
@Override @Override
public List<Device> getDeviceListWithoutPagination(int tenantId) public List<Device> getDeviceListWithoutPagination(int tenantId)
@ -197,10 +359,26 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT DM_DEVICE.ID AS DEVICE_ID, DEVICE_IDENTIFICATION, DESCRIPTION, DM_DEVICE.NAME AS DEVICE_NAME, DM_DEVICE_TYPE.NAME AS DEVICE_TYPE,\n" + String sql = "SELECT " +
"DM_ENROLMENT.ID AS ENROLMENT_ID, DATE_OF_ENROLMENT,OWNER, OWNERSHIP,IS_TRANSFERRED, STATUS, DATE_OF_LAST_UPDATE, LAST_BILLED_DATE,\n" + "DM_DEVICE.ID AS DEVICE_ID, " +
"TIMESTAMPDIFF(DAY, DATE_OF_ENROLMENT, CURDATE()) as DAYS_SINCE_ENROLLED FROM DM_DEVICE JOIN DM_ENROLMENT\n" + "DEVICE_IDENTIFICATION, " +
"ON (DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) JOIN DM_DEVICE_TYPE ON (DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID) WHERE DM_ENROLMENT.TENANT_ID=?"; "DESCRIPTION, " +
"DM_DEVICE.NAME AS DEVICE_NAME, " +
"DM_DEVICE_TYPE.NAME AS DEVICE_TYPE, " +
"DM_ENROLMENT.ID AS ENROLMENT_ID, " +
"DATE_OF_ENROLMENT, " +
"OWNER, " +
"OWNERSHIP, " +
"IS_TRANSFERRED, " +
"STATUS, " +
"DATE_OF_LAST_UPDATE, " +
"TIMESTAMPDIFF(DAY, DATE_OF_ENROLMENT, CURDATE()) as DAYS_SINCE_ENROLLED " +
"FROM " +
"DM_DEVICE " +
"JOIN DM_ENROLMENT ON (DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) " +
"JOIN DM_DEVICE_TYPE ON (DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID) " +
"WHERE " +
"DM_ENROLMENT.TENANT_ID = ? ";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
ResultSet rs = stmt.executeQuery(); ResultSet rs = stmt.executeQuery();

@ -263,6 +263,34 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
} }
// TODO - add Oracle support for below billing method
@Override
public List<Device> getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
// TODO - add Oracle support for below billing method
@Override
public List<Device> getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
// TODO - add Oracle support for below billing method
@Override
public List<Device> getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
// TODO - add Oracle support for below billing method
@Override
public List<Device> getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
@Override @Override
public List<Device> getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { public List<Device> getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException {
return null; return null;

@ -179,6 +179,35 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
} }
// TODO - add PostgreSQL support for below billing method
@Override
public List<Device> getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
// TODO - add PostgreSQL support for below billing method
@Override
public List<Device> getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
// TODO - add PostgreSQL support for below billing method
@Override
public List<Device> getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
// TODO - add PostgreSQL support for below billing method
@Override
public List<Device> getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
//Return only not removed id list //Return only not removed id list
@Override @Override
public List<Device> getDevicesIds(PaginationRequest request, int tenantId) public List<Device> getDevicesIds(PaginationRequest request, int tenantId)

@ -189,6 +189,35 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
} }
// TODO - add SQL support for below billing method
@Override
public List<Device> getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
// TODO - add SQL support for below billing method
@Override
public List<Device> getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
// TODO - add SQL support for below billing method
@Override
public List<Device> getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
// TODO - add SQL support for below billing method
@Override
public List<Device> getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
throws DeviceManagementDAOException {
return null;
}
//Return only not removed id list //Return only not removed id list
@Override @Override
public List<Device> getDevicesIds(PaginationRequest request, int tenantId) public List<Device> getDevicesIds(PaginationRequest request, int tenantId)

@ -144,14 +144,6 @@ public final class DeviceManagementDAOUtil {
public static EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException { public static EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
String columnName = "LAST_BILLED_DATE";
ResultSetMetaData rsmd = rs.getMetaData();
int columns = rsmd.getColumnCount();
for (int x = 1; x <= columns; x++) {
if (columnName.equals(rsmd.getColumnName(x))) {
enrolmentInfo.setLastBilledDate(rs.getLong("LAST_BILLED_DATE"));
}
}
enrolmentInfo.setId(rs.getInt("ENROLMENT_ID")); enrolmentInfo.setId(rs.getInt("ENROLMENT_ID"));
enrolmentInfo.setOwner(rs.getString("OWNER")); enrolmentInfo.setOwner(rs.getString("OWNER"));
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP"))); enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP")));
@ -162,15 +154,12 @@ public final class DeviceManagementDAOUtil {
return enrolmentInfo; return enrolmentInfo;
} }
/* This is used to set the enrollment data of the billing query */
public static EnrolmentInfo loadEnrolmentBilling(ResultSet rs) throws SQLException { public static EnrolmentInfo loadEnrolmentBilling(ResultSet rs) throws SQLException {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setId(rs.getInt("ENROLMENT_ID"));
enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime()); enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime());
enrolmentInfo.setLastBilledDate(rs.getLong("LAST_BILLED_DATE"));
enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS")));
if (EnrolmentInfo.Status.valueOf(rs.getString("STATUS")).equals("REMOVED")) {
enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime()); enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime());
} enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS")));
return enrolmentInfo; return enrolmentInfo;
} }
@ -245,29 +234,23 @@ public final class DeviceManagementDAOUtil {
return device; return device;
} }
public static Device loadDeviceIds(ResultSet rs) throws SQLException { /* This is used to set the device data of the billing query */
public static Device loadDeviceBilling(ResultSet rs) throws SQLException {
Device device = new Device(); Device device = new Device();
device.setId(rs.getInt("DEVICE_ID")); device.setId(rs.getInt("DEVICE_ID"));
device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));
device.setEnrolmentInfo(loadEnrolmentStatus(rs)); device.setName(rs.getString("DESCRIPTION"));
device.setDescription(rs.getString("NAME"));
device.setEnrolmentInfo(loadEnrolmentBilling(rs));
return device; return device;
} }
public static DeviceBilling loadDeviceBilling(ResultSet rs) throws SQLException { public static Device loadDeviceIds(ResultSet rs) throws SQLException {
DeviceBilling device = new DeviceBilling(); Device device = new Device();
device.setId(rs.getInt("ID")); device.setId(rs.getInt("DEVICE_ID"));
device.setName(rs.getString("DEVICE_NAME"));
device.setDescription(rs.getString("DESCRIPTION"));
device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));
device.setDaysUsed((int) rs.getLong("DAYS_SINCE_ENROLLED")); device.setEnrolmentInfo(loadEnrolmentStatus(rs));
device.setEnrolmentInfo(loadEnrolmentBilling(rs));
return device; return device;
// if (removedDevices) {
// device.setDaysUsed((int) rs.getLong("DAYS_USED"));
// } else {
// device.setDaysSinceEnrolled((int) rs.getLong("DAYS_SINCE_ENROLLED"));
// }
} }
public static DeviceMonitoringData loadDevice(ResultSet rs, String deviceTypeName) throws SQLException { public static DeviceMonitoringData loadDevice(ResultSet rs, String deviceTypeName) throws SQLException {

@ -208,16 +208,6 @@ public interface DeviceManagementProviderService {
*/ */
PaginationResult getAllDevices(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException; PaginationResult getAllDevices(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException;
/**
* Method to retrieve all the devices with pagination support.
*
* @param request PaginationRequest object holding the data for pagination
* @return PaginationResult - Result including the required parameters necessary to do pagination.
* @throws DeviceManagementException If some unusual behaviour is observed while fetching billing of
* devices.
*/
PaginationResult getAllDevicesBillings(PaginationRequest request, int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException;
/** /**
* Method to retrieve all the devices with pagination support. * Method to retrieve all the devices with pagination support.
* *
@ -225,9 +215,7 @@ public interface DeviceManagementProviderService {
* @throws DeviceManagementException If some unusual behaviour is observed while fetching billing of * @throws DeviceManagementException If some unusual behaviour is observed while fetching billing of
* devices. * devices.
*/ */
PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException; PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException;
/** /**
* Method to retrieve all the devices with pagination support. * Method to retrieve all the devices with pagination support.

@ -69,8 +69,10 @@ import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.StartupOperationConfig; import org.wso2.carbon.device.mgt.common.StartupOperationConfig;
import org.wso2.carbon.device.mgt.common.BillingResponse;
import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.MobileAppTypes;
import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfigurationException; import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfigurationException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
@ -119,11 +121,11 @@ import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypePlatformVersion;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository;
import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey; import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey;
import org.wso2.carbon.device.mgt.core.cache.impl.BillingCacheManagerImpl;
import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO; import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO;
import org.wso2.carbon.device.mgt.core.dao.BillingDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; 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.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
@ -141,6 +143,7 @@ import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener; import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
@ -164,8 +167,7 @@ import java.io.StringWriter;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.text.Format; import java.time.LocalDateTime;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Collection; import java.util.Collection;
@ -193,7 +195,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
private final EnrollmentDAO enrollmentDAO; private final EnrollmentDAO enrollmentDAO;
private final ApplicationDAO applicationDAO; private final ApplicationDAO applicationDAO;
private MetadataDAO metadataDAO; private MetadataDAO metadataDAO;
private final BillingDAO billingDAO;
private final DeviceStatusDAO deviceStatusDAO; private final DeviceStatusDAO deviceStatusDAO;
public DeviceManagementProviderServiceImpl() { public DeviceManagementProviderServiceImpl() {
@ -203,7 +204,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
this.enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); this.enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO(); this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO();
this.billingDAO = DeviceManagementDAOFactory.getBillingDAO();
this.deviceStatusDAO = DeviceManagementDAOFactory.getDeviceStatusDAO(); this.deviceStatusDAO = DeviceManagementDAOFactory.getDeviceStatusDAO();
/* Registering a listener to retrieve events when some device management service plugin is installed after /* Registering a listener to retrieve events when some device management service plugin is installed after
@ -1021,236 +1021,232 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return this.getAllDevices(request, true); return this.getAllDevices(request, true);
} }
public PaginationResult calculateCost(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill, List<Device> allDevices) throws DeviceManagementException { /**
* Calculate cost of a tenants Device List.
* Once the full device list of a tenant is sent here devices are looped for cost calculation
* Cost per tenant is retrieved from the Meta Table
* When looping the devices the most recent device status of that device is retrieved from status table
* If device is enrolled prior to start date now in removed state --> time is calculated from - startDate to last updated time
* If device is enrolled prior to start date now in not removed --> time is calculated from - startDate to endDate
* If device is enrolled after the start date now in removed state --> time is calculated from - dateOfEnrollment to last updated time
* If device is enrolled after the start date now in not removed --> time is calculated from - dateOfEnrollment to endDate
* Once time is calculated cost is set for each device
*
* @param tenantDomain Tenant domain cost id calculated for.
* @param startDate start date of usage period.
* @param endDate end date of usage period.
* @param allDevices device list of the tenant for the selected time-period.
* @return Whether status is changed or not
* @throws DeviceManagementException on errors while trying to calculate Cost
*/
public BillingResponse calculateCost(String tenantDomain, Timestamp startDate, Timestamp endDate, List<Device> allDevices) throws MetadataManagementDAOException, DeviceManagementException {
PaginationResult paginationResult = new PaginationResult(); BillingResponse billingResponse = new BillingResponse();
List<Device> deviceStatusNotAvailable = new ArrayList<>();
double totalCost = 0.0; double totalCost = 0.0;
boolean allDevicesBilledDateIsValid = true;
ArrayList<String> lastBilledDatesList = new ArrayList<>();
List<Billing> invalidDevices = new ArrayList<>();
List<Device> removeBillingPeriodInvalidDevices = new ArrayList<>() ;
List<Device> removeStatusUpdateInvalidDevices = new ArrayList<>() ;
try { try {
MetadataManagementDAOFactory.beginTransaction(); MetadataManagementDAOFactory.openConnection();
Metadata metadata = metadataDAO.getMetadata(MultitenantConstants.SUPER_TENANT_ID, DeviceManagementConstants.META_KEY); Metadata metadata = metadataDAO.getMetadata(MultitenantConstants.SUPER_TENANT_ID, DeviceManagementConstants.META_KEY);
Gson g = new Gson(); Gson g = new Gson();
Collection<Cost> costData = null; Collection<Cost> costData = null;
Type collectionType = new TypeToken<Collection<Cost>>() {
Type collectionType = new TypeToken<Collection<Cost>>() {}.getType(); }.getType();
if (metadata != null) { if (metadata != null) {
costData = g.fromJson(metadata.getMetaValue(), collectionType); costData = g.fromJson(metadata.getMetaValue(), collectionType);
for (Cost tenantCost : costData) { for (Cost tenantCost : costData) {
if (tenantCost.getTenantDomain().equals(tenantDomain)) { if (tenantCost.getTenantDomain().equals(tenantDomain)) {
for (Device device : allDevices) { for (Device device : allDevices) {
device.setDeviceStatusInfo(getDeviceStatusHistory(device, null, null, true));
long dateDiff = 0; long dateDiff = 0;
device.setDeviceStatusInfo(getDeviceStatusHistory(device, null, endDate, true));
List<DeviceStatus> deviceStatus = device.getDeviceStatusInfo(); List<DeviceStatus> deviceStatus = device.getDeviceStatusInfo();
boolean firstDateBilled = false; if (device.getEnrolmentInfo().getDateOfEnrolment() < startDate.getTime()) {
boolean deviceStatusIsValid = false; if (!deviceStatus.isEmpty() && deviceStatus.get(0).getStatus().equals("REMOVED")) {
if (deviceStatus.get(0).getUpdateTime().getTime() >= startDate.getTime()) {
List<Billing> deviceBilling = billingDAO.getBilling(device.getId(), startDate, endDate); dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - startDate.getTime();
boolean billDateIsInvalid = false;
if (deviceBilling.isEmpty()) {
billDateIsInvalid = false;
}
if (generateBill) {
for (Billing bill : deviceBilling) {
if ((bill.getBillingStart() <= startDate.getTime() && startDate.getTime() <= bill.getBillingEnd()) ||
(bill.getBillingStart() <= endDate.getTime() && endDate.getTime() <= bill.getBillingEnd())) {
billDateIsInvalid = true;
invalidDevices.add(bill);
}
} }
} else if (!deviceStatus.isEmpty() && !deviceStatus.get(0).getStatus().equals("REMOVED")) {
dateDiff = endDate.getTime() - startDate.getTime();
} }
if (!billDateIsInvalid) {
for (int i = 0; i < deviceStatus.size(); i++) {
if (DeviceManagementConstants.ACTIVE_STATUS.equals(deviceStatus.get(i).getStatus().toString())) {
if (deviceStatus.size() > i + 1) {
if (!firstDateBilled) {
firstDateBilled = true;
if (device.getEnrolmentInfo().getLastBilledDate() == 0) {
deviceStatusIsValid = true;
dateDiff = dateDiff + (deviceStatus.get(i + 1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime());
} else { } else {
if (deviceStatus.get(i + 1).getUpdateTime().getTime() >= device.getEnrolmentInfo().getLastBilledDate()) { if (!deviceStatus.isEmpty() && deviceStatus.get(0).getStatus().equals("REMOVED")) {
deviceStatusIsValid = true; if (deviceStatus.get(0).getUpdateTime().getTime() >= device.getEnrolmentInfo().getDateOfEnrolment()) {
dateDiff = dateDiff + (deviceStatus.get(i + 1).getUpdateTime().getTime() - device.getEnrolmentInfo().getLastBilledDate()); dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - device.getEnrolmentInfo().getDateOfEnrolment();
}
}
} else {
if (deviceStatus.get(i).getUpdateTime().getTime() >= device.getEnrolmentInfo().getLastBilledDate()) {
deviceStatusIsValid = true;
dateDiff = dateDiff + (deviceStatus.get(i + 1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime());
}
}
} else {
// If only one status row is retrieved this block is executed
if (!firstDateBilled) {
firstDateBilled = true;
// Is executed if there is no lastBilled date and if the updates time is before the end date
if (device.getEnrolmentInfo().getLastBilledDate() == 0) {
if (endDate.getTime() >= deviceStatus.get(i).getUpdateTime().getTime()) {
deviceStatusIsValid = true;
dateDiff = dateDiff + (endDate.getTime() - deviceStatus.get(i).getUpdateTime().getTime());
}
} else {
if (endDate.getTime() >= device.getEnrolmentInfo().getLastBilledDate()) {
deviceStatusIsValid = true;
dateDiff = dateDiff + (endDate.getTime() - device.getEnrolmentInfo().getLastBilledDate());
}
}
} else {
if (device.getEnrolmentInfo().getLastBilledDate() <= deviceStatus.get(i).getUpdateTime().getTime()
&& endDate.getTime() >= deviceStatus.get(i).getUpdateTime().getTime()) {
deviceStatusIsValid = true;
dateDiff = dateDiff + (endDate.getTime() - deviceStatus.get(i).getUpdateTime().getTime());
}
if (device.getEnrolmentInfo().getLastBilledDate() >= deviceStatus.get(i).getUpdateTime().getTime()
&& endDate.getTime() >= device.getEnrolmentInfo().getLastBilledDate()) {
deviceStatusIsValid = true;
dateDiff = dateDiff + (endDate.getTime() - device.getEnrolmentInfo().getLastBilledDate());
}
}
} }
} else if (!deviceStatus.isEmpty() && !deviceStatus.get(0).getStatus().equals("REMOVED")) {
dateDiff = endDate.getTime() - device.getEnrolmentInfo().getDateOfEnrolment();
} }
} }
long dateInDays = TimeUnit.DAYS.convert(dateDiff, TimeUnit.MILLISECONDS); long dateInDays = TimeUnit.DAYS.convert(dateDiff, TimeUnit.MILLISECONDS);
double cost = (tenantCost.getCost() / 365) * dateInDays; double cost = (tenantCost.getCost() / 365) * dateInDays;
totalCost = cost + totalCost; totalCost += cost;
device.setCost(Math.round(cost * 100.0) / 100.0); device.setCost(Math.round(cost * 100.0) / 100.0);
device.setDaysUsed((int) dateInDays); long totalDays = dateInDays + device.getDaysUsed();
device.setDaysUsed((int) totalDays);
if (generateBill) { if (deviceStatus.isEmpty()) {
enrollmentDAO.updateEnrollmentLastBilledDate(device.getEnrolmentInfo(), endDate, tenantId); deviceStatusNotAvailable.add(device);
billingDAO.addBilling(device.getId(), tenantId, startDate, endDate);
DeviceManagementDAOFactory.commitTransaction();
}
} else {
for (int i = 0; i < deviceStatus.size(); i++) {
if (endDate.getTime() >= deviceStatus.get(i).getUpdateTime().getTime()
&& startDate.getTime() <= deviceStatus.get(i).getUpdateTime().getTime()) {
deviceStatusIsValid = true;
}
}
if (device.getEnrolmentInfo().getLastBilledDate() != 0) {
Date date = new Date(device.getEnrolmentInfo().getLastBilledDate());
Format format = new SimpleDateFormat("yyyy MM dd");
for (String lastBillDate : lastBilledDatesList) {
if (!lastBillDate.equals(format.format(date))) {
lastBilledDatesList.add(format.format(date));
}
}
}
removeBillingPeriodInvalidDevices.add(device);
}
if (!deviceStatusIsValid) {
removeStatusUpdateInvalidDevices.add(device);
} }
} }
} }
} }
} }
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving device list pertaining to the current tenant"; String msg = "Error occurred calculating cost of devices";
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} catch (Exception e) { } catch (SQLException e) {
String msg = "Error occurred in getAllDevices"; String msg = "Error when retrieving data";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (MetadataManagementDAOException e) {
String msg = "Error when retrieving metadata of billing feature";
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection();
MetadataManagementDAOFactory.closeConnection(); MetadataManagementDAOFactory.closeConnection();
} }
if(!removeBillingPeriodInvalidDevices.isEmpty() && removeBillingPeriodInvalidDevices.size() == allDevices.size()) { if (!deviceStatusNotAvailable.isEmpty()) {
allDevicesBilledDateIsValid = false; allDevices.removeAll(deviceStatusNotAvailable);
paginationResult.setMessage("Invalid bill period.");
}
if(!removeStatusUpdateInvalidDevices.isEmpty() && removeStatusUpdateInvalidDevices.size() == allDevices.size()) {
allDevicesBilledDateIsValid = false;
if (paginationResult.getMessage() != null){
paginationResult.setMessage(paginationResult.getMessage() + " and no device updates within entered bill period.");
} else {
paginationResult.setMessage("Devices have not been updated within the given period or entered end date comes before the " +
"last billed date.");
} }
} Calendar calStart = Calendar.getInstance();
allDevices.removeAll(removeBillingPeriodInvalidDevices); Calendar calEnd = Calendar.getInstance();
allDevices.removeAll(removeStatusUpdateInvalidDevices); calStart.setTimeInMillis(startDate.getTime());
calEnd.setTimeInMillis(endDate.getTime());
paginationResult.setBilledDateIsValid(allDevicesBilledDateIsValid); billingResponse.setDevice(allDevices);
paginationResult.setData(allDevices); billingResponse.setYear(String.valueOf(calStart.get(Calendar.YEAR)));
paginationResult.setTotalCost(Math.round(totalCost * 100.0) / 100.0); billingResponse.setStartDate(startDate.toString());
return paginationResult; billingResponse.setEndDate(endDate.toString());
billingResponse.setBillPeriod(calStart.get(Calendar.YEAR) + " - " + calEnd.get(Calendar.YEAR));
billingResponse.setTotalCostPerYear(Math.round(totalCost * 100.0) / 100.0);
billingResponse.setDeviceCount(allDevices.size());
return billingResponse;
} }
@Override @Override
public PaginationResult getAllDevicesBillings(PaginationRequest request, int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException { public PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException {
if (request == null) {
String msg = "Received incomplete pagination request for method getAllDeviceBillings";
log.error(msg);
throw new DeviceManagementException(msg);
}
DeviceManagerUtil.validateDeviceListPageSize(request);
PaginationResult paginationResult = new PaginationResult(); PaginationResult paginationResult = new PaginationResult();
List<Device> allDevices; List<Device> allDevices = new ArrayList<>();
int count = 0; List<BillingResponse> billingResponseList = new ArrayList<>();
double totalCost = 0.0;
int deviceCount = 0;
Timestamp initialStartDate = startDate;
boolean remainingDaysConsidered = false;
try { try {
DeviceManagementDAOFactory.beginTransaction(); DeviceManagementDAOFactory.openConnection();
allDevices = deviceDAO.getDevices(request, tenantId);
count = deviceDAO.getDeviceCount(request, tenantId);
paginationResult = calculateCost(tenantId, tenantDomain, startDate, endDate, generateBill, allDevices);
} catch (DeviceManagementDAOException e) { // TODO Do the check of cache enabling here
String msg = "Error occurred while retrieving device bill list pertaining to the current tenant"; paginationResult = BillingCacheManagerImpl.getInstance().getBillingFromCache(tenantDomain, startDate, endDate);
log.error(msg, e); if (paginationResult == null) {
throw new DeviceManagementException(msg, e); paginationResult = new PaginationResult();
} catch (Exception e) { long difference_In_Time = endDate.getTime() - startDate.getTime();
String msg = "Error occurred in getAllDevicesBillings";
log.error(msg, e); long difference_In_Years = (difference_In_Time / (1000L * 60 * 60 * 24 * 365));
throw new DeviceManagementException(msg, e);
long difference_In_Days = (difference_In_Time / (1000 * 60 * 60 * 24)) % 365;
for (int i = 1; i <= difference_In_Years; i++) {
List<Device> allDevicesPerYear = new ArrayList<>();
LocalDateTime oneYearAfterStart = startDate.toLocalDateTime().plusYears(1);
Timestamp newStartDate;
Timestamp newEndDate;
if (i == difference_In_Years) {
if (difference_In_Days == 0 || Timestamp.valueOf(oneYearAfterStart).getTime() >= endDate.getTime()) {
remainingDaysConsidered = true;
oneYearAfterStart = startDate.toLocalDateTime();
newEndDate = endDate;
} else if (Timestamp.valueOf(oneYearAfterStart).getTime() >= endDate.getTime()) {
newEndDate = Timestamp.valueOf(oneYearAfterStart);
} else {
oneYearAfterStart = startDate.toLocalDateTime().plusYears(1);
newEndDate = Timestamp.valueOf(oneYearAfterStart);
} }
paginationResult.setRecordsFiltered(count); } else {
paginationResult.setRecordsTotal(count); oneYearAfterStart = startDate.toLocalDateTime().plusYears(1);
return paginationResult; newEndDate = Timestamp.valueOf(oneYearAfterStart);
} }
@Override newStartDate = startDate;
public PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException {
PaginationResult paginationResult = new PaginationResult(); // The query returns devices which are enrolled in this year now in not removed state
List<Device> allDevices; allDevicesPerYear.addAll(deviceDAO.getNonRemovedYearlyDeviceList(tenantId, newStartDate, newEndDate));
try {
DeviceManagementDAOFactory.beginTransaction(); // The query returns devices which are enrolled in this year now in removed state
allDevices = deviceDAO.getDeviceListWithoutPagination(tenantId); allDevicesPerYear.addAll(deviceDAO.getRemovedYearlyDeviceList(tenantId, newStartDate, newEndDate));
paginationResult = calculateCost(tenantId, tenantDomain, startDate, endDate, generateBill, allDevices);
// The query returns devices which are enrolled prior this year now in not removed state
allDevicesPerYear.addAll(deviceDAO.getNonRemovedPriorYearsDeviceList(tenantId, newStartDate, newEndDate));
// The query returns devices which are enrolled prior this year now in removed state
allDevicesPerYear.addAll(deviceDAO.getRemovedPriorYearsDeviceList(tenantId, newStartDate, newEndDate));
BillingResponse billingResponse = calculateCost(tenantDomain, newStartDate, newEndDate, allDevicesPerYear);
billingResponseList.add(billingResponse);
allDevices.addAll(billingResponse.getDevice());
totalCost = totalCost + billingResponse.getTotalCostPerYear();
deviceCount = deviceCount + billingResponse.getDeviceCount();
LocalDateTime nextStartDate = oneYearAfterStart.plusDays(1);
startDate = Timestamp.valueOf(nextStartDate);
}
if (difference_In_Days != 0 && !remainingDaysConsidered) {
List<Device> allDevicesPerRemainingDays = new ArrayList<>();
// The query returns devices which are enrolled in this year now in not removed state
allDevicesPerRemainingDays.addAll(deviceDAO.getNonRemovedYearlyDeviceList(tenantId, startDate, endDate));
// The query returns devices which are enrolled in this year now in removed state
allDevicesPerRemainingDays.addAll(deviceDAO.getRemovedYearlyDeviceList(tenantId, startDate, endDate));
// The query returns devices which are enrolled prior this year now in not removed state
allDevicesPerRemainingDays.addAll(deviceDAO.getNonRemovedPriorYearsDeviceList(tenantId, startDate, endDate));
// The query returns devices which are enrolled prior this year now in removed state
allDevicesPerRemainingDays.addAll(deviceDAO.getRemovedPriorYearsDeviceList(tenantId, startDate, endDate));
BillingResponse billingResponse = calculateCost(tenantDomain, startDate, endDate, allDevicesPerRemainingDays);
billingResponseList.add(billingResponse);
allDevices.addAll(billingResponse.getDevice());
totalCost = totalCost + billingResponse.getTotalCostPerYear();
deviceCount = deviceCount + billingResponse.getDeviceCount();
}
Calendar calStart = Calendar.getInstance();
Calendar calEnd = Calendar.getInstance();
calStart.setTimeInMillis(initialStartDate.getTime());
calEnd.setTimeInMillis(endDate.getTime());
BillingResponse billingResponse = new BillingResponse("all", Math.round(totalCost * 100.0) / 100.0, allDevices, calStart.get(Calendar.YEAR) + " - " + calEnd.get(Calendar.YEAR), initialStartDate.toString(), endDate.toString(), allDevices.size());
billingResponseList.add(billingResponse);
paginationResult.setData(billingResponseList);
paginationResult.setTotalCost(Math.round(totalCost * 100.0) / 100.0);
paginationResult.setTotalDeviceCount(deviceCount);
BillingCacheManagerImpl.getInstance().addBillingToCache(paginationResult, tenantDomain, initialStartDate, endDate);
return paginationResult;
}
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving device bill list without pagination pertaining to the current tenant"; String msg = "Error occurred while retrieving device bill list related to the current tenant";
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} catch (Exception e) { } catch (MetadataManagementDAOException e) {
String msg = "Error occurred in createBillingFile"; String msg = "Error when retrieving metadata of billing feature";
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
} }
return paginationResult; return paginationResult;
} }

@ -58,6 +58,7 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.EnrollmentConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.EnrollmentConfiguration;
@ -76,6 +77,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.type.mgt.DeviceTypeMetaDefinition; import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.cache.BillingCacheKey;
import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey; import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey;
import org.wso2.carbon.device.mgt.core.cache.GeoCacheKey; import org.wso2.carbon.device.mgt.core.cache.GeoCacheKey;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
@ -137,6 +139,7 @@ public final class DeviceManagerUtil {
public static final String GENERAL_CONFIG_RESOURCE_PATH = "general"; public static final String GENERAL_CONFIG_RESOURCE_PATH = "general";
private static boolean isDeviceCacheInitialized = false; private static boolean isDeviceCacheInitialized = false;
private static boolean isBillingCacheInitialized = false;
private static boolean isAPIResourcePermissionCacheInitialized = false; private static boolean isAPIResourcePermissionCacheInitialized = false;
private static boolean isGeoFenceCacheInitialized = false; private static boolean isGeoFenceCacheInitialized = false;
@ -652,6 +655,47 @@ public final class DeviceManagerUtil {
} }
} }
/**
* Enable Billing caching according to the configurations provided by cdm-config.xml
*/
public static void initializeBillingCache() {
DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
int billingCacheExpiry = config.getBillingCacheConfiguration().getExpiryTime();
long billingCacheCapacity = config.getBillingCacheConfiguration().getCapacity();
CacheManager manager = getCacheManager();
if (config.getBillingCacheConfiguration().isEnabled()) {
if(!isBillingCacheInitialized) {
isBillingCacheInitialized = true;
if (manager != null) {
if (billingCacheExpiry > 0) {
manager.<BillingCacheKey, PaginationResult>createCacheBuilder(DeviceManagementConstants.BILLING_CACHE).
setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
billingCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
Duration(TimeUnit.SECONDS, billingCacheExpiry)).setStoreByValue(true).build();
if(billingCacheCapacity > 0 ) {
((CacheImpl) manager.<BillingCacheKey, PaginationResult>getCache(DeviceManagementConstants.BILLING_CACHE)).
setCapacity(billingCacheCapacity);
}
} else {
manager.<BillingCacheKey, PaginationResult>getCache(DeviceManagementConstants.BILLING_CACHE);
}
} else {
if (billingCacheExpiry > 0) {
Caching.getCacheManager().
<BillingCacheKey, PaginationResult>createCacheBuilder(DeviceManagementConstants.BILLING_CACHE).
setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
billingCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
Duration(TimeUnit.SECONDS, billingCacheExpiry)).setStoreByValue(true).build();
((CacheImpl)(manager.<BillingCacheKey, PaginationResult>getCache(DeviceManagementConstants.BILLING_CACHE))).
setCapacity(billingCacheCapacity);
} else {
Caching.getCacheManager().<BillingCacheKey, PaginationResult>getCache(DeviceManagementConstants.BILLING_CACHE);
}
}
}
}
}
/** /**
* Enable Geofence caching according to the configurations proviced by cdm-config.xml * Enable Geofence caching according to the configurations proviced by cdm-config.xml
*/ */
@ -711,6 +755,28 @@ public final class DeviceManagerUtil {
return deviceCache; return deviceCache;
} }
/**
* Get billing cache object
* @return {@link Cache<BillingCacheKey, PaginationResult>}
*/
public static Cache<BillingCacheKey, PaginationResult> getBillingCache() {
DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
CacheManager manager = getCacheManager();
Cache<BillingCacheKey, PaginationResult> billingCache = null;
if (config.getBillingCacheConfiguration().isEnabled()) {
if(!isBillingCacheInitialized) {
initializeBillingCache();
}
if (manager != null) {
billingCache = manager.getCache(DeviceManagementConstants.BILLING_CACHE);
} else {
billingCache = Caching.getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER)
.getCache(DeviceManagementConstants.BILLING_CACHE);
}
}
return billingCache;
}
/** /**
* Get geofence cache object * Get geofence cache object
* @return {@link Cache<GeoCacheKey, GeofenceData>} * @return {@link Cache<GeoCacheKey, GeofenceData>}

@ -94,7 +94,6 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL,
TENANT_ID INT NOT NULL, TENANT_ID INT NOT NULL,
LAST_BILLED_DATE BIGINT DEFAULT 0,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
@ -564,16 +563,6 @@ ORDER BY TENANT_ID, DEVICE_ID;
-- END OF DASHBOARD RELATED VIEWS -- -- END OF DASHBOARD RELATED VIEWS --
CREATE TABLE IF NOT EXISTS DM_BILLING (
INVOICE_ID INTEGER AUTO_INCREMENT NOT NULL,
TENANT_ID INTEGER DEFAULT 0,
DEVICE_ID INTEGER DEFAULT NULL,
BILLING_START TIMESTAMP NOT NULL,
BILLING_END TIMESTAMP NOT NULL,
PRIMARY KEY (INVOICE_ID),
CONSTRAINT fk_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
-- DM_EXT_GROUP_MAPPING TABLE-- -- DM_EXT_GROUP_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_EXT_GROUP_MAPPING ( CREATE TABLE IF NOT EXISTS DM_EXT_GROUP_MAPPING (
ID INT NOT NULL AUTO_INCREMENT, ID INT NOT NULL AUTO_INCREMENT,

@ -94,6 +94,11 @@
<ExpiryTime>600</ExpiryTime> <ExpiryTime>600</ExpiryTime>
<Capacity>10000</Capacity> <Capacity>10000</Capacity>
</GeoFenceCacheConfiguration> </GeoFenceCacheConfiguration>
<BillingCacheConfiguration>
<Enable>true</Enable>
<ExpiryTime>600</ExpiryTime>
<Capacity>10000</Capacity>
</BillingCacheConfiguration>
<EventOperationTaskConfiguration> <EventOperationTaskConfiguration>
<Enable>true</Enable> <Enable>true</Enable>
</EventOperationTaskConfiguration> </EventOperationTaskConfiguration>

@ -211,6 +211,7 @@
<Scope>perm:windows:location</Scope> <Scope>perm:windows:location</Scope>
<Scope>perm:admin:tenant:view</Scope> <Scope>perm:admin:tenant:view</Scope>
<Scope>perm:admin:metadata:view</Scope> <Scope>perm:admin:metadata:view</Scope>
<Scope>perm:admin:usage:view</Scope>
</Scopes> </Scopes>
<SSOConfiguration> <SSOConfiguration>
<Issuer>device-mgt</Issuer> <Issuer>device-mgt</Issuer>

@ -165,6 +165,17 @@
<Capacity>10000</Capacity> <Capacity>10000</Capacity>
{% endif %} {% endif %}
</GeoFenceCacheConfiguration> </GeoFenceCacheConfiguration>
<BillingCacheConfiguration>
{% if device_mgt_conf.billing_cache_conf is defined %}
<Enable>{{device_mgt_conf.billing_cache_conf.enable}}</Enable>
<ExpiryTime>{{device_mgt_conf.billing_cache_conf.expiry_time}}</ExpiryTime>
<Capacity>{{device_mgt_conf.billing_cache_conf.capacity}}</Capacity>
{% else %}
<Enable>true</Enable>
<ExpiryTime>600</ExpiryTime>
<Capacity>10000</Capacity>
{% endif %}
</BillingCacheConfiguration>
<EventOperationTaskConfiguration> <EventOperationTaskConfiguration>
{% if device_mgt_conf.event_operation_task_conf is defined %} {% if device_mgt_conf.event_operation_task_conf is defined %}
<Enable>{{device_mgt_conf.event_operation_task_conf.enable}}</Enable> <Enable>{{device_mgt_conf.event_operation_task_conf.enable}}</Enable>

@ -52,17 +52,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE (
CONSTRAINT uk_DM_DEVICE UNIQUE (NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID) CONSTRAINT uk_DM_DEVICE UNIQUE (NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID)
); );
CREATE TABLE IF NOT EXISTS DM_BILLING (
INVOICE_ID INTEGER auto_increment NOT NULL,
TENANT_ID INTEGER default 0,
DEVICE_ID INT default NULL,
BILLING_START TIMESTAMP not null,
BILLING_END TIMESTAMP not null,
PRIMARY KEY (INVOICE_ID),
CONSTRAINT FK_DM_BILLING_DM_DEVICE
FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID)
);
CREATE TABLE IF NOT EXISTS DM_DEVICE_PROPERTIES ( CREATE TABLE IF NOT EXISTS DM_DEVICE_PROPERTIES (
DEVICE_TYPE_NAME VARCHAR(300) NOT NULL, DEVICE_TYPE_NAME VARCHAR(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL, DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL,
@ -114,7 +103,6 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL,
TENANT_ID INT NOT NULL, TENANT_ID INT NOT NULL,
LAST_BILLED_DATE BIGINT DEFAULT 0,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,

@ -66,18 +66,6 @@ CREATE TABLE DM_DEVICE (
REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
); );
IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_BILLING]') AND TYPE IN (N'U'))
CREATE TABLE DM_BILLING (
INVOICE_ID INTEGER IDENTITY(1,1) NOT NULL,
TENANT_ID INTEGER DEFAULT 0,
DEVICE_ID INTEGER DEFAULT NULL,
BILLING_START DATETIME2 NOT NULL,
BILLING_END DATETIME2 NOT NULL,
PRIMARY KEY (INVOICE_ID),
CONSTRAINT FK_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_DEVICE_PROPERTIES]') AND TYPE IN (N'U')) IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[DM_DEVICE_PROPERTIES]') AND TYPE IN (N'U'))
CREATE TABLE DM_DEVICE_PROPERTIES ( CREATE TABLE DM_DEVICE_PROPERTIES (
DEVICE_TYPE_NAME VARCHAR(300) NOT NULL, DEVICE_TYPE_NAME VARCHAR(300) NOT NULL,
@ -158,7 +146,6 @@ CREATE TABLE DM_ENROLMENT (
DATE_OF_ENROLMENT DATETIME2 DEFAULT NULL, DATE_OF_ENROLMENT DATETIME2 DEFAULT NULL,
DATE_OF_LAST_UPDATE DATETIME2 DEFAULT NULL, DATE_OF_LAST_UPDATE DATETIME2 DEFAULT NULL,
TENANT_ID INTEGER NOT NULL, TENANT_ID INTEGER NOT NULL,
LAST_BILLED_DATE BIGINT DEFAULT 0,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION

@ -59,17 +59,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE (
REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
)ENGINE = InnoDB; )ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS DM_BILLING (
INVOICE_ID INTEGER AUTO_INCREMENT NOT NULL,
TENANT_ID INTEGER DEFAULT 0,
DEVICE_ID INTEGER DEFAULT NULL,
BILLING_START TIMESTAMP NOT NULL,
BILLING_END TIMESTAMP NOT NULL,
PRIMARY KEY (INVOICE_ID),
CONSTRAINT fk_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
)ENGINE = InnoDB;
CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID); CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID);
CREATE INDEX IDX_DM_DEVICE_TYPE_ID_DEVICE_IDENTIFICATION ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID,DEVICE_IDENTIFICATION); CREATE INDEX IDX_DM_DEVICE_TYPE_ID_DEVICE_IDENTIFICATION ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID,DEVICE_IDENTIFICATION);
@ -129,7 +118,6 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL, DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL,
TENANT_ID INT NOT NULL, TENANT_ID INT NOT NULL,
LAST_BILLED_DATE BIGINT DEFAULT 0,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION

@ -124,19 +124,6 @@ WHEN (NEW.ID IS NULL)
END; END;
/ /
CREATE TABLE DM_BILLING (
INVOICE_ID NUMBER(10) NOT NULL,
TENANT_ID NUMBER(10) DEFAULT 0,
DEVICE_ID NUMBER(10) DEFAULT NULL,
BILLING_START TIMESTAMP NOT NULL,
BILLING_END TIMESTAMP NOT NULL,
CONSTRAINT PK_DM_BILLING PRIMARY KEY (INVOICE_ID),
CONSTRAINT fk_DM_BILLING_DM_DEVICE2
FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID)
)
/
CREATE TABLE DM_DEVICE_PROPERTIES ( CREATE TABLE DM_DEVICE_PROPERTIES (
DEVICE_TYPE_NAME VARCHAR2(300) NOT NULL, DEVICE_TYPE_NAME VARCHAR2(300) NOT NULL,
DEVICE_IDENTIFICATION VARCHAR2(300) NOT NULL, DEVICE_IDENTIFICATION VARCHAR2(300) NOT NULL,
@ -221,7 +208,6 @@ CREATE TABLE DM_ENROLMENT (
DATE_OF_ENROLMENT TIMESTAMP(0) DEFAULT NULL, DATE_OF_ENROLMENT TIMESTAMP(0) DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP(0) DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP(0) DEFAULT NULL,
TENANT_ID NUMBER(10) NOT NULL, TENANT_ID NUMBER(10) NOT NULL,
LAST_BILLED_DATE BIGINT DEFAULT 0,
CONSTRAINT PK_DM_ENROLMENT PRIMARY KEY (ID), CONSTRAINT PK_DM_ENROLMENT PRIMARY KEY (ID),
CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) DM_DEVICE (ID)

@ -57,17 +57,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE (
REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
); );
CREATE TABLE IF NOT EXISTS DM_BILLING (
INVOICE_ID INTEGER DEFAULT NEXTVAL ('DM_BILLING_seq') NOT NULL,
TENANT_ID INTEGER DEFAULT 0,
DEVICE_ID INTEGER DEFAULT NULL,
BILLING_START TIMESTAMP(0) NOT NULL,
BILLING_END TIMESTAMP(0) NOT NULL,
PRIMARY KEY (INVOICE_ID),
CONSTRAINT fk_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID); CREATE INDEX IDX_DM_DEVICE ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID);
CREATE INDEX IDX_DM_DEVICE_TYPE_ID_DEVICE_IDENTIFICATION ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID,DEVICE_IDENTIFICATION); CREATE INDEX IDX_DM_DEVICE_TYPE_ID_DEVICE_IDENTIFICATION ON DM_DEVICE(TENANT_ID, DEVICE_TYPE_ID,DEVICE_IDENTIFICATION);
@ -127,7 +116,6 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
DATE_OF_ENROLMENT TIMESTAMP(0) NULL DEFAULT NULL, DATE_OF_ENROLMENT TIMESTAMP(0) NULL DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP(0) NULL DEFAULT NULL, DATE_OF_LAST_UPDATE TIMESTAMP(0) NULL DEFAULT NULL,
TENANT_ID INTEGER NOT NULL, TENANT_ID INTEGER NOT NULL,
LAST_BILLED_DATE BIGINT DEFAULT 0,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION

Loading…
Cancel
Save