From ead01f837d7e7360cba92ac37d0730b37012c2ab Mon Sep 17 00:00:00 2001 From: charitha Date: Thu, 26 Jul 2018 12:23:47 +0530 Subject: [PATCH] Fixed issue in Geo fencing --- .../impl/GeoLocationBasedServiceImpl.java | 99 ++- .../mgt/common/DeviceManagementConstants.java | 2 +- .../service/GeoLocationProviderService.java | 18 +- .../GeoLocationProviderServiceImpl.java | 81 ++- .../GeoLocationProviderServiceTest.java | 72 +-- .../cdmf.unit.geo-dashboard/geo-dashboard.hbs | 2 +- .../public/js/websocket.js | 2 +- .../cdmf.unit.geo-devices/geo-devices.hbs | 71 +-- .../public/js/websocket.js | 32 +- .../service/api/GeoLocationBasedService.java | 550 ----------------- .../impl/GeoLocationBasedServiceImpl.java | 565 ------------------ .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 - .../impl/GeoLocationBasedServiceImplTest.java | 78 --- 13 files changed, 175 insertions(+), 1399 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java 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 7244f00587..a8811e5418 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,6 +29,7 @@ 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.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.DeviceManagementException; @@ -163,17 +164,20 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); } - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - DeviceIdentifier identifier = new DeviceIdentifier(); identifier.setId(deviceId); identifier.setType(deviceType); + Device device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(identifier, false); + if (device == null || device.getEnrolmentInfo() == null) { + if (log.isDebugEnabled()) { + log.debug("Device not found: " + identifier.toString()); + } + return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build(); + } + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - geoService.createGeoAlert(alert, identifier, alertType); + geoService.createGeoAlert(alert, identifier, alertType, device.getEnrolmentInfo().getOwner()); return Response.ok().build(); } catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) { String error = "Error occurred while creating the geo alert for " + deviceType + " with id: " + deviceId; @@ -181,7 +185,12 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); } catch (AlertAlreadyExistException e) { String error = "A geo alert with this name already exists."; - log.error(error,e); + log.error(error, e); + return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); + } catch (DeviceManagementException e) { + String error = "Error occurred while retrieving the device enrollment info of " + + deviceType + " with id: " + deviceId; + log.error(error, e); return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); } } @@ -202,7 +211,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); } catch (AlertAlreadyExistException e) { String error = "A geo alert with this name already exists."; - log.error(error,e); + log.error(error, e); return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); } } @@ -222,17 +231,20 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); } - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - DeviceIdentifier identifier = new DeviceIdentifier(); identifier.setId(deviceId); identifier.setType(deviceType); + Device device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(identifier, false); + if (device == null || device.getEnrolmentInfo() == null) { + if (log.isDebugEnabled()) { + log.debug("Device not found: " + identifier.toString()); + } + return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build(); + } + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - geoService.updateGeoAlert(alert, identifier, alertType); + geoService.updateGeoAlert(alert, identifier, alertType, device.getEnrolmentInfo().getOwner()); return Response.ok().build(); } catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) { String error = "Error occurred while creating the geo alert for " + deviceType + " with id: " + deviceId; @@ -240,7 +252,12 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); } catch (AlertAlreadyExistException e) { String error = "A geo alert with this name already exists."; - log.error(error,e); + log.error(error, e); + return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); + } catch (DeviceManagementException e) { + String error = "Error occurred while retrieving the device enrollment info of " + + deviceType + " with id: " + deviceId; + log.error(error, e); return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); } } @@ -260,7 +277,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); } catch (AlertAlreadyExistException e) { String error = "A geo alert with this name already exists."; - log.error(error,e); + log.error(error, e); return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); } } @@ -280,22 +297,30 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); } - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - DeviceIdentifier identifier = new DeviceIdentifier(); identifier.setId(deviceId); identifier.setType(deviceType); + Device device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(identifier, false); + if (device == null || device.getEnrolmentInfo() == null) { + if (log.isDebugEnabled()) { + log.debug("Device not found: " + identifier.toString()); + } + return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build(); + } + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - geoService.removeGeoAlert(alertType, identifier, queryName); + geoService.removeGeoAlert(alertType, identifier, queryName, device.getEnrolmentInfo().getOwner()); return Response.ok().build(); } catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) { String error = "Error occurred while removing the geo alert for " + deviceType + " with id: " + deviceId; log.error(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } catch (DeviceManagementException e) { + String error = "Error occurred while retrieving the device enrollment info of " + + deviceType + " with id: " + deviceId; + log.error(error, e); + return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); } } @@ -329,34 +354,37 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); } - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - DeviceIdentifier identifier = new DeviceIdentifier(); identifier.setId(deviceId); identifier.setType(deviceType); + Device device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(identifier, false); + if (device == null || device.getEnrolmentInfo() == null) { + if (log.isDebugEnabled()) { + log.debug("Device not found: " + identifier.toString()); + } + return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build(); + } + GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); if (GeoServices.ALERT_TYPE_WITHIN.equals(alertType)) { - List alerts = geoService.getWithinAlerts(identifier); + List alerts = geoService.getWithinAlerts(identifier, device.getEnrolmentInfo().getOwner()); return Response.ok().entity(alerts).build(); } else if (GeoServices.ALERT_TYPE_EXIT.equals(alertType)) { - List alerts = geoService.getExitAlerts(identifier); + List alerts = geoService.getExitAlerts(identifier, device.getEnrolmentInfo().getOwner()); return Response.ok().entity(alerts).build(); } else if (GeoServices.ALERT_TYPE_SPEED.equals(alertType)) { - String result = geoService.getSpeedAlerts(identifier); + String result = geoService.getSpeedAlerts(identifier, device.getEnrolmentInfo().getOwner()); return Response.ok().entity(result).build(); } else if (GeoServices.ALERT_TYPE_PROXIMITY.equals(alertType)) { - String result = geoService.getProximityAlerts(identifier); + String result = geoService.getProximityAlerts(identifier, device.getEnrolmentInfo().getOwner()); return Response.ok().entity(result).build(); } else if (GeoServices.ALERT_TYPE_STATIONARY.equals(alertType)) { - List alerts = geoService.getStationaryAlerts(identifier); + List alerts = geoService.getStationaryAlerts(identifier, device.getEnrolmentInfo().getOwner()); return Response.ok().entity(alerts).build(); } else if (GeoServices.ALERT_TYPE_TRAFFIC.equals(alertType)) { - List alerts = geoService.getTrafficAlerts(identifier); + List alerts = geoService.getTrafficAlerts(identifier, device.getEnrolmentInfo().getOwner()); return Response.ok().entity(alerts).build(); } return null; @@ -364,6 +392,11 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { String error = "Error occurred while getting the geo alerts for " + deviceType + " with id: " + deviceId; log.error(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } catch (DeviceManagementException e) { + String error = "Error occurred while retrieving the device enrollment info of " + + deviceType + " with id: " + deviceId; + log.error(error, e); + return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java index 3aa85254f8..e5b1183673 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java @@ -105,7 +105,7 @@ public final class DeviceManagementConstants { public static final String ALERT_TYPE_PROXIMITY = "Proximity"; public static final String ALERT_TYPE_STATIONARY = "Stationery"; public static final String ALERT_TYPE_TRAFFIC = "Traffic"; - public static final String REGISTRY_PATH_FOR_ALERTS = "/_system/governance/geo/alerts/"; + public static final String REGISTRY_PATH_FOR_ALERTS = "/geo/alerts/"; public static final String PROXIMITY_DISTANCE = "proximityDistance"; public static final String PROXIMITY_TIME = "proximityTime"; public static final String STATIONARY_NAME = "stationeryName"; 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 92bd4e0d2f..f58fb8d0c6 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 @@ -28,45 +28,45 @@ import java.util.List; */ public interface GeoLocationProviderService { - List getWithinAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; + List getWithinAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException; List getWithinAlerts() throws GeoLocationBasedServiceException; - List getExitAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; + List getExitAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException; List getExitAlerts() throws GeoLocationBasedServiceException; - boolean createGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType) + boolean createGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType, String owner) throws GeoLocationBasedServiceException, AlertAlreadyExistException; boolean createGeoAlert(Alert alert, String alertType) throws GeoLocationBasedServiceException,AlertAlreadyExistException; - boolean updateGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType) + boolean updateGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType, String owner) throws GeoLocationBasedServiceException, AlertAlreadyExistException; boolean updateGeoAlert(Alert alert, String alertType) throws GeoLocationBasedServiceException,AlertAlreadyExistException; - boolean removeGeoAlert(String alertType, DeviceIdentifier identifier, String queryName) + boolean removeGeoAlert(String alertType, DeviceIdentifier identifier, String queryName, String owner) throws GeoLocationBasedServiceException; boolean removeGeoAlert(String alertType, String queryName) throws GeoLocationBasedServiceException; - String getSpeedAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; + String getSpeedAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException; String getSpeedAlerts() throws GeoLocationBasedServiceException; - String getProximityAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; + String getProximityAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException; String getProximityAlerts() throws GeoLocationBasedServiceException; - List getStationaryAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; + List getStationaryAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException; List getStationaryAlerts() throws GeoLocationBasedServiceException; - List getTrafficAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException; + List getTrafficAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException; List getTrafficAlerts() throws GeoLocationBasedServiceException; } 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 6be4f67488..1fd4700b39 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 @@ -55,7 +55,6 @@ import org.wso2.carbon.registry.api.Resource; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; -import javax.persistence.EntityExistsException; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; @@ -114,16 +113,16 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic private static final String SSLV3 = "SSLv3"; @Override - public List getWithinAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + public List getWithinAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException { Registry registry = getGovernanceRegistry(); String registryPath = GeoServices.REGISTRY_PATH_FOR_ALERTS + - GeoServices.ALERT_TYPE_WITHIN + "/" + identifier.getId() + "/"; + GeoServices.ALERT_TYPE_WITHIN + "/" + owner + "/" + identifier.getId() + "/"; Resource resource; try { resource = registry.get(registryPath); } catch (RegistryException e) { - log.error("Error while reading the registry path: " + registryPath); + log.error("Error while reading the registry path: " + registryPath + ". Error: " + e.getMessage()); return null; } @@ -171,7 +170,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic try { resource = registry.get(registryPath); } catch (RegistryException e) { - log.error("Error while reading the registry path: " + registryPath); + log.error("Error while reading the registry path: " + registryPath + ". Error: " + e.getMessage()); return Collections.emptyList(); } @@ -209,16 +208,16 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } @Override - public List getExitAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + public List getExitAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException { Registry registry = getGovernanceRegistry(); String registryPath = GeoServices.REGISTRY_PATH_FOR_ALERTS + - GeoServices.ALERT_TYPE_EXIT + "/" + identifier.getId() + "/"; + GeoServices.ALERT_TYPE_EXIT + "/" + owner + "/" + identifier.getId() + "/"; Resource resource; try { resource = registry.get(registryPath); } catch (RegistryException e) { - log.error("Error while reading the registry path: " + registryPath); + log.error("Error while reading the registry path: " + registryPath + ". Error: " + e.getMessage()); return null; } @@ -266,7 +265,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic try { resource = registry.get(registryPath); } catch (RegistryException e) { - log.error("Error while reading the registry path: " + registryPath); + log.error("Error while reading the registry path: " + registryPath + ". Error: " + e.getMessage()); return Collections.emptyList(); } @@ -304,9 +303,9 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } @Override - public boolean createGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType) + public boolean createGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType, String owner) throws GeoLocationBasedServiceException, AlertAlreadyExistException { - return saveGeoAlert(alert, identifier, alertType, false); + return saveGeoAlert(alert, identifier, alertType, false, owner); } @Override @@ -316,9 +315,9 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } @Override - public boolean updateGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType) + public boolean updateGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType, String owner) throws GeoLocationBasedServiceException, AlertAlreadyExistException { - return saveGeoAlert(alert, identifier, alertType, true); + return saveGeoAlert(alert, identifier, alertType, true, owner); } @Override @@ -327,7 +326,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic return saveGeoAlert(alert, alertType, true); } - public boolean saveGeoAlert(Alert alert, String alertType, boolean isUpdate) + private boolean saveGeoAlert(Alert alert, String alertType, boolean isUpdate) throws GeoLocationBasedServiceException,AlertAlreadyExistException { Type type = new TypeToken>() { @@ -434,7 +433,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } - public boolean saveGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType, boolean isUpdate) + private boolean saveGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType, boolean isUpdate, String owner) throws GeoLocationBasedServiceException, AlertAlreadyExistException { Type type = new TypeToken>() { @@ -483,8 +482,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic try { ExecutionPlanConfigurationDto[] allActiveExecutionPlanConfigs = null; String activeExecutionPlan = null; - String executionPlanName = getExecutionPlanName(alertType, alert.getQueryName(), - identifier.getId()); + String executionPlanName = getExecutionPlanName(alertType, alert.getQueryName(), identifier.getId(), owner); eventprocessorStub = getEventProcessorAdminServiceStub(); String parsedTemplate = parseTemplate(alertType, parseMap); String validationResponse = eventprocessorStub.validateExecutionPlan(parsedTemplate); @@ -507,7 +505,7 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic + executionPlanName); } } - updateRegistry(getRegistryPath(alertType, identifier, alert.getQueryName()), identifier, content, + updateRegistry(getRegistryPath(alertType, identifier, alert.getQueryName(), owner), identifier, content, options); eventprocessorStub.deployExecutionPlan(parsedTemplate); } @@ -545,27 +543,27 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } } - private String getRegistryPath(String alertType, DeviceIdentifier identifier, String queryName) + private String getRegistryPath(String alertType, DeviceIdentifier identifier, String queryName, String owner) throws GeoLocationBasedServiceException { String path = ""; if (GeoServices.ALERT_TYPE_WITHIN.equals(alertType)) { path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_WITHIN + - "/" + identifier.getId() + "/" + queryName; + "/" + owner + "/" + identifier.getId() + "/" + queryName; } else if (GeoServices.ALERT_TYPE_EXIT.equals(alertType)) { path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_EXIT + - "/" + identifier.getId() + "/" + queryName; + "/" + owner + "/" + identifier.getId() + "/" + queryName; } else if (GeoServices.ALERT_TYPE_SPEED.equals(alertType)) { path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_SPEED + - "/" + identifier.getId(); + "/" + owner + "/" + identifier.getId(); } else if (GeoServices.ALERT_TYPE_PROXIMITY.equals(alertType)) { path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_PROXIMITY + - "/" + identifier.getId() + "/" + queryName; + "/" + owner + "/" + identifier.getId() + "/" + queryName; } else if (GeoServices.ALERT_TYPE_STATIONARY.equals(alertType)) { path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_STATIONARY + - "/" + identifier.getId() + "/" + queryName; + "/" + owner + "/" + identifier.getId() + "/" + queryName; } else if (GeoServices.ALERT_TYPE_TRAFFIC.equals(alertType)) { path = GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_TRAFFIC + - "/" + identifier.getId() + "/" + queryName; + "/" + owner + "/" + identifier.getId() + "/" + queryName; } else { throw new GeoLocationBasedServiceException( "Unrecognized execution plan type: " + alertType); @@ -601,11 +599,11 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic return path; } - private String getExecutionPlanName(String alertType, String queryName, String deviceId) { + private String getExecutionPlanName(String alertType, String queryName, String deviceId, String owner) { if ("Traffic".equals(alertType)) { return "Geo-ExecutionPlan-Traffic_" + queryName + "_alert"; } else { - return "Geo-ExecutionPlan-" + alertType + "_" + queryName + "---_" + deviceId + "_alert"; + return "Geo-ExecutionPlan-" + alertType + "_" + queryName + "---_" + owner + "_" + deviceId + "_alert"; } } @@ -621,10 +619,10 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } @Override - public boolean removeGeoAlert(String alertType, DeviceIdentifier identifier, String queryName) + public boolean removeGeoAlert(String alertType, DeviceIdentifier identifier, String queryName, String owner) throws GeoLocationBasedServiceException { - removeFromRegistry(alertType, identifier, queryName); - String executionPlanName = getExecutionPlanName(alertType, queryName, identifier.getId()); + removeFromRegistry(alertType, identifier, queryName, owner); + String executionPlanName = getExecutionPlanName(alertType, queryName, identifier.getId(), owner); EventProcessorAdminServiceStub eventprocessorStub = null; try { eventprocessorStub = getEventProcessorAdminServiceStub(); @@ -674,11 +672,11 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } } - private void removeFromRegistry(String alertType, DeviceIdentifier identifier, String queryName) + private void removeFromRegistry(String alertType, DeviceIdentifier identifier, String queryName, String owner) throws GeoLocationBasedServiceException { String path = "unknown"; try { - path = getRegistryPath(alertType, identifier, queryName); + path = getRegistryPath(alertType, identifier, queryName, owner); getGovernanceRegistry().delete(path); } catch (RegistryException e) { throw new GeoLocationBasedServiceException( @@ -746,11 +744,11 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } @Override - public String getSpeedAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + public String getSpeedAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException { try { Registry registry = getGovernanceRegistry(); Resource resource = registry.get(GeoServices.REGISTRY_PATH_FOR_ALERTS + - GeoServices.ALERT_TYPE_SPEED + "/" + identifier.getId()); + GeoServices.ALERT_TYPE_SPEED + "/" + owner + "/" + identifier.getId()); if (resource == null) { return "{'content': false}"; } @@ -782,12 +780,11 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } @Override - public String getProximityAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + public String getProximityAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException { try { Registry registry = getGovernanceRegistry(); - Resource resource = registry.get(GeoServices.REGISTRY_PATH_FOR_ALERTS + - GeoServices.ALERT_TYPE_PROXIMITY - + "/" + identifier.getId()); + Resource resource = registry.get(GeoServices.REGISTRY_PATH_FOR_ALERTS + GeoServices.ALERT_TYPE_PROXIMITY + + "/" + owner + "/" + identifier.getId()); if (resource != null) { Properties props = resource.getProperties(); @@ -830,11 +827,11 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic @Override - public List getStationaryAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + public List getStationaryAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException { Registry registry = getGovernanceRegistry(); String registryPath = GeoServices.REGISTRY_PATH_FOR_ALERTS + - GeoServices.ALERT_TYPE_STATIONARY + "/" + identifier.getId() + "/"; + GeoServices.ALERT_TYPE_STATIONARY + "/" + owner + "/" + identifier.getId() + "/"; Resource resource; try { resource = registry.get(registryPath); @@ -933,10 +930,10 @@ public class GeoLocationProviderServiceImpl implements GeoLocationProviderServic } @Override - public List getTrafficAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException { + public List getTrafficAlerts(DeviceIdentifier identifier, String owner) throws GeoLocationBasedServiceException { Registry registry = getGovernanceRegistry(); String registryPath = GeoServices.REGISTRY_PATH_FOR_ALERTS + - GeoServices.ALERT_TYPE_STATIONARY + "/" + identifier.getId() + "/"; + GeoServices.ALERT_TYPE_STATIONARY + "/" + owner + "/" + identifier.getId() + "/"; Resource resource; try { resource = registry.get(registryPath); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceTest.java index 73222074c5..1e0916d079 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/geo/service/GeoLocationProviderServiceTest.java @@ -19,21 +19,17 @@ package org.wso2.carbon.device.mgt.core.geo.service; -import org.apache.axis2.AxisFault; import org.mockito.Mockito; - import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.geo.service.Alert; import org.wso2.carbon.device.mgt.common.geo.service.AlertAlreadyExistException; import org.wso2.carbon.device.mgt.common.geo.service.GeoFence; 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.core.TestDeviceManagementService; import org.wso2.carbon.device.mgt.core.common.TestDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; @@ -59,70 +55,76 @@ public class GeoLocationProviderServiceTest { private static final String SAMPLE_STATIONARY_TIME = "1500"; private static final String SAMPLE_FLUCTUATION_RADIUS = "2000"; - private EventProcessorAdminServiceStub mockEventProcessorAdminServiceStub; private GeoLocationProviderServiceImpl geoLocationProviderServiceImpl; private ExecutionPlanConfigurationDto[] mockExecutionPlanConfigurationDto = new ExecutionPlanConfigurationDto[1]; - + private Device device; + @BeforeClass public void init() throws Exception { initMocks(); - enrollDevice(); + device = enrollDevice(); } - @Test (description = "Create a sample geo exit-alert with relevant details.") + @Test(description = "Create a sample geo exit-alert with relevant details.") public void createGeoExitAlert() throws GeoLocationBasedServiceException, AlertAlreadyExistException { - Boolean result = geoLocationProviderServiceImpl. - createGeoAlert(getExitAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_EXIT); + Boolean result = geoLocationProviderServiceImpl. + createGeoAlert(getExitAlert(), getDeviceIdentifier(), + DeviceManagementConstants.GeoServices.ALERT_TYPE_EXIT, device.getEnrolmentInfo().getOwner()); Assert.assertEquals(result, Boolean.TRUE); } - @Test (description = "Create a sample geo within-alert with relevant details.") + @Test(description = "Create a sample geo within-alert with relevant details.") public void createGeoWithinAlert() throws GeoLocationBasedServiceException, AlertAlreadyExistException { - Boolean result = geoLocationProviderServiceImpl. - createGeoAlert(getWithinAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_WITHIN); + Boolean result = geoLocationProviderServiceImpl. + createGeoAlert(getWithinAlert(), getDeviceIdentifier(), + DeviceManagementConstants.GeoServices.ALERT_TYPE_WITHIN, device.getEnrolmentInfo().getOwner()); Assert.assertEquals(result, Boolean.TRUE); } - @Test (description = "Create a sample geo proximity-alert with relevant details.") + @Test(description = "Create a sample geo proximity-alert with relevant details.") public void createGeoProximityAlert() throws GeoLocationBasedServiceException, AlertAlreadyExistException { Boolean result = geoLocationProviderServiceImpl. - createGeoAlert(getProximityAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_PROXIMITY); + createGeoAlert(getProximityAlert(), getDeviceIdentifier(), + DeviceManagementConstants.GeoServices.ALERT_TYPE_PROXIMITY, device.getEnrolmentInfo().getOwner()); Assert.assertEquals(result, Boolean.TRUE); } - @Test (description = "Create a sample geo speed-alert with relevant details.") + @Test(description = "Create a sample geo speed-alert with relevant details.") public void createGeoSpeedAlert() throws GeoLocationBasedServiceException, AlertAlreadyExistException { Boolean result = geoLocationProviderServiceImpl. - createGeoAlert(getSpeedAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_SPEED); + createGeoAlert(getSpeedAlert(), getDeviceIdentifier(), + DeviceManagementConstants.GeoServices.ALERT_TYPE_SPEED, device.getEnrolmentInfo().getOwner()); Assert.assertEquals(result, Boolean.TRUE); } - @Test (description = "Create a sample geo stationary-alert with relevant details.") + @Test(description = "Create a sample geo stationary-alert with relevant details.") public void createGeoStationaryAlert() throws GeoLocationBasedServiceException, AlertAlreadyExistException { Boolean result = geoLocationProviderServiceImpl. - createGeoAlert(getStationaryAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_STATIONARY); + createGeoAlert(getStationaryAlert(), getDeviceIdentifier(), + DeviceManagementConstants.GeoServices.ALERT_TYPE_STATIONARY, device.getEnrolmentInfo().getOwner()); Assert.assertEquals(result, Boolean.TRUE); } - @Test (description = "Create a sample geo traffic-alert with relevant details.") + @Test(description = "Create a sample geo traffic-alert with relevant details.") public void createGeoTrafficAlert() throws GeoLocationBasedServiceException, AlertAlreadyExistException { Boolean result = geoLocationProviderServiceImpl. - createGeoAlert(getTrafficAlert(), getDeviceIdentifier(), DeviceManagementConstants.GeoServices.ALERT_TYPE_TRAFFIC); + createGeoAlert(getTrafficAlert(), getDeviceIdentifier(), + DeviceManagementConstants.GeoServices.ALERT_TYPE_TRAFFIC, device.getEnrolmentInfo().getOwner()); Assert.assertEquals(result, Boolean.TRUE); } @Test(dependsOnMethods = "createGeoSpeedAlert", description = "retrieve saved geo speed-alert.") public void getGeoSpeedAlerts() throws GeoLocationBasedServiceException { String result; - result = geoLocationProviderServiceImpl.getSpeedAlerts(getDeviceIdentifier()); + result = geoLocationProviderServiceImpl.getSpeedAlerts(getDeviceIdentifier(), device.getEnrolmentInfo().getOwner()); Assert.assertNotNull(result); Assert.assertEquals(result, "{'speedLimit':" + SAMPLE_SPEED_ALERT_VALUE + "}"); } - @Test(dependsOnMethods = "createGeoTrafficAlert" , description = "retrieve saved geo exit-alert.") + @Test(dependsOnMethods = "createGeoTrafficAlert", description = "retrieve saved geo exit-alert.") public void getGeoTrafficAlerts() throws GeoLocationBasedServiceException { List geoFences; - geoFences = geoLocationProviderServiceImpl.getTrafficAlerts(getDeviceIdentifier()); + geoFences = geoLocationProviderServiceImpl.getTrafficAlerts(getDeviceIdentifier(), device.getEnrolmentInfo().getOwner()); Assert.assertNotNull(geoFences); GeoFence geoFenceNode = geoFences.get(0); Assert.assertEquals(geoFenceNode.getGeoJson(), "{\n" + @@ -133,7 +135,7 @@ public class GeoLocationProviderServiceTest { @Test(dependsOnMethods = "createGeoStationaryAlert", description = "retrieve saved geo stationary-alert.") public void getGeoStationaryAlerts() throws GeoLocationBasedServiceException { List geoFences; - geoFences = geoLocationProviderServiceImpl.getStationaryAlerts(getDeviceIdentifier()); + geoFences = geoLocationProviderServiceImpl.getStationaryAlerts(getDeviceIdentifier(), device.getEnrolmentInfo().getOwner()); Assert.assertNotNull(geoFences); GeoFence geoFenceNode = geoFences.get(0); Assert.assertEquals(geoFenceNode.getAreaName(), SAMPLE_AREA_NAME); @@ -142,7 +144,7 @@ public class GeoLocationProviderServiceTest { } private void initMocks() throws JWTClientException, RemoteException { - mockEventProcessorAdminServiceStub = Mockito.mock(EventProcessorAdminServiceStub.class); + EventProcessorAdminServiceStub mockEventProcessorAdminServiceStub = Mockito.mock(EventProcessorAdminServiceStub.class); geoLocationProviderServiceImpl = Mockito.mock(GeoLocationProviderServiceImpl.class, Mockito.CALLS_REAL_METHODS); mockExecutionPlanConfigurationDto[0] = Mockito.mock(ExecutionPlanConfigurationDto.class); Mockito.doReturn(mockEventProcessorAdminServiceStub). @@ -156,8 +158,8 @@ public class GeoLocationProviderServiceTest { private DeviceIdentifier getDeviceIdentifier() { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId("1234"); - deviceIdentifier.setType("TEST"); + deviceIdentifier.setId(device.getDeviceIdentifier()); + deviceIdentifier.setType(device.getType()); return deviceIdentifier; } @@ -200,7 +202,7 @@ public class GeoLocationProviderServiceTest { } private Alert getSpeedAlert() { - Alert alert = new Alert(); + Alert alert = new Alert(); alert.setDeviceId(DEVICE_ID); alert.setParseData("{\n" + " \"" + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\",\n" + @@ -226,7 +228,7 @@ public class GeoLocationProviderServiceTest { Alert alert = new Alert(); alert.setDeviceId(DEVICE_ID); alert.setParseData("{\n" + - " \"" + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON +"\": \"" + SAMPLE_GEO_JSON + "\"\n" + + " \"" + DeviceManagementConstants.GeoServices.GEO_FENCE_GEO_JSON + "\": \"" + SAMPLE_GEO_JSON + "\"\n" + "}"); alert.setCustomName(SAMPLE_AREA_NAME); alert.setExecutionPlan("EXECUTION_PLAN"); @@ -234,7 +236,7 @@ public class GeoLocationProviderServiceTest { return alert; } - private void enrollDevice() throws Exception { + private Device enrollDevice() throws Exception { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(DEVICE_ID, DEVICE_TYPE); Device device = TestDataHolder.generateDummyDeviceData(deviceIdentifier); DeviceManagementProviderService deviceMgtService = DeviceManagementDataHolder.getInstance(). @@ -245,9 +247,11 @@ public class GeoLocationProviderServiceTest { Device returnedDevice = deviceMgtService.getDevice(deviceIdentifier); - if (!returnedDevice.getDeviceIdentifier().equals(deviceIdentifier.getId())) { - throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!"); - } + if (!returnedDevice.getDeviceIdentifier().equals(deviceIdentifier.getId())) { + throw new Exception("Incorrect device with ID - " + device.getDeviceIdentifier() + " returned!"); } + + return returnedDevice; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-dashboard/geo-dashboard.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-dashboard/geo-dashboard.hbs index cb2a518ef6..fdb006aeb5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-dashboard/geo-dashboard.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-dashboard/geo-dashboard.hbs @@ -522,7 +522,7 @@ {{#if geoServicesEnabled}}
Speed km/h
Heading
- + {{/if}} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-dashboard/public/js/websocket.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-dashboard/public/js/websocket.js index dcc0b7d5cb..eb5a157252 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-dashboard/public/js/websocket.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-dashboard/public/js/websocket.js @@ -78,7 +78,7 @@ function initializeGeoLocation(geoFencingEnabled) { geoPublicUri = geoCharts.data("geo-public-uri"); webSocketURL = wsEndPoint + "iot.per.device.stream.geo.FusedSpatialEvent/1.0.0?" + "deviceId=" + deviceId + "&deviceType=" + deviceType + "&websocketToken=" + wsToken; - alertWebSocketURL = wsEndPoint + "iot.per.device.stream.geo.AlertsNotifications/1.0.0?" + alertWebSocketURL = wsEndPoint + "iot.per.device.stream.geo.AlertNotifications/1.0.0?" + "deviceId=" + deviceId + "&deviceType=" + deviceType + "&websocketToken=" + wsToken; $("#proximity_alert").hide(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-devices/geo-devices.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-devices/geo-devices.hbs index bbcae34eea..63a861940d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-devices/geo-devices.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-devices/geo-devices.hbs @@ -31,28 +31,14 @@
-{{#if geoServicesEnabled}} -
-
-
-{{/if}} +
- {{#if geoServicesEnabled}} -
-
-
- Alerts Stream  - Spatial Stream -
-
- {{else}} -
-
-
- {{/if}} +
+
+
@@ -891,10 +870,6 @@ {{js "js/typeahead.bundle.min.js" }} {{js "js/geo_remote.js" }} {{js "js/app.js" }} - {{js "js/geo_exit_fence.js" }} - {{js "js/geo_within.js" }} - {{js "js/geo_stationary.js" }} - {{js "js/geo_speed.js" }} {{!js "js/jquery/jquery-ui.min.js" }} @@ -913,46 +888,12 @@ {{js "js/geo_fencing.js" }} + {{/zone}} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-devices/public/js/websocket.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-devices/public/js/websocket.js index 83f0fbd0c3..d25e5dab81 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-devices/public/js/websocket.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.geo-devices/public/js/websocket.js @@ -68,25 +68,21 @@ function initializeOnAlertWebSocket() { } function initializeGeoLocation(geoFencingEnabled) { - if (true) { - var geoCharts = $("#geo-charts"); - var wsEndPoint = geoCharts.data("ws-endpoint"); - wsToken = geoCharts.data("ws-token"); - geoPublicUri = geoCharts.data("geo-public-uri"); - geoPublicUri = geoCharts.data("geo-public-uri"); - webSocketURL = wsEndPoint + "iot.per.device.stream.geo.FusedSpatialEvent/1.0.0?" + "&websocketToken=" + wsToken; - alertWebSocketURL = wsEndPoint + "iot.per.device.stream.geo.AlertsNotifications/1.0.0?" + "&websocketToken=" + wsToken; - $("#proximity_alert").hide(); - - if (geoFencingEnabled) { - disconnect(); - initializeSpatialStreamWebSocket(); - initializeOnAlertWebSocket(); - } - initialLoad(geoFencingEnabled); - } else { - noty({text: 'Invalid Access! No device information provided to track!', type: 'error'}); + var geoCharts = $("#geo-charts"); + var wsEndPoint = geoCharts.data("ws-endpoint"); + wsToken = geoCharts.data("ws-token"); + geoPublicUri = geoCharts.data("geo-public-uri"); + geoPublicUri = geoCharts.data("geo-public-uri"); + webSocketURL = wsEndPoint + "iot.per.device.stream.geo.FusedSpatialEvent/1.0.0?" + "&websocketToken=" + wsToken; + alertWebSocketURL = wsEndPoint + "iot.per.device.stream.geo.AlertNotifications/1.0.0?" + "&websocketToken=" + wsToken; + $("#proximity_alert").hide(); + + if (geoFencingEnabled) { + disconnect(); + initializeSpatialStreamWebSocket(); + initializeOnAlertWebSocket(); } + initialLoad(geoFencingEnabled); } function disconnect(){ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java b/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java deleted file mode 100644 index 76796bbeb6..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GeoLocationBasedService.java +++ /dev/null @@ -1,550 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.service.api; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -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.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.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; - -@SwaggerDefinition( - info = @Info( - version = "0.9.0", - title = "", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = "name", value = "geo_services"), - @ExtensionProperty(name = "context", value = "/api/device-mgt/v0.9/geo-services"), - }) - } - ), - tags = { - @Tag(name = "device_management", description = "") - } -) -@Scopes( - scopes = { - @Scope( - name = "View Analytics", - description = "", - key = "perm:geo-service:analytics-view", - permissions = {"/device-mgt/devices/owning-device/view-analytics"} - ), - @Scope( - name = "Manage Alerts", - description = "", - key = "perm:geo-service:alerts-manage", - permissions = {"/device-mgt/devices/owning-device/manage-alerts"} - ) - } -) -@Path("/geo-services") -@Api(value = "Geo Service", - description = "This carries all the resources related to the geo service functionalities.") -public interface GeoLocationBasedService { - /** - * Retrieve Analytics for the device type - */ - @GET - @Path("stats/{deviceType}/{deviceId}") - @ApiOperation( - consumes = "application/json", - produces = "application/json", - httpMethod = "GET", - value = "Retrieve Analytics for the device type", - notes = "", - response = Response.class, - tags = "Geo Service Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 200, - message = "OK.", - response = Response.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), - }), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid Device Identifiers 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 getGeoDeviceStats( - @ApiParam( - name = "deviceId", - value = "The registered device Id.", - required = true) - @PathParam("deviceId") String deviceId, - @ApiParam( - name = "device-type", - value = "The device type, such as ios, android or windows.", - required = true) - @PathParam("deviceType") - @Size(max = 45) - String deviceType, - @ApiParam( - name = "from", - value = "Get stats from what time", - required = true) - @QueryParam("from") long from, - @ApiParam( - name = "to", - value = "Get stats up to what time", - required = true) - @QueryParam("to") long to); - - /** - * Get data to show device locations in a map - */ - @GET - @Path("stats/device-locations") - @ApiOperation( - consumes = "application/json", - produces = "application/json", - httpMethod = "GET", - value = "Retrieve locations of devices", - notes = "", - response = Response.class, - tags = "Geo Service Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 200, - message = "OK.", - response = Response.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests."), - }), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid parameters 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 getGeoDeviceLocations( - @ApiParam( - name = "minLat", - value = "minimum latitude", - required = true) - @QueryParam("minLat") double minLat, - @ApiParam( - name = "maxLat", - value = "maxmimum latitude", - required = true) - @QueryParam("maxLat") double maxLat, - @ApiParam( - name = "minLong", - value = "minimum longitude", - required = true) - @QueryParam("minLong") double minLong, - @ApiParam( - name = "maxLong", - value = "maximum longitudeude", - required = true) - @QueryParam("maxLong") double maxLong, - @ApiParam( - name = "zoom", - value = "zoom level", - required = true) - @QueryParam("zoom") int zoom); - - - /** - * Create Geo alerts - */ - @POST - @Path("alerts/{alertType}/{deviceType}/{deviceId}") - @ApiOperation( - consumes = "application/json", - produces = "application/json", - httpMethod = "GET", - value = "Create Geo alerts for the device", - notes = "", - response = Response.class, - tags = "Geo Service Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") - }) - } - ) - @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 Device Identifiers 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 createGeoAlerts( - @ApiParam( - name = "alert", - value = "The alert object", - required = true) - @Valid Alert alert, - @ApiParam( - name = "deviceId", - value = "The registered device Id.", - required = true) - @PathParam("deviceId") String deviceId, - @ApiParam( - name = "device-type", - value = "The device type, such as ios, android or windows.", - required = true) - @PathParam("deviceType") - @Size(max = 45) - String deviceType, - @ApiParam( - name = "alertType", - value = "The alert type, such as Within, Speed, Stationary", - required = true) - @PathParam("alertType") String alertType); - - /** - * Update Geo alerts - */ - @PUT - @Path("alerts/{alertType}/{deviceType}/{deviceId}") - @ApiOperation( - consumes = "application/json", - produces = "application/json", - httpMethod = "GET", - value = "Update Geo alerts for the device", - notes = "", - response = Response.class, - tags = "Geo Service Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") - }) - } - ) - @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 Device Identifiers 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 updateGeoAlerts( - @ApiParam( - name = "alert", - value = "The alert object", - required = true) - @Valid Alert alert, - @ApiParam( - name = "deviceId", - value = "The registered device Id.", - required = true) - @PathParam("deviceId") String deviceId, - @ApiParam( - name = "device-type", - value = "The device type, such as ios, android or windows.", - required = true) - @PathParam("deviceType") - @Size(max = 45) - String deviceType, - @ApiParam( - name = "alertType", - value = "The alert type, such as Within, Speed, Stationary", - required = true) - @PathParam("alertType") String alertType); - - /** - * Retrieve Geo alerts - */ - @GET - @Path("alerts/{alertType}/{deviceType}/{deviceId}") - @ApiOperation( - consumes = "application/json", - produces = "application/json", - httpMethod = "GET", - value = "Retrieve Geo alerts for the device", - notes = "", - response = Response.class, - tags = "Geo Service Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 200, - message = "OK.", - response = Response.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid Device Identifiers 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 getGeoAlerts( - @ApiParam( - name = "deviceId", - value = "The registered device Id.", - required = true) - @PathParam("deviceId") String deviceId, - @ApiParam( - name = "device-type", - value = "The device type, such as ios, android or windows.", - required = true) - @PathParam("deviceType") - @Size(max = 45) - String deviceType, - @ApiParam( - name = "alertType", - value = "The alert type, such as Within, Speed, Stationary", - required = true) - @PathParam("alertType") String alertType); - - /** - * Retrieve Geo alerts history - */ - @GET - @Path("alerts/history/{deviceType}/{deviceId}") - @ApiOperation( - consumes = "application/json", - produces = "application/json", - httpMethod = "GET", - value = "Retrieve Geo alerts history for the device", - notes = "", - response = Response.class, - tags = "Geo Service Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 200, - message = "OK.", - response = Response.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid Device Identifiers 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 getGeoAlertsHistory( - @ApiParam( - name = "deviceId", - value = "The registered device Id.", - required = true) - @PathParam("deviceId") String deviceId, - @ApiParam( - name = "device-type", - value = "The device type, such as ios, android or windows.", - required = true) - @PathParam("deviceType") - @Size(max = 45) - String deviceType, - @ApiParam( - name = "from", - value = "Get stats from what time", - required = true) - @QueryParam("from") long from, - @ApiParam( - name = "to", - value = "Get stats up to what time", - required = true) - @QueryParam("to") long to); - - @DELETE - @Path("alerts/{alertType}/{deviceType}/{deviceId}") - @ApiOperation( - consumes = "application/json", - produces = "application/json", - httpMethod = "DELETE", - value = "Deletes Geo alerts for the device", - notes = "", - response = Response.class, - tags = "Geo Service Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") - }) - } - ) - @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 Device Identifiers 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 removeGeoAlerts( - @ApiParam( - name = "deviceId", - value = "The registered device Id.", - required = true) - @PathParam("deviceId") String deviceId, - @ApiParam( - name = "deviceType", - value = "The device type, such as ios, android or windows.", - required = true) - @PathParam("deviceType") String deviceType, - @ApiParam( - name = "alertType", - value = "The alert type, such as Within, Speed, Stationary", - required = true) - @PathParam("alertType") String alertType, - @ApiParam( - name = "queryName", - value = "The query name.", - required = true) - @QueryParam("queryName") String queryName); -} - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java deleted file mode 100644 index 7c865b9778..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java +++ /dev/null @@ -1,565 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.service.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.analytics.api.AnalyticsDataAPI; -import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil; -import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; -import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; -import org.wso2.carbon.analytics.dataservice.commons.SortByField; -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.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; -import org.wso2.carbon.device.mgt.common.geo.service.*; -import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; -import org.wso2.carbon.device.mgt.core.geo.GeoCluster; -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; -import org.wso2.carbon.device.mgt.core.geo.geoHash.geoHashStrategy.GeoHashLengthStrategy; -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.service.api.GeoLocationBasedService; -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; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -import javax.ws.rs.*; -import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * The api for - */ -public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { - - private static Log log = LogFactory.getLog(GeoLocationBasedServiceImpl.class); - - @Path("stats/{deviceType}/{deviceId}") - @GET - @Consumes("application/json") - @Produces("application/json") - public Response getGeoDeviceStats(@PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @QueryParam("from") long from, @QueryParam("to") long to) { - try { - if (!DeviceManagerUtil.isPublishLocationResponseEnabled()) { - return Response.status(Response.Status.BAD_REQUEST.getStatusCode()) - .entity("Unable to retrive Geo Device stats. Geo Data publishing does not enabled.").build(); - } - } catch (DeviceManagementException e) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(e.getMessage()).build(); - } - String tableName = "IOT_PER_DEVICE_STREAM_GEO_FUSEDSPATIALEVENT"; - String fromDate = String.valueOf(from); - String toDate = String.valueOf(to); - String query = "id:" + deviceId + " AND type:" + deviceType; - if (from != 0 || to != 0) { - query += " AND timeStamp : [" + fromDate + " TO " + toDate + "]"; - } - try { - if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( - new DeviceIdentifier(deviceId, deviceType), - DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - List sortByFields = new ArrayList<>(); - SortByField sortByField = new SortByField("timeStamp", SortType.ASC); - sortByFields.add(sortByField); - - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername()); - - try { - String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser); - int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain); - AnalyticsDataAPI analyticsDataAPI = DeviceMgtAPIUtils.getAnalyticsDataAPI(); - List searchResults = analyticsDataAPI.search(tenantId, tableName, query, - 0, - 100, - sortByFields); - List events = getEventBeans(analyticsDataAPI, tenantId, tableName, new ArrayList(), - searchResults); - return Response.ok().entity(events).build(); - } catch (AnalyticsException | UserStoreException e) { - log.error("Failed to perform search on table: " + tableName + " : " + e.getMessage(), e); - throw DeviceMgtUtil.buildBadRequestException( - Constants.ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT); - } - } catch (DeviceAccessAuthorizationException e) { - log.error(e.getErrorMessage()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - } - - @Path("stats/device-locations") - @GET - @Consumes("application/json") - @Produces("application/json") - public Response getGeoDeviceLocations( - @QueryParam("minLat") double minLat, - @QueryParam("maxLat") double maxLat, - @QueryParam("minLong") double minLong, - @QueryParam("maxLong") double maxLong, - @QueryParam("zoom") int zoom) { - - GeoHashLengthStrategy geoHashLengthStrategy = new ZoomGeoHashLengthStrategy(); - GeoCoordinate southWest = new GeoCoordinate(minLat, minLong); - GeoCoordinate northEast = new GeoCoordinate(maxLat, maxLong); - int geohashLength = geoHashLengthStrategy.getGeohashLength(southWest, northEast, zoom); - DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); - List geoClusters; - try { - geoClusters = deviceManagementService.findGeoClusters(null, southWest, northEast, geohashLength); - } catch (DeviceManagementException e) { - String msg = "Error occurred while retrieving geo clusters "; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - return Response.ok().entity(geoClusters).build(); - - } - - @Path("alerts/{alertType}/{deviceType}/{deviceId}") - @POST - @Consumes("application/json") - @Produces("application/json") - public Response createGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @PathParam("alertType") String alertType) { - try { - if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( - new DeviceIdentifier(deviceId, deviceType), - DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setId(deviceId); - identifier.setType(deviceType); - - GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - geoService.createGeoAlert(alert, identifier, alertType); - return Response.ok().build(); - } catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) { - String error = "Error occurred while creating the geo alert for " + deviceType + " with id: " + deviceId; - log.error(error, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); - } catch (AlertAlreadyExistException e) { - String error = "A geo alert with this name already exists."; - log.error(error,e); - return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); - } - } - - - @Path("alerts/{alertType}") - @POST - @Consumes("application/json") - @Produces("application/json") - public Response createGeoAlertsForGeoClusters(Alert alert, @PathParam("alertType") String alertType) { - try { - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - - GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - geoService.createGeoAlert(alert, alertType); - return Response.ok().build(); - } catch (GeoLocationBasedServiceException e) { - String error = "Error occurred while creating " + alertType + " alert"; - log.error(error, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); - } catch (AlertAlreadyExistException e) { - String error = "A geo alert with this name already exists."; - log.error(error,e); - return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); - } - } - - - @Path("alerts/{alertType}/{deviceType}/{deviceId}") - @PUT - @Consumes("application/json") - @Produces("application/json") - public Response updateGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @PathParam("alertType") String alertType) { - try { - if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( - new DeviceIdentifier(deviceId, deviceType), - DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setId(deviceId); - identifier.setType(deviceType); - - GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - geoService.updateGeoAlert(alert, identifier, alertType); - return Response.ok().build(); - } catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) { - String error = "Error occurred while creating the geo alert for " + deviceType + " with id: " + deviceId; - log.error(error, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); - } catch (AlertAlreadyExistException e) { - String error = "A geo alert with this name already exists."; - log.error(error,e); - return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); - } - } - - @Path("alerts/{alertType}") - @PUT - @Consumes("application/json") - @Produces("application/json") - public Response updateGeoAlertsForGeoClusters(Alert alert, @PathParam("alertType") String alertType) { - try { - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - - GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - geoService.updateGeoAlert(alert, alertType); - return Response.ok().build(); - } catch (GeoLocationBasedServiceException e) { - String error = "Error occurred while updating the geo alert for geo clusters"; - log.error(error, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); - } catch (AlertAlreadyExistException e) { - String error = "A geo alert with this name already exists."; - log.error(error,e); - return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); - } - } - - @Path("alerts/{alertType}/{deviceType}/{deviceId}") - @DELETE - @Consumes("application/json") - @Produces("application/json") - public Response removeGeoAlerts(@PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @PathParam("alertType") String alertType, - @QueryParam("queryName") String queryName) { - try { - if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( - new DeviceIdentifier(deviceId, deviceType), - DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setId(deviceId); - identifier.setType(deviceType); - - GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - geoService.removeGeoAlert(alertType, identifier, queryName); - return Response.ok().build(); - } catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) { - String error = "Error occurred while removing the geo alert for " + deviceType + " with id: " + deviceId; - log.error(error, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); - } - } - - @Path("alerts/{alertType}") - @DELETE - @Consumes("application/json") - @Produces("application/json") - public Response removeGeoAlertsForGeoClusters(@PathParam("alertType") String alertType, @QueryParam("queryName") String queryName) { - try { - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - - GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - geoService.removeGeoAlert(alertType, queryName); - return Response.ok().build(); - } catch (GeoLocationBasedServiceException e) { - String error = "Error occurred while removing the geo alert for geo clusters"; - log.error(error, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); - } - } - - @Path("alerts/{alertType}/{deviceType}/{deviceId}") - @GET - @Consumes("application/json") - @Produces("application/json") - public Response getGeoAlerts(@PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @PathParam("alertType") String alertType) { - try { - if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( - new DeviceIdentifier(deviceId, deviceType), - DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setId(deviceId); - identifier.setType(deviceType); - - GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - - if (GeoServices.ALERT_TYPE_WITHIN.equals(alertType)) { - List alerts = geoService.getWithinAlerts(identifier); - return Response.ok().entity(alerts).build(); - } else if (GeoServices.ALERT_TYPE_EXIT.equals(alertType)) { - List alerts = geoService.getExitAlerts(identifier); - return Response.ok().entity(alerts).build(); - } else if (GeoServices.ALERT_TYPE_SPEED.equals(alertType)) { - String result = geoService.getSpeedAlerts(identifier); - return Response.ok().entity(result).build(); - } else if (GeoServices.ALERT_TYPE_PROXIMITY.equals(alertType)) { - String result = geoService.getProximityAlerts(identifier); - return Response.ok().entity(result).build(); - } else if (GeoServices.ALERT_TYPE_STATIONARY.equals(alertType)) { - List alerts = geoService.getStationaryAlerts(identifier); - return Response.ok().entity(alerts).build(); - } else if (GeoServices.ALERT_TYPE_TRAFFIC.equals(alertType)) { - List alerts = geoService.getTrafficAlerts(identifier); - return Response.ok().entity(alerts).build(); - } - return null; - } catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) { - String error = "Error occurred while getting the geo alerts for " + deviceType + " with id: " + deviceId; - log.error(error, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); - } - } - - @Path("alerts/{alertType}") - @GET - @Consumes("application/json") - @Produces("application/json") - public Response getGeoAlertsForGeoClusters(@PathParam("alertType") String alertType) { - try { - - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername() - ); - - GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); - - if (GeoServices.ALERT_TYPE_WITHIN.equals(alertType)) { - List alerts = geoService.getWithinAlerts(); - return Response.ok().entity(alerts).build(); - } else if (GeoServices.ALERT_TYPE_EXIT.equals(alertType)) { - List alerts = geoService.getExitAlerts(); - return Response.ok().entity(alerts).build(); - } else if (GeoServices.ALERT_TYPE_SPEED.equals(alertType)) { - String result = geoService.getSpeedAlerts(); - return Response.ok().entity(result).build(); - } else if (GeoServices.ALERT_TYPE_PROXIMITY.equals(alertType)) { - String result = geoService.getProximityAlerts(); - return Response.ok().entity(result).build(); - } else if (GeoServices.ALERT_TYPE_STATIONARY.equals(alertType)) { - List alerts = geoService.getStationaryAlerts(); - return Response.ok().entity(alerts).build(); - } else if (GeoServices.ALERT_TYPE_TRAFFIC.equals(alertType)) { - List alerts = geoService.getTrafficAlerts(); - return Response.ok().entity(alerts).build(); - } - return null; - } catch (GeoLocationBasedServiceException e) { - String error = "Error occurred while getting the geo alerts for " + alertType + " alert"; - log.error(error, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); - } - } - - @Path("alerts/history/{deviceType}/{deviceId}") - @GET - @Consumes("application/json") - @Produces("application/json") - public Response getGeoAlertsHistory(@PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @QueryParam("from") long from, @QueryParam("to") long to) { - String tableName = "IOT_PER_DEVICE_STREAM_GEO_ALERTNOTIFICATIONS"; - String fromDate = String.valueOf(from); - String toDate = String.valueOf(to); - String query = "id:" + deviceId + " AND type:" + deviceType; - if (from != 0 || to != 0) { - query += " AND timeStamp : [" + fromDate + " TO " + toDate + "]"; - } - try { - if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( - new DeviceIdentifier(deviceId, deviceType), - DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - List sortByFields = new ArrayList<>(); - SortByField sortByField = new SortByField("timeStamp", SortType.ASC); - sortByFields.add(sortByField); - - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername()); - - try { - String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser); - int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain); - AnalyticsDataAPI analyticsDataAPI = DeviceMgtAPIUtils.getAnalyticsDataAPI(); - List searchResults = analyticsDataAPI.search(tenantId, tableName, query, - 0, - 100, - sortByFields); - List events = getEventBeans(analyticsDataAPI, tenantId, tableName, new ArrayList(), - searchResults); - return Response.ok().entity(events).build(); - } catch (AnalyticsException | UserStoreException e) { - log.error("Failed to perform search on table: " + tableName + " : " + e.getMessage(), e); - throw DeviceMgtUtil.buildBadRequestException( - Constants.ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT); - } - } catch (DeviceAccessAuthorizationException e) { - log.error(e.getErrorMessage()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - } - - @Path("alerts/history") - @GET - @Consumes("application/json") - @Produces("application/json") - public Response getGeoAlertsHistoryForGeoClusters(@QueryParam("from") long from, @QueryParam("to") long to) { - String tableName = "IOT_PER_DEVICE_STREAM_GEO_ALERTNOTIFICATIONS"; - String fromDate = String.valueOf(from); - String toDate = String.valueOf(to); - String query = ""; - if (from != 0 || to != 0) { - query = "timeStamp : [" + fromDate + " TO " + toDate + "]"; - } - try { - List sortByFields = new ArrayList<>(); - SortByField sortByField = new SortByField("timeStamp", SortType.ASC); - sortByFields.add(sortByField); - - // this is the user who initiates the request - String authorizedUser = MultitenantUtils.getTenantAwareUsername( - CarbonContext.getThreadLocalCarbonContext().getUsername()); - - try { - String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser); - int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain); - AnalyticsDataAPI analyticsDataAPI = DeviceMgtAPIUtils.getAnalyticsDataAPI(); - List searchResults = analyticsDataAPI.search(tenantId, tableName, query, - 0, - 100, - sortByFields); - List events = getEventBeans(analyticsDataAPI, tenantId, tableName, new ArrayList(), - searchResults); - return Response.ok().entity(events).build(); - } catch (AnalyticsException | UserStoreException e) { - log.error("Failed to perform search on table: " + tableName + " : " + e.getMessage(), e); - throw DeviceMgtUtil.buildBadRequestException( - Constants.ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT); - } - } catch (Exception e) { - log.error(e.getMessage()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - } - - private List getEventBeans(AnalyticsDataAPI analyticsDataAPI, int tenantId, String tableName, - List columns, - List searchResults) throws AnalyticsException { - List ids = getIds(searchResults); - List requiredColumns = (columns == null || columns.isEmpty()) ? null : columns; - AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, requiredColumns, ids); - List records = AnalyticsDataAPIUtil.listRecords(analyticsDataAPI, response); - Map eventBeanMap = getEventBeanKeyedWithIds(records); - return getSortedEventBeans(eventBeanMap, searchResults); - } - - private List getSortedEventBeans(Map eventBeanMap, - List searchResults) { - List sortedRecords = new ArrayList<>(); - for (SearchResultEntry entry : searchResults) { - sortedRecords.add(eventBeanMap.get(entry.getId())); - } - return sortedRecords; - } - - private Map getEventBeanKeyedWithIds(List records) { - Map eventBeanMap = new HashMap<>(); - for (Record record : records) { - Event event = getEventBean(record); - eventBeanMap.put(event.getId(), event); - } - return eventBeanMap; - } - - private List getIds(List searchResults) { - List ids = new ArrayList<>(); - if (searchResults != null) { - for (SearchResultEntry resultEntry : searchResults) { - ids.add(resultEntry.getId()); - } - } - return ids; - } - - private static Event getEventBean(Record record) { - Event eventBean = new Event(); - eventBean.setId(record.getId()); - eventBean.setTableName(record.getTableName()); - eventBean.setTimestamp(record.getTimestamp()); - eventBean.setValues(record.getValues()); - return eventBean; - } -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/webapp/WEB-INF/cxf-servlet.xml index e4bea07957..06da04568e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -37,7 +37,6 @@ - @@ -81,7 +80,6 @@ - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java deleted file mode 100644 index d320a626b4..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.v09.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImplTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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.service.impl; - -import org.mockito.Mockito; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.geo.GeoCluster; -import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService; - -import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.List; - -public class GeoLocationBasedServiceImplTest { - private DeviceManagementProviderService deviceManagementProviderService; - private PrivilegedCarbonContext context; - private GeoLocationBasedService geoLocationBasedService; - - @BeforeClass - public void init() { - deviceManagementProviderService = Mockito.mock(DeviceManagementProviderService.class); - geoLocationBasedService = new GeoLocationBasedServiceImpl(); - context = Mockito.mock(PrivilegedCarbonContext.class); - Mockito.doReturn("admin").when(context).getUsername(); - } - - @Test(description = "This method tests the behaviour of getGeoDeviceLocations when there are no devices" + - "in the given map boundaries") - public void testGetGeoDeviceLocations1() throws DeviceManagementException { - Mockito.doReturn(new ArrayList()).when(deviceManagementProviderService) - .findGeoClusters(null, Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt()); - Response response = geoLocationBasedService.getGeoDeviceLocations(0.4, 15, 75.6, - 90.1, 6); - Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), - "getGeoDeviceLocations request failed with valid parameters"); - } - - @Test(description = "This method tests the behaviour of getGeoDeviceLocations when there are devices" + - "in the given map boundaries") - public void testGetGeoDeviceLocations2() throws DeviceManagementException { - List geoClusters = new ArrayList<>(); - geoClusters.add(new GeoCluster(new GeoCoordinate(1.5, 80.7), - new GeoCoordinate(1.1, 79.5), new GeoCoordinate(1.9, 82.1), 3, - "tb32", "aegtew234", "android", "1234")); - geoClusters.add(new GeoCluster(new GeoCoordinate(10.2, 86.1), - new GeoCoordinate(9.8, 84.7), new GeoCoordinate(11.1, 88.1), 4, - "t1gd", "swerty12s", "android", "1234")); - Mockito.doReturn(geoClusters).when(deviceManagementProviderService) - .findGeoClusters(null,Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt()); - Response response = geoLocationBasedService.getGeoDeviceLocations(0.4, 15, 75.6, - 90.1, 6); - Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), - "getGeoDeviceLocations request failed with valid parameters"); - } -}