Add event configuration operation creation tasks

corrective-policy
Pahansith 4 years ago
parent a401c9d91d
commit 75b619d5f9

@ -65,4 +65,13 @@ public class EventConfig {
}
return false;
}
@Override
public String toString() {
return "{eventId=" + eventId +
", eventSource='" + eventSource + '\'' +
", eventLogic='" + eventLogic + '\'' +
", actions='" + actions + '\'' +
'}';
}
}

@ -44,4 +44,10 @@ public interface EventConfigurationProviderService {
*/
List<Integer> updateEventsOfDeviceGroup(List<EventConfig> eventConfig, List<Integer> removedEventIdList,
List<Integer> groupIds, int tenantId) throws EventConfigurationException;
List<EventConfig> getEvents(List<Integer> createdEventIds) throws EventConfigurationException;
List<EventConfig> getEventsOfGroup(int groupId, int tenantId) throws EventConfigurationException;
List<String> getEventsSourcesOfGroup(int groupId, int tenantId) throws EventConfigurationException;
}

@ -0,0 +1,21 @@
/*
* 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 interface EventMetaData {}

@ -0,0 +1,69 @@
/*
* 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;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.List;
public class EventOperation {
private String eventSource;
private EventMetaData eventDefinition;
private String eventTriggers;
public String getEventSource() {
return eventSource;
}
public void setEventSource(String eventSource) {
this.eventSource = eventSource;
}
public EventMetaData getEventDefinition() {
return eventDefinition;
}
public void setEventDefinition(EventMetaData eventDefinition) {
this.eventDefinition = eventDefinition;
}
public String getEventTriggers() {
return eventTriggers;
}
public void setEventTriggers(List<EventConfig> eventList) {
JsonArray eventTriggers = new JsonArray();
JsonObject eventTrigger;
for (EventConfig eventConfig : eventList) {
eventTrigger = new JsonObject();
eventTrigger.addProperty("eventId", eventConfig.getEventId());
eventTrigger.addProperty("eventLogic", eventConfig.getEventLogic());
eventTrigger.addProperty("actions", eventConfig.getActions());
eventTriggers.add(eventTrigger);
}
this.eventTriggers = eventTriggers.toString();
}
public String toJSON() {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -0,0 +1,110 @@
/*
* 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.geo.service;
import org.wso2.carbon.device.mgt.common.event.config.EventMetaData;
public class GeoFenceEventMeta implements EventMetaData {
private int id;
private String fenceName;
private String description;
private double latitude;
private double longitude;
private float radius;
private String geoJson;
private String fenceShape;
public GeoFenceEventMeta() {
}
public GeoFenceEventMeta(GeofenceData geofenceData) {
this.id = geofenceData.getId();
this.fenceName = geofenceData.getFenceName();
this.description = geofenceData.getDescription();
this.latitude = geofenceData.getLatitude();
this.longitude = geofenceData.getLongitude();
this.radius = geofenceData.getRadius();
this.geoJson = geofenceData.getGeoJson();
this.fenceShape = geofenceData.getFenceShape();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFenceName() {
return fenceName;
}
public void setFenceName(String fenceName) {
this.fenceName = fenceName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public float getRadius() {
return radius;
}
public void setRadius(float radius) {
this.radius = radius;
}
public String getGeoJson() {
return geoJson;
}
public void setGeoJson(String geoJson) {
this.geoJson = geoJson;
}
public String getFenceShape() {
return fenceShape;
}
public void setFenceShape(String fenceShape) {
this.fenceShape = fenceShape;
}
}

@ -147,4 +147,8 @@ public interface GeoLocationProviderService {
List<Integer> groupIds, int fenceId) throws GeoLocationBasedServiceException;
List<GeofenceData> getGeoFenceEvents(List<GeofenceData> geoFences) throws GeoLocationBasedServiceException;
List<GeofenceData> getGeoFencesOfGroup(int groupId, int tenantId, boolean requireEventData) throws GeoLocationBasedServiceException;
List<EventConfig> getEventsOfGeoFence(int geoFenceId) throws GeoLocationBasedServiceException;
}

@ -19,6 +19,7 @@
package org.wso2.carbon.device.mgt.common.geo.service;
import org.wso2.carbon.device.mgt.common.event.config.EventConfig;
import org.wso2.carbon.device.mgt.common.event.config.EventMetaData;
import java.util.List;

@ -50,6 +50,8 @@ public interface EventConfigDAO {
*/
List<EventConfig> getEventsOfGroups(List<Integer> groupIds, int tenantId) throws EventManagementDAOException;
List<EventConfig> getEventsOfGroups(int groupId, int tenantId) throws EventManagementDAOException;
/**
* Delete event group mapping records using the group ids
* @param groupIdsToDelete id of groups
@ -76,13 +78,14 @@ public interface EventConfigDAO {
/**
* Get event records by event ids
* @param eventIds filtering event ids
* @param tenantId tenant id of the events
* @return filtered event configuration list
* @throws EventManagementDAOException error occurred while reading events
*/
List<EventConfig> getEventsById(List<Integer> eventIds, int tenantId) throws EventManagementDAOException;
List<EventConfig> getEventsById(List<Integer> eventIds) throws EventManagementDAOException;
List<Integer> getGroupsOfEvents(List<Integer> updateEventIdList) throws EventManagementDAOException;
void deleteEventGroupMappingRecordsByEventIds(List<Integer> removedEventIdList) throws EventManagementDAOException;
List<String> getEventSourcesOfGroups(int groupId, int tenantId) throws EventManagementDAOException;
}

