Add device status filter apis

pull/250/head
Pramila Niroshan 1 year ago
parent a2544c1520
commit e6ca2e0d1c

@ -0,0 +1,241 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api;
import io.entgra.device.mgt.core.apimgt.annotations.Scope;
import io.entgra.device.mgt.core.apimgt.annotations.Scopes;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.beans.ErrorResponse;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.Constants;
import io.swagger.annotations.*;
import org.apache.axis2.transport.http.HTTPConstants;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* Metadata related REST-API implementation.
*/
@SwaggerDefinition(
info = @Info(
version = "1.0.0",
title = "Device Status Filter Service",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name", value = "DeviceStatusManagement"),
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/device-status-filter"),
})
}
),
tags = {
@Tag(name = "device_management")
}
)
@Scopes(
scopes = {
@Scope(
name = "View Device Status Filter",
description = "View device status details",
key = "dm:devicestatusfilter:view",
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devicestatusfilter/view"}
),
@Scope(
name = "Update Device status filter",
description = "Updating Device status filter",
key = "dm:devicestatusfilter:update",
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devicestatusfilter/update"}
),
}
)
@Api(value = "Device Status Management")
@Path("/device-status-filters")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface DeviceStatusFilterService {
@GET
@ApiOperation(
httpMethod = HTTPConstants.HEADER_GET,
value = "Get device status filters",
notes = "Get device status filters for the tenant of the logged in user",
tags = "Tenant Metadata Management"
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved device status filters.",
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 = 500,
message = "Internal Server Error. " +
"\n Server error occurred while getting device status filters.",
response = ErrorResponse.class)
})
Response getDeviceStatusFilters( @ApiParam(
name = "deviceType",
value = "The device type.",
required = true) @QueryParam("device-type") String deviceType);
@GET
@Path("/is-enabled")
@ApiOperation(
httpMethod = HTTPConstants.HEADER_GET,
value = "Get device status filter",
notes = "Get device status filter enable or not for the tenant of the logged in user",
tags = "Tenant Metadata Management"
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved device status filter.",
response = Response.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 = 500,
message = "Internal Server Error. " +
"\n Server error occurred while getting white label artifact.",
response = ErrorResponse.class)
})
Response getDeviceStatusCheck();
@PUT
@Path("/is-enabled")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HTTPConstants.HEADER_POST,
value = "Update Device status check for tenant",
notes = "Update Device status check for the tenant of the logged in user",
tags = "Tenant Metadata Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "dm:devicestatusfilter:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully updated device status check.",
response = Response.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 = 500,
message = "Internal Server Error. " +
"\n Server error occurred while updating device status check.",
response = ErrorResponse.class)
})
Response updateDeviceStatusCheck(
@ApiParam(
name = "Device status check",
value = "The device status filtering is enable or not.",
required = true)
@QueryParam("isEnabled") boolean isEnabled);
@PUT
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HTTPConstants.HEADER_POST,
value = "Update Device status filters for given device type for tenant",
notes = "Update Device status filters for given device type for the tenant of the logged in user",
tags = "Tenant Metadata Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "dm:devicestatusfilter:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully updated device status filters for given device type..",
response = Response.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 = 500,
message = "Internal Server Error. " +
"\n Server error occurred while updating device status filters for given device type.",
response = ErrorResponse.class)
})
Response updateDeviceStatusFilters(
@ApiParam(
name = "deviceType",
value = "The device type for which you want to update device status filters.",
required = true)
@QueryParam("deviceType") String deviceType,
@ApiParam(
name = "deviceStatus",
value = "A list of device status values to update for the given device type.",
required = true)
@QueryParam("deviceStatus") List<String> deviceStatus);
}

