Change Geo fence create API - Attach Event creation

corrective-policy
Pahansith 4 years ago
parent 0f915a2961
commit bd8cf5237d

@ -0,0 +1,50 @@
/*
* 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.jaxrs.beans;
import io.swagger.annotations.ApiModelProperty;
public class EventAction {
@ApiModelProperty(
name = "actionType",
value = "Type of the event action to be triggered in the device level")
private String actionType;
@ApiModelProperty(
name = "payload",
value = "Payload of the event action")
private Object payload;
public String getActionType() {
return actionType;
}
public void setActionType(String actionType) {
this.actionType = actionType;
}
public Object getPayload() {
return payload;
}
public void setPayload(Object payload) {
this.payload = payload;
}
}

@ -0,0 +1,51 @@
/*
* 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.jaxrs.beans;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
public class EventConfig {
@ApiModelProperty(
name = "eventLogic",
value = "Logic of the event should be handled at the device level")
private String eventLogic;
@ApiModelProperty(
name = "actions",
value = "List of actions to be triggered according to the logic")
private List<EventAction> actions;
public String getEventLogic() {
return eventLogic;
}
public void setEventLogic(String eventLogic) {
this.eventLogic = eventLogic;
}
public List<EventAction> getActions() {
return actions;
}
public void setActions(List<EventAction> actions) {
this.actions = actions;
}
}

@ -20,6 +20,8 @@ package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
public class GeofenceWrapper {
@ApiModelProperty(
@ -64,6 +66,13 @@ public class GeofenceWrapper {
value = "Shape of the fence")
private String fenceShape;
@ApiModelProperty(
name = "eventConfig",
value = "Event configuration of the geofence")
private List<EventConfig> eventConfig;
private List<Integer> groupIds;
public int getId() {
return id;
}
@ -127,4 +136,20 @@ public class GeofenceWrapper {
public void setFenceShape(String fenceShape) {
this.fenceShape = fenceShape;
}
public List<EventConfig> getEventConfig() {
return eventConfig;
}
public void setEventConfig(List<EventConfig> eventConfig) {
this.eventConfig = eventConfig;
}
public List<Integer> getGroupIds() {
return groupIds;
}
public void setGroupIds(List<Integer> groupIds) {
this.groupIds = groupIds;
}
}

@ -33,6 +33,7 @@ import io.swagger.annotations.Tag;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.mgt.common.geo.service.Alert;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.GeofenceWrapper;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
@ -872,14 +873,15 @@ public interface GeoLocationBasedService {
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid Geofence data found.",
response = Response.class),
response = ErrorResponse.class),
@ApiResponse(
code = 401,
message = "Unauthorized. \n Unauthorized request."),
message = "Unauthorized. \n Unauthorized request.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error on retrieving stats",
response = Response.class)
response = ErrorResponse.class)
})
Response createGeofence(@ApiParam(name = "fence", value = "Geo fence data")GeofenceWrapper geofenceWrapper);

@ -18,6 +18,9 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
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.wso2.carbon.analytics.api.AnalyticsDataAPI;
@ -35,6 +38,9 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices;
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.*;
@ -45,6 +51,8 @@ import org.wso2.carbon.device.mgt.core.geo.geoHash.geoHashStrategy.GeoHashLength
import org.wso2.carbon.device.mgt.core.geo.geoHash.geoHashStrategy.ZoomGeoHashLengthStrategy;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.EventAction;
import org.wso2.carbon.device.mgt.jaxrs.beans.GeofenceWrapper;
import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
@ -598,19 +606,39 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
geofenceData.setRadius(geofenceWrapper.getRadius());
geofenceData.setGeoJson(geofenceWrapper.getGeoJson());
geofenceData.setFenceShape(geofenceWrapper.getFenceShape());
geofenceData.setGroupIds(geofenceWrapper.getGroupIds());
geofenceData.setEventConfig(mapRequestEvent(geofenceWrapper.getEventConfig()));
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
if (!geoService.createGeofence(geofenceData)) {
String msg = "Failed to create geofence";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
return Response.status(Response.Status.CREATED).build();
return Response.status(Response.Status.CREATED).entity("Geo Fence record created successfully").build();
} catch (GeoLocationBasedServiceException e) {
String msg = "Failed to create geofence";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (EventConfigurationException e) {
String msg = "Failed to create event configuration for Geo Fence";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
private List<EventConfig> mapRequestEvent(List<org.wso2.carbon.device.mgt.jaxrs.beans.EventConfig> eventConfig) {
List<EventConfig> savingEventList = new ArrayList<>();
for (org.wso2.carbon.device.mgt.jaxrs.beans.EventConfig event : eventConfig) {
EventConfig savingConfig = new EventConfig();
savingConfig.setEventLogic(event.getEventLogic());
String eventJson = new Gson().toJson(event.getActions());
savingConfig.setActions(eventJson);
savingEventList.add(savingConfig);
}
return savingEventList;
}
@Path("/geo-fence/{fenceId}")

@ -62,6 +62,7 @@ import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorization
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshotWrapper;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService;
import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
@ -567,6 +568,15 @@ public class DeviceMgtAPIUtils {
return geoService;
}
public static EventConfigurationProviderService getEventConfigService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
EventConfigurationProviderService eventService = (EventConfigurationProviderService) ctx.getOSGiService(EventConfigurationProviderService.class, null);
if (eventService == null) {
throw new IllegalStateException("Event configuration service has not been initialized.");
}
return eventService;
}
public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI =

@ -136,4 +136,10 @@ public final class DeviceManagementConstants {
public static final String TENANT_ADMIN_PASSWORD = "tenant-admin-password";
}
public static final class EventServices {
private EventServices() { throw new AssertionError(); }
public static final String GEOFENCE = "GEOFENCE";
}
}

@ -0,0 +1,40 @@
/*
* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.event.config;
public class EventAction {
private String actionType;
private Object payload;
public String getActionType() {
return actionType;
}
public void setActionType(String actionType) {
this.actionType = actionType;
}
public Object getPayload() {
return payload;
}
public void setPayload(Object payload) {
this.payload = payload;
}
}

@ -0,0 +1,60 @@
/*
* 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 java.util.List;
public class EventConfig {
private int eventId;
private String eventSource;
private String eventLogic;
private String actions;
public String getEventLogic() {
return eventLogic;
}
public void setEventLogic(String eventLogic) {
this.eventLogic = eventLogic;
}
public String getActions() {
return actions;
}
public void setActions(String actions) {
this.actions = actions;
}
public int getEventId() {
return eventId;
}
public void setEventId(int eventId) {
this.eventId = eventId;
}
public String getEventSource() {
return eventSource;
}
public void setEventSource(String eventSource) {
this.eventSource = eventSource;
}
}

@ -0,0 +1,37 @@
/*
* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.event.config;
public class EventConfigurationException extends Exception {
public EventConfigurationException() {
super();
}
public EventConfigurationException(String message) {
super(message);
}
public EventConfigurationException(String message, Throwable cause) {
super(message, cause);
}
public EventConfigurationException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,26 @@
/*
* 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 java.util.List;
public interface EventConfigurationProviderService {
boolean createEventOfDeviceGroup(List<EventConfig> eventConfigList, List<Integer> groupIds, int tenantId)
throws EventConfigurationException;
}

@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.common.geo.service;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
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.EventConfigurationException;
import java.util.List;
@ -78,7 +79,7 @@ public interface GeoLocationProviderService {
* @return true if the fence creation success
* @throws GeoLocationBasedServiceException error occurs while creating a geofence
*/
boolean createGeofence(GeofenceData geofenceData) throws GeoLocationBasedServiceException;
boolean createGeofence(GeofenceData geofenceData) throws GeoLocationBasedServiceException, EventConfigurationException;
/**
* Get geofence by ID

@ -18,6 +18,10 @@
package org.wso2.carbon.device.mgt.common.geo.service;
import org.wso2.carbon.device.mgt.common.event.config.EventConfig;
import java.util.List;
public class GeofenceData {
private int id;
private String fenceName;
@ -29,6 +33,8 @@ public class GeofenceData {
private String owner;
private String geoJson;
private String fenceShape;
private List<EventConfig> eventConfig;
private List<Integer> groupIds;
public int getId() {
return id;
@ -109,4 +115,20 @@ public class GeofenceData {
public void setFenceShape(String fenceShape) {
this.fenceShape = fenceShape;
}
public List<EventConfig> getEventConfig() {
return eventConfig;
}
public void setEventConfig(List<EventConfig> eventConfig) {
this.eventConfig = eventConfig;
}
public List<Integer> getGroupIds() {
return groupIds;
}
public void setGroupIds(List<Integer> groupIds) {
this.groupIds = groupIds;
}
}

@ -29,6 +29,7 @@ import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.device.mgt.core.dao.impl.ApplicationDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.DeviceTypeDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.EnrollmentDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.EventConfigDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.GeofenceDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.device.GenericDeviceDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.device.OracleDeviceDAOImpl;
@ -154,6 +155,10 @@ public class DeviceManagementDAOFactory {
return new GeofenceDAOImpl();
}
public static EventConfigDAO getEventConfigDAO() {
return new EventConfigDAOImpl();
}
public static void init(DataSourceConfig config) {
dataSource = resolveDataSource(config);
try {

@ -0,0 +1,29 @@
/*
* 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.dao;
import org.wso2.carbon.device.mgt.common.event.config.EventConfig;
import java.util.List;
public interface EventConfigDAO {
int[] storeEventRecords(List<EventConfig> eventConfigList, int tenantId) throws EventManagementDAOException;
boolean addEventGroupMappingRecords(int[] generatedEventIds, List<Integer> groupIds) throws EventManagementDAOException;
}

@ -0,0 +1,37 @@
/*
* 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.dao;
public class EventManagementDAOException extends Exception{
public EventManagementDAOException() {
super();
}
public EventManagementDAOException(String message) {
super(message);
}
public EventManagementDAOException(String message, Throwable cause) {
super(message, cause);
}
public EventManagementDAOException(Throwable cause) {
super(cause);
}
}

@ -89,4 +89,6 @@ public interface GeofenceDAO {
* @throws DeviceManagementDAOException error occurs while updating the data
*/
int updateGeofence(GeofenceData geofenceData, int fenceId) throws DeviceManagementDAOException;
boolean createGeofenceGroupMapping(GeofenceData geofenceData, List<Integer> groupIds) throws DeviceManagementDAOException;
}

