Add doc comments and format code

corrective-policy
Pahansith 4 years ago
parent d9d0ba5d90
commit 8c80185610

@ -22,7 +22,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.gson.Gson;
import jdk.nashorn.internal.parser.JSONParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;
@ -43,7 +42,6 @@ import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
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.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.geo.service.*;
@ -728,14 +726,14 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
}
List<GeofenceData> geoFences = geoService.getGeoFences(request);
if (requireEventData) {
geoFences = geoService.getGeoFenceEvents(geoFences);
geoFences = geoService.attachEventObjects(geoFences);
}
return getResponse(geoFences);
}
if (name != null && !name.isEmpty()) {
List<GeofenceData> geoFences = geoService.getGeoFences(name);
if (requireEventData) {
geoFences = geoService.getGeoFenceEvents(geoFences);
geoFences = geoService.attachEventObjects(geoFences);
}
return getResponse(geoFences);
}

@ -23,34 +23,53 @@ import java.util.List;
public interface EventConfigurationProviderService {
/**
* Create event configuration records
*
* @param eventConfigList event list to be added
* @param groupIds group ids of the events are mapped
* @param tenantId events owning tenant id
* @param groupIds group ids of the events are mapped
* @return generated event ids
* @throws EventConfigurationException errors thrown while creating event configuration
*/
List<Integer> createEventsOfDeviceGroup(List<EventConfig> eventConfigList, List<Integer> groupIds, int tenantId)
List<Integer> createEventsOfDeviceGroup(List<EventConfig> eventConfigList, List<Integer> groupIds)
throws EventConfigurationException;
/**
* Update event configuration records
* @param eventConfig updated event configuration list. event ids should be present for
* the updating events and event ids should be -1 for the newly creating events
*
* @param eventConfig updated event configuration list. event ids should be present for
* the updating events and event ids should be -1 for the newly creating events
* @param removedEventIdList event ids of removed while updating the event configuration
* @param groupIds group ids to be mapped with updated events
* @param tenantId
* @return
* @param groupIds group ids to be mapped with updated events
* @return Newly created event Ids
* @throws EventConfigurationException
*/
List<Integer> updateEventsOfDeviceGroup(List<EventConfig> eventConfig, List<Integer> removedEventIdList,
List<Integer> groupIds, int tenantId) throws EventConfigurationException;
List<Integer> groupIds) throws EventConfigurationException;
/**
* Retrieve event list using event IDs
*
* @param createdEventIds event ids
* @return {@link EventConfig} List of events of defined IDs
* @throws EventConfigurationException
*/
List<EventConfig> getEvents(List<Integer> createdEventIds) throws EventConfigurationException;
List<EventConfig> getEventsOfGroup(int groupId, int tenantId) throws EventConfigurationException;
/**
* Get event sources attached to a specific group
*
* @param groupId mapped group id of events
* @param tenantId event owning tenant
* @return Event sources of the group
* @throws EventConfigurationException error thrown while retrieving event sources
*/
List<String> getEventsSourcesOfGroup(int groupId, int tenantId) throws EventConfigurationException;
/**
* Delete events by event Ids
*
* @param eventList event list to be deleted
* @throws EventConfigurationException error thrown while deleting event records
*/
void deleteEvents(List<EventConfig> eventList) throws EventConfigurationException;
}