@ -0,0 +1,124 @@
/*
* Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.api.DeviceStatusFilterService;
import io.entgra.device.mgt.core.device.mgt.api.jaxrs.util.DeviceMgtAPIUtils;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
@Path("/device-status-filters")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class DeviceStatusFilterServiceImpl implements DeviceStatusFilterService {
private static final Log log = LogFactory.getLog(DeviceStatusFilterServiceImpl.class);
@Override
@GET
public Response getDeviceStatusFilters(@QueryParam("deviceType") String deviceType) {
List<String> result;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
DeviceStatusManagementService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceStatusManagmentService();
result = deviceManagementProviderService.getDeviceStatusFilters(deviceType, tenantId);
if (result != null && !result.isEmpty()) {
return Response.status(Response.Status.OK).entity(result).build();
} else {
return Response.status(Response.Status.NO_CONTENT).build();
}
} catch (MetadataManagementException e) {
String msg = "Error occurred while getting device status filter of the tenant.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Path("/is-enabled")
@Override
public Response getDeviceStatusCheck() {
boolean result;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
DeviceStatusManagementService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceStatusManagmentService();
result = deviceManagementProviderService.getDeviceStatusCheck(tenantId);
if (result) {
return Response.status(Response.Status.OK).entity(true).build();
} else {
return Response.status(Response.Status.NO_CONTENT).entity(false).build();
}
} catch (MetadataManagementException e) {
String msg = "Error occurred while getting device status filter of the tenant.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@PUT
@Path("/is-enabled")
public Response updateDeviceStatusCheck(
@QueryParam("isEnabled")
boolean isEnabled) {
boolean result;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
DeviceStatusManagementService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceStatusManagmentService();
result = deviceManagementProviderService.updateDefaultDeviceStatusCheck(tenantId, isEnabled);
if (result) {
return Response.status(Response.Status.OK).entity("Successfully updated device status check.").build();
} else {
return Response.status(Response.Status.NO_CONTENT).entity(false).build();
}
} catch (MetadataManagementException e) {
String msg = "Error occurred while updating device status check.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@Override
@PUT
public Response updateDeviceStatusFilters(
@QueryParam("deviceType")
String deviceType,
@QueryParam("deviceStatus")
List<String> deviceStatus
) {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
DeviceStatusManagementService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceStatusManagmentService();
deviceManagementProviderService.updateDefaultDeviceStatusFilters(tenantId, deviceType, deviceStatus);
return Response.status(Response.Status.OK).entity("Successfully updated device status filters for" + deviceType).build();
} catch (MetadataManagementException e) {
String msg = "Error occurred while updating device status for" + deviceType;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -50,6 +50,7 @@
<ref bean="analyticsArtifactsManagementService"/>
<ref bean="metadataService"/>
<ref bean="whitelabelService"/>
<ref bean="deviceStatusFilterService"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
@ -101,6 +102,7 @@
<bean id="analyticsArtifactsManagementService" class="io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.AnalyticsArtifactsManagementServiceImpl"/>
<bean id="metadataService" class="io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.MetadataServiceImpl"/>
<bean id="whitelabelService" class="io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.WhiteLabelServiceImpl"/>
<bean id="deviceStatusFilterService" class="io.entgra.device.mgt.core.device.mgt.api.jaxrs.service.impl.DeviceStatusFilterServiceImpl"/>
<!--<bean id="errorHandler" class="io.entgra.device.mgt.core.device.mgt.api.jaxrs.common.ErrorHandler"/>-->
<cxf:bus>

@ -45,9 +45,16 @@ public interface DeviceStatusManagementService {
*
* @throws MetadataManagementException if error while updating existing device status
*/
void updateDefaultDeviceStatusFilter(int tenantId)
void updateDefaultDeviceStatusFilters(int tenantId, String deviceType, List<String> deviceStatus)
throws MetadataManagementException;
/**
* This method is useful to update existing device status check
*
* @throws MetadataManagementException if error while updating existing device status
*/
boolean updateDefaultDeviceStatusCheck(int tenantId, boolean isChecked)
throws MetadataManagementException;
/**
* This method is useful to get existing device status filters
*
@ -55,6 +62,13 @@ public interface DeviceStatusManagementService {
*/
List<AllowedDeviceStatus> getDeviceStatusFilters(int tenantId) throws MetadataManagementException;
/**
* This method is useful to get existing device status filters by device type and tenant id
*
* @throws MetadataManagementException if error while getting existing device status
*/
List<String> getDeviceStatusFilters(String deviceType, int tenantId) throws MetadataManagementException;
/**
* This method is useful to get existing device status filters
*
@ -62,5 +76,10 @@ public interface DeviceStatusManagementService {
*/
boolean getDeviceStatusCheck(int tenantId) throws MetadataManagementException;
/**
* This method is useful to check status is valid for device type
*
* @throws MetadataManagementException if error while getting existing device status check
*/
boolean isDeviceStatusValid(String deviceType, String deviceStatus, int tenantId) throws MetadataManagementException;
}