@ -0,0 +1,108 @@
/*
* 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.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.event.config.EventConfig;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.EventConfigDAO;
import org.wso2.carbon.device.mgt.core.dao.EventManagementDAOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
public class EventConfigDAOImpl implements EventConfigDAO {
private static final Log log = LogFactory.getLog(EventConfigDAOImpl.class);
@Override
public int[] storeEventRecords(List<EventConfig> eventConfigList, int tenantId) throws EventManagementDAOException {
try {
Connection conn = this.getConnection();
String sql = "INSERT INTO DM_DEVICE_EVENT(" +
"EVENT_SOURCE, " +
"EVENT_LOGIC, " +
"ACTIONS, "+
"CREATED_TIMESTAMP, " +
"TENANT_ID) " +
"VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
for (EventConfig eventConfig : eventConfigList) {
stmt.setString(1, eventConfig.getEventSource());
stmt.setString(2, eventConfig.getEventLogic());
stmt.setString(3, eventConfig.getActions());
stmt.setTimestamp(4, new Timestamp(new Date().getTime()));
stmt.setInt(5, tenantId);
stmt.addBatch();
}
int[] createdRowCount = stmt.executeBatch();
int[] generatedIds = new int[createdRowCount.length];
ResultSet generatedKeys = stmt.getGeneratedKeys();
for (int i = 0; i < createdRowCount.length; i++) {
if (generatedKeys.next()) {
generatedIds[i] = generatedKeys.getInt(1);
}
}
return generatedIds;
}
} catch (SQLException e) {
String msg = "Error occurred while creating event configurations for the tenant id " + tenantId;
log.error(msg, e);
throw new EventManagementDAOException(msg, e);
}
}
@Override
public boolean addEventGroupMappingRecords(int[] generatedEventIds, List<Integer> groupIds) throws EventManagementDAOException {
try {
Connection conn = this.getConnection();
String sql = "INSERT INTO DM_DEVICE_EVENT_GROUP_MAPPING(" +
"EVENT_ID ," +
"GROUP_ID) " +
"VALUES (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
for (Integer groupId : groupIds) {
for (int i = 0; i < generatedEventIds.length; i++) {
stmt.setInt(1, generatedEventIds[i]);
stmt.setInt(2, groupId);
stmt.addBatch();
}
}
return stmt.executeBatch().length > 0;
}
} catch (SQLException e) {
String msg = "Error occurred while creating event group mapping records";
log.error(msg, e);
throw new EventManagementDAOException(msg, e);
}
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}
}

@ -85,8 +85,8 @@ public class GeofenceDAOImpl implements GeofenceDAO {
@Override
public GeofenceData getGeofence(int fenceId) throws DeviceManagementDAOException {
try {
GeofenceData geofenceData = null;
Connection conn = this.getConnection();
GeofenceData geofenceData = null;
String sql = "SELECT " +
"ID, " +
"FENCE_NAME, " +
@ -121,9 +121,9 @@ public class GeofenceDAOImpl implements GeofenceDAO {
public List<GeofenceData> getGeoFencesOfTenant(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException {
try {
Connection conn = this.getConnection();
boolean isNameProvided = false;
List<GeofenceData> geofenceData;
Connection conn = this.getConnection();
String sql = "SELECT " +
"ID, " +
"FENCE_NAME, " +
@ -201,8 +201,8 @@ public class GeofenceDAOImpl implements GeofenceDAO {
public List<GeofenceData> getGeoFencesOfTenant(int tenantId)
throws DeviceManagementDAOException {
try {
List<GeofenceData> geofenceData;
Connection conn = this.getConnection();
List<GeofenceData> geofenceData;
String sql = "SELECT " +
"ID, " +
"FENCE_NAME, " +
@ -277,6 +277,29 @@ public class GeofenceDAOImpl implements GeofenceDAO {
}
}
@Override
public boolean createGeofenceGroupMapping(GeofenceData geofenceData, List<Integer> groupIds) throws DeviceManagementDAOException {
try {
Connection conn = this.getConnection();
String sql = "INSERT INTO DM_GEOFENCE_GROUP_MAPPING(" +
"FENCE_ID, " +
"GROUP_ID) " +
"VALUES (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
for (Integer groupId : groupIds) {
stmt.setInt(1, geofenceData.getId());
stmt.setInt(2, groupId);
stmt.addBatch();
}
return stmt.executeBatch().length > 0;
}
} catch (SQLException e) {
String msg = "Error occurred while creating geofence group mapping records";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
private Connection getConnection() throws SQLException {
return DeviceManagementDAOFactory.getConnection();
}

@ -0,0 +1,63 @@
/*
* 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.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;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
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 java.util.List;
public class EventConfigurationProviderServiceImpl implements EventConfigurationProviderService {
private static final Log log = LogFactory.getLog(EventConfigurationProviderServiceImpl.class);
private final EventConfigDAO eventConfigDAO;
public EventConfigurationProviderServiceImpl() {
eventConfigDAO = DeviceManagementDAOFactory.getEventConfigDAO();
}
@Override
public boolean createEventOfDeviceGroup(List<EventConfig> eventConfigList, List<Integer> groupIds, int tenantId)
throws EventConfigurationException {
try {
DeviceManagementDAOFactory.beginTransaction();
int[] generatedEventIds = eventConfigDAO.storeEventRecords(eventConfigList, tenantId);
boolean isRecordsCreated = eventConfigDAO.addEventGroupMappingRecords(generatedEventIds, groupIds);
DeviceManagementDAOFactory.commitTransaction();
return isRecordsCreated;
} catch (TransactionManagementException e) {
String msg = "Failed to start/open transaction to store device event configurations";
throw new EventConfigurationException(msg, e);
} catch (EventManagementDAOException e) {
String msg = "Error occurred while saving event records";
log.error(msg, e);
DeviceManagementDAOFactory.rollbackTransaction();
throw new EventConfigurationException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
}

@ -32,12 +32,17 @@ 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;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.event.config.EventConfig;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationException;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.geo.service.Alert;
import org.wso2.carbon.device.mgt.common.geo.service.GeoFence;
@ -51,6 +56,7 @@ 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.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;
@ -1248,7 +1254,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
}
@Override
public boolean createGeofence(GeofenceData geofenceData) throws GeoLocationBasedServiceException {
public boolean createGeofence(GeofenceData geofenceData) throws GeoLocationBasedServiceException, EventConfigurationException {
int tenantId;
try {
tenantId = DeviceManagementDAOUtil.getTenantId();
@ -1265,7 +1271,8 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
geofenceData = geofenceDAO.saveGeofence(geofenceData);
GeoCacheManagerImpl.getInstance()
.addFenceToCache(geofenceData, geofenceData.getId(), tenantId);
return true;
geofenceDAO.createGeofenceGroupMapping(geofenceData, geofenceData.getGroupIds());
DeviceManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {
String msg = "Failed to begin transaction for saving geofence";
log.error(msg, e);
@ -1276,7 +1283,25 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
log.error(msg, e);
throw new GeoLocationBasedServiceException(msg, e);
} finally {
DeviceManagementDAOFactory.commitTransaction();
DeviceManagementDAOFactory.closeConnection();
}
try {
EventConfigurationProviderService eventConfigService = DeviceManagerUtil.getEventConfigService();
for (EventConfig eventConfig : geofenceData.getEventConfig()) {
eventConfig.setEventSource(DeviceManagementConstants.EventServices.GEOFENCE);
}
return eventConfigService.createEventOfDeviceGroup(geofenceData.getEventConfig(),
geofenceData.getGroupIds(), tenantId);
} catch (EventConfigurationException e) {
String msg = "Failed to store Geofence event configurations";
log.error(msg, e);
if (log.isDebugEnabled()) {
log.debug("Deleting the geofence record with ID " + geofenceData.getId()
+ " since the associated event or event group mapping couldn't save successfully");
}
this.deleteGeofenceData(geofenceData.getId());
throw new EventConfigurationException(msg, e);
}
}
@ -1460,7 +1485,9 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
try {
DeviceManagementDAOFactory.beginTransaction();
if (geofenceDAO.updateGeofence(geofenceData, fenceId) > 0) {
int updatedRowCount = geofenceDAO.updateGeofence(geofenceData, fenceId);
DeviceManagementDAOFactory.commitTransaction();
if (updatedRowCount > 0) {
GeoCacheManagerImpl.getInstance().updateGeoFenceInCache(geofenceData, fenceId, tenantId);
return true;
}
@ -1475,7 +1502,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic
log.error(msg, e);
throw new GeoLocationBasedServiceException(msg, e);
} finally {
DeviceManagementDAOFactory.commitTransaction();
DeviceManagementDAOFactory.closeConnection();
}
}
}

@ -21,6 +21,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
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.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
@ -50,6 +51,7 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl;
import org.wso2.carbon.device.mgt.core.event.config.EventConfigurationProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.geo.service.GeoLocationProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.metadata.mgt.MetadataManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory;
@ -334,6 +336,10 @@ public class DeviceManagementServiceComponent {
MetadataManagementService metadataManagementService = new MetadataManagementServiceImpl();
bundleContext.registerService(MetadataManagementService.class.getName(), metadataManagementService, null);
/* Registering Event Configuration Service */
EventConfigurationProviderService eventConfigurationService = new EventConfigurationProviderServiceImpl();
bundleContext.registerService(EventConfigurationProviderService.class.getName(), eventConfigurationService, null);
OTPManagementService otpManagementService = new OTPManagementServiceImpl();
bundleContext.registerService(OTPManagementService.class.getName(), otpManagementService, null);