@ -87,7 +87,7 @@ public interface GeoLocationProviderService {
/**
* Get geofence by ID
* @param fenceId id of the fence which should be retrieved
* @return Extracted geofence data
* @return {@link GeofenceData} Extracted geofence data
* @throws GeoLocationBasedServiceException error occurs while retrieving a geofence
*/
GeofenceData getGeoFences(int fenceId) throws GeoLocationBasedServiceException;
@ -95,7 +95,7 @@ public interface GeoLocationProviderService {
/**
* Get paginated geofence list
* @param request Pagination Request
* @return List of Geofences retrieved
* @return {@link GeofenceData} List of Geofences retrieved
* @throws GeoLocationBasedServiceException error occurs while retrieving geofences
*/
List<GeofenceData> getGeoFences(PaginationRequest request) throws GeoLocationBasedServiceException;
@ -103,14 +103,14 @@ public interface GeoLocationProviderService {
/**
* Search geo fences using the fence name
* @param name searching name of the fence
* @return list of fences found for the specific name
* @return {@link GeofenceData} list of fences found for the specific name
* @throws GeoLocationBasedServiceException for errors occur while querying geo fences
*/
List<GeofenceData> getGeoFences(String name) throws GeoLocationBasedServiceException;
/**
* Get all geo fences of the tenant
* @return list of the all geo fences of the tenant
* @return {@link GeofenceData} list of the all geo fences of the tenant
* @throws GeoLocationBasedServiceException for errors occur while querying geo fences
*/
List<GeofenceData> getGeoFences() throws GeoLocationBasedServiceException;
@ -146,11 +146,29 @@ public interface GeoLocationProviderService {
boolean updateGeoEventConfigurations(GeofenceData geofenceData, List<Integer> removedEventIdList,
List<Integer> groupIds, int fenceId) throws GeoLocationBasedServiceException;
List<GeofenceData> getGeoFenceEvents(List<GeofenceData> geoFences) throws GeoLocationBasedServiceException;
/**
* Attach event data into geofence objects
* @param geoFences list of GeofenceData to attach corresponding event data
* @return {@link GeofenceData} events attached geofence object list
* @throws GeoLocationBasedServiceException any errors occurred while attaching event records to geofences
*/
List<GeofenceData> attachEventObjects(List<GeofenceData> geoFences) throws GeoLocationBasedServiceException;
/**
* Get Geofence records of groups. Attaching with corresponding event data of fences
* @param groupId Id of the group geo which fences attached
* @param tenantId Id of the tenant which geo fences attached
* @param requireEventData use true for attach event records with the geo fence data
* @return {@link GeofenceData} Queried geo fence data using group Id
* @throws GeoLocationBasedServiceException any errors occurred while getting geofences of group
*/
List<GeofenceData> getGeoFencesOfGroup(int groupId, int tenantId, boolean requireEventData) throws GeoLocationBasedServiceException;
/**
* Get event records mapped with specific geo fence
* @param geoFenceId Id of the Geofence to retrieve mapped events
* @return {@link EventConfig} Event records of the geofence
* @throws GeoLocationBasedServiceException any errors occurred while reading event records to geofence
*/
List<EventConfig> getEventsOfGeoFence(int geoFenceId) throws GeoLocationBasedServiceException;
void deleteGeoFenceEvents(GeofenceData geofenceData, List<EventConfig> eventConfigList) throws GeoLocationBasedServiceException;
}

@ -61,19 +61,19 @@ public interface EventConfigDAO {
/**
* Update event records of the tenant
*
* @param eventsToUpdate updating event records
* @param tenantId event owning tenant id
* @throws EventManagementDAOException error occurred while updating events
*/
void updateEventRecords(List<EventConfig> eventsToUpdate, int tenantId) throws EventManagementDAOException;
void updateEventRecords(List<EventConfig> eventsToUpdate) throws EventManagementDAOException;
/**
* Delete events using event ids
*
* @param eventsIdsToDelete ids of the events which should be deleted
* @param tenantId event owning tenant id
* @throws EventManagementDAOException error occurred while deleting event records
*/
void deleteEventRecords(List<Integer> eventsIdsToDelete, int tenantId) throws EventManagementDAOException;
void deleteEventRecords(List<Integer> eventsIdsToDelete) throws EventManagementDAOException;
/**
* Get event records by event ids
@ -83,9 +83,27 @@ public interface EventConfigDAO {
*/
List<EventConfig> getEventsById(List<Integer> eventIds) throws EventManagementDAOException;
List<Integer> getGroupsOfEvents(List<Integer> updateEventIdList) throws EventManagementDAOException;
/**
* Get group ids belong to events using event ids
* @param eventIds Ids of the events mapped with group
* @return Group Id list
* @throws EventManagementDAOException thrown errors while retrieving group Ids of events
*/
List<Integer> getGroupsOfEvents(List<Integer> eventIds) throws EventManagementDAOException;
void deleteEventGroupMappingRecordsByEventIds(List<Integer> removedEventIdList) throws EventManagementDAOException;
/**
* Delete event group mapping records using event Ids
* @param eventIds Ids of the events
* @throws EventManagementDAOException thrown errors while deleting event group mappings
*/
void deleteEventGroupMappingRecordsByEventIds(List<Integer> eventIds) throws EventManagementDAOException;
/**
* Retrieve event sources mapped with specific groups and tenant
* @param groupId Id of the group
* @param tenantId Id of the tenant
* @return Event source list belong to
* @throws EventManagementDAOException thrown errors while retrieving event sources
*/
List<String> getEventSourcesOfGroups(int groupId, int tenantId) throws EventManagementDAOException;
}

@ -131,13 +131,45 @@ public interface GeofenceDAO {
*/
void deleteGeofenceEventMapping(List<Integer> removedEventIdList) throws DeviceManagementDAOException;
/**
* Get events of the geofence using fence ids
* @param geofenceIds ids of geo fences to be queried
* @return Event config list mapped with fence id
* @throws DeviceManagementDAOException error occurred while retrieving geo fence event map
*/
Map<Integer, List<EventConfig>> getEventsOfGeoFences(List<Integer> geofenceIds) throws DeviceManagementDAOException;
/**
* Get events of a particular geofence
* @param geofenceId id of the fence to be queried
* @return EventConfig list of the particular geofence
* @throws DeviceManagementDAOException thrown errors while getting events of geofence
*/
List<EventConfig> getEventsOfGeoFence(int geofenceId) throws DeviceManagementDAOException;
/**
* Get group Ids mapped with fence ids
* @param fenceIds fence id list to be queried
* @return GroupIds mapped with geofence id
* @throws DeviceManagementDAOException thrown errors while retrieving group Ids of geo fence
*/
Map<Integer, List<Integer>> getGroupIdsOfGeoFences(List<Integer> fenceIds) throws DeviceManagementDAOException;
/**
* Get geo fences of the specific group and tenant
* @param groupId id of the group
* @param tenantId tenant id of the geo fences
* @return List of geofence data mapped with specific group and tenant
* @throws DeviceManagementDAOException
*/
List<GeofenceData> getGeoFences(int groupId, int tenantId) throws DeviceManagementDAOException;
/**
* Get geofence using fence id and attached group Ids
* @param fenceId id of the fence
* @param requireGroupData true if mapped group data needed
* @return Geofence data
* @throws DeviceManagementDAOException
*/
GeofenceData getGeofence(int fenceId, boolean requireGroupData) throws DeviceManagementDAOException;
}

@ -183,7 +183,7 @@ public abstract class AbstractEventConfigDAO implements EventConfigDAO {
}
@Override
public void updateEventRecords(List<EventConfig> eventsToUpdate, int tenantId) throws EventManagementDAOException {
public void updateEventRecords(List<EventConfig> eventsToUpdate) throws EventManagementDAOException {
try {
Connection conn = this.getConnection();
String sql = "UPDATE DM_DEVICE_EVENT SET " +
@ -198,14 +198,14 @@ public abstract class AbstractEventConfigDAO implements EventConfigDAO {
stmt.executeBatch();
}
} catch (SQLException e) {
String msg = "Error occurred while updating event records of tenant " + tenantId;
String msg = "Error occurred while updating event records";
log.error(msg, e);
throw new EventManagementDAOException(msg, e);
}
}
@Override
public void deleteEventRecords(List<Integer> eventsIdsToDelete, int tenantId) throws EventManagementDAOException {
public void deleteEventRecords(List<Integer> eventsIdsToDelete) throws EventManagementDAOException {
try {
Connection conn = this.getConnection();
String sql = "DELETE FROM DM_DEVICE_EVENT WHERE ID = ?";
@ -217,7 +217,7 @@ public abstract class AbstractEventConfigDAO implements EventConfigDAO {
stmt.executeBatch();
}
} catch (SQLException e) {
String msg = "Error occurred while deleting event records of tenant " + tenantId;
String msg = "Error occurred while deleting event records of tenant";
log.error(msg, e);
throw new EventManagementDAOException(msg, e);
}

@ -416,7 +416,6 @@ public class GeofenceDAOImpl implements GeofenceDAO {
public Map<Integer, List<EventConfig>> getEventsOfGeoFences(List<Integer> geofenceIds) throws DeviceManagementDAOException {
try {
Map<Integer, List<EventConfig>> geoFenceEventMap = new HashMap<>();
List<EventConfig> eventList = new ArrayList<>();
Connection conn = this.getConnection();
String sql = "SELECT " +
"E.ID AS EVENT_ID, " +

@ -1,182 +0,0 @@
/*
* 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.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;
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;
public class DeviceEventOperationExecutor implements Runnable {
private static final Log log = LogFactory.getLog(DeviceEventOperationExecutor.class);
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, 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
public void run() {
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();
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;
}
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");
}
} 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);
}
}
}
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");
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;
}
}

@ -21,7 +21,6 @@ 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;
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;
@ -31,18 +30,13 @@ 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;
public class EventConfigurationProviderServiceImpl implements EventConfigurationProviderService {
private static final Log log = LogFactory.getLog(EventConfigurationProviderServiceImpl.class);
@ -53,8 +47,17 @@ public class EventConfigurationProviderServiceImpl implements EventConfiguration
}
@Override
public List<Integer> createEventsOfDeviceGroup(List<EventConfig> eventConfigList, List<Integer> groupIds, int tenantId)
public List<Integer> createEventsOfDeviceGroup(List<EventConfig> eventConfigList, List<Integer> groupIds)
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();
if (log.isDebugEnabled()) {
@ -85,13 +88,12 @@ public class EventConfigurationProviderServiceImpl implements EventConfiguration
}
@Override
public List<Integer> updateEventsOfDeviceGroup(List<EventConfig> newEventList,
List<Integer> removedEventIdList,
List<Integer> groupIds, int tenantId) throws EventConfigurationException {
public List<Integer> updateEventsOfDeviceGroup(List<EventConfig> newEventList, List<Integer> removedEventIdList,
List<Integer> groupIds) throws EventConfigurationException {
//todo when concerning about other event types, all of this steps might not necessary.
// so divide them into separate service methods
if (log.isDebugEnabled()) {
log.debug("Updating event configurations of tenant " + tenantId);
log.debug("Updating event configurations of tenant");
}
List<EventConfig> eventsToAdd;
try {
@ -126,7 +128,7 @@ public class EventConfigurationProviderServiceImpl implements EventConfiguration
if (log.isDebugEnabled()) {
log.debug("Updating event records ");
}
eventConfigDAO.updateEventRecords(eventsToUpdate, tenantId);
eventConfigDAO.updateEventRecords(eventsToUpdate);
}
@ -153,7 +155,7 @@ public class EventConfigurationProviderServiceImpl implements EventConfiguration
if (log.isDebugEnabled()) {
log.debug("Deleting removed event records");
}
eventConfigDAO.deleteEventRecords(removedEventIdList, tenantId);
eventConfigDAO.deleteEventRecords(removedEventIdList);
}
DeviceManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {
@ -171,7 +173,7 @@ public class EventConfigurationProviderServiceImpl implements EventConfiguration
if (log.isDebugEnabled()) {
log.debug("Adding new events while updating event");
}
return createEventsOfDeviceGroup(eventsToAdd, groupIds, tenantId);
return createEventsOfDeviceGroup(eventsToAdd, groupIds);
}
@Override
@ -192,24 +194,6 @@ public class EventConfigurationProviderServiceImpl implements EventConfiguration
}
}
@Override
public List<EventConfig> getEventsOfGroup(int groupId, int tenantId) throws EventConfigurationException {
try {
DeviceManagementDAOFactory.openConnection();
return eventConfigDAO.getEventsOfGroups(groupId, tenantId);
} catch (EventManagementDAOException e) {
String msg = "Error occurred while retrieving events of group " + groupId + " and tenant " + tenantId;
log.error(msg, e);
throw new EventConfigurationException(msg, e);
} catch (SQLException e) {
String msg = "Failed to open connection while retrieving event by IDs";
log.error(msg, e);
throw new EventConfigurationException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public List<String> getEventsSourcesOfGroup(int groupId, int tenantId) throws EventConfigurationException {
try {
@ -229,24 +213,16 @@ public class EventConfigurationProviderServiceImpl implements EventConfiguration
}
@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);
}
public void deleteEvents(List<EventConfig> events) throws EventConfigurationException {
try {
DeviceManagementDAOFactory.beginTransaction();
Set<Integer> eventIdSet = new HashSet<>();
for (EventConfig eventConfig : eventsOfGeoFence) {
for (EventConfig eventConfig : events) {
eventIdSet.add(eventConfig.getEventId());
}
if (!eventIdSet.isEmpty()) {
eventConfigDAO.deleteEventGroupMappingRecordsByEventIds(Lists.newArrayList(eventIdSet));
eventConfigDAO.deleteEventRecords(Lists.newArrayList(eventIdSet), tenantId);
eventConfigDAO.deleteEventRecords(Lists.newArrayList(eventIdSet));
}
DeviceManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {

@ -0,0 +1,230 @@
/*
* 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.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.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;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
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;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Event create/revoke operation creation task.
* Use at the time of single event create, update, delete
*/
public class EventOperationExecutor implements Runnable {
private static final Log log = LogFactory.getLog(EventOperationExecutor.class);
private final List<Integer> groupIds;
private final String eventSource;
private final EventMetaData eventMetaData;
private final int tenantId;
private final String operationCode;
private final GroupManagementProviderService groupManagementService;
private EventCreateCallback callback;
public EventOperationExecutor(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");
if (operationCode == null) {
log.error("Failed to start event operation task. Operation code is null");
return;
}
if (log.isDebugEnabled()) {
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);
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;
try {
group = groupManagementService.getGroup(groupId, false);
} catch (GroupManagementException e) {
log.error("Failed to retrieve group with group ID " + groupId, e);
continue;
}
try {
if (group != null) {
List<Device> allDevicesOfGroup = groupManagementService.getAllDevicesOfGroup(group.getName(), false);
if (allDevicesOfGroup == null || allDevicesOfGroup.isEmpty()) {
log.warn("No devices found in group " + group.getName());
} else {
devices.addAll(allDevicesOfGroup);
}
}
} catch (GroupManagementException e) {
log.error("Failed to retrieve devices of group with ID " + groupId + " and name " + group.getName(), e);
}
}
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
deviceIdentifiers.add(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
}
}
DeviceManagementProviderService deviceManagementProvider = DeviceManagementDataHolder
.getInstance().getDeviceManagementProvider();
try {
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);
}
}
/**
* Build operation to create EVENT_REVOKE operation.
* @param operation Operation object to build
*/
private void buildEventRevokeOperation(ProfileOperation operation) {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
createGeoFenceRevokeOperation(operation);
} //extend with another cases to handle other types of events
}
/**
* Build operation to create EVENT_CONFIG operation.
* @param operation Operation object to build
* @throws EventConfigurationException Failed while build the operation object
*/
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
}
/**
* Create EVENT_CONFIG operation object and attach payload to configure geo fence events
* @param operation operation object to set the payload
* @throws EventConfigurationException Failed while retrieving event list of geo fence
*/
private void createGeoFenceConfigOperation(ProfileOperation operation) throws EventConfigurationException {
GeoFenceEventMeta geoFenceMeta = (GeoFenceEventMeta) eventMetaData;
try {
GeoLocationProviderService geoLocationProviderService = DeviceManagementDataHolder
.getInstance().getGeoLocationProviderService();
List<EventConfig> eventConfigList = geoLocationProviderService.getEventsOfGeoFence(geoFenceMeta.getId());
if (log.isDebugEnabled()) {
log.debug("Retrieved event records of Geo Fence " + geoFenceMeta.getId() +
". events " + Arrays.toString(eventConfigList.toArray()));
}
List<EventOperation> eventOperations = new ArrayList<>();
EventOperation eventOperation = new EventOperation();
eventOperation.setEventDefinition(eventMetaData);
eventOperation.setEventSource(eventSource);
eventOperation.setEventTriggers(eventConfigList);
eventOperations.add(eventOperation);
operation.setPayLoad(new Gson().toJson(eventOperations));
}catch (GeoLocationBasedServiceException e) {
throw new EventConfigurationException("Failed to retrieve event data of Geo fence " + geoFenceMeta.getId()
+ " : " + geoFenceMeta.getFenceName(), e);
}
}
/**
* Create EVENT_REVOKE operation object and attach payload to configure geo fence events
* @param operation operation object to set the payload
*/
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));
}
/**
* Can be used to set the task callback to call after the task completed successfully
* @param callback Event callback object implemented inside the task starting class
*/
public void setCallback(EventCreateCallback callback) {
this.callback = callback;
}
}

@ -22,20 +22,17 @@ 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.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.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;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
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.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;
@ -43,161 +40,184 @@ 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 org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Event create/revoke operation creation task.
* Use at the time of devices assign into group, remove from group.
*/
public class GroupEventOperationExecutor implements Runnable {
private static final Log log = LogFactory.getLog(GroupEventOperationExecutor.class);
private final List<Integer> groupIds;
private final String eventSource;
private final EventMetaData eventMetaData;
private final int groupId;
private final List<DeviceIdentifier> deviceIdentifiers;
private final int tenantId;
private final String operationCode;
private final GroupManagementProviderService groupManagementService;
private final GeoLocationProviderService geoLocationProviderService;
private final EventConfigurationProviderService eventConfigurationService;
private EventCreateCallback callback;
public GroupEventOperationExecutor(EventMetaData eventMetaData, List<Integer> groupIds, int tenantId,
String eventSource, String operationCode) {
this.eventMetaData = eventMetaData;
this.groupIds = groupIds;
public GroupEventOperationExecutor(int groupId, List<DeviceIdentifier> deviceIdentifiers, int tenantId, String operationCode) {
this.groupId = groupId;
this.deviceIdentifiers = deviceIdentifiers;
this.tenantId = tenantId;
this.eventSource = eventSource;
this.operationCode = operationCode;
this.groupManagementService = DeviceManagementDataHolder.getInstance().getGroupManagementProviderService();
this.geoLocationProviderService = DeviceManagementDataHolder.getInstance().getGeoLocationProviderService();
this.eventConfigurationService = DeviceManagementDataHolder.getInstance().getEventConfigurationService();
}
@Override
public void run() {
log.info("Starting event operation creation task");
if (operationCode == null) {
log.error("Failed to start event operation task. Operation code is null");
return;
}
log.info("Starting event operation creation task for devices in group " + groupId + " tenant " + tenantId);
if (log.isDebugEnabled()) {
log.info("Starting " + operationCode + " operation creation task for event " + eventSource
+ " tenant " + tenantId + " group Ids "+ Arrays.toString(groupIds.toArray()));
log.debug("Event creation operation started for devices with IDs " + Arrays.toString(deviceIdentifiers.toArray()));
log.debug("Starting tenant flow for tenant with ID : " + tenantId);
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
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;
if (operationCode != null) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
try {
group = groupManagementService.getGroup(groupId, false);
} catch (GroupManagementException e) {
log.error("Failed to retrieve group with group ID " + groupId, e);
continue;
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;
}
DeviceManagementProviderService deviceManagementProvider = DeviceManagementDataHolder
.getInstance().getDeviceManagementProvider();
try {
if (group != null) {
List<Device> allDevicesOfGroup = groupManagementService.getAllDevicesOfGroup(group.getName(), false);
if (allDevicesOfGroup == null || allDevicesOfGroup.isEmpty()) {
log.warn("No devices found in group " + group.getName());
} else {
devices.addAll(allDevicesOfGroup);
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");
}
} catch (GroupManagementException e) {
log.error("Failed to retrieve devices of group with ID " + groupId + " and name " + group.getName(), e);
} 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);
}
}
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
deviceIdentifiers.add(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
log.info("Event operation creation succeeded");
if (callback != null) {
callback.onCompleteEventOperation(null);
}
}
DeviceManagementProviderService deviceManagementProvider = DeviceManagementDataHolder
.getInstance().getDeviceManagementProvider();
try {
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;
}
/**
* Build EVENT_REVOKE operation attaching event payload
* @param operation operation object to build
* @throws EventConfigurationException if not events found for the specific group
*/
private void buildEventRevokeOperation(ProfileOperation operation) throws 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);
}
log.info("Event operation creation task completed");
if (callback != null) {
callback.onCompleteEventOperation(null);
for (String eventSource : eventSources) {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
setGeoFenceRevokeOperationContent(operation);
} //extend with another cases to handle other types of events
}
}
private void buildEventRevokeOperation(ProfileOperation operation) {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
createGeoFenceRevokeOperation(operation);
} //extend with another cases to handle other types of events
/**
* Build EVENT_CONFIG operation attaching event payload
* @param operation operation object to build
* @throws EventConfigurationException if not events found for the specific group
*/
private void buildEventConfigOperationObject(ProfileOperation operation) throws 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)) {
setGeoFenceConfigOperationContent(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));
/**
* Set operation payload GeoFence for EVENT_CONFIG operation
* @param operation operation object to attach payload
* @throws EventConfigurationException failed while getting events of group
*/
private void setGeoFenceConfigOperationContent(ProfileOperation operation) throws EventConfigurationException {
log.info("Geo fence events found attached with group " + groupId + ", Started retrieving geo fences");
List<GeofenceData> geoFencesOfGroup = getGeoFencesOfGroup();
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 buildEventConfigOperation(ProfileOperation operation) throws EventConfigurationException {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
createGeoFenceConfigOperation(operation);
} //extend with another cases to handle other types of events
/**
* Get geo fence list of the group
* @return {@link GeofenceData} geofence data list of the geo fence
* @throws EventConfigurationException error occurred while querying geo fences of group
*/
private List<GeofenceData> getGeoFencesOfGroup() throws EventConfigurationException {
List<GeofenceData> geoFencesOfGroup;
try {
geoFencesOfGroup = geoLocationProviderService.getGeoFencesOfGroup(groupId, tenantId, true);
} catch (GeoLocationBasedServiceException e) {
String msg = "Failed to get geo fences of the group";
log.error(msg, e);
throw new EventConfigurationException(msg, e);
}
if (log.isDebugEnabled()) {
log.debug("Retrieved " + geoFencesOfGroup.size() + " geo fences defined for the group " + groupId);
}
return geoFencesOfGroup;
}
private void createGeoFenceConfigOperation(ProfileOperation operation) throws EventConfigurationException {
GeoFenceEventMeta geoFenceMeta = (GeoFenceEventMeta) eventMetaData;
try {
GeoLocationProviderService geoLocationProviderService = DeviceManagementDataHolder
.getInstance().getGeoLocationProviderService();
List<EventConfig> eventConfigList = geoLocationProviderService.getEventsOfGeoFence(geoFenceMeta.getId());
if (log.isDebugEnabled()) {
log.debug("Retrieved event records of Geo Fence " + geoFenceMeta.getId() +
". events " + Arrays.toString(eventConfigList.toArray()));
}
List<EventOperation> eventOperations = new ArrayList<>();
EventOperation eventOperation = new EventOperation();
eventOperation.setEventDefinition(eventMetaData);
eventOperation.setEventSource(eventSource);
eventOperation.setEventTriggers(eventConfigList);
eventOperations.add(eventOperation);
operation.setPayLoad(new Gson().toJson(eventOperations));
}catch (GeoLocationBasedServiceException e) {
throw new EventConfigurationException("Failed to retrieve event data of Geo fence " + geoFenceMeta.getId()
+ " : " + geoFenceMeta.getFenceName(), e);
/**
* Set operation payload GeoFence for EVENT_REVOKE operation
* @param operation operation object to attach payload
* @throws EventConfigurationException failed while getting events of group
*/
private void setGeoFenceRevokeOperationContent(ProfileOperation operation) throws EventConfigurationException {
List<GeofenceData> geoFencesOfGroup = getGeoFencesOfGroup();
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));
}
/**
* Can be used to set the task callback to call after the task completed successfully
* @param callback Event callback object implemented inside the task starting class
*/
public void setCallback(EventCreateCallback callback) {
this.callback = callback;
}

@ -54,7 +54,6 @@ 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;
@ -1294,7 +1293,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
setEventSource(geofenceData.getEventConfig());
EventConfigurationProviderService eventConfigService = DeviceManagementDataHolder
.getInstance().getEventConfigurationService();
createdEventIds = eventConfigService.createEventsOfDeviceGroup(geofenceData.getEventConfig(), geofenceData.getGroupIds(), tenantId);
createdEventIds = eventConfigService.createEventsOfDeviceGroup(geofenceData.getEventConfig(), geofenceData.getGroupIds());
DeviceManagementDAOFactory.beginTransaction();
geofenceDAO.createGeofenceEventMapping(geofenceData.getId(), createdEventIds);
DeviceManagementDAOFactory.commitTransaction();
@ -1323,21 +1322,36 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
return true;
}
/**
* Create event revoke task at the time of geofence edit.
* @param geofenceData updated geofence object
* @param tenantId id of the fence owning tenant
*/
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), 10, TimeUnit.SECONDS);
.getEventOperationExecutor(geofenceData), 10, TimeUnit.SECONDS);
}
/**
* Create event config operation at the time of geofence edit, geofence delete
* @param operationCode code of the creating event (EVENT_CONFIG / EVENT_REVOKE)
* @param geofenceData creating/deleting geofence object
* @param tenantId id of the fence owning tenant
*/
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);
.getEventOperationExecutor(geofenceData), 10, TimeUnit.SECONDS);
}
/**
* Set source of the event to GEOFENCE
* @param eventConfig event list to be set event source
*/
private void setEventSource(List<EventConfig> eventConfig) {
for (EventConfig eventConfigEntry : eventConfig) {
eventConfigEntry.setEventSource(DeviceManagementConstants.EventServices.GEOFENCE);
@ -1617,7 +1631,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
log.error(msg);
throw new GeoLocationBasedServiceException(msg);
}
createdEventIds = eventConfigService.updateEventsOfDeviceGroup(geofenceData.getEventConfig(), removedEventIdList, groupIds, tenantId);
createdEventIds = eventConfigService.updateEventsOfDeviceGroup(geofenceData.getEventConfig(), removedEventIdList, groupIds);
} catch (EventConfigurationException e) {
String msg = "Error occurred while updating event configuration data";
log.error(msg, e);
@ -1656,7 +1670,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
}
@Override
public List<GeofenceData> getGeoFenceEvents(List<GeofenceData> geoFences) throws GeoLocationBasedServiceException {
public List<GeofenceData> attachEventObjects(List<GeofenceData> geoFences) throws GeoLocationBasedServiceException {
try {
DeviceManagementDAOFactory.openConnection();
List<Integer> fenceIds = new ArrayList<>();
@ -1728,8 +1742,13 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
}
}
@Override
public void deleteGeoFenceEvents(GeofenceData geofenceData, List<EventConfig> eventList) throws GeoLocationBasedServiceException {
/**
* Delete events of geofence
* @param geofenceData geofence mapped with deleting events
* @param eventList events to be deleted
*/
private void deleteGeoFenceEvents(GeofenceData geofenceData, List<EventConfig> eventList)
throws GeoLocationBasedServiceException {
int tenantId;
try {
tenantId = DeviceManagementDAOUtil.getTenantId();

@ -22,31 +22,49 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.geo.service.GeoFenceEventMeta;
import org.wso2.carbon.device.mgt.common.geo.service.GeofenceData;
import org.wso2.carbon.device.mgt.core.event.config.DeviceEventOperationExecutor;
import org.wso2.carbon.device.mgt.core.event.config.GroupEventOperationExecutor;
import org.wso2.carbon.device.mgt.core.event.config.EventOperationExecutor;
import java.util.List;
/**
* Responsible for Event operation task creation management.
* Wrap event operation executor creation
*/
public class GeoFenceEventOperationManager {
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) {
/**
* Get executor for create EVENT_CONFIG / EVENT_REVOKE operations at the time of a geofence
* created, updated or deleted
* @param geofenceData created geofence data object
* @return {@link EventOperationExecutor} Created executor to create operations
*/
public EventOperationExecutor getEventOperationExecutor(GeofenceData geofenceData) {
GeoFenceEventMeta geoFenceEventMeta = new GeoFenceEventMeta(geofenceData);
GroupEventOperationExecutor executor = new GroupEventOperationExecutor(geoFenceEventMeta, geofenceData.getGroupIds(),
EventOperationExecutor executor = new EventOperationExecutor(geoFenceEventMeta, geofenceData.getGroupIds(),
tenantId, DeviceManagementConstants.EventServices.GEOFENCE, eventOperationCode);
executor.setCallback(callback);
return executor;
}
public DeviceEventOperationExecutor getDeviceEventOperationExecutor(int groupId, List<DeviceIdentifier> deviceIdentifiers) {
DeviceEventOperationExecutor executor = new DeviceEventOperationExecutor(groupId, deviceIdentifiers, tenantId, eventOperationCode);
/**
* Get executor for create EVENT_CONFIG / EVENT_REVOKE operations at the time of a device/s
* assigned into a group or removed from a group
* @param groupId Id of the assigned / removed group
* @param deviceIdentifiers Device identifiers assigned to / removed from the group
* @return {@link GroupEventOperationExecutor} Created executor to create operations
*/
public GroupEventOperationExecutor getEventOperationExecutor(int groupId, List<DeviceIdentifier> deviceIdentifiers) {
GroupEventOperationExecutor executor = new GroupEventOperationExecutor(groupId, deviceIdentifiers, tenantId, eventOperationCode);
executor.setCallback(callback);
return executor;
}

@ -1054,10 +1054,17 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
}
}
/**
* Create event config/revoke operation at the time of device removing from a group/assigning into group
* @param eventOperationCode code of the event operation(config/revoke)
* @param groupId Id of the device removing/assigning group
* @param deviceIdentifiers devices assigning to/removing from group
* @param tenantId tenant of the group
*/
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), 10, TimeUnit.SECONDS);
.getEventOperationExecutor(groupId, deviceIdentifiers), 10, TimeUnit.SECONDS);
}
}

Loading…
Cancel
Save