Add event delete API

4.x.x
Pahansith 4 years ago
parent fed779302a
commit d9d0ba5d90

@ -799,7 +799,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
for (int eventId : eventIds) {
eventsToRemove.add(eventId);
}
geoService.updateGeoEventConfigurations(geofenceData.getEventConfig(), eventsToRemove,
geoService.updateGeoEventConfigurations(geofenceData, eventsToRemove,
geofenceData.getGroupIds(), fenceId);
return Response.status(Response.Status.CREATED).entity("Geo Fence update successfully").build();
} catch (GeoLocationBasedServiceException e) {

@ -50,4 +50,7 @@ public interface EventConfigurationProviderService {
List<EventConfig> getEventsOfGroup(int groupId, int tenantId) throws EventConfigurationException;
List<String> getEventsSourcesOfGroup(int groupId, int tenantId) throws EventConfigurationException;
void deleteEvents(List<EventConfig> eventList) throws EventConfigurationException;
}

@ -0,0 +1,39 @@
/*
* Copyright (c) 2020, 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 org.wso2.carbon.device.mgt.common.event.config;
public class EventRevokeOperation {
private String eventSource;
private int id;
public String getEventSource() {
return eventSource;
}
public void setEventSource(String eventSource) {
this.eventSource = eventSource;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}

@ -136,14 +136,14 @@ public interface GeoLocationProviderService {
/**
* Update geofence event configuration
* @param eventConfig updated event configurations list
* @param geofenceData updated GeoFenceData object
* @param removedEventIdList removed event ids
* @param groupIds newly added group ids to be mapped with event records
* @param fenceId updating fence id
* @return true for successful update of geofence event data
* @throws GeoLocationBasedServiceException any errors occurred while updating event records of the fence
*/
boolean updateGeoEventConfigurations(List<EventConfig> eventConfig, List<Integer> removedEventIdList,
boolean updateGeoEventConfigurations(GeofenceData geofenceData, List<Integer> removedEventIdList,
List<Integer> groupIds, int fenceId) throws GeoLocationBasedServiceException;
List<GeofenceData> getGeoFenceEvents(List<GeofenceData> geoFences) throws GeoLocationBasedServiceException;
@ -151,4 +151,6 @@ public interface GeoLocationProviderService {
List<GeofenceData> getGeoFencesOfGroup(int groupId, int tenantId, boolean requireEventData) throws GeoLocationBasedServiceException;
List<EventConfig> getEventsOfGeoFence(int geoFenceId) throws GeoLocationBasedServiceException;
void deleteGeoFenceEvents(GeofenceData geofenceData, List<EventConfig> eventConfigList) throws GeoLocationBasedServiceException;
}

@ -98,6 +98,8 @@ public final class DeviceManagementConstants {
public static final String MONITOR_OPERATION_CODE = "MONITOR";
public static final String POLICY_OPERATION_CODE = PolicyOperation.POLICY_OPERATION_CODE;
public static final String POLICY_REVOKE_OPERATION_CODE = OperationMgtConstants.OperationCodes.POLICY_REVOKE;
public static final String EVENT_CONFIG_OPERATION_CODE = OperationMgtConstants.OperationCodes.EVENT_CONFIG;
public static final String EVENT_REVOKE_OPERATION_CODE = OperationMgtConstants.OperationCodes.EVENT_REVOKE;
}
public static final class CorrectiveActions {

@ -139,4 +139,5 @@ public interface GeofenceDAO {
List<GeofenceData> getGeoFences(int groupId, int tenantId) throws DeviceManagementDAOException;
GeofenceData getGeofence(int fenceId, boolean requireGroupData) throws DeviceManagementDAOException;
}

@ -150,7 +150,6 @@ public abstract class AbstractEventConfigDAO implements EventConfigDAO {
int index = 1;
for (Integer eventId : eventsIdsToDelete) {
stmt.setInt(index++, eventId);
stmt.addBatch();
}
stmt.executeUpdate();
}

@ -575,4 +575,56 @@ public class GeofenceDAOImpl implements GeofenceDAO {
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public GeofenceData getGeofence(int fenceId, boolean requireGroupData) throws DeviceManagementDAOException {
if (!requireGroupData) {
return getGeofence(fenceId);
}
try {
Connection con = this.getConnection();
String sql = "SELECT " +
"G.ID AS FENCE_ID, " +
"FENCE_NAME, " +
"G.DESCRIPTION, " +
"LATITUDE, " +
"LONGITUDE, " +
"RADIUS, " +
"GEO_JSON, " +
"FENCE_SHAPE, " +
"M.GROUP_ID AS GROUP_ID, " +
"GR.GROUP_NAME " +
"FROM DM_GEOFENCE G, DM_GEOFENCE_GROUP_MAPPING M, DM_GROUP GR " +
"WHERE G.ID = M.FENCE_ID " +
"AND M.GROUP_ID = GR.ID " +
"AND G.ID = ?";
try (PreparedStatement stmt = con.prepareStatement(sql)){
stmt.setInt(1, fenceId);
ResultSet rst = stmt.executeQuery();
List<Integer> groupIdList = new ArrayList<>();
GeofenceData geofenceData = null;
while (rst.next()) {
groupIdList.add(rst.getInt("GROUP_ID"));
if (rst.isLast()) {
geofenceData = new GeofenceData();
geofenceData.setId(rst.getInt("FENCE_ID"));
geofenceData.setFenceName(rst.getString("FENCE_NAME"));
geofenceData.setDescription(rst.getString("DESCRIPTION"));
geofenceData.setLatitude(rst.getDouble("LATITUDE"));
geofenceData.setLongitude(rst.getDouble("LONGITUDE"));
geofenceData.setRadius(rst.getFloat("RADIUS"));
geofenceData.setGeoJson(rst.getString("GEO_JSON"));
geofenceData.setFenceShape(rst.getString("FENCE_SHAPE"));
geofenceData.setGroupIds(groupIdList);
}
}
return geofenceData;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving Geo fence data " + fenceId;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
}

@ -18,13 +18,16 @@
package org.wso2.carbon.device.mgt.core.event.config;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationException;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService;
import org.wso2.carbon.device.mgt.common.event.config.EventOperation;
import org.wso2.carbon.device.mgt.common.event.config.EventRevokeOperation;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.geo.service.GeoFenceEventMeta;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException;
@ -32,11 +35,13 @@ import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.geo.service.GeofenceData;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.geo.task.EventCreateCallback;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -46,11 +51,18 @@ public class DeviceEventOperationExecutor implements Runnable {
private final int groupId;
private final List<DeviceIdentifier> deviceIdentifiers;
private final int tenantId;
private final String operationCode;
private final GeoLocationProviderService geoLocationProviderService;
private final EventConfigurationProviderService eventConfigurationService;
private EventCreateCallback callback;
public DeviceEventOperationExecutor(int groupId, List<DeviceIdentifier> deviceIdentifiers, int tenantId) {
public DeviceEventOperationExecutor(int groupId, List<DeviceIdentifier> deviceIdentifiers, int tenantId, String operationCode) {
this.groupId = groupId;
this.deviceIdentifiers = deviceIdentifiers;
this.tenantId = tenantId;
this.operationCode = operationCode;
this.geoLocationProviderService = DeviceManagementDataHolder.getInstance().getGeoLocationProviderService();
this.eventConfigurationService = DeviceManagementDataHolder.getInstance().getEventConfigurationService();
}
@Override
@ -58,66 +70,113 @@ public class DeviceEventOperationExecutor implements Runnable {
log.info("Starting event operation creation task for devices in group " + groupId + " tenant " + tenantId);
if (log.isDebugEnabled()) {
log.debug("Event creation operation started for devices with IDs " + Arrays.toString(deviceIdentifiers.toArray()));
log.debug("Starting tenant flow for tenant with ID : " + tenantId);
}
ProfileOperation operation = new ProfileOperation();
operation.setCode(OperationMgtConstants.OperationCodes.EVENT_CONFIG);
operation.setType(Operation.Type.PROFILE);
EventConfigurationProviderService eventConfigurationService = DeviceManagementDataHolder.getInstance().getEventConfigurationService();
try {
List<String> eventSources = eventConfigurationService.getEventsSourcesOfGroup(groupId, tenantId);
if (eventSources == null || eventSources.isEmpty()) {
log.info("No events applied for queried group with ID " + groupId);
}
for (String eventSource : eventSources) {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
setGeoFenceOperationContent(operation);
} //extend with another cases to handle other types of events
if (operationCode != null) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
try {
operation.setCode(operationCode);
operation.setType(Operation.Type.PROFILE);
if (operationCode.equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_CONFIG)) {
buildEventConfigOperationObject(operation);
} else if (operationCode.equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_REVOKE)) {
buildEventRevokeOperation(operation);
}
} catch (EventConfigurationException e) {
log.error("Failed to retrieve event sources of group " + groupId + ". Event creation operation failed.", e);
return;
} catch (GeoLocationBasedServiceException e) {
log.error("Failed to retrieve geo fences for group " + groupId + ". Event creation operation failed.", e);
return;
}
} catch (EventConfigurationException e) {
log.error("Failed to retrieve event sources of group " + groupId, e);
}
DeviceManagementProviderService deviceManagementProvider = DeviceManagementDataHolder
.getInstance().getDeviceManagementProvider();
try {
if (!deviceIdentifiers.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Creating event operations stared");
DeviceManagementProviderService deviceManagementProvider = DeviceManagementDataHolder
.getInstance().getDeviceManagementProvider();
try {
if (!deviceIdentifiers.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Creating event operations stared");
}
deviceManagementProvider.addOperation("android", operation, deviceIdentifiers); //TODO introduce a proper mechanism
} else {
log.info("Device identifiers are empty, Hence ignoring adding event operation");
}
deviceManagementProvider.addOperation("android", operation, deviceIdentifiers); //TODO introduce a proper mechanism
} else {
log.info("Device identifiers are empty, Hence ignoring adding event operation");
} catch (OperationManagementException e) {
log.error("Creating event operation failed with error ", e);
} catch (InvalidDeviceException e) {
log.error("Creating event operation failed.\n" +
"Could not found device/devices for the defined device identifiers.", e);
}
log.info("Event operation creation succeeded");
if (callback != null) {
callback.onCompleteEventOperation(null);
}
} catch (OperationManagementException e) {
log.error("Creating event operation failed with error ", e);
} catch (InvalidDeviceException e) {
log.error("Creating event operation failed.\n" +
"Could not found device/devices for the defined device identifiers.", e);
}
log.info("Event operation creation succeeded");
}
private void setGeoFenceOperationContent(ProfileOperation operation) {
private void buildEventRevokeOperation(ProfileOperation operation) throws GeoLocationBasedServiceException, EventConfigurationException {
List<String> eventSources = eventConfigurationService.getEventsSourcesOfGroup(groupId, tenantId);
if (eventSources == null || eventSources.isEmpty()) {
String msg = "No events applied for queried group with ID " + groupId;
log.info(msg);
throw new EventConfigurationException(msg);
}
for (String eventSource : eventSources) {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
setGeoFenceRevokeOperationContent(operation);
} //extend with another cases to handle other types of events
}
}
private void buildEventConfigOperationObject(ProfileOperation operation) throws EventConfigurationException, GeoLocationBasedServiceException {
List<String> eventSources = eventConfigurationService.getEventsSourcesOfGroup(groupId, tenantId);
if (eventSources == null || eventSources.isEmpty()) {
String msg = "No events applied for queried group with ID " + groupId;
log.info(msg);
throw new EventConfigurationException(msg);
}
for (String eventSource : eventSources) {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
setGeoFenceConfigOperationContent(operation);
} //extend with another cases to handle other types of events
}
}
private void setGeoFenceConfigOperationContent(ProfileOperation operation) throws GeoLocationBasedServiceException {
log.info("Geo fence events found attached with group " + groupId + ", Started retrieving geo fences");
GeoLocationProviderService geoLocationProviderService = DeviceManagementDataHolder.getInstance().getGeoLocationProviderService();
try {
List<GeofenceData> geoFencesOfGroup = geoLocationProviderService.getGeoFencesOfGroup(groupId, tenantId, true);
if (log.isDebugEnabled()) {
log.debug("Retrieved " + geoFencesOfGroup.size() + " geo fences defined for the group " + groupId);
}
for (GeofenceData geofenceData : geoFencesOfGroup) {
GeoFenceEventMeta geoFenceEventMeta = new GeoFenceEventMeta(geofenceData);
EventOperation eventOperation = new EventOperation();
eventOperation.setEventDefinition(geoFenceEventMeta);
eventOperation.setEventSource(DeviceManagementConstants.EventServices.GEOFENCE);
eventOperation.setEventTriggers(geofenceData.getEventConfig());
if (operation.getPayLoad() != null) {
operation.setPayLoad(operation.getPayLoad().toString().concat(eventOperation.toJSON()));
} else {
operation.setPayLoad(eventOperation.toJSON());
}
}
} catch (GeoLocationBasedServiceException e) {
log.error("Failed to retrieve geo fences for group " + groupId);
List<GeofenceData> geoFencesOfGroup = geoLocationProviderService.getGeoFencesOfGroup(groupId, tenantId, true);
if (log.isDebugEnabled()) {
log.debug("Retrieved " + geoFencesOfGroup.size() + " geo fences defined for the group " + groupId);
}
List<EventOperation> eventOperationList = new ArrayList<>();
for (GeofenceData geofenceData : geoFencesOfGroup) {
GeoFenceEventMeta geoFenceEventMeta = new GeoFenceEventMeta(geofenceData);
EventOperation eventOperation = new EventOperation();
eventOperation.setEventDefinition(geoFenceEventMeta);
eventOperation.setEventSource(DeviceManagementConstants.EventServices.GEOFENCE);
eventOperation.setEventTriggers(geofenceData.getEventConfig());
eventOperationList.add(eventOperation);
}
operation.setPayLoad(new Gson().toJson(eventOperationList));
}
private void setGeoFenceRevokeOperationContent(ProfileOperation operation) throws GeoLocationBasedServiceException {
List<GeofenceData> geoFencesOfGroup = geoLocationProviderService.getGeoFencesOfGroup(groupId, tenantId, true);
List<EventRevokeOperation> revokeOperationList = new ArrayList<>();
for (GeofenceData geofenceData : geoFencesOfGroup) {
EventRevokeOperation eventRevokeOperation = new EventRevokeOperation();
eventRevokeOperation.setEventSource(DeviceManagementConstants.EventServices.GEOFENCE);
eventRevokeOperation.setId(geofenceData.getId());
revokeOperationList.add(eventRevokeOperation);
}
operation.setPayLoad(new Gson().toJson(revokeOperationList));
}
public void setCallback(EventCreateCallback callback) {
this.callback = callback;
}
}

@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.core.event.config;
import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.event.config.EventAction;
@ -25,16 +26,20 @@ import org.wso2.carbon.device.mgt.common.event.config.EventConfig;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationException;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
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.EventConfigDAO;
import org.wso2.carbon.device.mgt.core.dao.EventManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.geo.task.GeoFenceEventOperationManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ -116,30 +121,40 @@ public class EventConfigurationProviderServiceImpl implements EventConfiguration
groupIdsToAdd.add(newGroupId);
}
}
if (log.isDebugEnabled()) {
log.debug("Updating event records ");
}
eventConfigDAO.updateEventRecords(eventsToUpdate, tenantId);
if (log.isDebugEnabled()) {
log.debug("Deleting event group mapping records of groups");
if (!eventsToUpdate.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Updating event records ");
}
eventConfigDAO.updateEventRecords(eventsToUpdate, tenantId);
}
eventConfigDAO.deleteEventGroupMappingRecordsByGroupIds(groupIdsToDelete);
if (log.isDebugEnabled()) {
log.debug("Creating event group mapping records for updated events");
if (!groupIdsToDelete.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Deleting event group mapping records of groups");
}
eventConfigDAO.deleteEventGroupMappingRecordsByGroupIds(groupIdsToDelete);
}
eventConfigDAO.addEventGroupMappingRecords(updateEventIdList, groupIdsToAdd);
if (log.isDebugEnabled()) {
log.debug("Deleting event group mapping records of removing events");
if (!groupIdsToAdd.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Creating event group mapping records for updated events");
}
eventConfigDAO.addEventGroupMappingRecords(updateEventIdList, groupIdsToAdd);
}
eventConfigDAO.deleteEventGroupMappingRecordsByEventIds(removedEventIdList);
if (log.isDebugEnabled()) {
log.debug("Deleting removed event records");
if (!removedEventIdList.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Deleting event group mapping records of removing events");
}
eventConfigDAO.deleteEventGroupMappingRecordsByEventIds(removedEventIdList);
if (log.isDebugEnabled()) {
log.debug("Deleting removed event records");
}
eventConfigDAO.deleteEventRecords(removedEventIdList, tenantId);
}
eventConfigDAO.deleteEventRecords(removedEventIdList, tenantId);
DeviceManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {
String msg = "Failed to start/open transaction to store device event configurations";
@ -212,4 +227,36 @@ public class EventConfigurationProviderServiceImpl implements EventConfiguration
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public void deleteEvents(List<EventConfig> eventsOfGeoFence) throws EventConfigurationException {
int tenantId;
try {
tenantId = DeviceManagementDAOUtil.getTenantId();
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving tenant Id";
log.error(msg, e);
throw new EventConfigurationException(msg, e);
}
try {
DeviceManagementDAOFactory.beginTransaction();
Set<Integer> eventIdSet = new HashSet<>();
for (EventConfig eventConfig : eventsOfGeoFence) {
eventIdSet.add(eventConfig.getEventId());
}
if (!eventIdSet.isEmpty()) {
eventConfigDAO.deleteEventGroupMappingRecordsByEventIds(Lists.newArrayList(eventIdSet));
eventConfigDAO.deleteEventRecords(Lists.newArrayList(eventIdSet), tenantId);
}
DeviceManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {
String msg = "Failed to start/open transaction to delete device event configurations";
throw new EventConfigurationException(msg, e);
} catch (EventManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while deleting event records";
log.error(msg, e);
throw new EventConfigurationException(msg, e);
}
}
}

@ -26,8 +26,10 @@ import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.event.config.EventConfig;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationException;
import org.wso2.carbon.device.mgt.common.event.config.EventMetaData;
import org.wso2.carbon.device.mgt.common.event.config.EventOperation;
import org.wso2.carbon.device.mgt.common.event.config.EventRevokeOperation;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.geo.service.GeoFenceEventMeta;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException;
@ -36,6 +38,7 @@ import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.geo.task.EventCreateCallback;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
@ -55,24 +58,47 @@ public class GroupEventOperationExecutor implements Runnable {
private final String eventSource;
private final EventMetaData eventMetaData;
private final int tenantId;
private final String operationCode;
private final GroupManagementProviderService groupManagementService;
private EventCreateCallback callback;
public GroupEventOperationExecutor(EventMetaData eventMetaData, List<Integer> groupIds, int tenantId, String eventSource) {
public GroupEventOperationExecutor(EventMetaData eventMetaData, List<Integer> groupIds, int tenantId,
String eventSource, String operationCode) {
this.eventMetaData = eventMetaData;
this.groupIds = groupIds;
this.tenantId = tenantId;
this.eventSource = eventSource;
this.operationCode = operationCode;
this.groupManagementService = DeviceManagementDataHolder.getInstance().getGroupManagementProviderService();
}
@Override
public void run() {
log.info("Starting event operation creation task for event " + eventSource + " tenant " + tenantId);
log.info("Starting event operation creation task");
if (operationCode == null) {
log.error("Failed to start event operation task. Operation code is null");
return;
}
if (log.isDebugEnabled()) {
log.debug("Event creation operation started for groups with IDs " + Arrays.toString(groupIds.toArray()));
log.info("Starting " + operationCode + " operation creation task for event " + eventSource
+ " tenant " + tenantId + " group Ids "+ Arrays.toString(groupIds.toArray()));
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
GroupManagementProviderService groupManagementService = DeviceManagementDataHolder
.getInstance().getGroupManagementProviderService();
ProfileOperation operation = new ProfileOperation();
operation.setType(Operation.Type.PROFILE);
try {
if (operationCode.equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_CONFIG)) {
operation.setCode(OperationMgtConstants.OperationCodes.EVENT_CONFIG);
buildEventConfigOperation(operation);
} else if (operationCode.equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_REVOKE)){
operation.setCode(OperationMgtConstants.OperationCodes.EVENT_REVOKE);
buildEventRevokeOperation(operation);
}
} catch (EventConfigurationException e) {
log.error("Event creation failed with message : " + e.getMessage(), e);
return;
}
Set<Device> devices = new HashSet<>();
for (Integer groupId : groupIds) {
DeviceGroup group;
@ -86,7 +112,7 @@ public class GroupEventOperationExecutor implements Runnable {
if (group != null) {
List<Device> allDevicesOfGroup = groupManagementService.getAllDevicesOfGroup(group.getName(), false);
if (allDevicesOfGroup == null || allDevicesOfGroup.isEmpty()) {
log.info("No devices found in group " + group.getName());
log.warn("No devices found in group " + group.getName());
} else {
devices.addAll(allDevicesOfGroup);
}
@ -95,44 +121,61 @@ public class GroupEventOperationExecutor implements Runnable {
log.error("Failed to retrieve devices of group with ID " + groupId + " and name " + group.getName(), e);
}
}
ProfileOperation operation = new ProfileOperation();
operation.setCode(OperationMgtConstants.OperationCodes.EVENT_CONFIG);
operation.setType(Operation.Type.PROFILE);
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
createGeoFenceOperation(operation);
} //extend with another cases to handle other types of events
if (log.isDebugEnabled()) {
log.debug("Starting tenant flow for tenant id " + tenantId);
if (devices.isEmpty()) {
log.warn("No devices found for the specified groups " + Arrays.toString(groupIds.toArray()));
return;
}
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
for (Device device : devices) {
if (device.getType().equalsIgnoreCase("android")) { //TODO introduce a proper mechanism for event handling for each device types
if (device.getType().equalsIgnoreCase("android")) {
//TODO introduce a proper mechanism for event handling for each device types
deviceIdentifiers.add(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
}
}
DeviceManagementProviderService deviceManagementProvider = DeviceManagementDataHolder
.getInstance().getDeviceManagementProvider();
try {
if (!deviceIdentifiers.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Creating event operations stared for devices" + Arrays.toString(deviceIdentifiers.toArray()));
}
deviceManagementProvider.addOperation("android", operation, deviceIdentifiers); //TODO introduce a proper mechanism
} else {
log.info("Device identifiers are empty, Hence ignoring adding event operation");
if (log.isDebugEnabled()) {
log.debug("Creating event operations stared for devices" + Arrays.toString(deviceIdentifiers.toArray()));
}
deviceManagementProvider.addOperation("android", operation, deviceIdentifiers);
//TODO introduce a proper mechanism
} catch (OperationManagementException e) {
log.error("Creating event operation failed with error ", e);
return;
} catch (InvalidDeviceException e) {
log.error("Creating event operation failed.\n" +
"Could not found device/devices for the defined device identifiers.", e);
return;
}
log.info("Event operation creation task completed");
if (callback != null) {
callback.onCompleteEventOperation(null);
}
}
private void buildEventRevokeOperation(ProfileOperation operation) {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
createGeoFenceRevokeOperation(operation);
} //extend with another cases to handle other types of events
}
private void createGeoFenceRevokeOperation(ProfileOperation operation) {
GeoFenceEventMeta geoFenceMeta = (GeoFenceEventMeta) eventMetaData;
EventRevokeOperation eventRevokeOperation = new EventRevokeOperation();
eventRevokeOperation.setEventSource(eventSource);
eventRevokeOperation.setId(geoFenceMeta.getId());
operation.setPayLoad(new Gson().toJson(eventRevokeOperation));
}
private void createGeoFenceOperation(ProfileOperation operation) {
private void buildEventConfigOperation(ProfileOperation operation) throws EventConfigurationException {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
createGeoFenceConfigOperation(operation);
} //extend with another cases to handle other types of events
}
private void createGeoFenceConfigOperation(ProfileOperation operation) throws EventConfigurationException {
GeoFenceEventMeta geoFenceMeta = (GeoFenceEventMeta) eventMetaData;
try {
GeoLocationProviderService geoLocationProviderService = DeviceManagementDataHolder
@ -149,9 +192,13 @@ public class GroupEventOperationExecutor implements Runnable {
eventOperation.setEventTriggers(eventConfigList);
eventOperations.add(eventOperation);
operation.setPayLoad(new Gson().toJson(eventOperations));
} catch (GeoLocationBasedServiceException e) {
log.error("Failed to retrieve event data of Geo fence " + geoFenceMeta.getId()
}catch (GeoLocationBasedServiceException e) {
throw new EventConfigurationException("Failed to retrieve event data of Geo fence " + geoFenceMeta.getId()
+ " : " + geoFenceMeta.getFenceName(), e);
}
}
public void setCallback(EventCreateCallback callback) {
this.callback = callback;
}
}

@ -54,8 +54,10 @@ 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.GeofenceDAO;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.geo.task.EventCreateCallback;
import org.wso2.carbon.device.mgt.core.geo.task.GeoFenceEventOperationManager;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub;
import org.wso2.carbon.event.processor.stub.types.ExecutionPlanConfigurationDto;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
@ -1289,9 +1291,9 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
}
List<Integer> createdEventIds;
try {
EventConfigurationProviderService eventConfigService = DeviceManagementDataHolder.getInstance()
.getEventConfigurationService();
setEventSource(geofenceData.getEventConfig());
EventConfigurationProviderService eventConfigService = DeviceManagementDataHolder
.getInstance().getEventConfigurationService();
createdEventIds = eventConfigService.createEventsOfDeviceGroup(geofenceData.getEventConfig(), geofenceData.getGroupIds(), tenantId);
DeviceManagementDAOFactory.beginTransaction();
geofenceDAO.createGeofenceEventMapping(geofenceData.getId(), createdEventIds);
@ -1317,15 +1319,23 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
} finally {
DeviceManagementDAOFactory.closeConnection();
}
createEventTask(geofenceData, tenantId);
createEventTask(OperationMgtConstants.OperationCodes.EVENT_CONFIG, geofenceData, tenantId);
return true;
}
private void createEventTask(GeofenceData geofenceData, int tenantId) {
GeoFenceEventOperationManager eventManager = new GeoFenceEventOperationManager();
private void createEventRevokeTask(GeofenceData geofenceData, int tenantId) {
GeoFenceEventOperationManager eventManager = new GeoFenceEventOperationManager(OperationMgtConstants.OperationCodes.EVENT_REVOKE,
tenantId, values -> createEventTask(OperationMgtConstants.OperationCodes.EVENT_CONFIG, geofenceData, tenantId));
ScheduledExecutorService eventOperationExecutor = Executors.newSingleThreadScheduledExecutor();
eventOperationExecutor.schedule(eventManager
.getGroupEventOperationExecutor(geofenceData, tenantId), 10, TimeUnit.SECONDS);
.getGroupEventOperationExecutor(geofenceData), 10, TimeUnit.SECONDS);
}
private void createEventTask(String operationCode, GeofenceData geofenceData, int tenantId) {
GeoFenceEventOperationManager eventManager = new GeoFenceEventOperationManager(operationCode, tenantId, null);
ScheduledExecutorService eventOperationExecutor = Executors.newSingleThreadScheduledExecutor();
eventOperationExecutor.schedule(eventManager
.getGroupEventOperationExecutor(geofenceData), 10, TimeUnit.SECONDS);
}
private void setEventSource(List<EventConfig> eventConfig) {
@ -1470,6 +1480,8 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
@Override
public boolean deleteGeofenceData(int fenceId) throws GeoLocationBasedServiceException {
int tenantId;
GeofenceData geofence;
List<EventConfig> eventsOfGeoFence;
try {
tenantId = DeviceManagementDAOUtil.getTenantId();
} catch (DeviceManagementDAOException e) {
@ -1480,12 +1492,25 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
try {
DeviceManagementDAOFactory.beginTransaction();
if (geofenceDAO.deleteGeofenceById(fenceId) > 0) {
DeviceManagementDAOFactory.commitTransaction();
GeoCacheManagerImpl.getInstance().removeFenceFromCache(fenceId, tenantId);
return true;
geofence = geofenceDAO.getGeofence(fenceId, true);
if (geofence == null) {
return false;
}
return false;
eventsOfGeoFence = geofenceDAO.getEventsOfGeoFence(fenceId);
List<Integer> eventIds = new ArrayList<>();
for (EventConfig config : eventsOfGeoFence) {
eventIds.add(config.getEventId());
}
if (!eventIds.isEmpty()) {
geofenceDAO.deleteGeofenceEventMapping(eventIds);
}
List<Integer> groupIdsOfGeoFence = geofenceDAO.getGroupIdsOfGeoFence(fenceId);
if (!groupIdsOfGeoFence.isEmpty()) {
geofenceDAO.deleteGeofenceGroupMapping(groupIdsOfGeoFence);
}
geofenceDAO.deleteGeofenceById(fenceId);
DeviceManagementDAOFactory.commitTransaction();
GeoCacheManagerImpl.getInstance().removeFenceFromCache(fenceId, tenantId);
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while deleting geofence";
@ -1498,6 +1523,8 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
} finally {
DeviceManagementDAOFactory.closeConnection();
}
this.deleteGeoFenceEvents(geofence, eventsOfGeoFence);
return true;
}
@Override
@ -1552,7 +1579,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
}
@Override
public boolean updateGeoEventConfigurations(List<EventConfig> eventConfig,
public boolean updateGeoEventConfigurations(GeofenceData geofenceData,
List<Integer> removedEventIdList, List<Integer> groupIds, int fenceId)
throws GeoLocationBasedServiceException {
if (log.isDebugEnabled()) {
@ -1579,17 +1606,18 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
}
List<Integer> createdEventIds;
int tenantId;
try {
int tenantId = DeviceManagementDAOUtil.getTenantId();
setEventSource(eventConfig);
EventConfigurationProviderService eventConfigService = DeviceManagementDataHolder.getInstance()
.getEventConfigurationService();
tenantId = DeviceManagementDAOUtil.getTenantId();
setEventSource(geofenceData.getEventConfig());
EventConfigurationProviderService eventConfigService = DeviceManagementDataHolder
.getInstance().getEventConfigurationService();
if (eventConfigService == null) {
String msg = "Failed to load EventConfigurationProviderService osgi service of tenant " + tenantId;
log.error(msg);
throw new GeoLocationBasedServiceException(msg);
}
createdEventIds = eventConfigService.updateEventsOfDeviceGroup(eventConfig, removedEventIdList, groupIds, tenantId);
createdEventIds = eventConfigService.updateEventsOfDeviceGroup(geofenceData.getEventConfig(), removedEventIdList, groupIds, tenantId);
} catch (EventConfigurationException e) {
String msg = "Error occurred while updating event configuration data";
log.error(msg, e);
@ -1623,6 +1651,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
if (log.isDebugEnabled()) {
log.debug("Update geofence event completed.");
}
createEventRevokeTask(geofenceData, tenantId);
return true;
}
@ -1698,4 +1727,30 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public void deleteGeoFenceEvents(GeofenceData geofenceData, List<EventConfig> eventList) throws GeoLocationBasedServiceException {
int tenantId;
try {
tenantId = DeviceManagementDAOUtil.getTenantId();
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving tenant id while get geofence data";
log.error(msg, e);
throw new GeoLocationBasedServiceException(msg, e);
}
try {
EventConfigurationProviderService eventConfigService = DeviceManagementDataHolder
.getInstance().getEventConfigurationService();
eventConfigService.deleteEvents(eventList);
createEventTask(OperationMgtConstants.OperationCodes.EVENT_REVOKE, geofenceData, tenantId);
} catch (EventConfigurationException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Failed to delete Geofence event configurations";
log.error(msg, e);
throw new GeoLocationBasedServiceException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
}

@ -0,0 +1,22 @@
/*
* Copyright (c) 2020, 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 org.wso2.carbon.device.mgt.core.geo.task;
public interface EventCreateCallback {
void onCompleteEventOperation(Object values);
}

@ -28,14 +28,26 @@ import org.wso2.carbon.device.mgt.core.event.config.GroupEventOperationExecutor;
import java.util.List;
public class GeoFenceEventOperationManager {
public GroupEventOperationExecutor getGroupEventOperationExecutor(GeofenceData geofenceData, int tenantId) {
private final int tenantId;
private final String eventOperationCode;
private final EventCreateCallback callback;
public GeoFenceEventOperationManager(String eventOperationCode, int tenantId, EventCreateCallback callback) {
this.eventOperationCode = eventOperationCode;
this.tenantId = tenantId;
this.callback = callback;
}
public GroupEventOperationExecutor getGroupEventOperationExecutor(GeofenceData geofenceData) {
GeoFenceEventMeta geoFenceEventMeta = new GeoFenceEventMeta(geofenceData);
return new GroupEventOperationExecutor(geoFenceEventMeta, geofenceData.getGroupIds(),
tenantId, DeviceManagementConstants.EventServices.GEOFENCE);
GroupEventOperationExecutor executor = new GroupEventOperationExecutor(geoFenceEventMeta, geofenceData.getGroupIds(),
tenantId, DeviceManagementConstants.EventServices.GEOFENCE, eventOperationCode);
executor.setCallback(callback);
return executor;
}
public DeviceEventOperationExecutor getDeviceEventOperationExecutor(int groupId, List<DeviceIdentifier> deviceIdentifiers,
int tenantId) {
return new DeviceEventOperationExecutor(groupId, deviceIdentifiers, tenantId);
public DeviceEventOperationExecutor getDeviceEventOperationExecutor(int groupId, List<DeviceIdentifier> deviceIdentifiers) {
DeviceEventOperationExecutor executor = new DeviceEventOperationExecutor(groupId, deviceIdentifiers, tenantId, eventOperationCode);
executor.setCallback(callback);
return executor;
}
}

@ -185,7 +185,9 @@ public class OperationManagerImpl implements OperationManager {
boolean isScheduledOperation = this.isTaskScheduledOperation(operation);
String initiatedBy = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (initiatedBy == null && isScheduledOperation) {
if (initiatedBy == null && (isScheduledOperation
|| operation.getCode().equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_CONFIG)
|| operation.getCode().equalsIgnoreCase(OperationMgtConstants.OperationCodes.EVENT_REVOKE))) {
if (log.isDebugEnabled()) {
log.debug("initiatedBy : " + SYSTEM);
}
@ -1331,12 +1333,10 @@ public class OperationManagerImpl implements OperationManager {
boolean status;
switch (operation.getCode()) {
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.POLICY_OPERATION_CODE:
status = true;
break;
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.MONITOR_OPERATION_CODE:
status = true;
break;
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.EVENT_CONFIG_OPERATION_CODE:
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.EVENT_REVOKE_OPERATION_CODE:
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.POLICY_REVOKE_OPERATION_CODE:
case DeviceManagementConstants.AuthorizationSkippedOperationCodes.MONITOR_OPERATION_CODE:
status = true;
break;
default:

@ -26,5 +26,6 @@ public class OperationMgtConstants {
public static final String POLICY_REVOKE = "POLICY_REVOKE";
public static final String EVENT_CONFIG = "EVENT_CONFIG";
public static final String EVENT_REVOKE = "EVENT_REVOKE";
}
}

@ -43,6 +43,7 @@ import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.geo.task.GeoFenceEventOperationManager;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
@ -799,7 +800,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
}
}
GroupManagementDAOFactory.commitTransaction();
createEventTask(groupId, deviceIdentifiers, tenantId);
createEventTask(OperationMgtConstants.OperationCodes.EVENT_CONFIG, groupId, deviceIdentifiers, tenantId);
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving device.";
log.error(msg, e);
@ -844,6 +845,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
this.groupDAO.removeDevice(groupId, device.getId(), tenantId);
}
GroupManagementDAOFactory.commitTransaction();
createEventTask(OperationMgtConstants.OperationCodes.EVENT_REVOKE, groupId, deviceIdentifiers, tenantId);
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving device.";
log.error(msg, e);
@ -1052,10 +1054,10 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
}
}
private void createEventTask(int groupId, List<DeviceIdentifier> deviceIdentifiers, int tenantId) {
GeoFenceEventOperationManager eventManager = new GeoFenceEventOperationManager();
private void createEventTask(String eventOperationCode, int groupId, List<DeviceIdentifier> deviceIdentifiers, int tenantId) {
GeoFenceEventOperationManager eventManager = new GeoFenceEventOperationManager(eventOperationCode, tenantId, null);
ScheduledExecutorService eventOperationExecutor = Executors.newSingleThreadScheduledExecutor();
eventOperationExecutor.schedule(eventManager
.getDeviceEventOperationExecutor(groupId, deviceIdentifiers, tenantId), 10, TimeUnit.SECONDS);
.getDeviceEventOperationExecutor(groupId, deviceIdentifiers), 10, TimeUnit.SECONDS);
}
}

Loading…
Cancel
Save