@ -64,6 +64,7 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManageme
import org.wso2.carbon.device.mgt.common.configuration.mgt.EnrollmentConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
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.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
@ -606,6 +607,18 @@ public final class DeviceManagerUtil {
return eventsPublisherService;
}
public static EventConfigurationProviderService getEventConfigService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
EventConfigurationProviderService eventConfigService =
(EventConfigurationProviderService) ctx.getOSGiService(EventConfigurationProviderService.class, null);
if (eventConfigService == null) {
String msg = "Event configuration service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return eventConfigService;
}
public static void initializeDeviceCache() {
DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
int deviceCacheExpiry = config.getDeviceCacheConfiguration().getExpiryTime();

@ -666,4 +666,46 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE (
PRIMARY KEY (ID)
);
-- END OF GEOFENCE RELATED DATA --
-- END OF GEOFENCE RELATED DATA --
-- DM_GEOFENCE_GROUP_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_GEOFENCE_GROUP_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
FENCE_ID INT NOT NULL,
GROUP_ID INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_geofence_group_mapping_geofence FOREIGN KEY (FENCE_ID) REFERENCES
DM_GEOFENCE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_geofence_group_mapping_group FOREIGN KEY (GROUP_ID) REFERENCES
DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB;
-- END OF DM_GEOFENCE_GROUP_MAPPING TABLE--
-- DM_DEVICE_EVENT TABLE --
CREATE TABLE IF NOT EXISTS DM_DEVICE_EVENT (
ID INT NOT NULL AUTO_INCREMENT,
EVENT_SOURCE VARCHAR(100) NOT NULL,
EVENT_LOGIC VARCHAR(100) NOT NULL,
ACTIONS TEXT DEFAULT NULL,
CREATED_TIMESTAMP TIMESTAMP NOT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID)
) ENGINE=InnoDB;
-- END OF DM_DEVICE_EVENT TABLE --
-- DM_DEVICE_EVENT_GROUP_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_DEVICE_EVENT_GROUP_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
EVENT_ID INT NOT NULL,
GROUP_ID INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_event_group_mapping_event FOREIGN KEY (EVENT_ID) REFERENCES
DM_DEVICE_EVENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_event_group_mapping_group FOREIGN KEY (GROUP_ID) REFERENCES
DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB;
-- END OF DM_DEVICE_EVENT_GROUP_MAPPING TABLE--

