From 7a9b5547bd56f6a5a9e3ce0dda30f324b5d77c88 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Tue, 8 Mar 2016 23:58:54 +0530 Subject: [PATCH 1/3] added feature extraction lifecycle listener --- modules/distribution/src/repository/conf/tomcat/context.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/distribution/src/repository/conf/tomcat/context.xml b/modules/distribution/src/repository/conf/tomcat/context.xml index a8e2ef6c..0c4bfa37 100644 --- a/modules/distribution/src/repository/conf/tomcat/context.xml +++ b/modules/distribution/src/repository/conf/tomcat/context.xml @@ -48,7 +48,7 @@ - + + + + + + + + Request coffee level + /device-mgt/devices/connectedcup/coffeelevel + /controller/coffeelevel + GET + connectedcup_user + + + Request temperature + /device-mgt/devices/connectedcup/temperature + /controller/temperature + GET + connectedcup_user + + + Order coffee cup + /device-mgt/devices/connectedcup/ordercoffee + /controller/ordercoffee + POST + connectedcup_user + + \ No newline at end of file diff --git a/modules/samples/connectedcup/component/manager/src/main/java/org/coffeeking/manager/service/ConnectedCupManagerService.java b/modules/samples/connectedcup/component/manager/src/main/java/org/coffeeking/manager/service/ConnectedCupManagerService.java index 635f3834..7047b4f2 100644 --- a/modules/samples/connectedcup/component/manager/src/main/java/org/coffeeking/manager/service/ConnectedCupManagerService.java +++ b/modules/samples/connectedcup/component/manager/src/main/java/org/coffeeking/manager/service/ConnectedCupManagerService.java @@ -21,9 +21,12 @@ package org.coffeeking.manager.service; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants; +import org.coffeeking.manager.service.util.APIUtil; import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.device.DeviceType; +import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil; import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil; +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.DeviceManagementException; @@ -52,76 +55,62 @@ import java.util.Date; import java.util.List; import java.util.UUID; -@API( name="connectedcup_mgt", version="1.0.0", context="/connectedcup_mgt") -public class ConnectedCupManagerService { - private static Log log = LogFactory.getLog(ConnectedCupManagerService.class); - private static final String SUPER_TENANT = "carbon.super"; +@API(name = "connectedcup_mgt", version = "1.0.0", context = "/connectedcup_mgt") +public class ConnectedCupManagerService { + private static Log log = LogFactory.getLog(ConnectedCupManagerService.class); @Context private HttpServletResponse response; + /** * @param name - * @param owner * @return */ - @Path("cup/register") + @Path("manager/device") @POST - public boolean register(@QueryParam("name") String name, @QueryParam("owner") String owner) { - - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + public boolean register(@QueryParam("name") String name) { String deviceId = shortUUID(); - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); - try { - if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { response.setStatus(Response.Status.CONFLICT.getStatusCode()); return false; } - Device device = new Device(); device.setDeviceIdentifier(deviceId); EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); enrolmentInfo.setDateOfEnrolment(new Date().getTime()); enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); device.setName(name); device.setType(ConnectedCupConstants.DEVICE_TYPE); - enrolmentInfo.setOwner(owner); + enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser()); device.setEnrolmentInfo(enrolmentInfo); - KeyGenerationUtil.createApplicationKeys(ConnectedCupConstants.DEVICE_TYPE); - TokenClient accessTokenClient = new TokenClient(ConnectedCupConstants.DEVICE_TYPE); - AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); - - //create token + AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(APIUtil.getAuthenticatedUser(), deviceId); String accessToken = accessTokenInfo.getAccess_token(); String refreshToken = accessTokenInfo.getRefresh_token(); List properties = new ArrayList<>(); - Device.Property accessTokenProperty = new Device.Property(); accessTokenProperty.setName("accessToken"); accessTokenProperty.setValue(accessToken); - Device.Property refreshTokenProperty = new Device.Property(); refreshTokenProperty.setName("refreshToken"); refreshTokenProperty.setValue(refreshToken); - properties.add(accessTokenProperty); properties.add(refreshTokenProperty); device.setProperties(properties); - boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); + boolean added = APIUtil.getDeviceManagementService().enrollDevice(device); if (added) { response.setStatus(Response.Status.OK.getStatusCode()); } else { response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); } - return added; } catch (DeviceManagementException e) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); @@ -129,108 +118,79 @@ public class ConnectedCupManagerService { } catch (AccessTokenException e) { e.printStackTrace(); } finally { - deviceManagement.endTenantFlow(); + PrivilegedCarbonContext.endTenantFlow(); } return true; - } - @Path("/device/remove/{device_id}") + @Path("manager/device/{device_id}") @DELETE public void removeDevice(@PathParam("device_id") String deviceId, @Context HttpServletResponse response) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); - try { - boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( - deviceIdentifier); + boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier); if (removed) { response.setStatus(Response.Status.OK.getStatusCode()); - } else { response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); - } } catch (DeviceManagementException e) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } finally { - deviceManagement.endTenantFlow(); + PrivilegedCarbonContext.endTenantFlow(); } - - } - @Path("/device/update/{device_id}") + @Path("manager/device/{device_id}") @POST public boolean updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name, @Context HttpServletResponse response) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); - try { - Device device = deviceManagement.getDeviceManagementService().getDevice( - deviceIdentifier); + Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); device.setDeviceIdentifier(deviceId); - // device.setDeviceTypeId(deviceTypeId); device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); - device.setName(name); device.setType(ConnectedCupConstants.DEVICE_TYPE); - - boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment( - device); - - + boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device); if (updated) { response.setStatus(Response.Status.OK.getStatusCode()); - } else { response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); - } return updated; } catch (DeviceManagementException e) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); return false; } finally { - deviceManagement.endTenantFlow(); + PrivilegedCarbonContext.endTenantFlow(); } - } - @Path("/device/{device_id}") + @Path("manager/device/{device_id}") @GET @Consumes("application/json") @Produces("application/json") public Device getDevice(@PathParam("device_id") String deviceId) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); - try { - Device device = deviceManagement.getDeviceManagementService().getDevice( - deviceIdentifier); - + Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); return device; } catch (DeviceManagementException e) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); return null; } finally { - deviceManagement.endTenantFlow(); + PrivilegedCarbonContext.endTenantFlow(); } - } private static String shortUUID() { @@ -239,4 +199,4 @@ public class ConnectedCupManagerService { return Long.toString(l, Character.MAX_RADIX); } -} \ No newline at end of file +} diff --git a/modules/samples/connectedcup/component/manager/src/main/java/org/coffeeking/manager/service/util/APIUtil.java b/modules/samples/connectedcup/component/manager/src/main/java/org/coffeeking/manager/service/util/APIUtil.java new file mode 100644 index 00000000..d6126e19 --- /dev/null +++ b/modules/samples/connectedcup/component/manager/src/main/java/org/coffeeking/manager/service/util/APIUtil.java @@ -0,0 +1,36 @@ +package org.coffeeking.manager.service.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; + +/** + * This class provides utility functions used by REST-API. + */ +public class APIUtil { + + private static Log log = LogFactory.getLog(APIUtil.class); + + public static String getAuthenticatedUser() { + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + String username = threadLocalCarbonContext.getUsername(); + String tenantDomain = threadLocalCarbonContext.getTenantDomain(); + if (username.endsWith(tenantDomain)) { + return username.substring(0, username.lastIndexOf("@")); + } + return username; + } + + public static DeviceManagementProviderService getDeviceManagementService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + DeviceManagementProviderService deviceManagementProviderService = + (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null); + if (deviceManagementProviderService == null) { + String msg = "Device Management service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return deviceManagementProviderService; + } +} diff --git a/modules/samples/connectedcup/component/manager/src/main/webapp/META-INF/permissions.xml b/modules/samples/connectedcup/component/manager/src/main/webapp/META-INF/permissions.xml new file mode 100644 index 00000000..a95581b5 --- /dev/null +++ b/modules/samples/connectedcup/component/manager/src/main/webapp/META-INF/permissions.xml @@ -0,0 +1,59 @@ + + + + + + + + + + Get device + /device-mgt/user/devices/list + /manager/device/{device_id} + GET + + + + Add device + /device-mgt/user/devices/add + /manager/device + POST + + + + Remove device + /device-mgt/user/devices/remove + /manager/device/{device_id} + DELETE + + + + Update device + /device-mgt/user/devices/update + /manager/device/{device_id} + POST + + + \ No newline at end of file diff --git a/modules/samples/connectedcup/component/manager/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/samples/connectedcup/component/manager/src/main/webapp/WEB-INF/cxf-servlet.xml index afbc4afc..e9037bb7 100644 --- a/modules/samples/connectedcup/component/manager/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/modules/samples/connectedcup/component/manager/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -25,7 +25,7 @@ http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> - + diff --git a/modules/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.type-view/public/js/download.js b/modules/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.type-view/public/js/download.js index 4d9d7e17..4c37784c 100644 --- a/modules/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.type-view/public/js/download.js +++ b/modules/samples/connectedcup/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.type-view/public/js/download.js @@ -36,31 +36,31 @@ function showPopup() { $(modalPopup).show(); setPopupMaxHeight(); $('#downloadForm').validate({ - rules: { - deviceName: { - minlength: 4, - required: true - } - }, - highlight: function (element) { - $(element).closest('.control-group').removeClass('success').addClass('error'); - }, - success: function (element) { - $(element).closest('.control-group').removeClass('error').addClass('success'); - $('label[for=deviceName]').remove(); - } - }); + rules: { + deviceName: { + minlength: 4, + required: true + } + }, + highlight: function (element) { + $(element).closest('.control-group').removeClass('success').addClass('error'); + }, + success: function (element) { + $(element).closest('.control-group').removeClass('error').addClass('success'); + $('label[for=deviceName]').remove(); + } + }); var deviceType = ""; $('.deviceType').each(function () { if (this.value != "") { deviceType = this.value; } }); - if (deviceType == 'digitaldisplay'){ + if (deviceType == 'digitaldisplay') { $('.sketchType').remove(); $('input[name="sketchType"][value="digitaldisplay"]').prop('checked', true); $("label[for='digitaldisplay']").text("Simple Agent"); - }else{ + } else { $('.sketchTypes').remove(); } } @@ -106,16 +106,16 @@ function attachEvents() { if (deviceName && deviceName.length >= 4) { payload.deviceName = deviceName; invokerUtil.post( - downloadDeviceAPI, - payload, - function (data, textStatus, jqxhr) { - doAction(data); - }, - function (data) { - doAction(data); - } + downloadDeviceAPI, + payload, + function (data, textStatus, jqxhr) { + doAction(data); + }, + function (data) { + doAction(data); + } ); - }else if(deviceName){ + } else if (deviceName) { $('.controls').append(''); $('.control-group').removeClass('success').addClass('error'); } else { @@ -137,7 +137,7 @@ function downloadAgent() { var $inputs = $('#downloadForm :input'); var values = {}; - $inputs.each(function() { + $inputs.each(function () { values[this.name] = $(this).val(); }); @@ -145,18 +145,17 @@ function downloadAgent() { payload.name = $inputs[0].value; payload.owner = $inputs[1].value; - var connectedCupRegisterURL = "/connectedcup_mgt/connectedcup/cup/register?" + - "name=" + encodeURI(payload.name) + "&owner=" + payload.owner; + var connectedCupRegisterURL = "/connectedcup_mgt/manager/device?name=" + encodeURI(payload.name); invokerUtil.post( - connectedCupRegisterURL, - payload, - function (data, textStatus, jqxhr) { - hidePopup(); - }, - function (data) { - hidePopup(); - } + connectedCupRegisterURL, + payload, + function (data, textStatus, jqxhr) { + hidePopup(); + }, + function (data) { + hidePopup(); + } ); var deviceName; diff --git a/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorControllerService.java b/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorControllerService.java index c1275ad9..0905dce8 100644 --- a/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorControllerService.java +++ b/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorControllerService.java @@ -134,7 +134,7 @@ public class CurrentSensorControllerService { @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Feature(code = "read-power", name = "Power x100", type = "monitor", + @Feature(code = "read-power", name = "Power", type = "monitor", description = "Request power reading from Arduino agent") public SensorRecord requestPower(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, @@ -164,7 +164,7 @@ public class CurrentSensorControllerService { @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Feature(code = "read-flowrate", name = "Flow Rate x100", type = "monitor", + @Feature(code = "read-flowrate", name = "Flow Rate", type = "monitor", description = "Request flow rate reading from Arduino agent") public SensorRecord requestFlowRate(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, @@ -227,11 +227,11 @@ public class CurrentSensorControllerService { Calendar.getInstance().getTimeInMillis()); SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_POWER, - String.valueOf(current * 230 / 100), + String.valueOf(current * 230), Calendar.getInstance().getTimeInMillis()); SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_FLOWRATE, - String.valueOf(flow_rate/100), + String.valueOf(flow_rate), Calendar.getInstance().getTimeInMillis()); if (!CurrentSensorServiceUtils.publishToDASCurrent(dataMsg.owner, dataMsg.deviceId, current)) { @@ -240,13 +240,13 @@ public class CurrentSensorControllerService { "] of owner [" + owner + "]"); } - if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.owner, dataMsg.deviceId, current * 230 / 100)) { + if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.owner, dataMsg.deviceId, current * 230)) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); log.warn("An error occured whilst trying to publish pin data of Power Sensor Data with ID [" + deviceId + "] of owner [" + owner + "]"); } - if (!CurrentSensorServiceUtils.publishToDASFlowRate(dataMsg.owner, dataMsg.deviceId, flow_rate/100)) { + if (!CurrentSensorServiceUtils.publishToDASFlowRate(dataMsg.owner, dataMsg.deviceId, flow_rate)) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId + "] of owner [" + owner + "]"); diff --git a/modules/samples/currentsensor/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.currentsensor.type-view/type-view.hbs b/modules/samples/currentsensor/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.currentsensor.type-view/type-view.hbs index 0b7978f2..cbbd7a95 100644 --- a/modules/samples/currentsensor/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.currentsensor.type-view/type-view.hbs +++ b/modules/samples/currentsensor/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.currentsensor.type-view/type-view.hbs @@ -1,5 +1,5 @@
-