@ -136,4 +136,7 @@ public interface GeofenceDAO {
List<EventConfig> getEventsOfGeoFence(int geofenceId) throws DeviceManagementDAOException;
Map<Integer, List<Integer>> getGroupIdsOfGeoFences(List<Integer> fenceIds) throws DeviceManagementDAOException;
List<GeofenceData> getGeoFences(int groupId, int tenantId) throws DeviceManagementDAOException;
}

@ -124,7 +124,17 @@ public class EventConfigDAOImpl implements EventConfigDAO {
for (Integer groupId : groupIds) {
stmt.setInt(index++, groupId);
}
return getEventConfigs(tenantId, eventList, stmt, index);
stmt.setInt(index, tenantId);
ResultSet rst = stmt.executeQuery();
while (rst.next()) {
EventConfig event = new EventConfig();
event.setEventId(rst.getInt("EVENT_ID"));
event.setEventSource(rst.getString("EVENT_SOURCE"));
event.setEventLogic(rst.getString("EVENT_LOGIC"));
event.setActions(rst.getString("ACTIONS"));
eventList.add(event);
}
return eventList;
}
} catch (SQLException e) {
String msg = "Error occurred while creating event group mapping records";
@ -133,6 +143,43 @@ public class EventConfigDAOImpl implements EventConfigDAO {
}
}
@Override
public List<EventConfig> getEventsOfGroups(int groupId, int tenantId) throws EventManagementDAOException {
try {
List<EventConfig> eventList = new ArrayList<>();
Connection conn = this.getConnection();
String sql = "SELECT " +
"E.ID AS EVENT_ID, " +
"EVENT_SOURCE, " +
"EVENT_LOGIC, " +
"ACTIONS " +
"FROM DM_DEVICE_EVENT E, DM_DEVICE_EVENT_GROUP_MAPPING G " +
"WHERE G.EVENT_ID = E.ID " +
"AND G.GROUP_ID = ? " +
"AND E.TENANT_ID = ? " +
"GROUP BY E.ID";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
ResultSet rst = stmt.executeQuery();
while (rst.next()) {
EventConfig event = new EventConfig();
event.setEventId(rst.getInt("EVENT_ID"));
event.setEventSource(rst.getString("EVENT_SOURCE"));
event.setEventLogic(rst.getString("EVENT_LOGIC"));
event.setActions(rst.getString("ACTIONS"));
eventList.add(event);
}
return eventList;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving event records of group " + groupId
+ " and tenant " + tenantId;
log.error(msg, e);
throw new EventManagementDAOException(msg, e);
}
}
@Override
public void deleteEventGroupMappingRecordsByEventIds(List<Integer> eventsIdsToDelete) throws EventManagementDAOException {
try {
@ -219,7 +266,7 @@ public class EventConfigDAOImpl implements EventConfigDAO {
}
@Override
public List<EventConfig> getEventsById(List<Integer> eventIdList, int tenantId) throws EventManagementDAOException {
public List<EventConfig> getEventsById(List<Integer> eventIdList) throws EventManagementDAOException {
try {
List<EventConfig> eventList = new ArrayList<>();
Connection conn = this.getConnection();
@ -239,7 +286,16 @@ public class EventConfigDAOImpl implements EventConfigDAO {
stmt.setInt(index++, eventId);
}
}
return getEventConfigs(tenantId, eventList, stmt, index);
ResultSet rst = stmt.executeQuery();
while (rst.next()) {
EventConfig event = new EventConfig();
event.setEventId(rst.getInt("EVENT_ID"));
event.setEventSource(rst.getString("EVENT_SOURCE"));
event.setEventLogic(rst.getString("EVENT_LOGIC"));
event.setActions(rst.getString("ACTIONS"));
eventList.add(event);
}
return eventList;
}
} catch (SQLException e) {
String msg = "Error occurred while creating event group mapping records";
@ -280,18 +336,33 @@ public class EventConfigDAOImpl implements EventConfigDAO {
}
}
private List<EventConfig> getEventConfigs(int tenantId, List<EventConfig> eventList, PreparedStatement stmt, int index) throws SQLException {
stmt.setInt(index, tenantId);
@Override
public List<String> getEventSourcesOfGroups(int groupId, int tenantId) throws EventManagementDAOException {
try {
List<String> eventSourceList = new ArrayList<>();
Connection conn = this.getConnection();
String sql = "SELECT " +
"EVENT_SOURCE " +
"FROM DM_DEVICE_EVENT E, DM_DEVICE_EVENT_GROUP_MAPPING G " +
"WHERE G.EVENT_ID = E.ID " +
"AND G.GROUP_ID = ?" +
"AND E.TENANT_ID = ?" +
"GROUP BY EVENT_SOURCE";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
ResultSet rst = stmt.executeQuery();
while (rst.next()) {
EventConfig event = new EventConfig();
event.setEventId(rst.getInt("EVENT_ID"));
event.setEventSource(rst.getString("EVENT_SOURCE"));
event.setEventLogic(rst.getString("EVENT_LOGIC"));
event.setActions(rst.getString("ACTIONS"));
eventList.add(event);
eventSourceList.add(rst.getString("EVENT_SOURCE"));
}
return eventSourceList;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving event records of group " + groupId
+ " and tenant " + tenantId;
log.error(msg, e);
throw new EventManagementDAOException(msg, e);
}
return eventList;
}
private Connection getConnection() throws SQLException {

@ -533,4 +533,48 @@ public class GeofenceDAOImpl implements GeofenceDAO {
}
return eventList;
}
@Override
public List<GeofenceData> getGeoFences(int groupId, int tenantId) throws DeviceManagementDAOException {
try {
Connection conn = this.getConnection();
String sql = "SELECT " +
"G.ID AS FENCE_ID, " +
"FENCE_NAME, " +
"DESCRIPTION, " +
"LATITUDE," +
"LONGITUDE, " +
"RADIUS, " +
"GEO_JSON, " +
"FENCE_SHAPE " +
"FROM DM_GEOFENCE G, DM_GEOFENCE_GROUP_MAPPING M " +
"WHERE M.GROUP_ID = ? AND TENANT_ID = ? " +
"GROUP BY G.ID";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
ResultSet rst = stmt.executeQuery();
List <GeofenceData> geofenceDataList = new ArrayList<>();
while (rst.next()) {
GeofenceData 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"));
geofenceDataList.add(geofenceData);
}
return geofenceDataList;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving Geo fences of group " + groupId
+ " and tenant " + tenantId;
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
}

@ -0,0 +1,120 @@
/*
* 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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.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.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.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;
public DeviceEventOperationExecutor(int groupId, List<DeviceIdentifier> deviceIdentifiers, int tenantId) {
this.groupId = groupId;
this.deviceIdentifiers = deviceIdentifiers;
this.tenantId = tenantId;
}
@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()));
}
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);
for (String eventSource : eventSources) {
if (eventSource.equalsIgnoreCase(DeviceManagementConstants.EventServices.GEOFENCE)) {
setGeoFenceOperationContent(operation);
} //extend with another cases to handle other types of events
}
} 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");
}
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");
}
private void setGeoFenceOperationContent(ProfileOperation operation) {
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);
}
}
}

@ -28,9 +28,16 @@ import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementExcepti
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.geo.task.GeoFenceEventOperationManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
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);
@ -151,4 +158,58 @@ public class EventConfigurationProviderServiceImpl implements EventConfiguration
}
return createEventsOfDeviceGroup(eventsToAdd, groupIds, tenantId);
}
@Override
public List<EventConfig> getEvents(List<Integer> createdEventIds) throws EventConfigurationException {
try {
DeviceManagementDAOFactory.openConnection();
return eventConfigDAO.getEventsById(createdEventIds);
} catch (EventManagementDAOException e) {
String msg = "Error occurred while retrieving event by IDs : " + Arrays.toString(createdEventIds.toArray());
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<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 {
DeviceManagementDAOFactory.openConnection();
return eventConfigDAO.getEventSourcesOfGroups(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();
}
}
}

@ -0,0 +1,153 @@
/*
* 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 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.EventMetaData;
import org.wso2.carbon.device.mgt.common.event.config.EventOperation;
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.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;
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 tenantId;
public GroupEventOperationExecutor(EventMetaData eventMetaData, List<Integer> groupIds, int tenantId, String eventSource) {
this.eventMetaData = eventMetaData;
this.groupIds = groupIds;
this.tenantId = tenantId;
this.eventSource = eventSource;
}
@Override
public void run() {
log.info("Starting event operation creation task for event " + eventSource + " tenant " + tenantId);
if (log.isDebugEnabled()) {
log.debug("Event creation operation started for groups with IDs " + Arrays.toString(groupIds.toArray()));
}
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);
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
GroupManagementProviderService groupManagementService = DeviceManagementDataHolder
.getInstance().getGroupManagementProviderService();
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.info("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);
}
}
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 (!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");
}
} 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 createGeoFenceOperation(ProfileOperation operation) {
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()));
}
EventOperation eventOperation = new EventOperation();
eventOperation.setEventDefinition(eventMetaData);
eventOperation.setEventSource(eventSource);
eventOperation.setEventTriggers(eventConfigList);
operation.setPayLoad(eventOperation.toJSON());
} catch (GeoLocationBasedServiceException e) {
log.error("Failed to retrieve event data of Geo fence " + geoFenceMeta.getId()
+ " : " + geoFenceMeta.getFenceName(), e);
}
}
}

@ -32,7 +32,6 @@ import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.formula.functions.Even;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils;
@ -55,8 +54,8 @@ 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.GeoFenceEventOperationManager;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
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;
@ -89,6 +88,9 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Collections;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices.DAS_PORT;
import static org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices.DEFAULT_HTTP_PROTOCOL;
@ -1285,11 +1287,12 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
} finally {
DeviceManagementDAOFactory.closeConnection();
}
List<Integer> createdEventIds;
try {
EventConfigurationProviderService eventConfigService = DeviceManagerUtil.getEventConfigService();
EventConfigurationProviderService eventConfigService = DeviceManagementDataHolder.getInstance()
.getEventConfigurationService();
setEventSource(geofenceData.getEventConfig());
List<Integer> createdEventIds = eventConfigService.createEventsOfDeviceGroup(geofenceData.getEventConfig(), geofenceData.getGroupIds(), tenantId);
createdEventIds = eventConfigService.createEventsOfDeviceGroup(geofenceData.getEventConfig(), geofenceData.getGroupIds(), tenantId);
DeviceManagementDAOFactory.beginTransaction();
geofenceDAO.createGeofenceEventMapping(geofenceData.getId(), createdEventIds);
DeviceManagementDAOFactory.commitTransaction();
@ -1314,9 +1317,17 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
} finally {
DeviceManagementDAOFactory.closeConnection();
}
createEventTask(geofenceData, tenantId);
return true;
}
private void createEventTask(GeofenceData geofenceData, int tenantId) {
GeoFenceEventOperationManager eventManager = new GeoFenceEventOperationManager();
ScheduledExecutorService eventOperationExecutor = Executors.newSingleThreadScheduledExecutor();
eventOperationExecutor.schedule(eventManager
.getGroupEventOperationExecutor(geofenceData, tenantId), 10, TimeUnit.SECONDS);
}
private void setEventSource(List<EventConfig> eventConfig) {
for (EventConfig eventConfigEntry : eventConfig) {
eventConfigEntry.setEventSource(DeviceManagementConstants.EventServices.GEOFENCE);
@ -1571,7 +1582,8 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
try {
int tenantId = DeviceManagementDAOUtil.getTenantId();
setEventSource(eventConfig);
EventConfigurationProviderService eventConfigService = DeviceManagerUtil.getEventConfigService();
EventConfigurationProviderService eventConfigService = DeviceManagementDataHolder.getInstance()
.getEventConfigurationService();
if (eventConfigService == null) {
String msg = "Failed to load EventConfigurationProviderService osgi service of tenant " + tenantId;
log.error(msg);
@ -1641,4 +1653,49 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public List<GeofenceData> getGeoFencesOfGroup(int groupId, int tenantId, boolean requireEventData) throws GeoLocationBasedServiceException {
try {
DeviceManagementDAOFactory.openConnection();
List<GeofenceData> geofenceDataList = geofenceDAO.getGeoFences(groupId, tenantId);
if (requireEventData) {
for (GeofenceData geoFenceData : geofenceDataList) {
List<EventConfig> eventsOfGeoFence = geofenceDAO.getEventsOfGeoFence(geoFenceData.getId());
geoFenceData.setEventConfig(eventsOfGeoFence);
}
}
DeviceManagementDAOFactory.closeConnection();
return geofenceDataList;
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving geo fences of group " + groupId
+ " and tenant " + tenantId;
log.error(msg, e);
throw new GeoLocationBasedServiceException(msg, e);
} catch (SQLException e) {
String msg = "Failed to obtain connection while retrieving geofence data of group "
+ groupId + " and tenant " + tenantId;
log.error(msg, e);
throw new GeoLocationBasedServiceException(msg, e);
}
}
@Override
public List<EventConfig> getEventsOfGeoFence(int geoFenceId) throws GeoLocationBasedServiceException {
try {
DeviceManagementDAOFactory.openConnection();
return geofenceDAO.getEventsOfGeoFence(geoFenceId);
} catch (SQLException e) {
String msg = "Failed to obtain connection while retrieving event data of geo fence "
+ geoFenceId;
log.error(msg, e);
throw new GeoLocationBasedServiceException(msg, e);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving event data of geo fence " + geoFenceId;
log.error(msg, e);
throw new GeoLocationBasedServiceException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
}

@ -0,0 +1,41 @@
/*
* 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;
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 java.util.List;
public class GeoFenceEventOperationManager {
public GroupEventOperationExecutor getGroupEventOperationExecutor(GeofenceData geofenceData, int tenantId) {
GeoFenceEventMeta geoFenceEventMeta = new GeoFenceEventMeta(geofenceData);
return new GroupEventOperationExecutor(geoFenceEventMeta, geofenceData.getGroupIds(),
tenantId, DeviceManagementConstants.EventServices.GEOFENCE);
}
public DeviceEventOperationExecutor getDeviceEventOperationExecutor(int groupId, List<DeviceIdentifier> deviceIdentifiers,
int tenantId) {
return new DeviceEventOperationExecutor(groupId, deviceIdentifiers, tenantId);
}
}

@ -22,6 +22,8 @@ import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
@ -71,6 +73,9 @@ public class DeviceManagementDataHolder {
private DeviceStatusTaskManagerService deviceStatusTaskManagerService;
private DeviceTypeGeneratorService deviceTypeGeneratorService;
private PrivacyComplianceProvider privacyComplianceProvider;
private EventConfigurationProviderService eventConfigurationService;
private GeoLocationProviderService geoLocationProviderService;
private final Map<DeviceType, DeviceStatusTaskPluginConfig> deviceStatusTaskPluginConfigs = Collections.synchronizedMap(
new HashMap<>());
@ -286,4 +291,20 @@ public class DeviceManagementDataHolder {
public void setDeviceInformationManager(DeviceInformationManager deviceInformationManager) {
this.deviceInformationManager = deviceInformationManager;
}
public void setEventConfigurationProviderService(EventConfigurationProviderService eventConfigurationService) {
this.eventConfigurationService = eventConfigurationService;
}
public EventConfigurationProviderService getEventConfigurationService() {
return eventConfigurationService;
}
public GeoLocationProviderService getGeoLocationProviderService() {
return geoLocationProviderService;
}
public void setGeoLocationProviderService(GeoLocationProviderService geoLocationProviderService) {
this.geoLocationProviderService = geoLocationProviderService;
}
}

@ -330,6 +330,7 @@ public class DeviceManagementServiceComponent {
/* Registering Geo Service */
GeoLocationProviderService geoService = new GeoLocationProviderServiceImpl();
DeviceManagementDataHolder.getInstance().setGeoLocationProviderService(geoService);
bundleContext.registerService(GeoLocationProviderService.class.getName(), geoService, null);
/* Registering Metadata Service */
@ -338,6 +339,7 @@ public class DeviceManagementServiceComponent {
/* Registering Event Configuration Service */
EventConfigurationProviderService eventConfigurationService = new EventConfigurationProviderServiceImpl();
DeviceManagementDataHolder.getInstance().setEventConfigurationProviderService(eventConfigurationService);
bundleContext.registerService(EventConfigurationProviderService.class.getName(), eventConfigurationService, null);
OTPManagementService otpManagementService = new OTPManagementServiceImpl();

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

@ -41,6 +41,7 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.GroupDAO;
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.util.DeviceManagerUtil;
import org.wso2.carbon.user.api.UserRealm;
@ -52,6 +53,9 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class GroupManagementProviderServiceImpl implements GroupManagementProviderService {
@ -795,6 +799,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
}
}
GroupManagementDAOFactory.commitTransaction();
createEventTask(groupId, deviceIdentifiers, tenantId);
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving device.";
log.error(msg, e);
@ -1046,4 +1051,11 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
tenantId));
}
}
private void createEventTask(int groupId, List<DeviceIdentifier> deviceIdentifiers, int tenantId) {
GeoFenceEventOperationManager eventManager = new GeoFenceEventOperationManager();
ScheduledExecutorService eventOperationExecutor = Executors.newSingleThreadScheduledExecutor();
eventOperationExecutor.schedule(eventManager
.getDeviceEventOperationExecutor(groupId, deviceIdentifiers, tenantId), 10, TimeUnit.SECONDS);
}
}

Loading…
Cancel
Save