From ca6b937a3a578bab3251ed7bd3d89642f087220c Mon Sep 17 00:00:00 2001 From: Pahansith Date: Mon, 14 Sep 2020 16:00:03 +0530 Subject: [PATCH] Create geofence API definitions --- .../device/mgt/jaxrs/beans/GeofenceList.java | 49 ++++ .../mgt/jaxrs/beans/GeofenceWrapper.java | 107 ++++++++ .../service/api/GeoLocationBasedService.java | 231 ++++++++++++++++++ .../impl/GeoLocationBasedServiceImpl.java | 144 +++++++++++ .../impl/util/RequestValidationUtil.java | 27 ++ .../service/GeoLocationProviderService.java | 43 ++++ .../mgt/common/geo/service/GeofenceData.java | 96 ++++++++ .../core/dao/DeviceManagementDAOFactory.java | 5 + .../device/mgt/core/dao/GeofenceDAO.java | 73 ++++++ .../mgt/core/dao/impl/GeofenceDAOImpl.java | 203 +++++++++++++++ .../GeoLocationProviderServiceImpl.java | 129 ++++++++++ .../src/main/resources/dbscripts/cdm/h2.sql | 17 ++ .../main/resources/dbscripts/cdm/mssql.sql | 17 ++ .../main/resources/dbscripts/cdm/mysql.sql | 16 ++ .../main/resources/dbscripts/cdm/oracle.sql | 17 ++ .../resources/dbscripts/cdm/postgresql.sql | 17 ++ 16 files changed, 1191 insertions(+) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/GeofenceList.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/GeofenceWrapper.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeofenceData.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/GeofenceDAO.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GeofenceDAOImpl.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/GeofenceList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/GeofenceList.java new file mode 100644 index 00000000000..519110366c0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/GeofenceList.java @@ -0,0 +1,49 @@ +/* + * 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 com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; + +import java.util.ArrayList; +import java.util.List; + +public class GeofenceList extends BasePaginatedResult { + private List geofenceList = new ArrayList<>(); + + @ApiModelProperty(value = "List of geofences returned") + @JsonProperty("geofences") + public List getGeofenceList() { + return geofenceList; + } + + public void setGeofenceList(List geofenceList) { + this.geofenceList = geofenceList; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{\n"); + sb.append(" count: ").append(getCount()).append(",\n"); + sb.append(" geofences: [").append(geofenceList).append("\n"); + sb.append("]}\n"); + return sb.toString(); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/GeofenceWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/GeofenceWrapper.java new file mode 100644 index 00000000000..51d14baf111 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/GeofenceWrapper.java @@ -0,0 +1,107 @@ +/* + * 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 GeofenceWrapper { + + @ApiModelProperty( + name = "id", + value = "Id of the geo fence") + private int id; + + @ApiModelProperty( + name = "fenceName", + value = "Name of the geo fence", + required = true) + private String fenceName; + + @ApiModelProperty( + name = "description", + value = "Description of the geo fence", + required = true) + private String description; + + @ApiModelProperty( + name = "latitude", + value = "Latitude of center of the geo fence", + required = true) + private double latitude; + + @ApiModelProperty( + name = "longitude", + value = "Longitude of center of the geo fence", + required = true) + private double longitude; + + @ApiModelProperty( + name = "radius", + value = "Radius from the center", + required = true) + private float radius; + + 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; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java index 0fbe424cdf9..21747fc774b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java @@ -33,12 +33,14 @@ 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.GeofenceWrapper; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import javax.validation.Valid; import javax.validation.constraints.Size; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; @@ -76,6 +78,12 @@ import javax.ws.rs.core.Response; description = "", key = "perm:geo-service:alerts-manage", permissions = {"/device-mgt/devices/owning-device/manage-alerts"} + ), + @Scope( + name = "Manage Geo Fences", + description = "", + key = "perm:geo-service:geo-fence", + permissions = {"/device-mgt/devices/owning-device/manage-geo-fence"} ) } ) @@ -833,5 +841,228 @@ public interface GeoLocationBasedService { value = "The query name.", required = true) @QueryParam("queryName") String queryName); + + @POST + @Path("/geo-fence") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "POST", + value = "Create Geo fence", + notes = "Create a new geo fence", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:geo-fence") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 201, + message = "Created.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid Geofence data found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response createGeofence(@ApiParam(name = "fence", value = "Geo fence data")GeofenceWrapper geofenceWrapper); + + + @GET + @Path("/geo-fence/{fenceId}") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "GET", + value = "Get Geo fence", + notes = "Get existing geo fence", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:geo-fence") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 404, + message = "Not found. \n No Geofence found for the Id", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response getGeofence( + @ApiParam( + name = "fenceId", + value = "Id of the fence", + required = true) + @PathParam("fenceId") int fenceId); + + + @GET + @Path("/geo-fence") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "GET", + value = "Get Geo fences", + notes = "Get all geo fence", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:geo-fence") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response getGeofence( + @QueryParam("offset") int offset, + @DefaultValue("10") + @QueryParam("limit") int limit); + + + @DELETE + @Path("/geo-fence/{fenceId}") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "DELETE", + value = "Delete Geo fence", + notes = "Delete an existing geo fence", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:geo-fence") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 404, + message = "Not found. \n No geofences found for the Id", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response deleteGeofence( + @ApiParam( + name = "fenceId", + value = "Id of the fence", + required = true) + @PathParam("fenceId") int fenceId); + + + @PUT + @Path("/geo-fence/{fenceId}") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "PUT", + value = "Update Geo fence", + notes = "Update an existing geo fence", + response = Response.class, + tags = "Geo Service Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:geo-fence") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid Geofence data found.", + response = Response.class), + @ApiResponse( + code = 404, + message = "Not found. \n No Geofence found for the Id", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response updateGeofence( + @ApiParam(name = "fence", value = "Geo fence data")GeofenceWrapper geofenceWrapper, + @ApiParam( + name = "fenceId", + value = "Id of the fence", + required = true) + @PathParam("fenceId") int fenceId); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java index ffb433eaec9..8c0c56fc8cc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java @@ -29,9 +29,12 @@ import org.wso2.carbon.analytics.dataservice.commons.SortType; import org.wso2.carbon.analytics.datasource.commons.Record; import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; import org.wso2.carbon.context.CarbonContext; +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.GeoServices; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; 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.*; @@ -42,7 +45,10 @@ 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.GeofenceList; +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; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; @@ -577,4 +583,142 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { eventBean.setValues(record.getValues()); return eventBean; } + + @Path("/geo-fence") + @POST + @Consumes("application/json") + @Produces("application/json") + public Response createGeofence(GeofenceWrapper geofenceWrapper) { + RequestValidationUtil.validateGeofenceData(geofenceWrapper); + try { + GeofenceData geofenceData = new GeofenceData(); + geofenceData.setFenceName(geofenceWrapper.getFenceName()); + geofenceData.setDescription(geofenceWrapper.getDescription()); + geofenceData.setLatitude(geofenceWrapper.getLatitude()); + geofenceData.setLongitude(geofenceWrapper.getLongitude()); + geofenceData.setRadius(geofenceWrapper.getRadius()); + + 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.CREATED).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(); + } + } + + @Path("/geo-fence/{fenceId}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Response getGeofence(@PathParam("fenceId") int fenceId) { + try { + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); + GeofenceData geofenceData = geoService.getGeofence(fenceId); + if (geofenceData == null) { + String msg = "No valid Geofence found for ID " + fenceId; + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); + } + return Response.status(Response.Status.OK).entity(getMappedResponseBean(geofenceData)).build(); + } catch (GeoLocationBasedServiceException e) { + String msg = "Server error occurred while retrieving Geofence for Id " + fenceId; + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + /** + * Wrap geofence data retrieved from DB into Response Bean + * @param geofenceData retrieved data fromDB + * @return Response bean with geofence data + */ + private GeofenceWrapper getMappedResponseBean(GeofenceData geofenceData) { + GeofenceWrapper geofenceWrapper = new GeofenceWrapper(); + geofenceWrapper.setId(geofenceData.getId()); + geofenceWrapper.setFenceName(geofenceData.getFenceName()); + geofenceWrapper.setDescription(geofenceData.getDescription()); + geofenceWrapper.setLatitude(geofenceData.getLatitude()); + geofenceWrapper.setLongitude(geofenceData.getLongitude()); + geofenceWrapper.setRadius(geofenceData.getRadius()); + return geofenceWrapper; + } + + @Path("/geo-fence") + @GET + @Consumes("application/json") + @Produces("application/json") + public Response getGeofence(@QueryParam("offset") int offset, + @DefaultValue("10") + @QueryParam("limit") int limit) { + try { + PaginationRequest request = new PaginationRequest(offset, limit); + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); + List geofence = geoService.getGeofence(request); + List geofenceList = new ArrayList<>(); + for (GeofenceData geofenceData : geofence) { + geofenceList.add(getMappedResponseBean(geofenceData)); + } + PaginationResult paginationResult = new PaginationResult(); + paginationResult.setData(geofenceList); + paginationResult.setRecordsTotal(geofenceList.size()); + return Response.status(Response.Status.OK).entity(paginationResult).build(); + } catch (GeoLocationBasedServiceException e) { + String msg = "Failed to retrieve geofence data"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + + @Path("/geo-fence/{fenceId}") + @DELETE + @Consumes("application/json") + @Produces("application/json") + public Response deleteGeofence(@PathParam("fenceId") int fenceId) { + try { + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); + if (!geoService.deleteGeofenceData(fenceId)) { + String msg = "No valid Geofence found for ID " + fenceId; + log.error(msg); + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); + } + return Response.status(Response.Status.OK).build(); + } catch (GeoLocationBasedServiceException e) { + String msg = "Failed to delete geofence data"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @Path("/geo-fence/{fenceId}") + @PUT + @Consumes("application/json") + @Produces("application/json") + public Response updateGeofence(GeofenceWrapper geofenceWrapper, @PathParam("fenceId") int fenceId) { + RequestValidationUtil.validateGeofenceData(geofenceWrapper); + try { + GeofenceData geofenceData = new GeofenceData(); + geofenceData.setFenceName(geofenceWrapper.getFenceName()); + geofenceData.setDescription(geofenceWrapper.getDescription()); + geofenceData.setLatitude(geofenceWrapper.getLatitude()); + geofenceData.setLongitude(geofenceWrapper.getLongitude()); + geofenceData.setRadius(geofenceWrapper.getRadius()); + + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); + if (!geoService.updateGeofence(geofenceData, fenceId)) { + String msg = "No valid Geofence found for ID " + fenceId; + log.error(msg); + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); + } + return Response.status(Response.Status.CREATED).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(); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java index a0259da67eb..8bafe1b8460 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java @@ -30,6 +30,7 @@ import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; 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.beans.OldPasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ProfileFeature; @@ -524,4 +525,30 @@ public class RequestValidationUtil { && StringUtils.isEmpty(emailAddress); } + public static void validateGeofenceData(GeofenceWrapper geofenceWrapper) { + if (geofenceWrapper.getFenceName() == null || geofenceWrapper.getFenceName().trim().isEmpty()) { + String msg = "Geofence name should not be null or empty"; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build()); + } + if (geofenceWrapper.getLatitude() < -90 || geofenceWrapper.getLatitude() > 90) { + String msg = "Latitude should be a value between -90 and 90"; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build()); + } + if (geofenceWrapper.getLongitude() < -180 || geofenceWrapper.getLongitude() > 180) { + String msg = "Longitude should be a value between -180 and 180"; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build()); + } + if (geofenceWrapper.getRadius() < 1) { + String msg = "Minimum radius of the fence should be 1m"; + log.error(msg); + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build()); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoLocationProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoLocationProviderService.java index f58fb8d0c60..1449ca6b044 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoLocationProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeoLocationProviderService.java @@ -19,6 +19,8 @@ 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 java.util.List; @@ -69,4 +71,45 @@ public interface GeoLocationProviderService { List getTrafficAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException; List getTrafficAlerts() throws GeoLocationBasedServiceException; + + /** + * Create new GeoFence + * @param geofenceData fence data + * @return true if the fence creation success + * @throws GeoLocationBasedServiceException error occurs while creating a geofence + */ + boolean createGeofence(GeofenceData geofenceData) throws GeoLocationBasedServiceException; + + /** + * Get geofence by ID + * @param fenceId id of the fence which should be retrieved + * @return Extracted geofence data + * @throws GeoLocationBasedServiceException error occurs while retrieving a geofence + */ + GeofenceData getGeofence(int fenceId) throws GeoLocationBasedServiceException; + + /** + * Get paginated geofence list + * @param request Pagination Request + * @return List of Geofences retrieved + * @throws GeoLocationBasedServiceException error occurs while retrieving geofences + */ + List getGeofence(PaginationRequest request) throws GeoLocationBasedServiceException; + + /** + * Delete Geofence with ID + * @param fenceId Id of the fence which should be deleted + * @return true if deletion success. false if not record found for the used Id + * @throws GeoLocationBasedServiceException + */ + boolean deleteGeofenceData(int fenceId) throws GeoLocationBasedServiceException; + + /** + * Update a Geofence. Will not be updated tenantId and owner + * @param geofenceData Bean with updated geofence data + * @param fenceId Id of the fence which should be updated + * @return true if update success. false if not a record found for the used Id + * @throws GeoLocationBasedServiceException + */ + boolean updateGeofence(GeofenceData geofenceData, int fenceId) throws GeoLocationBasedServiceException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeofenceData.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeofenceData.java new file mode 100644 index 00000000000..5c0ee4293a3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/geo/service/GeofenceData.java @@ -0,0 +1,96 @@ +/* + * 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.apache.commons.lang.StringUtils; + +public class GeofenceData { + private int id; + private String fenceName; + private String description; + private double latitude; + private double longitude; + private float radius; + private int tenantId; + private String owner; + + 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 int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java index 0e1e0695a9c..255047a7a54 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java @@ -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.GeofenceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.GenericDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.OracleDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.PostgreSQLDeviceDAOImpl; @@ -149,6 +150,10 @@ public class DeviceManagementDAOFactory { return new PrivacyComplianceDAOImpl(); } + public static GeofenceDAO getGeofenceDAO() { + return new GeofenceDAOImpl(); + } + public static void init(DataSourceConfig config) { dataSource = resolveDataSource(config); try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/GeofenceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/GeofenceDAO.java new file mode 100644 index 00000000000..27e8d72f1be --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/GeofenceDAO.java @@ -0,0 +1,73 @@ +/* + * 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.PaginationRequest; +import org.wso2.carbon.device.mgt.common.geo.service.GeofenceData; + +import java.util.List; + +/** + * Use to manage geofence data in DB + */ +public interface GeofenceDAO { + + /** + * Create new record of GeoFence + * @param geofenceData GeoFence record data + * @return created row count + * @throws DeviceManagementDAOException error occurs while saving the data + */ + int saveGeofence(GeofenceData geofenceData) throws DeviceManagementDAOException; + + /** + * Retrieve a geofence record for specified Id + * @param fenceId Id of the fence which should be queried + * @return Retrieved geofence data with tenant and owner info + * @throws DeviceManagementDAOException error occurs while reading the data + */ + GeofenceData getGeofence(int fenceId) throws DeviceManagementDAOException; + + /** + * Retrieve a paginated list of geofence data for a specific tenant + * @param request pagination request with offset and limit + * @param tenantId Id of the tenant which fences owned + * @return List of geofences retrieved + * @throws DeviceManagementDAOException error occurs while reading the data + */ + List getGeofencesOfTenant(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException; + + /** + * Delete a geofence using the geofence Id + * @param fenceId Id of the fence which should be deleted + * @return Affected row count + * @throws DeviceManagementDAOException error occurs while deleting the data + */ + int deleteGeofenceById(int fenceId) throws DeviceManagementDAOException; + + /** + * Update a geofence record using fence id + * @param geofenceData updated geofence data + * @param fenceId id of the fence which should be updated + * @return affected row count + * @throws DeviceManagementDAOException error occurs while updating the data + */ + int updateGeofence(GeofenceData geofenceData, int fenceId) throws DeviceManagementDAOException; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GeofenceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GeofenceDAOImpl.java new file mode 100644 index 00000000000..15d0ee859c1 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GeofenceDAOImpl.java @@ -0,0 +1,203 @@ +/* + * 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.PaginationRequest; +import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException; +import org.wso2.carbon.device.mgt.common.geo.service.GeofenceData; +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 java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +public class GeofenceDAOImpl implements GeofenceDAO { + private static final Log log = LogFactory.getLog(GeofenceDAOImpl.class); + @Override + public int saveGeofence(GeofenceData geofenceData) throws DeviceManagementDAOException { + try { + Connection conn = this.getConnection(); + String sql = "INSERT INTO DM_GEOFENCE(" + + "FENCE_NAME, " + + "DESCRIPTION, " + + "LATITUDE, " + + "LONGITUDE, " + + "RADIUS, " + + "CREATED_TIMESTAMP, " + + "OWNER, " + + "TENANT_ID) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, geofenceData.getFenceName()); + stmt.setString(2, geofenceData.getDescription()); + stmt.setDouble(3, geofenceData.getLatitude()); + stmt.setDouble(4, geofenceData.getLongitude()); + stmt.setFloat(5, geofenceData.getRadius()); + stmt.setTimestamp(6, new Timestamp(new Date().getTime())); + stmt.setString(7, geofenceData.getOwner()); + stmt.setInt(8, geofenceData.getTenantId()); + return stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while creating Geofence for the tenant id "+geofenceData.getTenantId(); + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + @Override + public GeofenceData getGeofence(int fenceId) throws DeviceManagementDAOException { + try { + GeofenceData geofenceData = null; + Connection conn = this.getConnection(); + String sql = "SELECT " + + "ID, " + + "FENCE_NAME, " + + "DESCRIPTION, " + + "LATITUDE, " + + "LONGITUDE, " + + "RADIUS, " + + "OWNER, " + + "TENANT_ID " + + "FROM DM_GEOFENCE " + + "WHERE ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, fenceId); + try (ResultSet rst = stmt.executeQuery()) { + List geofenceDataList = extractGeofenceData(rst); + if (!geofenceDataList.isEmpty()) { + geofenceData = geofenceDataList.get(0); + } + } + } + return geofenceData; + } catch (SQLException e) { + String msg = "Error occurred while retrieving Geofence with id "+fenceId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + @Override + public List getGeofencesOfTenant(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + try { + List geofenceData; + Connection conn = this.getConnection(); + String sql = "SELECT " + + "ID, " + + "FENCE_NAME, " + + "DESCRIPTION, " + + "LATITUDE, " + + "LONGITUDE, " + + "RADIUS, " + + "OWNER, " + + "TENANT_ID " + + "FROM DM_GEOFENCE " + + "WHERE TENANT_ID = ? " + + "LIMIT ? OFFSET ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, tenantId); + stmt.setInt(2, request.getRowCount()); + stmt.setInt(3, request.getStartIndex()); + try (ResultSet rst = stmt.executeQuery()) { + geofenceData = extractGeofenceData(rst); + } + } + return geofenceData; + } catch (SQLException e) { + String msg = "Error occurred while retrieving Geofence of the tenant " + tenantId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + @Override + public int deleteGeofenceById(int fenceId) throws DeviceManagementDAOException { + try { + Connection conn = this.getConnection(); + String sql = "DELETE FROM DM_GEOFENCE WHERE ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, fenceId); + return stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while deleting Geofence with ID " + fenceId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + @Override + public int updateGeofence(GeofenceData geofenceData, int fenceId) throws DeviceManagementDAOException { + try { + Connection conn = this.getConnection(); + String sql = "UPDATE DM_GEOFENCE SET " + + "FENCE_NAME = ?, " + + "DESCRIPTION = ?, " + + "LATITUDE = ?, " + + "LONGITUDE = ?, " + + "RADIUS = ? " + + "WHERE ID = ?"; + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, geofenceData.getFenceName()); + stmt.setString(2, geofenceData.getDescription()); + stmt.setDouble(3, geofenceData.getLatitude()); + stmt.setDouble(4, geofenceData.getLongitude()); + stmt.setFloat(5, geofenceData.getRadius()); + stmt.setInt(6, fenceId); + return stmt.executeUpdate(); + } + } catch (SQLException e) { + String msg = "Error occurred while updating Geofence record with id " + fenceId; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + private Connection getConnection() throws SQLException { + return DeviceManagementDAOFactory.getConnection(); + } + + private List extractGeofenceData(ResultSet rst) throws SQLException { + List geofenceDataList = new ArrayList<>(); + while (rst.next()) { + GeofenceData geofenceData = new GeofenceData(); + geofenceData.setId(rst.getInt("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.setOwner(rst.getString("OWNER")); + geofenceData.setTenantId(rst.getInt("TENANT_ID")); + geofenceDataList.add(geofenceData); + } + return geofenceDataList; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java index ccb0317a38e..080e729fc23 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceImpl.java @@ -37,11 +37,19 @@ 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.GeoServices; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; +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; import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException; import org.wso2.carbon.device.mgt.common.geo.service.AlertAlreadyExistException; +import org.wso2.carbon.device.mgt.common.geo.service.GeofenceData; +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.internal.DeviceManagementDataHolder; import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub; import org.wso2.carbon.event.processor.stub.types.ExecutionPlanConfigurationDto; @@ -68,6 +76,7 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -113,6 +122,12 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic private static final String SSLV3 = "SSLv3"; + private final GeofenceDAO geofenceDAO; + + public GeoLocationProviderServiceImpl() { + this.geofenceDAO = DeviceManagementDAOFactory.getGeofenceDAO(); + } + @Override public List getWithinAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException { @@ -1231,4 +1246,118 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } return jwtClientManagerService; } + + @Override + public boolean createGeofence(GeofenceData geofenceData) throws GeoLocationBasedServiceException { + try { + geofenceData.setTenantId(DeviceManagementDAOUtil.getTenantId()); + geofenceData.setOwner(PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername()); + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while retrieving tenant Id"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } + + try { + DeviceManagementDAOFactory.beginTransaction(); + return geofenceDAO.saveGeofence(geofenceData) > 0; + } catch (TransactionManagementException e) { + String msg = "Failed to begin transaction for saving geofence"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } catch (DeviceManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while saving geofence"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } finally { + DeviceManagementDAOFactory.commitTransaction(); + } + } + + @Override + public GeofenceData getGeofence(int fenceId) throws GeoLocationBasedServiceException { + try { + DeviceManagementDAOFactory.openConnection(); + return geofenceDAO.getGeofence(fenceId); + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while retrieving Geofence data with ID "+fenceId; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } catch (SQLException e) { + String msg = "Failed to open the DB connection to retrieve Geofence"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Override + public List getGeofence(PaginationRequest request) throws GeoLocationBasedServiceException { + int tenantId; + try { + tenantId = DeviceManagementDAOUtil.getTenantId(); + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while retrieving tenant id while get geofence data"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } + + try { + if (log.isDebugEnabled()) { + log.debug("Retrieving geofence data for the tenant " + tenantId); + } + DeviceManagementDAOFactory.openConnection(); + return geofenceDAO.getGeofencesOfTenant(request, tenantId); + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while retrieving geofence data for the tenant " + tenantId; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } catch (SQLException e) { + String msg = "Failed to open the DB connection to retrieve Geofence"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + + @Override + public boolean deleteGeofenceData(int fenceId) throws GeoLocationBasedServiceException { + try { + DeviceManagementDAOFactory.beginTransaction(); + return geofenceDAO.deleteGeofenceById(fenceId) > 0; + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while deleting geofence"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Failed to begin transaction to delete geofence"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } finally { + DeviceManagementDAOFactory.commitTransaction(); + } + } + + @Override + public boolean updateGeofence(GeofenceData geofenceData, int fenceId) + throws GeoLocationBasedServiceException { + try { + DeviceManagementDAOFactory.beginTransaction(); + return geofenceDAO.updateGeofence(geofenceData, fenceId) > 0; + } catch (TransactionManagementException e) { + String msg = "Failed to begin transaction for saving geofence"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } catch (DeviceManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while saving geofence"; + log.error(msg, e); + throw new GeoLocationBasedServiceException(msg, e); + } finally { + DeviceManagementDAOFactory.commitTransaction(); + } + } } diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql index 623bd6b374e..fa9c18e9ff4 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -645,3 +645,20 @@ DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID ORDER BY TENANT_ID, DEVICE_ID; -- END OF DASHBOARD RELATED VIEWS -- + +-- GEOFENCE RELATED DATA -- + +CREATE TABLE IF NOT EXISTS DM_GEOFENCE ( + ID INT NOT NULL AUTO_INCREMENT, + FENCE_NAME VARCHAR(100) NOT NULL, + DESCRIPTION TEXT DEFAULT NULL, + LATITUDE DOUBLE NULL, + LONGITUDE DOUBLE NULL, + RADIUS DOUBLE NULL, + CREATED_TIMESTAMP TIMESTAMP NOT NULL, + OWNER VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); + +-- END OF GEOFENCE RELATED DATA -- \ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql index 058bceb53bd..fc3e5232195 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -694,3 +694,20 @@ DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID ORDER BY TENANT_ID, DEVICE_ID'); -- END OF DASHBOARD RELATED VIEWS -- + +-- DM_GEOFENCE TABLE-- + +CREATE TABLE DM_GEOFENCE ( + ID INT IDENTITY NOT NULL, + FENCE_NAME VARCHAR(255) NOT NULL, + DESCRIPTION VARCHAR(MAX) DEFAULT NULL, + LATITUDE DECIMAL(3,5) NOT NULL, + LONGITUDE DECIMAL(3,5) NOT NULL, + RADIUS DECIMAL(30,4) NOT NULL, + CREATED_TIMESTAMP DATETIME2 NOT NULL, + OWNER VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); + +-- END OF DM_GEOFENCE TABLE-- \ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql index f1244dd87ea..5a91561b25d 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -711,3 +711,19 @@ ORDER BY TENANT_ID, DEVICE_ID; -- END OF DASHBOARD RELATED VIEWS -- +-- DM_GEOFENCE TABLE-- + +CREATE TABLE IF NOT EXISTS DM_GEOFENCE ( + ID INT NOT NULL AUTO_INCREMENT, + FENCE_NAME VARCHAR(255) NOT NULL, + DESCRIPTION TEXT DEFAULT NULL, + LATITUDE DOUBLE NOT NULL, + LONGITUDE DOUBLE NOT NULL, + RADIUS DOUBLE NOT NULL, + CREATED_TIMESTAMP TIMESTAMP NOT NULL, + OWNER VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +) ENGINE=InnoDB; + +-- END OF DM_GEOFENCE TABLE-- \ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql index 325bb770b36..c29f8efb5e3 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -1063,3 +1063,20 @@ DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID / -- END OF DASHBOARD RELATED VIEWS -- + +-- DM_GEOFENCE TABLE-- + +CREATE TABLE DM_GEOFENCE ( + ID NUMBER(10) NOT NULL, + FENCE_NAME VARCHAR2(255) NOT NULL, + DESCRIPTION CLOB DEFAULT NULL, + LATITUDE BINARY_DOUBLE NOT NULL, + LONGITUDE BINARY_DOUBLE NOT NULL, + RADIUS BINARY_DOUBLE NOT NULL, + CREATED_TIMESTAMP TIMESTAMP(0) NOT NULL, + OWNER VARCHAR2(255) NOT NULL, + TENANT_ID NUMBER(10) DEFAULT 0, + CONSTRAINT PK_DM_GEOFENCE PRIMARY KEY (ID) +); + +-- END OF DM_GEOFENCE TABLE-- \ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql index d6956255753..c96ef55b545 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -700,3 +700,20 @@ WHERE ORDER BY TENANT_ID, DEVICE_ID; -- END OF DASHBOARD RELATED VIEWS -- + +-- DM_GEOFENCE TABLE-- + +CREATE TABLE IF NOT EXISTS DM_GEOFENCE ( + ID INTEGER DEFAULT NEXTVAL ('DM_GEOFENCE_seq') NOT NULL, + FENCE_NAME VARCHAR(255) NOT NULL, + DESCRIPTION TEXT DEFAULT NULL, + LATITUDE DECIMAL(3,5) NOT NULL, + LONGITUDE DECIMAL(3,5) NOT NULL, + RADIUS DECIMAL(35,3) NOT NULL, + CREATED_TIMESTAMP TIMESTAMP(0) NOT NULL, + OWNER VARCHAR(255) NOT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); + +-- END OF DM_GEOFENCE TABLE-- \ No newline at end of file