From 4f28e803aff2fd148f590d338769121dd4f746c1 Mon Sep 17 00:00:00 2001 From: NuwanSameera Date: Tue, 19 Apr 2016 17:21:09 +0530 Subject: [PATCH] Remove monitor operations from controoler api. --- .../api/ConnectedCupControllerService.java | 21 +--- .../ConnectedCupControllerServiceImpl.java | 64 +++------- .../api/ConnectedCupManagerService.java | 1 + .../api/ConnectedCupManagerServiceImpl.java | 77 +++++++----- .../transport/ConnectedCupMQTTConnector.java | 13 -- .../api/util/ConnectedCupServiceUtils.java | 6 +- .../api/src/main/webapp/WEB-INF/web.xml | 30 ++--- .../api/CurrentSensorControllerService.java | 36 ------ .../CurrentSensorControllerServiceImpl.java | 90 ++++--------- .../api/CurrentSensorManagerService.java | 1 + .../api/CurrentSensorManagerServiceImpl.java | 87 ++++++++----- .../currentsensor/api/util/APIUtil.java | 14 +++ .../api/util/CurrentSensorServiceUtils.java | 14 +-- .../api/src/main/webapp/WEB-INF/web.xml | 33 ++--- .../api/DoorManagerControllerService.java | 16 --- .../api/DoorManagerControllerServiceImpl.java | 61 +++++---- .../api/DoorManagerManagerService.java | 2 +- .../api/DoorManagerManagerServiceImpl.java | 119 ++++++++++-------- .../transport/DoorManagerMQTTConnector.java | 3 - .../doormanager/api/util/APIUtil.java | 13 ++ .../api/util/DoorManagerServiceUtils.java | 6 +- .../api/src/main/webapp/WEB-INF/web.xml | 31 ++--- .../resources/database/doormanagerDM_DB.h2.db | Bin 18432 -> 18432 bytes .../api/FireAlarmControllerService.java | 32 ----- .../api/FireAlarmControllerServiceImpl.java | 86 ++++++------- .../api/FireAlarmManagerService.java | 2 +- .../api/FireAlarmManagerServiceImpl.java | 116 ++++++++++------- .../api/transport/MQTTConnector.java | 7 -- .../firealarm/api/util/APIUtil.java | 13 ++ .../firealarm/api/util/ServiceUtils.java | 6 +- .../api/src/main/webapp/WEB-INF/web.xml | 31 ++--- 31 files changed, 477 insertions(+), 554 deletions(-) diff --git a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupControllerService.java b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupControllerService.java index 07d64723..9f8be82c 100644 --- a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupControllerService.java +++ b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupControllerService.java @@ -31,27 +31,14 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -@API( name="connectedcup", version="1.0.0", context="/connectedcup" , tags = {"connectedcup"}) -@DeviceType( value = "connectedcup") +@API(name = "connectedcup", version = "1.0.0", context = "/connectedcup", tags = {"connectedcup"}) +@DeviceType(value = "connectedcup") public interface ConnectedCupControllerService { - @Path("device/coffeelevel") - @GET - @Produces(MediaType.APPLICATION_JSON) - @Feature(code = "coffeelevel", name = "Coffee Level", type = "monitor", - description = "Request Coffee Level from Connected cup") - Response readCoffeeLevel(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId); - - @Path("device/temperature") - @GET - @Produces(MediaType.APPLICATION_JSON) - @Feature(code = "temperature", name = "Temperature", type = "monitor", - description = "Request Temperature reading from Connected cup") - Response readTemperature(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId); - - @Path("device/ordercoffee") @POST + @Feature(code = "ordercoffee", name = "Order Coffee", type = "control", + description = "Order coffee cup") Response orderCoffee(@QueryParam("deviceId") String deviceId, @QueryParam("deviceOwner") String deviceOwner); } diff --git a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupControllerServiceImpl.java b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupControllerServiceImpl.java index c60c2b08..2ca55b9a 100644 --- a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupControllerServiceImpl.java +++ b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupControllerServiceImpl.java @@ -24,11 +24,16 @@ import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants; import org.coffeeking.api.transport.ConnectedCupMQTTConnector; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; -import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager; -import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord; import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener; import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; public class ConnectedCupControllerServiceImpl implements ConnectedCupControllerService { @@ -36,6 +41,17 @@ public class ConnectedCupControllerServiceImpl implements ConnectedCupController private static Log log = LogFactory.getLog(ConnectedCupControllerServiceImpl.class); private static ConnectedCupMQTTConnector connectedCupMQTTConnector; + @Path("device/ordercoffee") + @POST + public Response orderCoffee(@QueryParam("deviceId") String deviceId, @QueryParam("deviceOwner") String deviceOwner) { + log.info("Coffee ordered....!"); + + if (log.isDebugEnabled()) { + log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT"); + } + return Response.ok().entity("Coffee ordered.").build(); + } + public ConnectedCupMQTTConnector getConnectedCupMQTTConnector() { return ConnectedCupControllerServiceImpl.connectedCupMQTTConnector; } @@ -73,46 +89,4 @@ public class ConnectedCupControllerServiceImpl implements ConnectedCupController return false; } - public Response readCoffeeLevel(String owner, String deviceId) { - if (log.isDebugEnabled()) { - log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT"); - } - - try { - String mqttResource = ConnectedCupConstants.LEVEL_CONTEXT.replace("/", ""); - connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, ""); - - SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, - ConnectedCupConstants.SENSOR_LEVEL); - return Response.ok().entity(sensorRecord).build(); - } catch (DeviceControllerException | TransportHandlerException e) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } - } - - public Response readTemperature(String owner, String deviceId) { - - if (log.isDebugEnabled()) { - log.debug("Sending request to read connected cup temperature of device " + "[" + deviceId + "] via MQTT"); - } - try { - String mqttResource = ConnectedCupConstants.TEMPERATURE_CONTEXT.replace("/", ""); - connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, ""); - - SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, - ConnectedCupConstants.SENSOR_TEMPERATURE); - return Response.ok().entity(sensorRecord).build(); - } catch (DeviceControllerException | TransportHandlerException e) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } - } - - public Response orderCoffee(String deviceId, String deviceOwner) { - log.info("Coffee ordered....!"); - - if (log.isDebugEnabled()) { - log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT"); - } - return Response.ok().entity("Coffee ordered.").build(); - } -} \ No newline at end of file +} diff --git a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupManagerService.java b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupManagerService.java index dc353e5c..d0f563b3 100644 --- a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupManagerService.java +++ b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupManagerService.java @@ -32,6 +32,7 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +@Path("enrollment") @API( name="connectedcup_mgt", version="1.0.0", context="/connectedcup_mgt", tags = {"connectedcup"}) @DeviceType("connectedcup") public interface ConnectedCupManagerService { diff --git a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupManagerServiceImpl.java b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupManagerServiceImpl.java index 3e6a3d5e..317ec1b6 100644 --- a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupManagerServiceImpl.java +++ b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/ConnectedCupManagerServiceImpl.java @@ -26,42 +26,30 @@ import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +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.MediaType; import javax.ws.rs.core.Response; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.UUID; -public class ConnectedCupManagerServiceImpl implements ConnectedCupManagerService{ +@Path("enrollment") +public class ConnectedCupManagerServiceImpl implements ConnectedCupManagerService { private static Log log = LogFactory.getLog(ConnectedCupManagerServiceImpl.class); - private boolean register(String deviceId, String name) { - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); - if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { - 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(ConnectedCupConstants.DEVICE_TYPE); - enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser()); - device.setEnrolmentInfo(enrolmentInfo); - boolean added = APIUtil.getDeviceManagementService().enrollDevice(device); - return added; - } catch (DeviceManagementException e) { - return false; - } - } - - public Response removeDevice(String deviceId) { + @Path("devices/{device_id}") + @DELETE + public Response removeDevice(@PathParam("device_id") String deviceId) { try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); @@ -78,7 +66,9 @@ public class ConnectedCupManagerServiceImpl implements ConnectedCupManagerServic } } - public Response updateDevice(String deviceId, String name) { + @Path("devices/{device_id}") + @PUT + public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); @@ -100,7 +90,11 @@ public class ConnectedCupManagerServiceImpl implements ConnectedCupManagerServic } } - public Response getDevice(String deviceId) { + @Path("devices/{device_id}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response getDevice(@PathParam("device_id") String deviceId) { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); @@ -113,6 +107,31 @@ public class ConnectedCupManagerServiceImpl implements ConnectedCupManagerServic } } + private boolean register(String deviceId, String name) { + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); + if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + 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(ConnectedCupConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser()); + device.setEnrolmentInfo(enrolmentInfo); + boolean added = APIUtil.getDeviceManagementService().enrollDevice(device); + return added; + } catch (DeviceManagementException e) { + return false; + } + } + private static String shortUUID() { UUID uuid = UUID.randomUUID(); long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong(); diff --git a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/transport/ConnectedCupMQTTConnector.java b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/transport/ConnectedCupMQTTConnector.java index 9018c1cc..be5f9ae7 100644 --- a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/transport/ConnectedCupMQTTConnector.java +++ b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/transport/ConnectedCupMQTTConnector.java @@ -31,7 +31,6 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.iot.config.server.DeviceManagementConfigurationManager; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; -import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager; import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; @@ -138,18 +137,6 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler { String owner = device.getEnrolmentInfo().getOwner(); ctx.setTenantDomain(MultitenantUtils.getTenantDomain(owner), true); ctx.setUsername(owner); - switch (messageData[0]) { - case "temperature": - SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_TEMPERATURE, - String.valueOf(messageData[1]), - Calendar.getInstance().getTimeInMillis()); - break; - case "coffeelevel": - SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_LEVEL, - String.valueOf(messageData[1]), - Calendar.getInstance().getTimeInMillis()); - break; - } if (!ConnectedCupServiceUtils.publishToDAS(deviceId, messageData[0], Float.parseFloat (messageData[1]))) { log.error("MQTT Subscriber: Publishing data to DAS failed."); diff --git a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/util/ConnectedCupServiceUtils.java b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/util/ConnectedCupServiceUtils.java index b985aef5..efbe8ebb 100644 --- a/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/util/ConnectedCupServiceUtils.java +++ b/modules/samples/connectedcup/component/api/src/main/java/org/coffeeking/api/util/ConnectedCupServiceUtils.java @@ -28,7 +28,7 @@ import org.apache.http.impl.nio.client.HttpAsyncClients; import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService; +import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import javax.ws.rs.HttpMethod; @@ -195,8 +195,8 @@ public class ConnectedCupServiceUtils { public static boolean publishToDAS(String deviceId, String sensor, float values) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( - DeviceAnalyticsService.class, null); + EventsPublisherService deviceAnalyticsService = (EventsPublisherService) ctx.getOSGiService( + EventsPublisherService.class, null); String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); Object metdaData[] = {owner, ConnectedCupConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object payloadData[] = {values}; diff --git a/modules/samples/connectedcup/component/api/src/main/webapp/WEB-INF/web.xml b/modules/samples/connectedcup/component/api/src/main/webapp/WEB-INF/web.xml index be105f99..55a9dd85 100644 --- a/modules/samples/connectedcup/component/api/src/main/webapp/WEB-INF/web.xml +++ b/modules/samples/connectedcup/component/api/src/main/webapp/WEB-INF/web.xml @@ -21,27 +21,31 @@ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> ConnectedCup-Webapp + - JAX-WS/JAX-RS Endpoint - JAX-WS/JAX-RS Servlet CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - + org.apache.cxf.transport.servlet.CXFServlet 1 CXFServlet /* - isAdminService false doAuthentication - false + true + + + isSharedWithAllTenants + true + + + providerTenantDomain + carbon.super @@ -53,17 +57,5 @@ managed-api-owner admin - - managed-api-context-template - /connectedcup/{version} - - - managed-api-application - connectedcup - - - managed-api-isSecured - true - diff --git a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorControllerService.java b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorControllerService.java index 3bf43fb4..99ae365f 100644 --- a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorControllerService.java +++ b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorControllerService.java @@ -45,42 +45,6 @@ public interface CurrentSensorControllerService { Response registerDeviceIP(@PathParam("owner") String owner, @PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP, @PathParam("port") String devicePort); - /** - * @param deviceId - * @return - */ - @Path("device/read-current") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Feature(code = "read-current", name = "Current", type = "monitor", - description = "Request current reading from Arduino agent") - Response requestCurrent(@HeaderParam("deviceId") String deviceId); - - /** - * @param deviceId - * @return - */ - @Path("device/read-power") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Feature(code = "read-power", name = "Power", type = "monitor", - description = "Request power reading from Arduino agent") - Response requestPower(@HeaderParam("deviceId") String deviceId); - - /** - * @param deviceId - * @return - */ - @Path("device/read-flowrate") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Feature(code = "read-flowrate", name = "Flow Rate", type = "monitor", - description = "Request flow rate reading from Arduino agent") - Response requestFlowRate(@HeaderParam("deviceId") String deviceId); - /** * @param dataMsg */ diff --git a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorControllerServiceImpl.java b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorControllerServiceImpl.java index 419ab13f..0b3bf815 100644 --- a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorControllerServiceImpl.java +++ b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorControllerServiceImpl.java @@ -24,10 +24,17 @@ import org.homeautomation.currentsensor.api.dto.DeviceJSON; import org.homeautomation.currentsensor.api.util.CurrentSensorServiceUtils; import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants; import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; -import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager; -import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord; import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Calendar; import java.util.concurrent.ConcurrentHashMap; @@ -37,18 +44,10 @@ public class CurrentSensorControllerServiceImpl implements CurrentSensorControll private static Log log = LogFactory.getLog(CurrentSensorControllerServiceImpl.class); private ConcurrentHashMap deviceToIpMap = new ConcurrentHashMap<>(); - private boolean waitForServerStartup() { - while (!IoTServerStartupListener.isServerReady()) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - return true; - } - } - return false; - } - - public Response registerDeviceIP(String owner, String deviceId, String deviceIP, String devicePort) { + @Path("device/register/{owner}/{deviceId}/{ip}/{port}") + @POST + public Response registerDeviceIP(@PathParam("owner") String owner, @PathParam("deviceId") String deviceId, + @PathParam("ip") String deviceIP, @PathParam("port") String devicePort) { //TODO:: Need to get IP from the request itself String result; @@ -64,48 +63,15 @@ public class CurrentSensorControllerServiceImpl implements CurrentSensorControll return Response.ok().entity(result).build(); } - public Response requestCurrent(String deviceId) { - SensorRecord sensorRecord = null; - try { - sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, - CurrentSensorConstants.SENSOR_CURRENT); - } catch (DeviceControllerException e) { - Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - - return Response.ok().entity(sensorRecord).build(); - } - - public Response requestPower(String deviceId) { - SensorRecord sensorRecord = null; - try { - sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, - CurrentSensorConstants.SENSOR_POWER); - } catch (DeviceControllerException e) { - Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - return Response.ok().entity(sensorRecord).build(); - } - - public Response requestFlowRate(String deviceId) { - SensorRecord sensorRecord = null; - try { - sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, - CurrentSensorConstants.SENSOR_FLOWRATE); - } catch (DeviceControllerException e) { - Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - return Response.ok().entity(sensorRecord).build(); - } - + @Path("device/push-data") + @POST + @Consumes(MediaType.APPLICATION_JSON) public Response pushData(final DeviceJSON dataMsg) { - String owner = dataMsg.owner; String deviceId = dataMsg.deviceId; String deviceIp = dataMsg.reply; float current = dataMsg.current; float flow_rate = dataMsg.flow_rate; - String registeredIp = deviceToIpMap.get(deviceId); if (registeredIp == null) { @@ -117,19 +83,6 @@ public class CurrentSensorControllerServiceImpl implements CurrentSensorControll " is already registered under some other IP. Re-registration required"); return Response.status(Response.Status.CONFLICT.getStatusCode()).build(); } - - 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)) { log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId + "] of owner [" + owner + "]"); @@ -150,4 +103,15 @@ public class CurrentSensorControllerServiceImpl implements CurrentSensorControll return Response.ok().build(); } + private boolean waitForServerStartup() { + while (!IoTServerStartupListener.isServerReady()) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + return true; + } + } + return false; + } + } diff --git a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorManagerService.java b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorManagerService.java index 46e50a6f..a6a4a941 100644 --- a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorManagerService.java +++ b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorManagerService.java @@ -32,6 +32,7 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +@Path("enrollment") @API(name = "currentsensor_mgt", version = "1.0.0", context = "/currentsensor_mgt", tags = {"currentsensor"}) @DeviceType(value = "currentsensor") public interface CurrentSensorManagerService { diff --git a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorManagerServiceImpl.java b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorManagerServiceImpl.java index ef39365b..800b922c 100644 --- a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorManagerServiceImpl.java +++ b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/CurrentSensorManagerServiceImpl.java @@ -22,7 +22,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.identity.jwt.client.extension.JWTClient; -import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.homeautomation.currentsensor.api.util.APIUtil; @@ -39,44 +38,31 @@ import org.wso2.carbon.device.mgt.iot.util.ZipArchive; import org.wso2.carbon.device.mgt.iot.util.ZipUtil; import org.wso2.carbon.user.api.UserStoreException; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +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.MediaType; import javax.ws.rs.core.Response; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.UUID; +@Path("enrollment") class CurrentSensorManagerServiceImpl implements CurrentSensorManagerService { private static Log log = LogFactory.getLog(CurrentSensorManagerServiceImpl.class); private static ApiApplicationKey apiApplicationKey; private static final String KEY_TYPE = "PRODUCTION"; - private boolean register(String deviceId, String name) { - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); - if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { - 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); - return added; - } catch (DeviceManagementException e) { - return false; - } - } - - public Response removeDevice(String deviceId) { + @Path("devices/{device_id}") + @DELETE + public Response removeDevice(@PathParam("device_id") String deviceId) { try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); @@ -93,7 +79,9 @@ class CurrentSensorManagerServiceImpl implements CurrentSensorManagerService { } } - public Response updateDevice(String deviceId, String name) { + @Path("devices/{device_id}") + @PUT + public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); @@ -115,7 +103,11 @@ class CurrentSensorManagerServiceImpl implements CurrentSensorManagerService { } } - public Response getDevice(String deviceId) { + @Path("devices/{device_id}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response getDevice(@PathParam("device_id") String deviceId) { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); @@ -128,7 +120,11 @@ class CurrentSensorManagerServiceImpl implements CurrentSensorManagerService { } } - public Response downloadSketch(String deviceName, String sketchType) { + @Path("devices/{sketch_type}/download") + @GET + @Produces(MediaType.APPLICATION_JSON) + public Response downloadSketch(@QueryParam("deviceName") String deviceName, + @PathParam("sketch_type") String sketchType) { try { ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName); Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); @@ -149,6 +145,31 @@ class CurrentSensorManagerServiceImpl implements CurrentSensorManagerService { } } + private boolean register(String deviceId, String name) { + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); + if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + 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); + return added; + } catch (DeviceManagementException e) { + return false; + } + } + private ZipArchive createDownloadFile(String owner, String deviceName) throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException, UserStoreException { @@ -166,14 +187,14 @@ class CurrentSensorManagerServiceImpl implements CurrentSensorManagerService { apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( CurrentSensorConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true); } - JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient(); + JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient(); String scopes = "device_type_" + CurrentSensorConstants.DEVICE_TYPE + " device_" + deviceId; AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret(), owner, scopes); //create token - String accessToken = accessTokenInfo.getAccess_token(); - String refreshToken = accessTokenInfo.getRefresh_token(); + String accessToken = accessTokenInfo.getAccessToken(); + String refreshToken = accessTokenInfo.getRefreshToken(); //Register the device with CDMF boolean status = register(deviceId, deviceName); if (!status) { diff --git a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/util/APIUtil.java b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/util/APIUtil.java index 1bf609e1..07325ebd 100644 --- a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/util/APIUtil.java +++ b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/util/APIUtil.java @@ -5,6 +5,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; /** * This class provides utility functions used by REST-API. @@ -52,4 +53,17 @@ public class APIUtil { } return apiManagementProviderService; } + + public static JWTClientManagerService getJWTClientManagerService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + JWTClientManagerService jwtClientManagerService = + (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null); + if (jwtClientManagerService == null) { + String msg = "JWT Client manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return jwtClientManagerService; + } + } diff --git a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/util/CurrentSensorServiceUtils.java b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/util/CurrentSensorServiceUtils.java index e6b4d4b0..ff9c2767 100644 --- a/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/util/CurrentSensorServiceUtils.java +++ b/modules/samples/currentsensor/component/api/src/main/java/org/homeautomation/currentsensor/api/util/CurrentSensorServiceUtils.java @@ -23,7 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService; +import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; public class CurrentSensorServiceUtils { @@ -34,8 +34,8 @@ public class CurrentSensorServiceUtils { public static boolean publishToDASCurrent(String deviceId, float current) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( - DeviceAnalyticsService.class, null); + EventsPublisherService deviceAnalyticsService = (EventsPublisherService) ctx.getOSGiService( + EventsPublisherService.class, null); String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object payloadData[] = {current}; @@ -50,8 +50,8 @@ public class CurrentSensorServiceUtils { public static boolean publishToDASPower(String deviceId, float power) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( - DeviceAnalyticsService.class, null); + EventsPublisherService deviceAnalyticsService = (EventsPublisherService) ctx.getOSGiService( + EventsPublisherService.class, null); String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object payloadData[] = {power}; @@ -66,8 +66,8 @@ public class CurrentSensorServiceUtils { public static boolean publishToDASFlowRate(String deviceId, float flowRate) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( - DeviceAnalyticsService.class, null); + EventsPublisherService deviceAnalyticsService = (EventsPublisherService) ctx.getOSGiService( + EventsPublisherService.class, null); String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object payloadData[] = {flowRate}; diff --git a/modules/samples/currentsensor/component/api/src/main/webapp/WEB-INF/web.xml b/modules/samples/currentsensor/component/api/src/main/webapp/WEB-INF/web.xml index d5258879..d9dd952f 100644 --- a/modules/samples/currentsensor/component/api/src/main/webapp/WEB-INF/web.xml +++ b/modules/samples/currentsensor/component/api/src/main/webapp/WEB-INF/web.xml @@ -21,40 +21,41 @@ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> Current-Sensor-Agent-Webapp + - JAX-WS/JAX-RS IOT Current Sensor Endpoint - JAX-WS/JAX-RS Servlet CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - + org.apache.cxf.transport.servlet.CXFServlet 1 CXFServlet /* - - - managed-api-enabled - true + isAdminService + false - managed-api-owner - admin + doAuthentication + true - managed-api-context-template - /currentsensor/{version} + isSharedWithAllTenants + true - managed-api-application - currentsensor + providerTenantDomain + carbon.super + + - managed-api-isSecured + managed-api-enabled true + + managed-api-owner + admin + diff --git a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerControllerService.java b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerControllerService.java index df06e2b5..39d22998 100644 --- a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerControllerService.java +++ b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerControllerService.java @@ -77,22 +77,6 @@ public interface DoorManagerControllerService { @HeaderParam("protocol") String protocol, @FormParam("state") String state); - /** - * Request current status of door lock safe - * - * @param owner owner of the device - * @param deviceId unique identifier for given device - * @param protocol transport protocol which is being using here MQTT - */ - @GET - @Path("device/current-status") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Feature(code = "current-status", name = "Door Locker Status", type = "monitor", - description = "Request current status of door safe") - Response requestStatusOfDoorLockSafe(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, - @HeaderParam("protocol") String protocol); - /** * @param userInfo user information which are required to test given user is authorized to open requested door * @return if user is authorized open the the door allow to open it diff --git a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerControllerServiceImpl.java b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerControllerServiceImpl.java index 08b4f220..3b7def7b 100644 --- a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerControllerServiceImpl.java +++ b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerControllerServiceImpl.java @@ -38,22 +38,27 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; -import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager; -import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord; import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener; import org.wso2.carbon.identity.jwt.client.extension.JWTClient; -import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; -import javax.ws.rs.core.Context; + +import javax.ws.rs.Consumes; +import javax.ws.rs.FormParam; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Calendar; import java.util.HashMap; import java.util.Map; -public class DoorManagerControllerServiceImpl implements DoorManagerControllerService{ +public class DoorManagerControllerServiceImpl implements DoorManagerControllerService { private static Log log = LogFactory.getLog(DoorManagerControllerServiceImpl.class); private static String CURRENT_STATUS = "doorLockerCurrentStatus"; @@ -66,7 +71,6 @@ public class DoorManagerControllerServiceImpl implements DoorManagerControllerSe doorManager = new DoorManager(); } - @Context //injected response proxy supporting multiple thread private boolean waitForServerStartup() { while (!IoTServerStartupListener.isServerReady()) { try { @@ -102,9 +106,14 @@ public class DoorManagerControllerServiceImpl implements DoorManagerControllerSe connectorThread.start(); } - - public Response assignUserToLock(String owner, String deviceId, String protocol, String cardNumber, String userName, - String emailAddress) { + @Path("device/assign-user") + @POST + public Response assignUserToLock(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @FormParam("cardNumber") String cardNumber, + @FormParam("userName") String userName, + @FormParam("emailAddress") String emailAddress) { if (userName != null && cardNumber != null && deviceId != null) { try { @@ -119,22 +128,22 @@ public class DoorManagerControllerServiceImpl implements DoorManagerControllerSe apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( DoorManagerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true); } - JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient(); + JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient(); String scopes = "device_type_" + DoorManagerConstants.DEVICE_TYPE + " device_" + deviceId; AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret(), owner, scopes); - String accessToken = accessTokenInfo.getAccess_token(); + String accessToken = accessTokenInfo.getAccessToken(); if (accessToken == null) { return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); } Map claims = new HashMap<>(); claims.put(DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, accessToken); claims.put(DoorManagerConstants.DEVICE_CLAIMS_REFRESH_TOKEN, - accessTokenInfo.getRefresh_token()); + accessTokenInfo.getRefreshToken()); claims.put(DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, cardNumber); userStoreManager.setUserClaimValues(userName, claims, null); - doorLockSafe.setAccessToken(accessTokenInfo.getAccess_token()); - doorLockSafe.setRefreshToken(accessTokenInfo.getRefresh_token()); + doorLockSafe.setAccessToken(accessTokenInfo.getAccessToken()); + doorLockSafe.setRefreshToken(accessTokenInfo.getRefreshToken()); doorLockSafe.setDeviceId(deviceId); doorLockSafe.setOwner(owner); doorLockSafe.setEmailAddress(emailAddress); @@ -162,7 +171,12 @@ public class DoorManagerControllerServiceImpl implements DoorManagerControllerSe } } - public Response changeStatusOfDoorLockSafe(String owner, String deviceId, String protocol, String state) { + @Path("device/change-status") + @POST + public Response changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @FormParam("state") String state) { try { int lockerCurrentState; if (state.toUpperCase().equals("LOCK")) { @@ -170,8 +184,6 @@ public class DoorManagerControllerServiceImpl implements DoorManagerControllerSe } else { lockerCurrentState = 1; } - SensorDataManager.getInstance().setSensorRecord(deviceId, CURRENT_STATUS, - String.valueOf(lockerCurrentState), Calendar.getInstance().getTimeInMillis()); doorManagerMQTTConnector.sendCommandViaMQTT(owner, deviceId, "DoorManager:", state.toUpperCase()); return Response.ok().build(); } catch (DeviceManagementException e) { @@ -181,16 +193,11 @@ public class DoorManagerControllerServiceImpl implements DoorManagerControllerSe } } - public Response requestStatusOfDoorLockSafe(String owner, String deviceId, String protocol) { - SensorRecord sensorRecord = null; - try { - sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, CURRENT_STATUS); - return Response.ok(sensorRecord).entity(sensorRecord).build(); - } catch (DeviceControllerException e) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - } - + @GET + @Path("device/get-user-info") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @SuppressWarnings("unchecked") public Response get_user_info(final UserInfo userInfo) { if (userInfo.userName != null && userInfo.cardNumber != null && userInfo.deviceId != null) { try { diff --git a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerManagerService.java b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerManagerService.java index 4ad85fa7..0f7e39c6 100644 --- a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerManagerService.java +++ b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerManagerService.java @@ -32,6 +32,7 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +@Path("enrollment") @SuppressWarnings("NonJaxWsWebServices") @DeviceType(value = "doormanager") @API(name = "doormanager_mgt", version = "1.0.0", context = "/doormanager_mgt" , tags = {"doormanager"}) @@ -41,7 +42,6 @@ public interface DoorManagerManagerService { @DELETE Response removeDevice(@PathParam("device_id") String deviceId); - @Path("devices/{device_id}") @PUT Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name); diff --git a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerManagerServiceImpl.java b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerManagerServiceImpl.java index e3d8fde0..399279d3 100644 --- a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerManagerServiceImpl.java +++ b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/DoorManagerManagerServiceImpl.java @@ -37,66 +37,38 @@ import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; import org.wso2.carbon.device.mgt.iot.util.ZipArchive; import org.wso2.carbon.device.mgt.iot.util.ZipUtil; import org.wso2.carbon.identity.jwt.client.extension.JWTClient; -import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.user.api.UserStoreException; import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +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.MediaType; + import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.UUID; -public class DoorManagerManagerServiceImpl implements DoorManagerManagerService{ +@Path("enrollment") +public class DoorManagerManagerServiceImpl implements DoorManagerManagerService { private static Log log = LogFactory.getLog(DoorManagerManagerServiceImpl.class); - @Context //injected response proxy supporting multiple thread - private HttpServletResponse response; private static ApiApplicationKey apiApplicationKey; private static final String KEY_TYPE = "PRODUCTION"; - /** - * Generate UUID - * - * @return generated UUID - */ - 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 boolean register(String deviceId,String name) { - - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE); - if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { - 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(DoorManagerConstants.DEVICE_TYPE); - enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser()); - device.setEnrolmentInfo(enrolmentInfo); - boolean added = APIUtil.getDeviceManagementService().enrollDevice(device); - return added; - } catch (DeviceManagementException e) { - return false; - } - } - - public Response removeDevice(String deviceId) { + @Path("devices/{device_id}") + @DELETE + public Response removeDevice(@PathParam("device_id") String deviceId) { try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); @@ -113,7 +85,9 @@ public class DoorManagerManagerServiceImpl implements DoorManagerManagerService{ } } - public Response updateDevice(String deviceId, String name) { + @Path("devices/{device_id}") + @PUT + public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) { try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); @@ -134,7 +108,11 @@ public class DoorManagerManagerServiceImpl implements DoorManagerManagerService{ } } - public Response getDevice(String deviceId) { + @Path("devices/{device_id}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response getDevice(@PathParam("device_id") String deviceId) { try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); @@ -146,7 +124,10 @@ public class DoorManagerManagerServiceImpl implements DoorManagerManagerService{ } } - public Response downloadSketch(String deviceName) { + @Path("devices/download") + @GET + @Produces(MediaType.APPLICATION_JSON) + public Response downloadSketch(@QueryParam("deviceName") String deviceName) { try { ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); @@ -170,7 +151,9 @@ public class DoorManagerManagerServiceImpl implements DoorManagerManagerService{ } } - public Response generateSketchLink(String deviceName) { + @Path("devices/generate_link") + @GET + public Response generateSketchLink(@QueryParam("deviceName") String deviceName){ try { ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName); Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); @@ -207,14 +190,14 @@ public class DoorManagerManagerServiceImpl implements DoorManagerManagerService{ apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( DoorManagerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true); } - JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient(); + JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient(); String scopes = "device_type_" + DoorManagerConstants.DEVICE_TYPE + " device_" + deviceId; AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret(), owner, scopes); //create token - String accessToken = accessTokenInfo.getAccess_token(); - String refreshToken = accessTokenInfo.getRefresh_token(); + String accessToken = accessTokenInfo.getAccessToken(); + String refreshToken = accessTokenInfo.getRefreshToken(); //Register the device with CDMF boolean status = register(deviceId, deviceName); if (!status) { @@ -229,4 +212,40 @@ public class DoorManagerManagerServiceImpl implements DoorManagerManagerService{ return zipFile; } + /** + * Generate UUID + * + * @return generated UUID + */ + 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 boolean register(String deviceId, String name) { + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE); + if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + 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(DoorManagerConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser()); + device.setEnrolmentInfo(enrolmentInfo); + boolean added = APIUtil.getDeviceManagementService().enrollDevice(device); + return added; + } catch (DeviceManagementException e) { + return false; + } + } + } diff --git a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/transport/DoorManagerMQTTConnector.java b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/transport/DoorManagerMQTTConnector.java index dda7f335..cff9d4d8 100644 --- a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/transport/DoorManagerMQTTConnector.java +++ b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/transport/DoorManagerMQTTConnector.java @@ -28,7 +28,6 @@ import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; -import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager; import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler; @@ -117,8 +116,6 @@ public class DoorManagerMQTTConnector extends MQTTTransportHandler { lockerStatus = 1; } try { - SensorDataManager.getInstance().setSensorRecord(deviceId, "doorLockerCurrentStatus", - String.valueOf(lockerStatus), Calendar.getInstance().getTimeInMillis()); if (!DoorManagerServiceUtils.publishToDASLockerStatus(owner, deviceId, lockerStatus)) { log.warn("An error occurred while trying to publish with ID [" + deviceId + "] of owner [" + owner + "]"); diff --git a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/util/APIUtil.java b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/util/APIUtil.java index cda4d25f..6e403b65 100644 --- a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/util/APIUtil.java +++ b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/util/APIUtil.java @@ -21,6 +21,7 @@ package org.homeautomation.doormanager.api.util; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; /** * This class provides utility functions used by REST-API. @@ -65,4 +66,16 @@ public class APIUtil { } return apiManagementProviderService; } + + public static JWTClientManagerService getJWTClientManagerService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + JWTClientManagerService jwtClientManagerService = + (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null); + if (jwtClientManagerService == null) { + String msg = "JWT Client manager service has not initialized."; + throw new IllegalStateException(msg); + } + return jwtClientManagerService; + } + } diff --git a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/util/DoorManagerServiceUtils.java b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/util/DoorManagerServiceUtils.java index 1a45a021..876ff33c 100644 --- a/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/util/DoorManagerServiceUtils.java +++ b/modules/samples/doormanager/component/api/src/main/java/org/homeautomation/doormanager/api/util/DoorManagerServiceUtils.java @@ -23,7 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService; +import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; public class DoorManagerServiceUtils { @@ -53,8 +53,8 @@ public class DoorManagerServiceUtils { if (ctx.getTenantDomain(true) == null) { ctx.setTenantDomain("carbon.super", true); } - DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( - DeviceAnalyticsService.class, null); + EventsPublisherService deviceAnalyticsService = (EventsPublisherService) ctx.getOSGiService( + EventsPublisherService.class, null); Object metaData[] = {owner, DoorManagerConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; try { deviceAnalyticsService.publishEvent(definition, STREAM_DEFINITION_VERSION, metaData, diff --git a/modules/samples/doormanager/component/api/src/main/webapp/WEB-INF/web.xml b/modules/samples/doormanager/component/api/src/main/webapp/WEB-INF/web.xml index ab77f3a7..8f029527 100644 --- a/modules/samples/doormanager/component/api/src/main/webapp/WEB-INF/web.xml +++ b/modules/samples/doormanager/component/api/src/main/webapp/WEB-INF/web.xml @@ -21,13 +21,10 @@ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> Sample-Webapp-Controller + - JAX-WS/JAX-RS Endpoint - JAX-WS/JAX-RS Servlet CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - + org.apache.cxf.transport.servlet.CXFServlet 1 @@ -40,27 +37,25 @@ doAuthentication - false - - - - managed-api-enabled true - managed-api-owner - admin + isSharedWithAllTenants + true - managed-api-context-template - /doormanager/{version} + providerTenantDomain + carbon.super + + - managed-api-application - doormanager + managed-api-enabled + true - managed-api-isSecured - true + managed-api-owner + admin + diff --git a/modules/samples/doormanager/feature/feature/src/main/resources/database/doormanagerDM_DB.h2.db b/modules/samples/doormanager/feature/feature/src/main/resources/database/doormanagerDM_DB.h2.db index e3cd583dfe592cd1d9cecb569b791ea8d3586e9d..da2768b4f2ab9cf4c7f855250ed9fd87aa3ebe73 100644 GIT binary patch delta 53 ncmZpez}PT>aRCR9lDJaRCR<&*=|-GJpVMb>L<}j`!>n16Z*NE|M?+0P?pHi2wiq diff --git a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmControllerService.java b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmControllerService.java index 7cd1e63f..2b500f80 100644 --- a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmControllerService.java +++ b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmControllerService.java @@ -51,38 +51,6 @@ public interface FireAlarmControllerService { @Consumes(MediaType.APPLICATION_JSON) Response registerDevice(final DeviceJSON agentInfo); - /** - * @param owner device owner - * @param deviceId unique identifier for given device type - * @param protocol name of supported protocol. here MQTT is used - * @return sensor record - */ - @Path("device/read-temperature") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Feature(code = "read-temperature", name = "Temperature", type = "monitor", - description = "Request temperature reading from device") - Response readTemperature(@HeaderParam("owner") String owner, - @HeaderParam("deviceId") String deviceId, - @HeaderParam("protocol") String protocol); - - /** - * @param owner device owner - * @param deviceId unique identifier for given device type - * @param protocol name of supported protocol. here MQTT is used - * @return sensor record - */ - @Path("device/read-humidity") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Feature(code = "read-humidity", name = "Humidity", type = "monitor", - description = "Request humidity reading from device") - Response readHumidity(@HeaderParam("owner") String owner, - @HeaderParam("deviceId") String deviceId, - @HeaderParam("protocol") String protocol); - /** * @param owner device owner * @param deviceId unique identifier for given device type diff --git a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmControllerServiceImpl.java b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmControllerServiceImpl.java index 41e90d48..ca77c7f3 100644 --- a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmControllerServiceImpl.java +++ b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmControllerServiceImpl.java @@ -23,13 +23,19 @@ import org.apache.commons.logging.LogFactory; import org.homeautomation.firealarm.api.dto.DeviceJSON; import org.homeautomation.firealarm.api.exception.DeviceTypeException; import org.homeautomation.firealarm.api.transport.MQTTConnector; -import org.homeautomation.firealarm.plugin.constants.DeviceTypeConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; -import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager; -import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord; import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener; + +import javax.ws.rs.Consumes; +import javax.ws.rs.FormParam; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; public class FireAlarmControllerServiceImpl implements FireAlarmControllerService { @@ -37,6 +43,35 @@ public class FireAlarmControllerServiceImpl implements FireAlarmControllerServic private static Log log = LogFactory.getLog(FireAlarmControllerServiceImpl.class); private MQTTConnector mqttConnector; + @Path("device/register") + @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(); + } + return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Message body not " + + "well-formed and still invalid").build(); + } + + @Path("device/change-status") + @POST + public Response changeBuzzerState(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @FormParam("state") String state) { + try { + mqttConnector.sendCommandViaMQTT(owner, deviceId, "buzzer:", state.toUpperCase()); + return Response.ok().build(); + } catch (DeviceManagementException e) { + log.error(e); + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } catch (DeviceTypeException e) { + log.error(e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); + } + } + private boolean waitForServerStartup() { while (!IoTServerStartupListener.isServerReady()) { try { @@ -74,47 +109,4 @@ public class FireAlarmControllerServiceImpl implements FireAlarmControllerServic connectorThread.start(); } - 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(); - } - return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Message body not " + - "well-formed and still invalid").build(); - } - - public Response readTemperature(String owner, String deviceId, String protocol) { - SensorRecord sensorRecord = null; - try { - sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, - DeviceTypeConstants.SENSOR_TEMPERATURE); - } catch (DeviceControllerException e) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - return Response.ok().entity(sensorRecord).build(); - } - - public Response readHumidity(String owner, String deviceId, String protocol) { - SensorRecord sensorRecord = null; - try { - sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, - DeviceTypeConstants.SENSOR_HUMIDITY); - } catch (DeviceControllerException e) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - return Response.ok().entity(sensorRecord).build(); - } - - public Response changeBuzzerState(String owner, String deviceId, String protocol, String state) { - try { - mqttConnector.sendCommandViaMQTT(owner, deviceId, "buzzer:", state.toUpperCase()); - return Response.ok().build(); - } catch (DeviceManagementException e) { - log.error(e); - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } catch (DeviceTypeException e) { - log.error(e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); - } - } - -} \ No newline at end of file +} diff --git a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmManagerService.java b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmManagerService.java index 24a3513b..17e03801 100644 --- a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmManagerService.java +++ b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmManagerService.java @@ -32,6 +32,7 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +@Path("enrollment") @SuppressWarnings("NonJaxWsWebServices") @API(name = "firealarm_mgt", version = "1.0.0", context = "/firealarm_mgt" ,tags = {"firealarm"}) @DeviceType(value = "firealarm") @@ -56,7 +57,6 @@ public interface FireAlarmManagerService { @Produces(MediaType.APPLICATION_JSON) Response downloadSketch(@QueryParam("deviceName") String deviceName); - @Path("devices/generate_link") @GET Response generateSketchLink(@QueryParam("deviceName") String deviceName); diff --git a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmManagerServiceImpl.java b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmManagerServiceImpl.java index a7b69160..dbf7f27b 100644 --- a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmManagerServiceImpl.java +++ b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/FireAlarmManagerServiceImpl.java @@ -36,11 +36,19 @@ import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; import org.wso2.carbon.device.mgt.iot.util.ZipArchive; import org.wso2.carbon.device.mgt.iot.util.ZipUtil; import org.wso2.carbon.identity.jwt.client.extension.JWTClient; -import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.user.api.UserStoreException; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +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.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.nio.ByteBuffer; @@ -48,51 +56,16 @@ import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.UUID; +@Path("enrollment") public class FireAlarmManagerServiceImpl implements FireAlarmManagerService{ private static Log log = LogFactory.getLog(FireAlarmManagerServiceImpl.class); - private static ApiApplicationKey apiApplicationKey; private static final String KEY_TYPE = "PRODUCTION"; - /** - * Generate UUID - * - * @return generated UUID - */ - 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 boolean register(String deviceId,String name) { - - try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); - if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { - 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(DeviceTypeConstants.DEVICE_TYPE); - enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser()); - device.setEnrolmentInfo(enrolmentInfo); - boolean added = APIUtil.getDeviceManagementService().enrollDevice(device); - return added; - } catch (DeviceManagementException e) { - return false; - } - } - - public Response removeDevice(String deviceId) { + @Path("devices/{device_id}") + @DELETE + public Response removeDevice(@PathParam("device_id") String deviceId) { try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); @@ -109,7 +82,9 @@ public class FireAlarmManagerServiceImpl implements FireAlarmManagerService{ } } - public Response updateDevice(String deviceId, String name) { + @Path("devices/{device_id}") + @PUT + public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) { try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); @@ -130,7 +105,11 @@ public class FireAlarmManagerServiceImpl implements FireAlarmManagerService{ } } - public Response getDevice(String deviceId) { + @Path("devices/{device_id}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response getDevice(@PathParam("device_id") String deviceId) { try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); @@ -142,7 +121,10 @@ public class FireAlarmManagerServiceImpl implements FireAlarmManagerService{ } } - public Response downloadSketch(String deviceName) { + @Path("devices/download") + @GET + @Produces(MediaType.APPLICATION_JSON) + public Response downloadSketch(@QueryParam("deviceName") String deviceName) { try { ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); @@ -166,7 +148,9 @@ public class FireAlarmManagerServiceImpl implements FireAlarmManagerService{ } } - public Response generateSketchLink(String deviceName) { + @Path("devices/generate_link") + @GET + public Response generateSketchLink(@QueryParam("deviceName") String deviceName) { try { ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName); Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); @@ -203,14 +187,14 @@ public class FireAlarmManagerServiceImpl implements FireAlarmManagerService{ apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( DeviceTypeConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true); } - JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient(); + JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient(); String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId; AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret(), owner, scopes); //create token - String accessToken = accessTokenInfo.getAccess_token(); - String refreshToken = accessTokenInfo.getRefresh_token(); + String accessToken = accessTokenInfo.getAccessToken(); + String refreshToken = accessTokenInfo.getRefreshToken(); //Register the device with CDMF boolean status = register(deviceId, deviceName); if (!status) { @@ -225,4 +209,42 @@ public class FireAlarmManagerServiceImpl implements FireAlarmManagerService{ return zipFile; } + + /** + * Generate UUID + * + * @return generated UUID + */ + 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 boolean register(String deviceId,String name) { + + try { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); + if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + 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(DeviceTypeConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser()); + device.setEnrolmentInfo(enrolmentInfo); + boolean added = APIUtil.getDeviceManagementService().enrollDevice(device); + return added; + } catch (DeviceManagementException e) { + return false; + } + } + } diff --git a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/transport/MQTTConnector.java b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/transport/MQTTConnector.java index 573402cd..a48f719b 100644 --- a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/transport/MQTTConnector.java +++ b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/transport/MQTTConnector.java @@ -27,7 +27,6 @@ import org.homeautomation.firealarm.api.util.ServiceUtils; import org.homeautomation.firealarm.plugin.constants.DeviceTypeConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; -import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager; import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler; @@ -110,12 +109,6 @@ public class MQTTConnector extends MQTTTransportHandler { log.debug("Received MQTT message for: [OWNER-" + owner + "] & [DEVICE.ID-" + deviceId + "]"); } if (messageData.length == 4) { - SensorDataManager.getInstance().setSensorRecord(deviceId, DeviceTypeConstants.SENSOR_TEMPERATURE, - messageData[1], Calendar.getInstance().getTimeInMillis()); - SensorDataManager.getInstance().setSensorRecord(deviceId, DeviceTypeConstants.SENSOR_HUMIDITY, - messageData[3], Calendar.getInstance().getTimeInMillis()); - - if (!ServiceUtils.publishTemperatureToDAS(owner, deviceId, messageData[1])) { log.error("MQTT Subscriber: Publishing data to DAS failed."); } diff --git a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/util/APIUtil.java b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/util/APIUtil.java index 66914921..0dd601ed 100644 --- a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/util/APIUtil.java +++ b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/util/APIUtil.java @@ -21,6 +21,7 @@ package org.homeautomation.firealarm.api.util; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; /** * This class provides utility functions used by REST-API. @@ -64,4 +65,16 @@ public class APIUtil { } return apiManagementProviderService; } + + public static JWTClientManagerService getJWTClientManagerService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + JWTClientManagerService jwtClientManagerService = + (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null); + if (jwtClientManagerService == null) { + String msg = "JWT Client manager service has not initialized."; + throw new IllegalStateException(msg); + } + return jwtClientManagerService; + } + } diff --git a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/util/ServiceUtils.java b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/util/ServiceUtils.java index 536e187d..d2642043 100644 --- a/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/util/ServiceUtils.java +++ b/modules/samples/firealarm/component/api/src/main/java/org/homeautomation/firealarm/api/util/ServiceUtils.java @@ -21,7 +21,7 @@ package org.homeautomation.firealarm.api.util; import org.homeautomation.firealarm.plugin.constants.DeviceTypeConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService; +import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; public class ServiceUtils { @@ -67,8 +67,8 @@ public class ServiceUtils { if (ctx.getTenantDomain(true) == null) { ctx.setTenantDomain("carbon.super", true); } - DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( - DeviceAnalyticsService.class, null); + EventsPublisherService deviceAnalyticsService = (EventsPublisherService) ctx.getOSGiService( + EventsPublisherService.class, null); Object metaData[] = {owner, DeviceTypeConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; try { deviceAnalyticsService.publishEvent(definition, SENSOR_STREAM_VERSION, metaData, diff --git a/modules/samples/firealarm/component/api/src/main/webapp/WEB-INF/web.xml b/modules/samples/firealarm/component/api/src/main/webapp/WEB-INF/web.xml index 7f6126d2..0cff816a 100644 --- a/modules/samples/firealarm/component/api/src/main/webapp/WEB-INF/web.xml +++ b/modules/samples/firealarm/component/api/src/main/webapp/WEB-INF/web.xml @@ -23,13 +23,10 @@ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> Sample-Webapp-Controller + - JAX-WS/JAX-RS Endpoint - JAX-WS/JAX-RS Servlet CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - + org.apache.cxf.transport.servlet.CXFServlet 1 @@ -42,27 +39,25 @@ doAuthentication - false - - - - managed-api-enabled true - managed-api-owner - admin + isSharedWithAllTenants + true - managed-api-context-template - /firealarm/{version} + providerTenantDomain + carbon.super + + - managed-api-application - firealarm + managed-api-enabled + true - managed-api-isSecured - true + managed-api-owner + admin +