Smart Meeter

+

Smart Meter


diff --git a/modules/samples/currentsensor/feature/feature/src/main/resources/configs/currentsensor.json b/modules/samples/currentsensor/feature/feature/src/main/resources/configs/currentsensor.json index 909b708d..a0487d6a 100644 --- a/modules/samples/currentsensor/feature/feature/src/main/resources/configs/currentsensor.json +++ b/modules/samples/currentsensor/feature/feature/src/main/resources/configs/currentsensor.json @@ -16,7 +16,7 @@ } }, { - "name": "Power x100", + "name": "Power", "table": "DEVICE_POWER_SUMMARY", "ui_unit": { "name": "cdmf.unit.analytics.line-chart", @@ -27,13 +27,13 @@ } }, { - "name": "Flow Rate x100", + "name": "Flow Rate", "table": "DEVICE_FLOWRATE_SUMMARY", "ui_unit": { "name": "cdmf.unit.analytics.line-chart", "data":[ {"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}}, - {"column": {"name":"FlowRate", "label":"flowrate", "ui-mapping":"y-axis"}} + {"column": {"name":"Flow Rate", "label":"flowrate", "ui-mapping":"y-axis"}} ] } } diff --git a/modules/samples/firealarm/component/controller/src/main/java/org.homeautomation/firealarm/controller/api/ControllerService.java b/modules/samples/firealarm/component/controller/src/main/java/org.homeautomation/firealarm/controller/api/ControllerService.java index 20fdcd86..e3c25903 100644 --- a/modules/samples/firealarm/component/controller/src/main/java/org.homeautomation/firealarm/controller/api/ControllerService.java +++ b/modules/samples/firealarm/component/controller/src/main/java/org.homeautomation/firealarm/controller/api/ControllerService.java @@ -105,11 +105,15 @@ public class ControllerService { @POST @Consumes(MediaType.APPLICATION_JSON) public Response registerDevice(final DeviceJSON agentInfo) { - if ((agentInfo.deviceId != null) && (agentInfo.owner != null)) { - return Response.status(Response.Status.OK).entity("Device has been registered successfully").build(); + try { + if ((agentInfo.deviceId != null) && (agentInfo.owner != null)) { + return Response.status(Response.Status.OK).entity("Device has been registered successfully").build(); + } + return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Message body not " + + "well-formed and still invalid").build(); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } - return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Message body not " + - "well-formed and still invalid").build(); } /** @@ -130,14 +134,17 @@ public class ControllerService { @HeaderParam("protocol") String protocol, @Context HttpServletResponse response) { SensorRecord sensorRecord = null; - if (isPermitted(owner, deviceId, response)) { - try { + try { + if (isPermitted(owner, deviceId, response)) { + sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, DeviceTypeConstants.SENSOR_TEMPERATURE); - } catch (DeviceControllerException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + response.setStatus(Response.Status.OK.getStatusCode()); } - response.setStatus(Response.Status.OK.getStatusCode()); + } catch (DeviceControllerException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } return sensorRecord; } @@ -160,14 +167,16 @@ public class ControllerService { @HeaderParam("protocol") String protocol, @Context HttpServletResponse response) { SensorRecord sensorRecord = null; - if (isPermitted(owner, deviceId, response)) { - try { + try { + if (isPermitted(owner, deviceId, response)) { sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, DeviceTypeConstants.SENSOR_HUMIDITY); - } catch (DeviceControllerException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + response.setStatus(Response.Status.OK.getStatusCode()); } - response.setStatus(Response.Status.OK.getStatusCode()); + } catch (DeviceControllerException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } return sensorRecord; } @@ -198,6 +207,8 @@ public class ControllerService { } catch (DeviceTypeException e) { log.error(e); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } } } @@ -214,6 +225,8 @@ public class ControllerService { } } catch (DeviceManagementException e) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } return false; } From 1ac7f554359069040563365d08013d367e74c1a2 Mon Sep 17 00:00:00 2001 From: NuwanSameera Date: Tue, 15 Mar 2016 10:50:03 +0530 Subject: [PATCH 3/3] Add permissions.xml to current sensor device type. --- .../api/CurrentSensorControllerService.java | 113 ++---- .../manager/api/dto/DeviceJSON.java | 23 +- .../api/util/CurrentSensorServiceUtils.java | 22 +- .../src/main/webapp/META-INF/permissions.xml | 66 ++++ .../api/CurrentSensorManagerService.java | 374 ++++++++---------- .../manager/api/util/APIUtil.java | 36 ++ .../src/main/webapp/META-INF/permissions.xml | 66 ++++ .../constants/CurrentSensorConstants.java | 1 + .../plugin/impl/CurrentSensorManager.java | 40 +- .../impl/CurrentSensorManagerService.java | 117 +++--- .../plugin/impl/dao/CurrentSensorDAO.java | 35 +- .../dao/impl/CurrentSensorDeviceDAOImpl.java | 48 +-- .../plugin/impl/util/CurrentSensorUtils.java | 4 - .../plugin/internal/ServiceComponent.java | 29 +- 14 files changed, 514 insertions(+), 460 deletions(-) create mode 100644 modules/samples/currentsensor/component/controller/src/main/webapp/META-INF/permissions.xml create mode 100644 modules/samples/currentsensor/component/manager/src/main/java/org/homeautomation/currentsensor/manager/api/util/APIUtil.java create mode 100644 modules/samples/currentsensor/component/manager/src/main/webapp/META-INF/permissions.xml diff --git a/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorControllerService.java b/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorControllerService.java index 0905dce8..ca9b4fb0 100644 --- a/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorControllerService.java +++ b/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorControllerService.java @@ -49,7 +49,6 @@ public class CurrentSensorControllerService { private static Log log = LogFactory.getLog(CurrentSensorControllerService.class); private ConcurrentHashMap deviceToIpMap = new ConcurrentHashMap<>(); - private static final String SUPER_TENANT = "carbon.super"; private boolean waitForServerStartup() { while (!DeviceManagement.isServerReady()) { @@ -62,7 +61,6 @@ public class CurrentSensorControllerService { return false; } - @Path("controller/register/{owner}/{deviceId}/{ip}/{port}") @POST public String registerDeviceIP(@PathParam("owner") String owner, @@ -71,28 +69,21 @@ public class CurrentSensorControllerService { @PathParam("port") String devicePort, @Context HttpServletResponse response, @Context HttpServletRequest request) { - System.out.println("Register Call.."); //TODO:: Need to get IP from the request itself String result; - if (log.isDebugEnabled()) { log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: " + owner); } - String deviceHttpEndpoint = deviceIP + ":" + devicePort; deviceToIpMap.put(deviceId, deviceHttpEndpoint); - result = "Device-IP Registered"; response.setStatus(Response.Status.OK.getStatusCode()); - if (log.isDebugEnabled()) { log.debug(result); } - return result; } - /** * @param owner * @param deviceId @@ -111,14 +102,12 @@ public class CurrentSensorControllerService { @HeaderParam("protocol") String protocol, @Context HttpServletResponse response) { SensorRecord sensorRecord = null; - try { sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, - CurrentSensorConstants.SENSOR_CURRENT); + CurrentSensorConstants.SENSOR_CURRENT); } catch (DeviceControllerException e) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } - response.setStatus(Response.Status.OK.getStatusCode()); return sensorRecord; } @@ -141,14 +130,12 @@ public class CurrentSensorControllerService { @HeaderParam("protocol") String protocol, @Context HttpServletResponse response) { SensorRecord sensorRecord = null; - try { sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, - CurrentSensorConstants.SENSOR_POWER); + CurrentSensorConstants.SENSOR_POWER); } catch (DeviceControllerException e) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } - response.setStatus(Response.Status.OK.getStatusCode()); return sensorRecord; } @@ -171,14 +158,12 @@ public class CurrentSensorControllerService { @HeaderParam("protocol") String protocol, @Context HttpServletResponse response) { SensorRecord sensorRecord = null; - try { sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, - CurrentSensorConstants.SENSOR_FLOWRATE); + CurrentSensorConstants.SENSOR_FLOWRATE); } catch (DeviceControllerException e) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } - response.setStatus(Response.Status.OK.getStatusCode()); return sensorRecord; } @@ -191,69 +176,47 @@ public class CurrentSensorControllerService { @POST @Consumes(MediaType.APPLICATION_JSON) public void pushData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { - String owner = dataMsg.owner; String deviceId = dataMsg.deviceId; String deviceIp = dataMsg.reply; float current = dataMsg.current; float flow_rate = dataMsg.flow_rate; - try { - DeviceValidator deviceValidator = new DeviceValidator(); - if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, - CurrentSensorConstants.DEVICE_TYPE))) { - response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); - log.warn("Temperature data Received from unregistered raspberrypi device [" + deviceId + - "] for owner [" + owner + "]"); - return; - } - - String registeredIp = deviceToIpMap.get(deviceId); - - if (registeredIp == null) { - log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp + - " for device ID - " + deviceId); - response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); - return; - } else if (!registeredIp.equals(deviceIp)) { - log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId + - " is already registered under some other IP. Re-registration required"); - response.setStatus(Response.Status.CONFLICT.getStatusCode()); - return; - } - - SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_CURRENT, - String.valueOf(current), - Calendar.getInstance().getTimeInMillis()); - - SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_POWER, - String.valueOf(current * 230), - Calendar.getInstance().getTimeInMillis()); - - SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_FLOWRATE, - String.valueOf(flow_rate), - Calendar.getInstance().getTimeInMillis()); - - if (!CurrentSensorServiceUtils.publishToDASCurrent(dataMsg.owner, dataMsg.deviceId, current)) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId + - "] of owner [" + owner + "]"); - } - - if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.owner, dataMsg.deviceId, current * 230)) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - log.warn("An error occured whilst trying to publish pin data of Power Sensor Data with ID [" + deviceId + - "] of owner [" + owner + "]"); - } - - if (!CurrentSensorServiceUtils.publishToDASFlowRate(dataMsg.owner, dataMsg.deviceId, flow_rate)) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId + - "] of owner [" + owner + "]"); - } - } catch (DeviceManagementException e) { - String errorMsg = "Validation attempt for deviceId [" + deviceId + "] of owner [" + owner + "] failed.\n"; - log.error(errorMsg + Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase() + "\n" + e.getErrorMessage()); + String registeredIp = deviceToIpMap.get(deviceId); + if (registeredIp == null) { + log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp + + " for device ID - " + deviceId); + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return; + } else if (!registeredIp.equals(deviceIp)) { + log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId + + " is already registered under some other IP. Re-registration required"); + response.setStatus(Response.Status.CONFLICT.getStatusCode()); + return; + } + SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_CURRENT, + String.valueOf(current), + Calendar.getInstance().getTimeInMillis()); + SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_POWER, + String.valueOf(current * 230), + Calendar.getInstance().getTimeInMillis()); + SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_FLOWRATE, + String.valueOf(flow_rate), + Calendar.getInstance().getTimeInMillis()); + if (!CurrentSensorServiceUtils.publishToDASCurrent(dataMsg.deviceId, current)) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + + deviceId + "] of owner [" + owner + "]"); + } + if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.deviceId, current * 230)) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + log.warn("An error occured whilst trying to publish pin data of Power Sensor Data with ID [" + + deviceId + "] of owner [" + owner + "]"); + } + if (!CurrentSensorServiceUtils.publishToDASFlowRate(dataMsg.deviceId, flow_rate)) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + + deviceId + "] of owner [" + owner + "]"); } } diff --git a/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/dto/DeviceJSON.java b/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/dto/DeviceJSON.java index abbe83d5..461a7c08 100644 --- a/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/dto/DeviceJSON.java +++ b/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/dto/DeviceJSON.java @@ -27,11 +27,20 @@ import javax.xml.bind.annotation.XmlRootElement; @JsonIgnoreProperties(ignoreUnknown = true) public class DeviceJSON { - @XmlElement(required = true) public String owner; - @XmlElement(required = true) public String deviceId; - @XmlElement(required = true) public String reply; - @XmlElement public Long time; - @XmlElement public String key; - @XmlElement public float current; - @XmlElement public float flow_rate; + + @XmlElement(required = true) + public String owner; + @XmlElement(required = true) + public String deviceId; + @XmlElement(required = true) + public String reply; + @XmlElement + public Long time; + @XmlElement + public String key; + @XmlElement + public float current; + @XmlElement + public float flow_rate; + } diff --git a/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/util/CurrentSensorServiceUtils.java b/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/util/CurrentSensorServiceUtils.java index 6c098a1d..780b72eb 100644 --- a/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/util/CurrentSensorServiceUtils.java +++ b/modules/samples/currentsensor/component/controller/src/main/java/org/homeautomation/currentsensor/manager/api/util/CurrentSensorServiceUtils.java @@ -26,23 +26,19 @@ import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfiguration import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService; public class CurrentSensorServiceUtils { - private static final Log log = LogFactory.getLog(CurrentSensorServiceUtils.class); - //TODO; replace this tenant domain - private static final String SUPER_TENANT = "carbon.super"; + private static final Log log = LogFactory.getLog(CurrentSensorServiceUtils.class); private static final String CURRENT_STREAM_DEFINITION = "org.wso2.iot.devices.current"; private static final String POWER_STREAM_DEFINITION = "org.wso2.iot.devices.power"; private static final String FLOWRATE_STREAM_DEFINITION = "org.wso2.iot.devices.flowrate"; - public static boolean publishToDASCurrent(String owner, String deviceId, float current) { - PrivilegedCarbonContext.startTenantFlow(); + public static boolean publishToDASCurrent(String deviceId, float current) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - ctx.setTenantDomain(SUPER_TENANT, true); + String owner = ctx.getUsername(); DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( DeviceAnalyticsService.class, null); Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object payloadCurrent[] = {current}; - try { deviceAnalyticsService.publishEvent(CURRENT_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadCurrent); } catch (DataPublisherConfigurationException e) { @@ -53,15 +49,13 @@ public class CurrentSensorServiceUtils { return true; } - public static boolean publishToDASPower(String owner, String deviceId, float power) { - PrivilegedCarbonContext.startTenantFlow(); + public static boolean publishToDASPower(String deviceId, float power) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - ctx.setTenantDomain(SUPER_TENANT, true); + String owner = ctx.getUsername(); DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( DeviceAnalyticsService.class, null); Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object payloadPower[] = {power}; - try { deviceAnalyticsService.publishEvent(POWER_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadPower); } catch (DataPublisherConfigurationException e) { @@ -72,15 +66,13 @@ public class CurrentSensorServiceUtils { return true; } - public static boolean publishToDASFlowRate(String owner, String deviceId, float flowRate) { - PrivilegedCarbonContext.startTenantFlow(); + public static boolean publishToDASFlowRate(String deviceId, float flowRate) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - ctx.setTenantDomain(SUPER_TENANT, true); + String owner = ctx.getUsername(); DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( DeviceAnalyticsService.class, null); Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object payload[] = {flowRate}; - try { deviceAnalyticsService.publishEvent(FLOWRATE_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payload); } catch (DataPublisherConfigurationException e) { diff --git a/modules/samples/currentsensor/component/controller/src/main/webapp/META-INF/permissions.xml b/modules/samples/currentsensor/component/controller/src/main/webapp/META-INF/permissions.xml new file mode 100644 index 00000000..594ec5a8 --- /dev/null +++ b/modules/samples/currentsensor/component/controller/src/main/webapp/META-INF/permissions.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + /device-mgt/devices/currentsensor/register + /controller/register/{owner}/{deviceId}/{ip}/{port} + POST + currentsensor_device + + + + /device-mgt/devices/currentsensor/read-current + /controller/read-current + GET + currentsensor_user + + + + /device-mgt/devices/currentsensor/read-power + /controller/read-power + GET + currentsensor_user + + + + /device-mgt/devices/currentsensor/read-flowrate + /controller/read-flowrate + GET + currentsensor_user + + + + /device-mgt/devices/currentsensor/push-data + /controller/push-data + POST + currentsensor_device + + diff --git a/modules/samples/currentsensor/component/manager/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorManagerService.java b/modules/samples/currentsensor/component/manager/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorManagerService.java index e919b0a1..aa8f6a8d 100644 --- a/modules/samples/currentsensor/component/manager/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorManagerService.java +++ b/modules/samples/currentsensor/component/manager/src/main/java/org/homeautomation/currentsensor/manager/api/CurrentSensorManagerService.java @@ -21,9 +21,12 @@ package org.homeautomation.currentsensor.manager.api; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.homeautomation.currentsensor.manager.api.util.APIUtil; import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants; +import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.device.DeviceType; import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil; +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.DeviceManagementException; @@ -50,205 +53,176 @@ import java.util.UUID; @DeviceType(value = "currentsensor") public class CurrentSensorManagerService { - private static Log log = LogFactory.getLog(CurrentSensorManagerService.class); - //TODO; replace this tenant domain - private final String SUPER_TENANT = "carbon.super"; - @Context //injected response proxy supporting multiple thread - private HttpServletResponse response; - - @Path("manager/device/register") - @PUT - public boolean register(@QueryParam("deviceId") String deviceId, - @QueryParam("name") String name, @QueryParam("owner") String owner) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); - - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); - try { - if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { - response.setStatus(Response.Status.CONFLICT.getStatusCode()); - return false; - } - - Device device = new Device(); - device.setDeviceIdentifier(deviceId); - EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); - enrolmentInfo.setDateOfEnrolment(new Date().getTime()); - enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); - enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); - device.setName(name); - device.setType(CurrentSensorConstants.DEVICE_TYPE); - enrolmentInfo.setOwner(owner); - device.setEnrolmentInfo(enrolmentInfo); - boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); - if (added) { - response.setStatus(Response.Status.OK.getStatusCode()); - } else { - response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); - } - - return added; - } catch (DeviceManagementException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return false; - } finally { - deviceManagement.endTenantFlow(); - } - } - - @Path("manager/device/remove/{device_id}") - @DELETE - public void removeDevice(@PathParam("device_id") String deviceId, - @Context HttpServletResponse response) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); - try { - boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( - deviceIdentifier); - if (removed) { - response.setStatus(Response.Status.OK.getStatusCode()); - } else { - response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); - } - } catch (DeviceManagementException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - } finally { - deviceManagement.endTenantFlow(); - } - } - - @Path("manager/device/update/{device_id}") - @POST - public boolean updateDevice(@PathParam("device_id") String deviceId, - @QueryParam("name") String name, - @Context HttpServletResponse response) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); - - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); - try { - Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); - device.setDeviceIdentifier(deviceId); - - // device.setDeviceTypeId(deviceTypeId); - device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); - - device.setName(name); - device.setType(CurrentSensorConstants.DEVICE_TYPE); - - boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device); - - if (updated) { - response.setStatus(Response.Status.OK.getStatusCode()); - - } else { - response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); - } - return updated; - } catch (DeviceManagementException e) { - log.error(e.getErrorMessage()); - return false; - } finally { - deviceManagement.endTenantFlow(); - } - } - - @Path("manager/device/{device_id}") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Device getDevice(@PathParam("device_id") String deviceId) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); - - try { - return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); - } catch (DeviceManagementException ex) { - log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex); - return null; - } finally { - deviceManagement.endTenantFlow(); - } - } - - @Path("manager/device/{sketch_type}/download") - @GET - @Produces(MediaType.APPLICATION_JSON) - public Response downloadSketch(@QueryParam("owner") String owner, - @QueryParam("deviceName") String deviceName, - @PathParam("sketch_type") String - sketchType) { - - try { - ZipArchive zipFile = createDownloadFile(owner, deviceName, sketchType); - Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); - response.type("application/zip"); - response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); - return response.build(); - - } catch (IllegalArgumentException ex) { - return Response.status(400).entity(ex.getMessage()).build();//bad request - } catch (DeviceManagementException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } catch (AccessTokenException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } catch (DeviceControllerException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } catch (IOException ex) { - return Response.status(500).entity(ex.getMessage()).build(); - } - } - - private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) - throws DeviceManagementException, AccessTokenException, DeviceControllerException { - if (owner == null) { - throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!"); - } - - //create new device id - String deviceId = shortUUID(); - - KeyGenerationUtil.createApplicationKeys("currentsensor"); - - TokenClient accessTokenClient = new TokenClient(CurrentSensorConstants.DEVICE_TYPE); - AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); - - //create token - String accessToken = accessTokenInfo.getAccess_token(); - String refreshToken = accessTokenInfo.getRefresh_token(); - //adding registering data - - boolean status; - - //Register the device with CDMF - status = register(deviceId, deviceName, owner); - - if (!status) { - String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner; - throw new DeviceManagementException(msg); - } - - ZipUtil ziputil = new ZipUtil(); - ZipArchive zipFile = ziputil.createZipFile(owner, SUPER_TENANT, sketchType, deviceId, deviceName, accessToken, - refreshToken); - zipFile.setDeviceId(deviceId); - return zipFile; - } - - private static String shortUUID() { - UUID uuid = UUID.randomUUID(); - long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong(); - return Long.toString(l, Character.MAX_RADIX); - } + private static Log log = LogFactory.getLog(CurrentSensorManagerService.class); + @Context //injected response proxy supporting multiple thread + private HttpServletResponse response; + + @Path("manager/device") + @PUT + public boolean register(@QueryParam("name") String name) { + String deviceId = shortUUID(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); + try { + if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + response.setStatus(Response.Status.CONFLICT.getStatusCode()); + return false; + } + Device device = new Device(); + device.setDeviceIdentifier(deviceId); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setDateOfEnrolment(new Date().getTime()); + enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setName(name); + device.setType(CurrentSensorConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser()); + device.setEnrolmentInfo(enrolmentInfo); + boolean added = APIUtil.getDeviceManagementService().enrollDevice(device); + if (added) { + response.setStatus(Response.Status.OK.getStatusCode()); + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + } + return added; + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return false; + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } + + @Path("manager/device/remove/{device_id}") + @DELETE + public void removeDevice(@PathParam("device_id") String deviceId, + @Context HttpServletResponse response) { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); + try { + boolean removed = APIUtil.getDeviceManagementService().disenrollDevice( + deviceIdentifier); + if (removed) { + response.setStatus(Response.Status.OK.getStatusCode()); + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + } + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } + + @Path("manager/device/update/{device_id}") + @POST + public boolean updateDevice(@PathParam("device_id") String deviceId, + @QueryParam("name") String name, + @Context HttpServletResponse response) { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); + try { + Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); + device.setDeviceIdentifier(deviceId); + device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); + device.setName(name); + device.setType(CurrentSensorConstants.DEVICE_TYPE); + boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device); + + if (updated) { + response.setStatus(Response.Status.OK.getStatusCode()); + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + } + return updated; + + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } + + @Path("manager/device/{device_id}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Device getDevice(@PathParam("device_id") String deviceId) { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); + try { + return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); + } catch (DeviceManagementException ex) { + log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex); + return null; + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } + + @Path("manager/device/{sketch_type}/download") + @GET + @Produces(MediaType.APPLICATION_JSON) + public Response downloadSketch(@QueryParam("owner") String owner, + @QueryParam("deviceName") String deviceName, + @PathParam("sketch_type") String sketchType) { + try { + ZipArchive zipFile = createDownloadFile(owner, deviceName, sketchType); + Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); + response.type("application/zip"); + response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); + return response.build(); + } catch (IllegalArgumentException ex) { + return Response.status(400).entity(ex.getMessage()).build();//bad request + } catch (DeviceManagementException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (AccessTokenException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (DeviceControllerException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (IOException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } + } + + private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) + throws DeviceManagementException, AccessTokenException, DeviceControllerException { + if (owner == null) { + throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!"); + } + String deviceId = shortUUID(); + KeyGenerationUtil.createApplicationKeys("currentsensor"); + TokenClient accessTokenClient = new TokenClient(CurrentSensorConstants.DEVICE_TYPE); + AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); + //create token + String accessToken = accessTokenInfo.getAccess_token(); + String refreshToken = accessTokenInfo.getRefresh_token(); + //adding registering data + boolean status; + //Register the device with CDMF + status = register(deviceId, deviceName, owner); + + if (!status) { + String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner; + throw new DeviceManagementException(msg); + } + + ZipUtil ziputil = new ZipUtil(); + ZipArchive zipFile = ziputil.createZipFile(owner, SUPER_TENANT, sketchType, deviceId, deviceName, accessToken, + refreshToken); + zipFile.setDeviceId(deviceId); + return zipFile; + } + + private static String shortUUID() { + UUID uuid = UUID.randomUUID(); + long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong(); + return Long.toString(l, Character.MAX_RADIX); + } } diff --git a/modules/samples/currentsensor/component/manager/src/main/java/org/homeautomation/currentsensor/manager/api/util/APIUtil.java b/modules/samples/currentsensor/component/manager/src/main/java/org/homeautomation/currentsensor/manager/api/util/APIUtil.java new file mode 100644 index 00000000..65d421f1 --- /dev/null +++ b/modules/samples/currentsensor/component/manager/src/main/java/org/homeautomation/currentsensor/manager/api/util/APIUtil.java @@ -0,0 +1,36 @@ +package org.homeautomation.currentsensor.manager.api.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; + +/** + * This class provides utility functions used by REST-API. + */ +public class APIUtil { + + private static Log log = LogFactory.getLog(APIUtil.class); + + public static String getAuthenticatedUser() { + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + String username = threadLocalCarbonContext.getUsername(); + String tenantDomain = threadLocalCarbonContext.getTenantDomain(); + if (username.endsWith(tenantDomain)) { + return username.substring(0, username.lastIndexOf("@")); + } + return username; + } + + public static DeviceManagementProviderService getDeviceManagementService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + DeviceManagementProviderService deviceManagementProviderService = + (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null); + if (deviceManagementProviderService == null) { + String msg = "Device Management service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return deviceManagementProviderService; + } +} diff --git a/modules/samples/currentsensor/component/manager/src/main/webapp/META-INF/permissions.xml b/modules/samples/currentsensor/component/manager/src/main/webapp/META-INF/permissions.xml new file mode 100644 index 00000000..91ed8325 --- /dev/null +++ b/modules/samples/currentsensor/component/manager/src/main/webapp/META-INF/permissions.xml @@ -0,0 +1,66 @@ + + + + + + + + + + Get device + /device-mgt/user/devices/list + /manager/device/{device_id} + GET + + + + Add device + /device-mgt/user/devices/add + /manager/device + POST + + + + Remove device + /device-mgt/user/devices/remove + /manager/device/{device_id} + DELETE + + + + Download device + /device-mgt/user/devices/add + /manager/device/{sketch_type}/download + GET + + + + Update device + /device-mgt/user/devices/update + /manager/device/{device_id} + POST + + + \ No newline at end of file diff --git a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/constants/CurrentSensorConstants.java b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/constants/CurrentSensorConstants.java index 73571075..abb51f66 100644 --- a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/constants/CurrentSensorConstants.java +++ b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/constants/CurrentSensorConstants.java @@ -27,4 +27,5 @@ public class CurrentSensorConstants { public final static String SENSOR_POWER = "power"; public final static String SENSOR_FLOWRATE = "flowrate"; public static final String DATA_SOURCE_NAME = "jdbc/currentsensorDM_DB"; + } diff --git a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/CurrentSensorManager.java b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/CurrentSensorManager.java index 6d702f67..ba88b21e 100644 --- a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/CurrentSensorManager.java +++ b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/CurrentSensorManager.java @@ -18,7 +18,6 @@ package org.homeautomation.currentsensor.plugin.impl; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.homeautomation.currentsensor.plugin.impl.dao.CurrentSensorDAO; @@ -34,7 +33,6 @@ import org.wso2.carbon.device.mgt.iot.util.iotdevice.util.IotDeviceManagementUti import java.util.ArrayList; import java.util.List; - /** * This represents the Current Sensor implementation of DeviceManagerService. */ @@ -43,8 +41,6 @@ public class CurrentSensorManager implements DeviceManager { private static final IotDeviceManagementDAOFactoryInterface iotDeviceManagementDAOFactory = new CurrentSensorDAO(); private static final Log log = LogFactory.getLog(CurrentSensorManager.class); - - @Override public FeatureManager getFeatureManager() { return null; @@ -72,8 +68,7 @@ public class CurrentSensorManager implements DeviceManager { log.debug("Enrolling a new Current Sensor device : " + device.getDeviceIdentifier()); } CurrentSensorDAO.beginTransaction(); - status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice( - iotDevice); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice(iotDevice); CurrentSensorDAO.commitTransaction(); } catch (IotDeviceManagementDAOException e) { try { @@ -98,8 +93,7 @@ public class CurrentSensorManager implements DeviceManager { log.debug("Modifying the Current Sensor device enrollment data"); } CurrentSensorDAO.beginTransaction(); - status = iotDeviceManagementDAOFactory.getIotDeviceDAO() - .updateIotDevice(iotDevice); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO().updateIotDevice(iotDevice); CurrentSensorDAO.commitTransaction(); } catch (IotDeviceManagementDAOException e) { try { @@ -109,7 +103,7 @@ public class CurrentSensorManager implements DeviceManager { log.warn(msg, iotDAOEx); } String msg = "Error while updating the enrollment of the Current Sensor device : " + - device.getDeviceIdentifier(); + device.getDeviceIdentifier(); log.error(msg, e); throw new DeviceManagementException(msg, e); } @@ -124,8 +118,7 @@ public class CurrentSensorManager implements DeviceManager { log.debug("Dis-enrolling Current Sensor device : " + deviceId); } CurrentSensorDAO.beginTransaction(); - status = iotDeviceManagementDAOFactory.getIotDeviceDAO() - .deleteIotDevice(deviceId.getId()); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO().deleteIotDevice(deviceId.getId()); CurrentSensorDAO.commitTransaction(); } catch (IotDeviceManagementDAOException e) { try { @@ -148,15 +141,12 @@ public class CurrentSensorManager implements DeviceManager { if (log.isDebugEnabled()) { log.debug("Checking the enrollment of Current Sensor device : " + deviceId.getId()); } - IotDevice iotDevice = - iotDeviceManagementDAOFactory.getIotDeviceDAO().getIotDevice( - deviceId.getId()); + IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO().getIotDevice(deviceId.getId()); if (iotDevice != null) { isEnrolled = true; } } catch (IotDeviceManagementDAOException e) { - String msg = "Error while checking the enrollment status of Current Sensor device : " + - deviceId.getId(); + String msg = "Error while checking the enrollment status of Current Sensor device : " + deviceId.getId(); log.error(msg, e); throw new DeviceManagementException(msg, e); } @@ -193,8 +183,7 @@ public class CurrentSensorManager implements DeviceManager { } @Override - public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) - throws DeviceManagementException { + public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) throws DeviceManagementException { return true; } @@ -203,8 +192,8 @@ public class CurrentSensorManager implements DeviceManager { } @Override - public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, - EnrolmentInfo.Status status) throws DeviceManagementException { + public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrolmentInfo.Status status) + throws DeviceManagementException { return false; } @@ -233,8 +222,7 @@ public class CurrentSensorManager implements DeviceManager { "updating the details of Current Sensor device : " + deviceIdentifier); } CurrentSensorDAO.beginTransaction(); - status = iotDeviceManagementDAOFactory.getIotDeviceDAO() - .updateIotDevice(iotDevice); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO().updateIotDevice(iotDevice); CurrentSensorDAO.commitTransaction(); } catch (IotDeviceManagementDAOException e) { try { @@ -243,8 +231,7 @@ public class CurrentSensorManager implements DeviceManager { String msg = "Error occurred while roll back the update device info transaction :" + device.toString(); log.warn(msg, iotDAOEx); } - String msg = - "Error while updating the Current Sensor device : " + deviceIdentifier; + String msg = "Error while updating the Current Sensor device : " + deviceIdentifier; log.error(msg, e); throw new DeviceManagementException(msg, e); } @@ -258,8 +245,7 @@ public class CurrentSensorManager implements DeviceManager { if (log.isDebugEnabled()) { log.debug("Fetching the details of all Current Sensor devices"); } - List iotDevices = - iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices(); + List iotDevices = iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices(); if (iotDevices != null) { devices = new ArrayList(); for (IotDevice iotDevice : iotDevices) { @@ -274,4 +260,4 @@ public class CurrentSensorManager implements DeviceManager { return devices; } -} \ No newline at end of file +} diff --git a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/CurrentSensorManagerService.java b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/CurrentSensorManagerService.java index b2b7db3f..55c1bf18 100644 --- a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/CurrentSensorManagerService.java +++ b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/CurrentSensorManagerService.java @@ -30,79 +30,84 @@ import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import java.util.List; -public class CurrentSensorManagerService implements DeviceManagementService{ - private DeviceManager deviceManager; - @Override - public String getType() { - return CurrentSensorConstants.DEVICE_TYPE; - } +public class CurrentSensorManagerService implements DeviceManagementService { - @Override - public String getProviderTenantDomain() { - return "carbon.super"; - } + private DeviceManager deviceManager; - @Override - public boolean isSharedWithAllTenants() { - return true; - } + @Override + public String getType() { + return CurrentSensorConstants.DEVICE_TYPE; + } - @Override - public String[] getSharedTenantsDomain() { - return new String[0]; - } + @Override + public String getProviderTenantDomain() { + return "carbon.super"; + } - @Override - public void init() throws DeviceManagementException { - deviceManager= new CurrentSensorManager(); - } + @Override + public boolean isSharedWithAllTenants() { + return true; + } - @Override - public DeviceManager getDeviceManager() { - return deviceManager; - } + @Override + public String[] getSharedTenantsDomain() { + return new String[0]; + } - @Override - public ApplicationManager getApplicationManager() { - return null; - } + @Override + public void init() throws DeviceManagementException { + deviceManager = new CurrentSensorManager(); + } - @Override - public void notifyOperationToDevices(Operation operation, List list) throws DeviceManagementException { + @Override + public DeviceManager getDeviceManager() { + return deviceManager; + } - } + @Override + public ApplicationManager getApplicationManager() { + return null; + } - @Override - public Application[] getApplications(String domain, int pageNumber, int size) - throws ApplicationManagementException { - return new Application[0]; - } + @Override + public void notifyOperationToDevices(Operation operation, List list) + throws DeviceManagementException { + } - @Override - public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, - String status) throws ApplicationManagementException { + @Override + public Application[] getApplications(String domain, int pageNumber, int size) + throws ApplicationManagementException { + return new Application[0]; + } - } + @Override + public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, + String status) throws ApplicationManagementException { - @Override - public String getApplicationStatus(DeviceIdentifier deviceId, Application application) - throws ApplicationManagementException { - return null; - } + } - @Override - public void installApplicationForDevices(Operation operation, List list) throws ApplicationManagementException { + @Override + public String getApplicationStatus(DeviceIdentifier deviceId, Application application) + throws ApplicationManagementException { + return null; + } - } + @Override + public void installApplicationForDevices(Operation operation, List list) + throws ApplicationManagementException { - @Override - public void installApplicationForUsers(Operation operation, List list) throws ApplicationManagementException { + } - } + @Override + public void installApplicationForUsers(Operation operation, List list) + throws ApplicationManagementException { - @Override - public void installApplicationForUserRoles(Operation operation, List list) throws ApplicationManagementException { + } - } + @Override + public void installApplicationForUserRoles(Operation operation, List list) + throws ApplicationManagementException { + + } } diff --git a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/dao/CurrentSensorDAO.java b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/dao/CurrentSensorDAO.java index 1aac11b8..b6a28392 100644 --- a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/dao/CurrentSensorDAO.java +++ b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/dao/CurrentSensorDAO.java @@ -34,8 +34,7 @@ import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; -public class CurrentSensorDAO extends IotDeviceManagementDAOFactory - implements IotDeviceManagementDAOFactoryInterface { +public class CurrentSensorDAO extends IotDeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface { private static final Log log = LogFactory.getLog(CurrentSensorDAO.class); static DataSource dataSource; // package local variable @@ -50,13 +49,12 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory return new CurrentSensorDeviceDAOImpl(); } - public static void initCurrentSensorDAO(){ + public static void initCurrentSensorDAO() { try { Context ctx = new InitialContext(); dataSource = (DataSource) ctx.lookup(CurrentSensorConstants.DATA_SOURCE_NAME); } catch (NamingException e) { - log.error("Error while looking up the data source: " + - CurrentSensorConstants.DATA_SOURCE_NAME); + log.error("Error while looking up the data source: " + CurrentSensorConstants.DATA_SOURCE_NAME); } } @@ -75,8 +73,7 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory try { currentConnection.set(dataSource.getConnection()); } catch (SQLException e) { - throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", - e); + throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e); } } return currentConnection.get(); @@ -90,7 +87,7 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory } else { if (log.isDebugEnabled()) { log.debug("Datasource connection associated with the current thread is null, hence commit " + - "has not been attempted"); + "has not been attempted"); } } } catch (SQLException e) { @@ -101,15 +98,14 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory } public static void closeConnection() throws IotDeviceManagementDAOException { - - Connection con = currentConnection.get(); - if(con != null){ - try { - con.close(); - } catch (SQLException e) { - log.error("Error occurred while close the connection"); - } - } + Connection con = currentConnection.get(); + if (con != null) { + try { + con.close(); + } catch (SQLException e) { + log.error("Error occurred while close the connection"); + } + } currentConnection.remove(); } @@ -121,7 +117,7 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory } else { if (log.isDebugEnabled()) { log.debug("Datasource connection associated with the current thread is null, hence rollback " + - "has not been attempted"); + "has not been attempted"); } } } catch (SQLException e) { @@ -130,4 +126,5 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory closeConnection(); } } -} \ No newline at end of file + +} diff --git a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/dao/impl/CurrentSensorDeviceDAOImpl.java b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/dao/impl/CurrentSensorDeviceDAOImpl.java index 1b30aa63..2ce1eafc 100644 --- a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/dao/impl/CurrentSensorDeviceDAOImpl.java +++ b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/dao/impl/CurrentSensorDeviceDAOImpl.java @@ -41,12 +41,10 @@ import java.util.Map; */ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO { - private static final Log log = LogFactory.getLog(CurrentSensorDeviceDAOImpl.class); @Override - public IotDevice getIotDevice(String iotDeviceId) - throws IotDeviceManagementDAOException { + public IotDevice getIotDevice(String iotDeviceId) throws IotDeviceManagementDAOException { Connection conn = null; PreparedStatement stmt = null; IotDevice iotDevice = null; @@ -54,24 +52,20 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO { try { conn = CurrentSensorDAO.getConnection(); String selectDBQuery = - "SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME" + - " FROM CURRENT_SENSOR_DEVICE WHERE CURRENT_SENSOR_DEVICE_ID = ?"; + "SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME FROM CURRENT_SENSOR_DEVICE WHERE " + + "CURRENT_SENSOR_DEVICE_ID = ?"; stmt = conn.prepareStatement(selectDBQuery); stmt.setString(1, iotDeviceId); resultSet = stmt.executeQuery(); if (resultSet.next()) { iotDevice = new IotDevice(); - iotDevice.setIotDeviceName(resultSet.getString( - CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME)); + iotDevice.setIotDeviceName(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME)); Map propertyMap = new HashMap(); - - iotDevice.setDeviceProperties(propertyMap); - if (log.isDebugEnabled()) { log.debug("Current Sensor device " + iotDeviceId + " data has been fetched from " + - "Current Sensor database."); + "Current Sensor database."); } } } catch (SQLException e) { @@ -82,7 +76,6 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO { IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); CurrentSensorDAO.closeConnection(); } - return iotDevice; } @@ -96,26 +89,23 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO { conn = CurrentSensorDAO.getConnection(); String createDBQuery = "INSERT INTO CURRENT_SENSOR_DEVICE(CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)"; - stmt = conn.prepareStatement(createDBQuery); stmt.setString(1, iotDevice.getIotDeviceId()); stmt.setString(2, iotDevice.getIotDeviceName()); if (iotDevice.getDeviceProperties() == null) { iotDevice.setDeviceProperties(new HashMap()); } - - int rows = stmt.executeUpdate(); if (rows > 0) { status = true; if (log.isDebugEnabled()) { log.debug("Current Sensor device " + iotDevice.getIotDeviceId() + " data has been" + - " added to the Current Sensor database."); + " added to the Current Sensor database."); } } } catch (SQLException e) { String msg = "Error occurred while adding the Current Sensor device '" + - iotDevice.getIotDeviceId() + "' to the Current Sensor db."; + iotDevice.getIotDeviceId() + "' to the Current Sensor db."; log.error(msg, e); throw new IotDeviceManagementDAOException(msg, e); } finally { @@ -125,8 +115,7 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO { } @Override - public boolean updateIotDevice(IotDevice iotDevice) - throws IotDeviceManagementDAOException { + public boolean updateIotDevice(IotDevice iotDevice) throws IotDeviceManagementDAOException { boolean status = false; Connection conn = null; PreparedStatement stmt = null; @@ -134,26 +123,23 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO { conn = CurrentSensorDAO.getConnection(); String updateDBQuery = "UPDATE CURRENT_SENSOR_DEVICE SET DEVICE_NAME = ? WHERE CURRENT_SENSOR_DEVICE_ID = ?"; - stmt = conn.prepareStatement(updateDBQuery); - if (iotDevice.getDeviceProperties() == null) { iotDevice.setDeviceProperties(new HashMap()); } stmt.setString(1, iotDevice.getIotDeviceName()); - stmt.setString(2, iotDevice.getIotDeviceId()); int rows = stmt.executeUpdate(); if (rows > 0) { status = true; if (log.isDebugEnabled()) { log.debug("Current Sensor device " + iotDevice.getIotDeviceId() + " data has been" + - " modified."); + " modified."); } } } catch (SQLException e) { String msg = "Error occurred while modifying the Current Sensor device '" + - iotDevice.getIotDeviceId() + "' data."; + iotDevice.getIotDeviceId() + "' data."; log.error(msg, e); throw new IotDeviceManagementDAOException(msg, e); } finally { @@ -163,8 +149,7 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO { } @Override - public boolean deleteIotDevice(String iotDeviceId) - throws IotDeviceManagementDAOException { + public boolean deleteIotDevice(String iotDeviceId) throws IotDeviceManagementDAOException { boolean status = false; Connection conn = null; PreparedStatement stmt = null; @@ -179,7 +164,7 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO { status = true; if (log.isDebugEnabled()) { log.debug("Current Sensor device " + iotDeviceId + " data has deleted" + - " from the Current Sensor database."); + " from the Current Sensor database."); } } } catch (SQLException e) { @@ -193,9 +178,7 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO { } @Override - public List getAllIotDevices() - throws IotDeviceManagementDAOException { - + public List getAllIotDevices() throws IotDeviceManagementDAOException { Connection conn = null; PreparedStatement stmt = null; ResultSet resultSet = null; @@ -205,17 +188,14 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO { try { conn = CurrentSensorDAO.getConnection(); String selectDBQuery = - "SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME " + - "FROM CURRENT_SENSOR_DEVICE"; + "SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME FROM CURRENT_SENSOR_DEVICE"; stmt = conn.prepareStatement(selectDBQuery); resultSet = stmt.executeQuery(); while (resultSet.next()) { iotDevice = new IotDevice(); iotDevice.setIotDeviceId(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_ID)); iotDevice.setIotDeviceName(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME)); - Map propertyMap = new HashMap(); - iotDevice.setDeviceProperties(propertyMap); iotDevices.add(iotDevice); } diff --git a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/util/CurrentSensorUtils.java b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/util/CurrentSensorUtils.java index 299f2b58..4b490801 100644 --- a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/util/CurrentSensorUtils.java +++ b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/impl/util/CurrentSensorUtils.java @@ -31,15 +31,11 @@ public class CurrentSensorUtils { private static Log log = LogFactory.getLog(CurrentSensorUtils.class); public static String getDeviceProperty(Map deviceProperties, String property) { - String deviceProperty = deviceProperties.get(property); - if (deviceProperty == null) { return ""; } - return deviceProperty; } - } diff --git a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/internal/ServiceComponent.java b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/internal/ServiceComponent.java index d9c8336e..9e0bcd35 100644 --- a/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/internal/ServiceComponent.java +++ b/modules/samples/currentsensor/component/plugin/src/main/java/org/homeautomation/currentsensor/plugin/internal/ServiceComponent.java @@ -40,11 +40,7 @@ import org.wso2.carbon.device.mgt.iot.service.DeviceTypeService; public class ServiceComponent { - private ServiceRegistration currentSensorServiceRegRef; - - - private static final Log log = LogFactory.getLog(ServiceComponent.class); protected void activate(ComponentContext ctx) { @@ -53,15 +49,8 @@ public class ServiceComponent { } try { BundleContext bundleContext = ctx.getBundleContext(); - - - currentSensorServiceRegRef = - bundleContext.registerService(DeviceManagementService.class.getName(), new - CurrentSensorManagerService(), - null); - - - + currentSensorServiceRegRef = bundleContext.registerService(DeviceManagementService.class.getName(), + new CurrentSensorManagerService(), null); if (log.isDebugEnabled()) { log.debug("Current Sensor Management Service Component has been successfully activated"); } @@ -70,7 +59,6 @@ public class ServiceComponent { } } - protected void deactivate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("De-activating Current Sensor Management Service Component"); @@ -79,7 +67,6 @@ public class ServiceComponent { if (currentSensorServiceRegRef != null) { currentSensorServiceRegRef.unregister(); } - if (log.isDebugEnabled()) { log.debug( "Current Sensor Management Service Component has been successfully de-activated"); @@ -89,20 +76,16 @@ public class ServiceComponent { } } - protected void setDeviceTypeService(DeviceTypeService deviceTypeService) { - /* This is to avoid this component getting initialized before the - common registered */ + /* This is to avoid this component getting initialized before the + common registered */ if (log.isDebugEnabled()) { log.debug("Data source service set to mobile service component"); } } - protected void unsetDeviceTypeService(DeviceTypeService deviceTypeService) { + protected void unsetDeviceTypeService(DeviceTypeService deviceTypeService) { //do nothing } - - - -} \ No newline at end of file +}