@ -730,4 +730,46 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE (
PRIMARY KEY (ID)
) ENGINE=InnoDB;
-- END OF DM_GEOFENCE TABLE--
-- END OF DM_GEOFENCE TABLE--
-- DM_GEOFENCE_GROUP_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_GEOFENCE_GROUP_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
FENCE_ID INT NOT NULL,
GROUP_ID INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_geofence_group_mapping_geofence FOREIGN KEY (FENCE_ID) REFERENCES
DM_GEOFENCE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_geofence_group_mapping_group FOREIGN KEY (GROUP_ID) REFERENCES
DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB;
-- END OF DM_GEOFENCE_GROUP_MAPPING TABLE--
-- DM_DEVICE_EVENT TABLE --
CREATE TABLE IF NOT EXISTS DM_DEVICE_EVENT (
ID INT NOT NULL AUTO_INCREMENT,
EVENT_SOURCE VARCHAR(100) NOT NULL,
EVENT_LOGIC VARCHAR(100) NOT NULL,
ACTIONS TEXT DEFAULT NULL,
CREATED_TIMESTAMP TIMESTAMP NOT NULL,
TENANT_ID INTEGER DEFAULT 0,
PRIMARY KEY (ID)
) ENGINE=InnoDB;
-- END OF DM_DEVICE_EVENT TABLE --
-- DM_DEVICE_EVENT_GROUP_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_DEVICE_EVENT_GROUP_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
EVENT_ID INT NOT NULL,
GROUP_ID INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_event_group_mapping_event FOREIGN KEY (EVENT_ID) REFERENCES
DM_DEVICE_EVENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_dm_event_group_mapping_group FOREIGN KEY (GROUP_ID) REFERENCES
DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB;
-- END OF DM_DEVICE_EVENT_GROUP_MAPPING TABLE--
Loading…
Cancel
Save