@ -39,6 +39,7 @@ import org.apache.commons.logging.LogFactory;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -84,8 +85,68 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement
}
@Override
public void updateDefaultDeviceStatusFilter(int tenantId) throws MetadataManagementException {
public void updateDefaultDeviceStatusFilters(int tenantId, String deviceType, List<String> deviceStatus) throws MetadataManagementException {
try {
MetadataManagementDAOFactory.beginTransaction();
// Retrieve the current device status metadata
Metadata metadata = metadataDAO.getMetadata(tenantId, MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY);
if (metadata != null) {
Gson gson = new Gson();
Type listType = new TypeToken<List<AllowedDeviceStatus>>() {
}.getType();
List<AllowedDeviceStatus> currentStatusList = gson.fromJson(metadata.getMetaValue(), listType);
// Find the status for the specified deviceType
for (AllowedDeviceStatus status : currentStatusList) {
if (status.getType().equalsIgnoreCase(deviceType)) {
// Update the status list for the specified deviceType
status.setStatus(deviceStatus);
break;
}
}
metadata.setMetaValue(gson.toJson(currentStatusList));
updateMetadataEntry(tenantId, metadata, MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY);
}
MetadataManagementDAOFactory.commitTransaction();
} catch (MetadataManagementDAOException e) {
MetadataManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while updating device status metadata entry.";
log.error(msg, e);
throw new MetadataManagementException(msg, e);
} catch (TransactionManagementException e) {
String msg = "Error occurred while opening a connection to the data source";
log.error(msg, e);
throw new MetadataManagementException(msg, e);
} finally {
MetadataManagementDAOFactory.closeConnection();
}
}
@Override
public boolean updateDefaultDeviceStatusCheck(int tenantId, boolean isChecked) throws MetadataManagementException {
boolean success = false;
try {
MetadataManagementDAOFactory.beginTransaction();
if (metadataDAO.isExist(tenantId, MetadataConstants.IS_DEVICE_STATUS_CHECK_META_KEY)) {
Metadata isDeviceStatusChecked = constructDeviceStatusCheckMetadata(isChecked);
// Add default device status check metadata entries
updateMetadataEntry(tenantId, isDeviceStatusChecked, MetadataConstants.IS_DEVICE_STATUS_CHECK_META_KEY);
success = true;
}
MetadataManagementDAOFactory.commitTransaction();
} catch (MetadataManagementDAOException e) {
MetadataManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while updating device status check metadata entry.";
log.error(msg, e);
throw new MetadataManagementException(msg, e);
} catch (TransactionManagementException e) {
String msg = "Error occurred while opening a connection to the data source";
log.error(msg, e);
throw new MetadataManagementException(msg, e);
} finally {
MetadataManagementDAOFactory.closeConnection();
}
return success;
}
@Override
@ -112,6 +173,35 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement
}
public List<String> getDeviceStatusFilters(String deviceType, int tenantId) throws MetadataManagementException {
try {
MetadataManagementDAOFactory.openConnection();
Metadata metadata = metadataDAO.getMetadata(tenantId, MetadataConstants.ALLOWED_DEVICE_STATUS_META_KEY);
Gson gson = new Gson();
Type listType = new TypeToken<List<AllowedDeviceStatus>>() {}.getType();
List<AllowedDeviceStatus> statusList = gson.fromJson(metadata.getMetaValue(), listType);
for (AllowedDeviceStatus status : statusList) {
if (status.getType().equalsIgnoreCase(deviceType)) {
return status.getStatus();
}
}
// Device type not found in metadata
return Collections.emptyList();
} catch (MetadataManagementDAOException e) {
String msg = "Error occurred while retrieving device status meta data for tenant: " + tenantId;
log.error(msg, e);
throw new MetadataManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source";
log.error(msg, e);
throw new MetadataManagementException(msg, e);
} finally {
MetadataManagementDAOFactory.closeConnection();
}
}
@Override
public boolean getDeviceStatusCheck(int tenantId) throws MetadataManagementException {
try {
@ -171,6 +261,13 @@ public class DeviceStatusManagementServiceImpl implements DeviceStatusManagement
}
}
private void updateMetadataEntry(int tenantId, Metadata metadata, String key) throws MetadataManagementDAOException {
metadataDAO.updateMetadata(tenantId, metadata);
if (log.isDebugEnabled()) {
log.debug(key + " metadata entry has been updated successfully");
}
}
private Metadata constructDeviceStatusMetadata(List<DeviceStatusItem> deviceStatusItems) {
Gson gson = new Gson();
String deviceStatusItemsJsonString = gson.toJson(deviceStatusItems);

@ -210,7 +210,6 @@
</AllowedStatus>
</DeviceStatusItem>
</DeviceStatusConfigurations>
CREATED, ACTIVE, INACTIVE, UNREACHABLE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED, DISENROLLMENT_REQUESTED,
<AppRegistration>
<Tags>
<Tag>analytics_management</Tag>
@ -378,6 +377,8 @@
<Scope>dm:geo:geo-fence:manage</Scope>
<Scope>dm:whitelable:view</Scope>
<Scope>dm:whitelable:update</Scope>
<Scope>dm:devicestatusfilter:view</Scope>
<Scope>dm:devicestatusfilter:update</Scope>
<Scope>dm:metadata:view</Scope>
<Scope>dm:metadata:create</Scope>
<Scope>dm:metadata:update</Scope>

Loading…
Cancel
Save