From d28a2bf4b32e741f709563ca1a1b3ab0b12327bc Mon Sep 17 00:00:00 2001 From: Shabirmean Date: Sat, 14 Nov 2015 18:23:48 +0530 Subject: [PATCH] Changes for the FireAlarmService to work with real device and SCEP service inclusions --- .../Agent/sketch/deviceConfig.properties | 7 +- .../plugin/constants/FireAlarmConstants.java | 7 + .../service/impl/FireAlarmService.java | 603 +++--- .../impl/{util => dto}/DeviceJSON.java | 2 +- .../transport/FireAlarmMQTTSubscriber.java | 110 ++ .../transport/FireAlarmXMPPConnector.java | 120 ++ .../impl/util/MQTTFirealarmSubscriber.java | 89 - .../src/main/webapp/META-INF/resources.xml | 105 + .../src/main/webapp/WEB-INF/cxf-servlet.xml | 14 +- modules/samples/pom.xml | 9 + .../pom.xml | 30 +- .../service/impl/VirtualFireAlarmService.java | 1745 +++++++++-------- .../VirtualFireAlarmEnrollmentException.java | 13 + .../VirtualFireAlarmMQTTSubscriber.java | 2 +- .../VirtualFireAlarmXMPPConnector.java | 5 +- .../service/impl/util/ContentType.java | 8 + .../util/VirtualFireAlarmServiceUtils.java | 29 + .../service/impl/util/scep/SCEPOperation.java | 21 + .../src/main/webapp/WEB-INF/cxf-servlet.xml | 4 +- 19 files changed, 1681 insertions(+), 1242 deletions(-) rename modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/{util => dto}/DeviceJSON.java (98%) create mode 100644 modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/transport/FireAlarmMQTTSubscriber.java create mode 100644 modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/transport/FireAlarmXMPPConnector.java delete mode 100644 modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/MQTTFirealarmSubscriber.java create mode 100644 modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/META-INF/resources.xml create mode 100644 modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/exception/VirtualFireAlarmEnrollmentException.java rename modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/{util => transport}/VirtualFireAlarmMQTTSubscriber.java (99%) rename modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/{util => transport}/VirtualFireAlarmXMPPConnector.java (94%) create mode 100644 modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/ContentType.java create mode 100644 modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/VirtualFireAlarmServiceUtils.java create mode 100644 modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/scep/SCEPOperation.java diff --git a/modules/samples/firealarm/Agent/sketch/deviceConfig.properties b/modules/samples/firealarm/Agent/sketch/deviceConfig.properties index 4af8602c..dd8500b6 100644 --- a/modules/samples/firealarm/Agent/sketch/deviceConfig.properties +++ b/modules/samples/firealarm/Agent/sketch/deviceConfig.properties @@ -18,15 +18,16 @@ #[Device-Configurations] owner=${DEVICE_OWNER} deviceId=${DEVICE_ID} -server-ep=${SERVER_EP} -service-ep=${SERVICE_EP} +device-name=${DEVICE_NAME} +controller-context=/firealarm/controller +https-ep=${HTTPS_EP} +http-ep=${HTTP_EP} apim-ep=${APIM_EP} mqtt-ep=${MQTT_EP} xmpp-ep=${XMPP_EP} auth-method=token auth-token=${DEVICE_TOKEN} refresh-token=${DEVICE_REFRESH_TOKEN} -network-interface=wlan0 push-interval=15 diff --git a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/constants/FireAlarmConstants.java b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/constants/FireAlarmConstants.java index 8725e4df..a2070809 100644 --- a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/constants/FireAlarmConstants.java +++ b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/constants/FireAlarmConstants.java @@ -22,4 +22,11 @@ public class FireAlarmConstants { public final static String DEVICE_PLUGIN_DEVICE_ID = "FIREALARM_DEVICE_ID"; public final static String STATE_ON = "ON"; public final static String STATE_OFF = "OFF"; + + public static final String URL_PREFIX = "http://"; + public static final String BULB_CONTEXT = "/BULB/"; + public static final String SONAR_CONTEXT = "/HUMIDITY/"; + public static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/"; + + public static final String SENSOR_TEMPERATURE = "temperature"; } diff --git a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmService.java b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmService.java index 4d17b8cb..de00b50c 100644 --- a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmService.java +++ b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmService.java @@ -41,12 +41,19 @@ import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppServerClient; import org.wso2.carbon.device.mgt.iot.common.exception.AccessTokenException; import org.wso2.carbon.device.mgt.iot.common.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.iot.common.sensormgt.SensorDataManager; +import org.wso2.carbon.device.mgt.iot.common.sensormgt.SensorRecord; import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants.FireAlarmConstants; -import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.util.DeviceJSON; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.dto.DeviceJSON; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.transport + .FireAlarmMQTTSubscriber; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.transport + .FireAlarmXMPPConnector; import org.wso2.carbon.utils.CarbonUtils; +import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -73,6 +80,7 @@ import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.UUID; @@ -86,24 +94,67 @@ public class FireAlarmService { private static Log log = LogFactory.getLog(FireAlarmService.class); //TODO; replace this tenant domain - private final String SUPER_TENANT = "carbon.super"; + private static final String SUPER_TENANT = "carbon.super"; @Context //injected response proxy supporting multiple thread private HttpServletResponse response; private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature"; - private static final String URL_PREFIX = "http://"; - private static final String BULB_CONTEXT = "/BULB/"; - private static final String SONAR_CONTEXT = "/SONAR/"; - private static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/"; - public static final String XMPP_PROTOCOL = "XMPP"; public static final String HTTP_PROTOCOL = "HTTP"; public static final String MQTT_PROTOCOL = "MQTT"; + private static FireAlarmMQTTSubscriber fireAlarmMQTTSubscriber; + private static FireAlarmXMPPConnector fireAlarmXMPPConnector; private static ConcurrentHashMap deviceToIpMap = new ConcurrentHashMap(); + public void setFireAlarmXMPPConnector( + final FireAlarmXMPPConnector fireAlarmXMPPConnector) { + this.fireAlarmXMPPConnector = fireAlarmXMPPConnector; + + Runnable mqttStarter = new Runnable() { + @Override + public void run() { + fireAlarmXMPPConnector.initConnector(); + fireAlarmXMPPConnector.connectAndLogin(); + } + }; + + Thread mqttStarterThread = new Thread(mqttStarter); + mqttStarterThread.setDaemon(true); + mqttStarterThread.start(); + } + + public void setFireAlarmMQTTSubscriber( + final FireAlarmMQTTSubscriber fireAlarmMQTTSubscriber) { + this.fireAlarmMQTTSubscriber = fireAlarmMQTTSubscriber; + + Runnable xmppStarter = new Runnable() { + @Override + public void run() { + fireAlarmMQTTSubscriber.initConnector(); + fireAlarmMQTTSubscriber.connectAndSubscribe(); + } + }; + + Thread xmppStarterThread = new Thread(xmppStarter); + xmppStarterThread.setDaemon(true); + xmppStarterThread.start(); + } + + public FireAlarmXMPPConnector getFireAlarmXMPPConnector() { + return fireAlarmXMPPConnector; + } + + public FireAlarmMQTTSubscriber getFireAlarmMQTTSubscriber() { + return fireAlarmMQTTSubscriber; + } + + /* --------------------------------------------------------------------------------------- + Device management specific APIs + Also contains utility methods required for the execution of these APIs + --------------------------------------------------------------------------------------- */ @Path("manager/device/register") @PUT public boolean register(@QueryParam("deviceId") String deviceId, @@ -281,7 +332,7 @@ public class FireAlarmService { public Response downloadSketch(@QueryParam("owner") String owner, @QueryParam("deviceName") String customDeviceName, @PathParam("sketch_type") String sketchType) { - + //TODO:: null check customDeviceName at UI level ZipArchive zipFile = null; try { zipFile = createDownloadFile(owner, customDeviceName, sketchType); @@ -335,7 +386,6 @@ public class FireAlarmService { TokenClient accessTokenClient = new TokenClient(FireAlarmConstants.DEVICE_TYPE); AccessTokenInfo accessTokenInfo = null; - accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); //create token @@ -343,8 +393,6 @@ public class FireAlarmService { String refreshToken = accessTokenInfo.getRefresh_token(); //adding registering data - - XmppAccount newXmppAccount = new XmppAccount(); newXmppAccount.setAccountName(owner + "_" + deviceId); newXmppAccount.setUsername(deviceId); @@ -354,21 +402,24 @@ public class FireAlarmService { XmppServerClient xmppServerClient = new XmppServerClient(); xmppServerClient.initControlQueue(); boolean status; + if(XmppConfig.getInstance().isEnabled()) { status = xmppServerClient.createXMPPAccount(newXmppAccount); - if (!status) { String msg = "XMPP Account was not created for device - " + deviceId + " of owner - " + owner + - ". XMPP might have been disabled in org.wso2.carbon.device.mgt.iot.common.config.server.configs"; + ".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot" + + ".common.config.server.configs"; log.warn(msg); throw new DeviceManagementException(msg); } } + //Register the device with CDMF String deviceName = customDeviceName + "_" + deviceId; status = register(deviceId, deviceName, owner); + if (!status) { String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner; @@ -378,8 +429,8 @@ public class FireAlarmService { ZipUtil ziputil = new ZipUtil(); ZipArchive zipFile = null; - - zipFile = ziputil.downloadSketch(owner,SUPER_TENANT, sketchType, deviceId, deviceName, accessToken, refreshToken); + zipFile = ziputil.downloadSketch(owner, SUPER_TENANT, sketchType, deviceId, deviceName, + accessToken, refreshToken); zipFile.setDeviceId(deviceId); return zipFile; } @@ -390,18 +441,27 @@ public class FireAlarmService { return Long.toString(l, Character.MAX_RADIX); } - @Path("controller/register/{owner}/{deviceId}/{ip}") + /* --------------------------------------------------------------------------------------- + Device specific APIs - Control APIs + Data-Publishing APIs + Also contains utility methods required for the execution of these APIs + --------------------------------------------------------------------------------------- */ + @Path("controller/register/{owner}/{deviceId}/{ip}/{port}") @POST public String registerDeviceIP(@PathParam("owner") String owner, @PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP, - @Context HttpServletResponse response) { + @PathParam("port") String devicePort, + @Context HttpServletResponse response, + @Context HttpServletRequest request) { + + //TODO:: Need to get IP from the request itself String result; log.info("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: " + owner); - deviceToIpMap.put(deviceId, deviceIP); + String deviceHttpEndpoint = deviceIP + ":" + devicePort; + deviceToIpMap.put(deviceId, deviceHttpEndpoint); result = "Device-IP Registered"; response.setStatus(Response.Status.OK.getStatusCode()); @@ -413,9 +473,8 @@ public class FireAlarmService { return result; } - - /* Service to switch "ON" and "OFF" the FireAlarm bulb - Called by an external client intended to control the FireAlarm bulb */ + /* Service to switch "ON" and "OFF" the Virtual FireAlarm bulb + Called by an external client intended to control the Virtual FireAlarm bulb */ @Path("controller/bulb/{state}") @POST public void switchBulb(@HeaderParam("owner") String owner, @@ -446,43 +505,41 @@ public class FireAlarmService { return; } - String deviceIP = deviceToIpMap.get(deviceId); - if (deviceIP == null) { - response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); - return; - } - String protocolString = protocol.toUpperCase(); - String callUrlPattern = BULB_CONTEXT + switchToState; + String callUrlPattern = FireAlarmConstants.BULB_CONTEXT + switchToState; - log.info("Sending command: '" + callUrlPattern + "' to firealarm at: " + deviceIP + " " + - "via" + " " + protocolString); + if (log.isDebugEnabled()) { + log.debug("Sending request to switch-bulb of device [" + deviceId + "] via " + + protocolString); + } try { switch (protocolString) { case HTTP_PROTOCOL: - sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true); + String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); + if (deviceHTTPEndpoint == null) { + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return; + } + + sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true); break; case MQTT_PROTOCOL: - sendCommandViaMQTT(owner, deviceId, BULB_CONTEXT.replace("/", ""), + sendCommandViaMQTT(owner, deviceId, + FireAlarmConstants.BULB_CONTEXT.replace("/", ""), switchToState); break; case XMPP_PROTOCOL: -// requestBulbChangeViaXMPP(switchToState, response); - sendCommandViaXMPP(owner, deviceId, BULB_CONTEXT, switchToState); + sendCommandViaXMPP(owner, deviceId, FireAlarmConstants.BULB_CONTEXT, + switchToState); break; default: - if (protocolString == null) { - sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true); - } else { response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); return; } - break; - } } catch (DeviceManagementException e) { - log.error("Failed to send command '" + callUrlPattern + "' to: " + deviceIP + " via" + - " " + protocol); + log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " + + protocolString); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); return; } @@ -513,43 +570,44 @@ public class FireAlarmService { return replyMsg; } - String deviceIp = deviceToIpMap.get(deviceId); + String protocolString = protocol.toUpperCase(); - if (deviceIp == null) { - replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner; - response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); - return replyMsg; + if (log.isDebugEnabled()) { + log.debug("Sending request to read sonar value of device [" + deviceId + "] via " + + protocolString); } try { - switch (protocol) { + switch (protocolString) { case HTTP_PROTOCOL: - log.info("Sending request to read sonar value at : " + deviceIp + - " via " + HTTP_PROTOCOL); - - replyMsg = sendCommandViaHTTP(deviceIp, 80, SONAR_CONTEXT, false); + String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); + if (deviceHTTPEndpoint == null) { + replyMsg = + "IP not registered for device: " + deviceId + " of owner: " + owner; + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return replyMsg; + } + + replyMsg = sendCommandViaHTTP(deviceHTTPEndpoint, + FireAlarmConstants.SONAR_CONTEXT, false); break; + case MQTT_PROTOCOL: + sendCommandViaMQTT(owner, deviceId, + FireAlarmConstants.SONAR_CONTEXT.replace("/", ""), + ""); + break; + case XMPP_PROTOCOL: - log.info("Sending request to read sonar value at : " + deviceIp + - " via " + - XMPP_PROTOCOL); - replyMsg = sendCommandViaXMPP(owner, deviceId, SONAR_CONTEXT, "."); + sendCommandViaXMPP(owner, deviceId, FireAlarmConstants.SONAR_CONTEXT, + ""); break; default: - if (protocol == null) { - log.info("Sending request to read sonar value at : " + deviceIp + - " via " + HTTP_PROTOCOL); - - replyMsg = sendCommandViaHTTP(deviceIp, 80, SONAR_CONTEXT, false); - } else { - replyMsg = "Requested protocol '" + protocol + "' is not supported"; + replyMsg = "Requested protocol '" + protocolString + "' is not supported"; response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); return replyMsg; } - break; - } } catch (DeviceManagementException e) { replyMsg = e.getErrorMessage(); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); @@ -564,11 +622,13 @@ public class FireAlarmService { @Path("controller/readtemperature") @GET - public String requestTemperature(@HeaderParam("owner") String owner, + @Consumes("application/json") + @Produces("application/json") + public SensorRecord requestTemperature(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, @HeaderParam("protocol") String protocol, @Context HttpServletResponse response) { - String replyMsg = ""; + SensorRecord sensorRecord = null; DeviceValidator deviceValidator = new DeviceValidator(); try { @@ -576,117 +636,72 @@ public class FireAlarmService { FireAlarmConstants .DEVICE_TYPE))) { response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); - return "Unauthorized Access"; } } catch (DeviceManagementException e) { - replyMsg = e.getErrorMessage(); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return replyMsg; } - String deviceIp = deviceToIpMap.get(deviceId); + String protocolString = protocol.toUpperCase(); - if (deviceIp == null) { - replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner; - response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); - return replyMsg; + if (log.isDebugEnabled()) { + log.debug( + "Sending request to read virtual-firealarm-temperature of device [" + + deviceId + + "] via " + protocolString); } try { - switch (protocol) { + switch (protocolString) { case HTTP_PROTOCOL: - log.info("Sending request to read firealarm-temperature at : " + deviceIp + - " via " + HTTP_PROTOCOL); - - replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false); + String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); + if (deviceHTTPEndpoint == null) { + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + } + String tString = sendCommandViaHTTP(deviceHTTPEndpoint, + FireAlarmConstants + .TEMPERATURE_CONTEXT, + false); + String temperatureValue = tString; + SensorDataManager.getInstance().setSensorRecord(deviceId, + FireAlarmConstants + .SENSOR_TEMPERATURE, + temperatureValue, + Calendar.getInstance() + .getTimeInMillis()); break; + case MQTT_PROTOCOL: + sendCommandViaMQTT(owner, deviceId, + FireAlarmConstants.TEMPERATURE_CONTEXT.replace("/", + ""), + ""); + break; + case XMPP_PROTOCOL: - log.info("Sending request to read firealarm-temperature at : " + deviceIp + - " via " + - XMPP_PROTOCOL); - replyMsg = sendCommandViaXMPP(owner, deviceId, TEMPERATURE_CONTEXT, "."); -// replyMsg = requestTemperatureViaXMPP(response); + sendCommandViaXMPP(owner, deviceId, FireAlarmConstants + .TEMPERATURE_CONTEXT, ""); break; default: - if (protocol == null) { - log.info("Sending request to read firealarm-temperature at : " + deviceIp + - " via " + HTTP_PROTOCOL); - - replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false); - } else { - replyMsg = "Requested protocol '" + protocol + "' is not supported"; response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); - return replyMsg; } - break; - } + sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, + FireAlarmConstants.SENSOR_TEMPERATURE); } catch (DeviceManagementException e) { - replyMsg = e.getErrorMessage(); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return replyMsg; + } catch (DeviceControllerException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } response.setStatus(Response.Status.OK.getStatusCode()); - replyMsg = "The current temperature of the device is " + replyMsg; - return replyMsg; + return sensorRecord; } - -// public String requestTemperatureViaXMPP(@Context HttpServletResponse response) { -// String replyMsg = ""; -// -// String sep = File.separator; -// String scriptsFolder = "repository" + sep + "resources" + sep + "scripts"; -// String scriptPath = CarbonUtils.getCarbonHome() + sep + scriptsFolder + sep -// + "xmpp_client.py -r Temperature"; -// String command = "python " + scriptPath; -// -// replyMsg = executeCommand(command); -// -// response.setStatus(HttpStatus.SC_OK); -// return replyMsg; -// } - - -// public String requestSonarViaXMPP(@Context HttpServletResponse response) { -// String replyMsg = ""; -// -// String sep = File.separator; -// String scriptsFolder = "repository" + sep + "resources" + sep + "scripts"; -// String scriptPath = CarbonUtils.getCarbonHome() + sep + scriptsFolder + sep -// + "xmpp_client.py -r Sonar"; -// String command = "python " + scriptPath; -// -// replyMsg = executeCommand(command); -// -// response.setStatus(HttpStatus.SC_OK); -// return replyMsg; -// } - - -// public String requestBulbChangeViaXMPP(String state, -// @Context HttpServletResponse response) { -// String replyMsg = ""; -// -// String sep = File.separator; -// String scriptsFolder = "repository" + sep + "resources" + sep + "scripts"; -// String scriptPath = CarbonUtils.getCarbonHome() + sep + scriptsFolder + sep -// + "xmpp_client.py -r Bulb -s " + state; -// String command = "python " + scriptPath; -// -// replyMsg = executeCommand(command); -// -// response.setStatus(HttpStatus.SC_OK); -// return replyMsg; -// } - - @Path("/controller/push_temperature") + @Path("controller/push_temperature") @POST @Consumes(MediaType.APPLICATION_JSON) - public void pushTemperatureData( - final DeviceJSON dataMsg, @Context HttpServletResponse response) { + public void pushTemperatureData(final DeviceJSON dataMsg, + @Context HttpServletResponse response) { boolean result; String deviceId = dataMsg.deviceId; String deviceIp = dataMsg.reply; @@ -701,227 +716,29 @@ public class FireAlarmService { 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"); + deviceId + + " is already registered under some other IP. Re-registration " + + "required"); response.setStatus(Response.Status.CONFLICT.getStatusCode()); return; } + SensorDataManager.getInstance().setSensorRecord(deviceId, + FireAlarmConstants + .SENSOR_TEMPERATURE, + String.valueOf(temperature), + Calendar.getInstance().getTimeInMillis()); - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - ctx.setTenantDomain(SUPER_TENANT, true); - DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx - .getOSGiService(DeviceAnalyticsService.class, null); - Object metdaData[] = {dataMsg.owner, FireAlarmConstants.DEVICE_TYPE, dataMsg.deviceId, - System.currentTimeMillis()}; - Object payloadData[] = {temperature}; - try { - deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", - metdaData, new Object[0], payloadData); - } catch (DataPublisherConfigurationException e) { + if (!publishToDAS(dataMsg.owner, dataMsg.deviceId, dataMsg.value)) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - - } finally { - PrivilegedCarbonContext.endTenantFlow(); } - } - - /* Service to push all the sensor data collected by the FireAlarm - Called by the FireAlarm device */ - -// @Path("/pushalarmdata") -// @POST -// @Consumes(MediaType.APPLICATION_JSON) -// public void pushAlarmData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { -// boolean result; -// String sensorValues = dataMsg.value; -// log.info("Recieved Sensor Data Values: " + sensorValues); -// -// String sensors[] = sensorValues.split(":"); -// try { -// if (sensors.length == 3) { -// String temperature = sensors[0]; -// String bulb = sensors[1]; -// String sonar = sensors[2]; - -// sensorValues = "Temperature:" + temperature + "C\tBulb Status:" + bulb + -// "\t\tSonar Status:" + sonar; -// log.info(sensorValues); -// DeviceController deviceController = new DeviceController(); -// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants -// .DEVICE_TYPE, -// dataMsg.deviceId, -// System.currentTimeMillis(), "DeviceData", -// temperature, "TEMPERATURE"); -// -// if (!result) { -// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); -// log.error("Error whilst pushing temperature: " + sensorValues); -// return; -// } -// -// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants -// .DEVICE_TYPE, -// dataMsg.deviceId, -// System.currentTimeMillis(), "DeviceData", -// bulb, -// "BULB"); -// -// if (!result) { -// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); -// log.error("Error whilst pushing Bulb data: " + sensorValues); -// return; -// } -// -// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants -// .DEVICE_TYPE, -// dataMsg.deviceId, -// System.currentTimeMillis(), "DeviceData", -// sonar, -// "SONAR"); -// -// if (!result) { -// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); -// log.error("Error whilst pushing Sonar data: " + sensorValues); -// } -// -// } else { -// DeviceController deviceController = new DeviceController(); -// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants -// .DEVICE_TYPE, -// dataMsg.deviceId, -// System.currentTimeMillis(), "DeviceData", -// dataMsg.value, dataMsg.reply); -// if (!result) { -// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); -// log.error("Error whilst pushing sensor data: " + sensorValues); -// } -// } -// -// } catch (UnauthorizedException e) { -// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); -// log.error("Data Push Attempt Failed at Publisher: " + e.getMessage()); -// } -// } - - - private String sendCommandViaXMPP(String deviceOwner, String deviceId, String resource, - String state) throws DeviceManagementException { - - String replyMsg = ""; - String scriptArguments = ""; - String command = ""; - - String seperator = File.separator; - String xmppServerURL = XmppConfig.getInstance().getXmppEndpoint(); - int indexOfChar = xmppServerURL.lastIndexOf(seperator); - if (indexOfChar != -1) { - xmppServerURL = xmppServerURL.substring((indexOfChar + 1), xmppServerURL.length()); - } - - indexOfChar = xmppServerURL.indexOf(":"); - if (indexOfChar != -1) { - xmppServerURL = xmppServerURL.substring(0, indexOfChar); - } - - String xmppAdminUName = XmppConfig.getInstance().getXmppUsername(); - String xmppAdminPass = XmppConfig.getInstance().getXmppPassword(); - - String xmppAdminUserLogin = xmppAdminUName + "@" + xmppServerURL + seperator + deviceOwner; - String clientToConnect = deviceId + "@" + xmppServerURL + seperator + deviceOwner; - - String scriptsFolder = "repository" + seperator + "resources" + seperator + "scripts"; - String scriptPath = CarbonUtils.getCarbonHome() + seperator + scriptsFolder + seperator - + "xmpp_client.py "; - - scriptArguments = - "-j " + xmppAdminUserLogin + " -p " + xmppAdminPass + " -c " + clientToConnect + - " -r " + resource + " -s " + state; - command = "python " + scriptPath + scriptArguments; - - if (log.isDebugEnabled()) { - log.debug("Connecting to XMPP Server via Admin credentials: " + xmppAdminUserLogin); - log.debug("Trying to contact xmpp device account: " + clientToConnect); - log.debug("Arguments used for the scripts: '" + scriptArguments + "'"); - log.debug("Command exceuted: '" + command + "'"); - } - -// switch (resource) { -// case BULB_CONTEXT: -// scriptArguments = "-r Bulb -s " + state; -// command = "python " + scriptPath + scriptArguments; -// break; -// case SONAR_CONTEXT: -// scriptArguments = "-r Sonar"; -// command = "python " + scriptPath + scriptArguments; -// break; -// case TEMPERATURE_CONTEXT: -// scriptArguments = "-r Temperature"; -// command = "python " + scriptPath + scriptArguments; -// break; -// } - - replyMsg = executeCommand(command); - return replyMsg; - } - - - private String executeCommand(String command) { - StringBuffer output = new StringBuffer(); - - Process p; - try { - p = Runtime.getRuntime().exec(command); - p.waitFor(); - BufferedReader reader = - new BufferedReader(new InputStreamReader(p.getInputStream())); - - String line = ""; - while ((line = reader.readLine()) != null) { - output.append(line + "\n"); - } - - } catch (Exception e) { - log.info(e.getMessage(), e); - } - - return output.toString(); - - } - - - private boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource, - String state) throws DeviceManagementException { - - boolean result = false; - DeviceController deviceController = new DeviceController(); - - try { - result = deviceController.publishMqttControl(deviceOwner, - FireAlarmConstants.DEVICE_TYPE, - deviceId, resource, state); - } catch (DeviceControllerException e) { - String errorMsg = "Error whilst trying to publish to MQTT Queue"; - log.error(errorMsg); - throw new DeviceManagementException(errorMsg, e); - } - return result; - } - - - private String sendCommandViaHTTP(final String deviceIp, int deviceServerPort, - String callUrlPattern, - boolean fireAndForgot) - throws DeviceManagementException { - - if (deviceServerPort == 0) { - deviceServerPort = 80; - } + private String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext, + boolean fireAndForgot) throws DeviceManagementException { String responseMsg = ""; - String urlString = URL_PREFIX + deviceIp + ":" + deviceServerPort + callUrlPattern; + String urlString = FireAlarmConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext; if (log.isDebugEnabled()) { log.debug(urlString); @@ -986,13 +803,54 @@ public class FireAlarmService { } } } - } return responseMsg; } - /* Utility methods relevant to creating and sending http requests */ + + private boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource, + String state) throws DeviceManagementException { + + boolean result = false; + DeviceController deviceController = new DeviceController(); + + try { + result = deviceController.publishMqttControl(deviceOwner, + FireAlarmConstants.DEVICE_TYPE, + deviceId, resource, state); + } catch (DeviceControllerException e) { + String errorMsg = "Error whilst trying to publish to MQTT Queue"; + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + return result; + } + + private void sendCommandViaXMPP(String deviceOwner, String deviceId, String resource, + String state) throws DeviceManagementException { + + String xmppServerDomain = XmppConfig.getInstance().getXmppEndpoint(); + int indexOfChar = xmppServerDomain.lastIndexOf(File.separator); + if (indexOfChar != -1) { + xmppServerDomain = xmppServerDomain.substring((indexOfChar + 1), + xmppServerDomain.length()); + } + + indexOfChar = xmppServerDomain.indexOf(":"); + if (indexOfChar != -1) { + xmppServerDomain = xmppServerDomain.substring(0, indexOfChar); + } + + String clientToConnect = deviceId + "@" + xmppServerDomain + File.separator + deviceOwner; + String message = resource.replace("/", "") + ":" + state; + + fireAlarmXMPPConnector.sendXMPPMessage(clientToConnect, message, "CONTROL-REQUEST"); + } + + /* --------------------------------------------------------------------------------------- + Utility methods relevant to creating and sending http requests + --------------------------------------------------------------------------------------- */ /* This methods creates and returns a http connection object */ @@ -1061,4 +919,25 @@ public class FireAlarmService { return completeResponse.toString(); } + public static boolean publishToDAS(String owner, String deviceId, float temperature) { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ctx.setTenantDomain(SUPER_TENANT, true); + DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( + DeviceAnalyticsService.class, null); + Object metdaData[] = {owner, FireAlarmConstants.DEVICE_TYPE, deviceId, + System.currentTimeMillis()}; + Object payloadData[] = {temperature}; + + try { + deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData, + new Object[0], payloadData); + } catch (DataPublisherConfigurationException e) { + return false; + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + return true; + } + } diff --git a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/DeviceJSON.java b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/dto/DeviceJSON.java similarity index 98% rename from modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/DeviceJSON.java rename to modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/dto/DeviceJSON.java index 2f6da159..97fd0278 100644 --- a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/DeviceJSON.java +++ b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/dto/DeviceJSON.java @@ -1,4 +1,4 @@ -package org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.util; +package org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.dto; import org.codehaus.jackson.annotate.JsonIgnoreProperties; diff --git a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/transport/FireAlarmMQTTSubscriber.java b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/transport/FireAlarmMQTTSubscriber.java new file mode 100644 index 00000000..6037242d --- /dev/null +++ b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/transport/FireAlarmMQTTSubscriber.java @@ -0,0 +1,110 @@ +package org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.transport; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.mqtt.MqttConfig; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.mqtt.MqttSubscriber; +import org.wso2.carbon.device.mgt.iot.common.sensormgt.SensorDataManager; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants.FireAlarmConstants; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.FireAlarmService; + +import java.io.File; +import java.util.Calendar; +import java.util.UUID; + +public class FireAlarmMQTTSubscriber extends MqttSubscriber { + private static Log log = LogFactory.getLog(FireAlarmMQTTSubscriber.class); + + private static final String subscribeTopic = + "wso2" + File.separator + "iot" + File.separator + "+" + File.separator + + FireAlarmConstants.DEVICE_TYPE + File.separator + "+" + File.separator + + "publisher"; + + private static final String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5); + private static String mqttEndpoint; + + private FireAlarmMQTTSubscriber() { + super(iotServerSubscriber, FireAlarmConstants.DEVICE_TYPE, + MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic); + } + + public void initConnector() { + mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint(); + } + + public void connectAndSubscribe() { + try { + super.connectAndSubscribe(); + } catch (DeviceManagementException e) { + log.error("Subscription to MQTT Broker at: " + mqttEndpoint + " failed"); + retryMQTTSubscription(); + } + } + + @Override + protected void postMessageArrived(String topic, MqttMessage message) { + String ownerAndId = topic.replace("wso2" + File.separator + "iot" + File.separator, ""); + ownerAndId = ownerAndId.replace(File.separator + FireAlarmConstants.DEVICE_TYPE + File.separator, ":"); + ownerAndId = ownerAndId.replace(File.separator + "publisher", ""); + + String owner = ownerAndId.split(":")[0]; + String deviceId = ownerAndId.split(":")[1]; + + log.info("Received MQTT message for: {OWNER-" + owner + "} & {DEVICE.ID-" + deviceId + "}"); + + if (message.toString().contains("PUBLISHER")) { + log.info("MQTT: Publisher Message [" + message.toString() + "] topic: [" + topic + "]"); + + float temperature = Float.parseFloat(message.toString().split(":")[2]); + if(!FireAlarmService.publishToDAS(owner, deviceId, temperature)) { + log.error("MQTT Subscriber: Publishing data to DAS failed."); + } + + if(log.isDebugEnabled()) { + log.debug("MQTT Subscriber: Published data to DAS successfully."); + } + } else if (message.toString().contains("TEMPERATURE")) { + log.info("MQTT: Reply Message [" + message.toString() + "] topic: [" + topic + "]"); + String temperatureValue = message.toString().split(":")[1]; + SensorDataManager.getInstance().setSensorRecord(deviceId, FireAlarmConstants.SENSOR_TEMPERATURE, temperatureValue, Calendar.getInstance().getTimeInMillis()); + } else { + log.info("MQTT: Message [" + message.toString() + "] topic: [" + topic + "]"); + } + } + + private void retryMQTTSubscription() { + Thread retryToSubscribe = new Thread() { + @Override + public void run() { + while (true) { + if (!isConnected()) { + if (log.isDebugEnabled()) { + log.debug("Subscriber re-trying to reach MQTT queue...."); + } + + try { + FireAlarmMQTTSubscriber.super.connectAndSubscribe(); + } catch (DeviceManagementException e1) { + if (log.isDebugEnabled()) { + log.debug("Attempt to re-connect to MQTT-Queue failed"); + } + } + } else { + break; + } + + try { + Thread.sleep(5000); + } catch (InterruptedException e1) { + log.error("MQTT: Thread S;eep Interrupt Exception"); + } + } + } + }; + + retryToSubscribe.setDaemon(true); + retryToSubscribe.start(); + } +} diff --git a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/transport/FireAlarmXMPPConnector.java b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/transport/FireAlarmXMPPConnector.java new file mode 100644 index 00000000..06b86ae7 --- /dev/null +++ b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/transport/FireAlarmXMPPConnector.java @@ -0,0 +1,120 @@ +package org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.transport; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jivesoftware.smack.packet.Message; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConnector; +import org.wso2.carbon.device.mgt.iot.common.sensormgt.SensorDataManager; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants + .FireAlarmConstants; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.FireAlarmService; + +import java.util.Calendar; + +public class FireAlarmXMPPConnector extends XmppConnector { + private static Log log = LogFactory.getLog(FireAlarmXMPPConnector.class); + + private static String xmppServerIP; + // private static int xmppServerPort; + private static String xmppAdminUsername; + private static String xmppAdminPassword; + private static String xmppAdminAccountJID; + + private FireAlarmXMPPConnector() { + super(XmppConfig.getInstance().getXmppServerIP(), + XmppConfig.getInstance().getSERVER_CONNECTION_PORT()); + } + + public void initConnector() { + xmppServerIP = XmppConfig.getInstance().getXmppServerIP(); + xmppAdminUsername = XmppConfig.getInstance().getXmppUsername(); + xmppAdminPassword = XmppConfig.getInstance().getXmppPassword(); + xmppAdminAccountJID = xmppAdminUsername + "@" + xmppServerIP; + } + + public void connectAndLogin() { + try { + super.connectAndLogin(xmppAdminUsername, xmppAdminPassword, null); + super.setMessageFilterOnReceiver(xmppAdminAccountJID); + } catch (DeviceManagementException e) { + log.error("Connect/Login attempt to XMPP Server at: " + xmppServerIP + " failed"); + retryXMPPConnection(); + } + } + + @Override + protected void processXMPPMessage(Message xmppMessage) { + String from = xmppMessage.getFrom(); + String subject = xmppMessage.getSubject(); + String message = xmppMessage.getBody(); + + int indexOfAt = from.indexOf("@"); + int indexOfSlash = from.indexOf("/"); + + String deviceId = from.substring(0, indexOfAt); + String owner = from.substring(indexOfSlash + 1, from.length()); + + log.info("Received XMPP message for: {OWNER-" + owner + "} & {DEVICE.ID-" + deviceId + "}"); + + if (subject.equals("PUBLISHER")) { + log.info("XMPP: Publisher Message [" + message + "] from [" + from + "]"); + + float temperature = Float.parseFloat(message.split(":")[1]); + if(!FireAlarmService.publishToDAS(owner, deviceId, temperature)) { + log.error("XMPP Connector: Publishing data to DAS failed."); + } + + if(log.isDebugEnabled()) { + log.debug("XMPP Connector: Published data to DAS successfully."); + } + } else if(subject.equals("CONTROL-REPLY")) { + log.info("XMPP: Reply Message [" + message + "] from [" + from + "]"); + String temperature = message.split(":")[1]; + SensorDataManager.getInstance().setSensorRecord(deviceId,FireAlarmConstants.SENSOR_TEMPERATURE, temperature, Calendar.getInstance().getTimeInMillis()); + } else { + log.info("SOME XMPP Message [" + message + "] from " + from + "]"); + } + + } + + private void retryXMPPConnection() { + Thread retryToConnect = new Thread() { + @Override + public void run() { + + while (true) { + if (!isConnected()) { + if (log.isDebugEnabled()) { + log.debug("Re-trying to reach XMPP Server...."); + } + + try { + FireAlarmXMPPConnector.super.connectAndLogin(xmppAdminUsername, + xmppAdminPassword, + null); + FireAlarmXMPPConnector.super.setMessageFilterOnReceiver( + xmppAdminAccountJID); + } catch (DeviceManagementException e1) { + if (log.isDebugEnabled()) { + log.debug("Attempt to re-connect to XMPP-Server failed"); + } + } + } else { + break; + } + + try { + Thread.sleep(5000); + } catch (InterruptedException e1) { + log.error("XMPP: Thread Sleep Interrupt Exception"); + } + } + } + }; + + retryToConnect.setDaemon(true); + retryToConnect.start(); + } +} diff --git a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/MQTTFirealarmSubscriber.java b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/MQTTFirealarmSubscriber.java deleted file mode 100644 index b941a95c..00000000 --- a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/MQTTFirealarmSubscriber.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - *//* - - -package org.wso2.carbon.device.mgt.iot.firealarm.api.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eclipse.paho.client.mqttv3.MqttMessage; -import org.wso2.carbon.device.mgt.iot.common.controlqueue.mqtt.MqttSubscriber; -import org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService; -import org.wso2.carbon.device.mgt.iot.firealarm.constants.FireAlarmConstants; - -import java.io.File; -import java.util.LinkedList; - -public class MQTTFirealarmSubscriber extends MqttSubscriber { - - private static Log log = LogFactory.getLog(MQTTFirealarmSubscriber.class); - private static final String subscribetopic = - "wso2" + File.separator + "iot" + File.separator + "+" + File.separator + - FireAlarmConstants.DEVICE_TYPE + File.separator + "#"; - - private MQTTFirealarmSubscriber() { - super("Subscriber", FireAlarmConstants.DEVICE_TYPE, FireAlarmControllerService.CONTROL_QUEUE_ENDPOINT, - subscribetopic); - } - - @Override protected void postMessageArrived(final String topic, final MqttMessage message) { - - int lastIndex = topic.lastIndexOf("/"); - String deviceId = topic.substring(lastIndex + 1); - - lastIndex = message.toString().lastIndexOf(":"); - String msgContext = message.toString().substring(lastIndex + 1); - - LinkedList deviceControlList = null; - LinkedList replyMessageList = null; - - if (msgContext.equals("IN") || msgContext.equals(FireAlarmConstants.STATE_ON) || msgContext - .equals(FireAlarmConstants.STATE_OFF)) { - log.info("Recieved a control message: "); - log.info("Control message topic: " + topic); - log.info("Control message: " + message.toString()); - // synchronized (FireAlarmControllerService.internalControlsQueue) { - // deviceControlList = FireAlarmControllerService.internalControlsQueue.get(deviceId); - synchronized (FireAlarmControllerService.getInternalControlsQueue()) { - deviceControlList = FireAlarmControllerService.getInternalControlsQueue().get(deviceId); - if (deviceControlList == null) { - // FireAlarmControllerService.internalControlsQueue - FireAlarmControllerService.getInternalControlsQueue() - .put(deviceId, deviceControlList = new LinkedList()); - } - } - deviceControlList.add(message.toString()); - } else if (msgContext.equals("OUT")) { - log.info("Recieved reply from a device: "); - log.info("Reply message topic: " + topic); - log.info("Reply message: " + message.toString().substring(0, lastIndex)); - // synchronized (FireAlarmControllerService.replyMsgQueue) { - // replyMessageList = FireAlarmControllerService.replyMsgQueue.get(deviceId); - synchronized (FireAlarmControllerService.getReplyMsgQueue()) { - replyMessageList = FireAlarmControllerService.getReplyMsgQueue().get(deviceId); - if (replyMessageList == null) { - // FireAlarmControllerService.replyMsgQueue - FireAlarmControllerService.getReplyMsgQueue() - .put(deviceId, replyMessageList = new LinkedList()); - } - } - replyMessageList.add(message.toString()); - } - - } - -} -*/ diff --git a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/META-INF/resources.xml b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/META-INF/resources.xml new file mode 100644 index 00000000..8618fdec --- /dev/null +++ b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/META-INF/resources.xml @@ -0,0 +1,105 @@ + + + + + + + + Any + PUT + http://localhost:9763/firealarm/manager/device/register + /manager/device/register/* + + + Any + DELETE + http://localhost:9763/firealarm/manager/device/remove + /manager/device/remove/* + + + Any + POST + http://localhost:9763/firealarm/manager/device/update + /manager/device/update/* + + + Any + GET + http://localhost:9763/firealarm/manager/device + /manager/device/* + + + Any + GET + http://localhost:9763/firealarm/manager/devices + /manager/devices/* + + + Any + GET + http://localhost:9763/firealarm/manager/device/{sketch_type}/download + /manager/device/{sketch_type}/download + + + Any + GET + http://localhost:9763/firealarm/manager/device/{sketch_type}/generate_link + /manager/device/{sketch_type}/generate_link + + + + Any + POST + http://localhost:9763/firealarm/controller/register/{owner}/{deviceId}/{ip}/{port} + /controller/register/{owner}/{deviceId}/{ip}/{port} + + + Any + POST + http://localhost:9763/firealarm/controller/controller/bulb/{state} + /controller/bulb/{state} + + + Any + GET + http://localhost:9763/firealarm/controller/controller/readsonar + /controller/readsonar + + + Any + GET + http://localhost:9763/firealarm/controller/controller/readtemperature + /controller/readtemperature + + + Any + POST + http://localhost:9763/firealarm/controller/controller/push_temperature + /controller/push_temperature + + \ No newline at end of file diff --git a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml index 8b358030..53c0995d 100644 --- a/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/modules/samples/firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -25,7 +25,10 @@ + class="org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.FireAlarmService"> + + + @@ -33,8 +36,11 @@ - - - + + + + diff --git a/modules/samples/pom.xml b/modules/samples/pom.xml index 0138e327..0ef9b153 100644 --- a/modules/samples/pom.xml +++ b/modules/samples/pom.xml @@ -109,6 +109,13 @@ provided + + org.wso2.carbon.devicemgt + org.wso2.carbon.certificate.mgt.core + ${carbon.device.mgt.version} + provided + + @@ -334,6 +341,7 @@ provided + org.wso2.carbon org.wso2.carbon.utils @@ -457,6 +465,7 @@ 3.1.0.wso2v2 3.0.0.wso2v1 + 1.7 2.6.1 diff --git a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/pom.xml b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/pom.xml index b41c55ed..fb345427 100644 --- a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/pom.xml +++ b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/pom.xml @@ -25,8 +25,31 @@ org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.core + + + org.apache.axis2.wso2 + axis2-client + + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.analytics + + org.wso2.carbon.devicemgt + org.wso2.carbon.certificate.mgt.core + + + commons-codec.wso2 + commons-codec + + + + + org.apache.cxf @@ -151,10 +174,13 @@ + - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.analytics + commons-codec + commons-codec + ${commons-codec.version} + org.igniterealtime.smack.wso2 smack diff --git a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmService.java b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmService.java index f3a07204..a4d7329b 100644 --- a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmService.java +++ b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmService.java @@ -16,6 +16,7 @@ package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl; +import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; @@ -23,6 +24,9 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; +import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse; +import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService; @@ -45,20 +49,34 @@ import org.wso2.carbon.device.mgt.iot.common.sensormgt.SensorRecord; import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.constants.VirtualFireAlarmConstants; - import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.dto.DeviceJSON; -import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.VirtualFireAlarmMQTTSubscriber; -import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.VirtualFireAlarmXMPPConnector; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.exception.VirtualFireAlarmEnrollmentException; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.ContentType; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.transport.VirtualFireAlarmMQTTSubscriber; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.VirtualFireAlarmServiceUtils; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.transport.VirtualFireAlarmXMPPConnector; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.scep.SCEPOperation; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.BufferedReader; import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; @@ -66,7 +84,11 @@ import java.net.ProtocolException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; @@ -74,726 +96,757 @@ import java.util.concurrent.Future; //@Path("/VirtualFireAlarmDeviceManager") public class VirtualFireAlarmService { - private static Log log = LogFactory.getLog(VirtualFireAlarmService.class); - - //TODO; replace this tenant domain - private static final String SUPER_TENANT = "carbon.super"; - - @Context //injected response proxy supporting multiple thread - private HttpServletResponse response; - - private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature"; - public static final String XMPP_PROTOCOL = "XMPP"; - public static final String HTTP_PROTOCOL = "HTTP"; - public static final String MQTT_PROTOCOL = "MQTT"; - - private static VirtualFireAlarmMQTTSubscriber virtualFireAlarmMQTTSubscriber; - private static VirtualFireAlarmXMPPConnector virtualFireAlarmXMPPConnector; - private static ConcurrentHashMap deviceToIpMap = - new ConcurrentHashMap(); - - public void setVirtualFireAlarmXMPPConnector( - final VirtualFireAlarmXMPPConnector virtualFireAlarmXMPPConnector) { - this.virtualFireAlarmXMPPConnector = virtualFireAlarmXMPPConnector; - - Runnable mqttStarter = new Runnable() { - @Override - public void run() { - virtualFireAlarmXMPPConnector.initConnector(); - virtualFireAlarmXMPPConnector.connectAndLogin(); - } - }; - - Thread mqttStarterThread = new Thread(mqttStarter); - mqttStarterThread.setDaemon(true); - mqttStarterThread.start(); - } - - public void setVirtualFireAlarmMQTTSubscriber( - final VirtualFireAlarmMQTTSubscriber virtualFireAlarmMQTTSubscriber) { - this.virtualFireAlarmMQTTSubscriber = virtualFireAlarmMQTTSubscriber; - - Runnable xmppStarter = new Runnable() { - @Override - public void run() { - virtualFireAlarmMQTTSubscriber.initConnector(); - virtualFireAlarmMQTTSubscriber.connectAndSubscribe(); - } - }; - - Thread xmppStarterThread = new Thread(xmppStarter); - xmppStarterThread.setDaemon(true); - xmppStarterThread.start(); - } - - public VirtualFireAlarmXMPPConnector getVirtualFireAlarmXMPPConnector() { - return virtualFireAlarmXMPPConnector; - } - - public VirtualFireAlarmMQTTSubscriber getVirtualFireAlarmMQTTSubscriber() { - return virtualFireAlarmMQTTSubscriber; - } + private static Log log = LogFactory.getLog(VirtualFireAlarmService.class); - /* --------------------------------------------------------------------------------------- - Device management specific APIs - Also contains utility methods required for the execution of these APIs - --------------------------------------------------------------------------------------- */ - @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(VirtualFireAlarmConstants.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); - enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); - - device.setName(name); - device.setType(VirtualFireAlarmConstants.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(VirtualFireAlarmConstants.DEVICE_TYPE); - try { - boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( + //TODO; replace this tenant domain + private static final String SUPER_TENANT = "carbon.super"; + + @Context //injected response proxy supporting multiple thread + private HttpServletResponse response; + + private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature"; + public static final String XMPP_PROTOCOL = "XMPP"; + public static final String HTTP_PROTOCOL = "HTTP"; + public static final String MQTT_PROTOCOL = "MQTT"; + + private static VirtualFireAlarmMQTTSubscriber virtualFireAlarmMQTTSubscriber; + private static VirtualFireAlarmXMPPConnector virtualFireAlarmXMPPConnector; + private static ConcurrentHashMap deviceToIpMap = + new ConcurrentHashMap(); + + public void setVirtualFireAlarmXMPPConnector( + final VirtualFireAlarmXMPPConnector virtualFireAlarmXMPPConnector) { + this.virtualFireAlarmXMPPConnector = virtualFireAlarmXMPPConnector; + + Runnable mqttStarter = new Runnable() { + @Override + public void run() { + virtualFireAlarmXMPPConnector.initConnector(); + virtualFireAlarmXMPPConnector.connectAndLogin(); + } + }; + + Thread mqttStarterThread = new Thread(mqttStarter); + mqttStarterThread.setDaemon(true); + mqttStarterThread.start(); + } + + public void setVirtualFireAlarmMQTTSubscriber( + final VirtualFireAlarmMQTTSubscriber virtualFireAlarmMQTTSubscriber) { + this.virtualFireAlarmMQTTSubscriber = virtualFireAlarmMQTTSubscriber; + + Runnable xmppStarter = new Runnable() { + @Override + public void run() { + virtualFireAlarmMQTTSubscriber.initConnector(); + virtualFireAlarmMQTTSubscriber.connectAndSubscribe(); + } + }; + + Thread xmppStarterThread = new Thread(xmppStarter); + xmppStarterThread.setDaemon(true); + xmppStarterThread.start(); + } + + public VirtualFireAlarmXMPPConnector getVirtualFireAlarmXMPPConnector() { + return virtualFireAlarmXMPPConnector; + } + + public VirtualFireAlarmMQTTSubscriber getVirtualFireAlarmMQTTSubscriber() { + return virtualFireAlarmMQTTSubscriber; + } + + /* --------------------------------------------------------------------------------------- + Device management specific APIs + Also contains utility methods required for the execution of these APIs + --------------------------------------------------------------------------------------- */ + @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(VirtualFireAlarmConstants.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); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + + device.setName(name); + device.setType(VirtualFireAlarmConstants.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(VirtualFireAlarmConstants.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(VirtualFireAlarmConstants.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(VirtualFireAlarmConstants.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) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return false; - } finally { - deviceManagement.endTenantFlow(); - } - - } - - @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(VirtualFireAlarmConstants.DEVICE_TYPE); - - try { - return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); - - } catch (DeviceManagementException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return null; - } finally { - deviceManagement.endTenantFlow(); - } - - } - - @Path("manager/devices/{username}") - @GET - @Consumes("application/json") - @Produces("application/json") - public Device[] getFirealarmDevices(@PathParam("username") String username) { - - DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); - - try { - List userDevices = - deviceManagement.getDeviceManagementService().getDevicesOfUser( - username); - ArrayList userDevicesforFirealarm = new ArrayList(); - for (Device device : userDevices) { - - if (device.getType().equals(VirtualFireAlarmConstants.DEVICE_TYPE) && - device.getEnrolmentInfo().getStatus().equals( - EnrolmentInfo.Status.ACTIVE)) { - userDevicesforFirealarm.add(device); - - } - } - - return userDevicesforFirealarm.toArray(new Device[] {}); - } catch (DeviceManagementException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return null; - } finally { - deviceManagement.endTenantFlow(); - } - - } - - @Path("manager/device/{sketch_type}/download") - @GET - @Produces("application/octet-stream") - public Response downloadSketch(@QueryParam("owner") String owner, - @QueryParam("deviceName") String customDeviceName, + 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(VirtualFireAlarmConstants.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(VirtualFireAlarmConstants.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) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return false; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @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(VirtualFireAlarmConstants.DEVICE_TYPE); + + try { + return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); + + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return null; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("manager/devices/{username}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device[] getFirealarmDevices(@PathParam("username") String username) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + try { + List userDevices = + deviceManagement.getDeviceManagementService().getDevicesOfUser( + username); + ArrayList userDevicesforFirealarm = new ArrayList(); + for (Device device : userDevices) { + + if (device.getType().equals(VirtualFireAlarmConstants.DEVICE_TYPE) && + device.getEnrolmentInfo().getStatus().equals( + EnrolmentInfo.Status.ACTIVE)) { + userDevicesforFirealarm.add(device); + + } + } + + return userDevicesforFirealarm.toArray(new Device[]{}); + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return null; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("manager/device/{sketch_type}/download") + @GET + @Produces("application/octet-stream") + public Response downloadSketch(@QueryParam("owner") String owner, + @QueryParam("deviceName") String customDeviceName, @PathParam("sketch_type") String sketchType) { - //TODO:: null check customDeviceName at UI level - ZipArchive zipFile = null; - try { - zipFile = createDownloadFile(owner, customDeviceName, sketchType); - Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); - rb.header("Content-Disposition", - "attachment; filename=\"" + zipFile.getFileName() + "\""); - return rb.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(); - } - - } - - @Path("manager/device/{sketch_type}/generate_link") - @GET - public Response generateSketchLink(@QueryParam("owner") String owner, - @QueryParam("deviceName") String customDeviceName, - @PathParam("sketch_type") String sketchType) { - - ZipArchive zipFile = null; - try { - zipFile = createDownloadFile(owner, customDeviceName, sketchType); - Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); - return rb.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(); - } - - } - - private ZipArchive createDownloadFile(String owner, String customDeviceName, 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(); - - TokenClient accessTokenClient = new TokenClient(VirtualFireAlarmConstants.DEVICE_TYPE); - AccessTokenInfo accessTokenInfo = null; - accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); - - //create token - String accessToken = accessTokenInfo.getAccess_token(); - String refreshToken = accessTokenInfo.getRefresh_token(); - //adding registering data - - XmppAccount newXmppAccount = new XmppAccount(); - newXmppAccount.setAccountName(owner + "_" + deviceId); - newXmppAccount.setUsername(deviceId); - newXmppAccount.setPassword(accessToken); - newXmppAccount.setEmail(deviceId + "@wso2.com"); - - XmppServerClient xmppServerClient = new XmppServerClient(); - xmppServerClient.initControlQueue(); - boolean status; - - if (XmppConfig.getInstance().isEnabled()) { - status = xmppServerClient.createXMPPAccount(newXmppAccount); - if (!status) { - String msg = - "XMPP Account was not created for device - " + deviceId + " of owner - " + - owner + - ".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot" + - ".common.config.server.configs"; - log.warn(msg); - throw new DeviceManagementException(msg); - } - } - - //Register the device with CDMF - String deviceName = customDeviceName + "_" + deviceId; - 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 = null; - zipFile = ziputil.downloadSketch(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); - } + //TODO:: null check customDeviceName at UI level + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, customDeviceName, sketchType); + Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); + rb.header("Content-Disposition", + "attachment; filename=\"" + zipFile.getFileName() + "\""); + return rb.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(); + } + + } + + @Path("manager/device/{sketch_type}/generate_link") + @GET + public Response generateSketchLink(@QueryParam("owner") String owner, + @QueryParam("deviceName") String customDeviceName, + @PathParam("sketch_type") String sketchType) { + + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, customDeviceName, sketchType); + Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); + return rb.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(); + } + + } + + private ZipArchive createDownloadFile(String owner, String customDeviceName, 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(); + + TokenClient accessTokenClient = new TokenClient(VirtualFireAlarmConstants.DEVICE_TYPE); + AccessTokenInfo accessTokenInfo = null; + accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); + + //create token + String accessToken = accessTokenInfo.getAccess_token(); + String refreshToken = accessTokenInfo.getRefresh_token(); + //adding registering data + + XmppAccount newXmppAccount = new XmppAccount(); + newXmppAccount.setAccountName(owner + "_" + deviceId); + newXmppAccount.setUsername(deviceId); + newXmppAccount.setPassword(accessToken); + newXmppAccount.setEmail(deviceId + "@wso2.com"); + + XmppServerClient xmppServerClient = new XmppServerClient(); + xmppServerClient.initControlQueue(); + boolean status; + + if (XmppConfig.getInstance().isEnabled()) { + status = xmppServerClient.createXMPPAccount(newXmppAccount); + if (!status) { + String msg = + "XMPP Account was not created for device - " + deviceId + " of owner - " + + owner + + ".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot" + + ".common.config.server.configs"; + log.warn(msg); + throw new DeviceManagementException(msg); + } + } + + //Register the device with CDMF + String deviceName = customDeviceName + "_" + deviceId; + status = register(deviceId, deviceName, owner); + + if (!status) { + String msg = "Error occurred while registering the device with " + "id: " + deviceId + + " owner:" + owner; + throw new DeviceManagementException(msg); + } - /* --------------------------------------------------------------------------------------- - Device specific APIs - Control APIs + Data-Publishing APIs - Also contains utility methods required for the execution of these APIs - --------------------------------------------------------------------------------------- */ - @Path("controller/register/{owner}/{deviceId}/{ip}/{port}") - @POST - public String registerDeviceIP(@PathParam("owner") String owner, - @PathParam("deviceId") String deviceId, - @PathParam("ip") String deviceIP, - @PathParam("port") String devicePort, - @Context HttpServletResponse response, - @Context HttpServletRequest request) { - - //TODO:: Need to get IP from the request itself - String result; - - log.info("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; - } - - /* Service to switch "ON" and "OFF" the Virtual FireAlarm bulb - Called by an external client intended to control the Virtual FireAlarm bulb */ - @Path("controller/bulb/{state}") - @POST - public void switchBulb(@HeaderParam("owner") String owner, - @HeaderParam("deviceId") String deviceId, - @HeaderParam("protocol") String protocol, - @PathParam("state") String state, - @Context HttpServletResponse response) { - - try { - DeviceValidator deviceValidator = new DeviceValidator(); - if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, - VirtualFireAlarmConstants.DEVICE_TYPE))) { - response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); - return; - } - } catch (DeviceManagementException e) { - log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner); - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return; - } - - String switchToState = state.toUpperCase(); - - if (!switchToState.equals(VirtualFireAlarmConstants.STATE_ON) && !switchToState.equals( - VirtualFireAlarmConstants.STATE_OFF)) { - log.error("The requested state change shoud be either - 'ON' or 'OFF'"); - response.setStatus(Response.Status.BAD_REQUEST.getStatusCode()); - return; - } - - String protocolString = protocol.toUpperCase(); - String callUrlPattern = VirtualFireAlarmConstants.BULB_CONTEXT + switchToState; + + ZipUtil ziputil = new ZipUtil(); + ZipArchive zipFile = null; + zipFile = ziputil.downloadSketch(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); + } + + /* --------------------------------------------------------------------------------------- + Device specific APIs - Control APIs + Data-Publishing APIs + Also contains utility methods required for the execution of these APIs + --------------------------------------------------------------------------------------- */ + @Path("controller/register/{owner}/{deviceId}/{ip}/{port}") + @POST + public String registerDeviceIP(@PathParam("owner") String owner, + @PathParam("deviceId") String deviceId, + @PathParam("ip") String deviceIP, + @PathParam("port") String devicePort, + @Context HttpServletResponse response, + @Context HttpServletRequest request) { + + //TODO:: Need to get IP from the request itself + String result; + + log.info("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("Sending request to switch-bulb of device [" + deviceId + "] via " + protocolString); - } - - try { - switch (protocolString) { - case HTTP_PROTOCOL: - String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); - if (deviceHTTPEndpoint == null) { - response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); - return; - } - - sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true); - break; - case MQTT_PROTOCOL: - sendCommandViaMQTT(owner, deviceId, VirtualFireAlarmConstants.BULB_CONTEXT.replace("/", ""), switchToState); - break; - case XMPP_PROTOCOL: - sendCommandViaXMPP(owner, deviceId, VirtualFireAlarmConstants.BULB_CONTEXT, switchToState); - break; - default: - response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); - return; - } - } catch (DeviceManagementException e) { - log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " + protocolString); - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return; - } - - response.setStatus(Response.Status.OK.getStatusCode()); - } - - - @Path("controller/readsonar") - @GET - public String requestSonarReading(@HeaderParam("owner") String owner, - @HeaderParam("deviceId") String deviceId, - @HeaderParam("protocol") String protocol, - @Context HttpServletResponse response) { - String replyMsg = ""; - - DeviceValidator deviceValidator = new DeviceValidator(); - try { - if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE))) { - response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); - return "Unauthorized Access"; - } - } catch (DeviceManagementException e) { - replyMsg = e.getErrorMessage(); - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return replyMsg; - } - - String protocolString = protocol.toUpperCase(); + log.debug(result); + } + + return result; + } + + /* Service to switch "ON" and "OFF" the Virtual FireAlarm bulb + Called by an external client intended to control the Virtual FireAlarm bulb */ + @Path("controller/bulb/{state}") + @POST + public void switchBulb(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @PathParam("state") String state, + @Context HttpServletResponse response) { + + try { + DeviceValidator deviceValidator = new DeviceValidator(); + if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, + VirtualFireAlarmConstants.DEVICE_TYPE))) { + response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); + return; + } + } catch (DeviceManagementException e) { + log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return; + } + + String switchToState = state.toUpperCase(); + + if (!switchToState.equals(VirtualFireAlarmConstants.STATE_ON) && !switchToState.equals( + VirtualFireAlarmConstants.STATE_OFF)) { + log.error("The requested state change shoud be either - 'ON' or 'OFF'"); + response.setStatus(Response.Status.BAD_REQUEST.getStatusCode()); + return; + } + + String protocolString = protocol.toUpperCase(); + String callUrlPattern = VirtualFireAlarmConstants.BULB_CONTEXT + switchToState; if (log.isDebugEnabled()) { - log.debug("Sending request to read sonar value of device [" + deviceId + "] via " + protocolString); + log.debug("Sending request to switch-bulb of device [" + deviceId + "] via " + + protocolString); } try { - switch (protocolString) { - case HTTP_PROTOCOL: - String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); - if (deviceHTTPEndpoint == null) { - replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner; - response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); - return replyMsg; - } - - replyMsg = sendCommandViaHTTP(deviceHTTPEndpoint, VirtualFireAlarmConstants.SONAR_CONTEXT, false); - break; - - case MQTT_PROTOCOL: - sendCommandViaMQTT(owner, deviceId, VirtualFireAlarmConstants.SONAR_CONTEXT.replace("/", ""), ""); - break; - - case XMPP_PROTOCOL: - sendCommandViaXMPP(owner, deviceId, VirtualFireAlarmConstants.SONAR_CONTEXT, ""); - break; - - default: - replyMsg = "Requested protocol '" + protocolString + "' is not supported"; - response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); - return replyMsg; - } - } catch (DeviceManagementException e) { - replyMsg = e.getErrorMessage(); - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - return replyMsg; - } - - response.setStatus(Response.Status.OK.getStatusCode()); - replyMsg = "The current sonar reading of the device is " + replyMsg; - return replyMsg; - } - - - @Path("controller/readtemperature") - @GET + switch (protocolString) { + case HTTP_PROTOCOL: + String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); + if (deviceHTTPEndpoint == null) { + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return; + } + + sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true); + break; + case MQTT_PROTOCOL: + sendCommandViaMQTT(owner, deviceId, + VirtualFireAlarmConstants.BULB_CONTEXT.replace("/", ""), + switchToState); + break; + case XMPP_PROTOCOL: + sendCommandViaXMPP(owner, deviceId, VirtualFireAlarmConstants.BULB_CONTEXT, + switchToState); + break; + default: + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + return; + } + } catch (DeviceManagementException e) { + log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " + + protocolString); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return; + } + + response.setStatus(Response.Status.OK.getStatusCode()); + } + + + @Path("controller/readsonar") + @GET + public String requestSonarReading(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @Context HttpServletResponse response) { + String replyMsg = ""; + + DeviceValidator deviceValidator = new DeviceValidator(); + try { + if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, + VirtualFireAlarmConstants.DEVICE_TYPE))) { + response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); + return "Unauthorized Access"; + } + } catch (DeviceManagementException e) { + replyMsg = e.getErrorMessage(); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return replyMsg; + } + + String protocolString = protocol.toUpperCase(); + + if (log.isDebugEnabled()) { + log.debug("Sending request to read sonar value of device [" + deviceId + "] via " + + protocolString); + } + + try { + switch (protocolString) { + case HTTP_PROTOCOL: + String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); + if (deviceHTTPEndpoint == null) { + replyMsg = + "IP not registered for device: " + deviceId + " of owner: " + owner; + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return replyMsg; + } + + replyMsg = sendCommandViaHTTP(deviceHTTPEndpoint, + VirtualFireAlarmConstants.SONAR_CONTEXT, false); + break; + + case MQTT_PROTOCOL: + sendCommandViaMQTT(owner, deviceId, + VirtualFireAlarmConstants.SONAR_CONTEXT.replace("/", ""), + ""); + break; + + case XMPP_PROTOCOL: + sendCommandViaXMPP(owner, deviceId, VirtualFireAlarmConstants.SONAR_CONTEXT, + ""); + break; + + default: + replyMsg = "Requested protocol '" + protocolString + "' is not supported"; + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + return replyMsg; + } + } catch (DeviceManagementException e) { + replyMsg = e.getErrorMessage(); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return replyMsg; + } + + response.setStatus(Response.Status.OK.getStatusCode()); + replyMsg = "The current sonar reading of the device is " + replyMsg; + return replyMsg; + } + + + @Path("controller/readtemperature") + @GET @Consumes("application/json") @Produces("application/json") - public SensorRecord requestTemperature(@HeaderParam("owner") String owner, - @HeaderParam("deviceId") String deviceId, - @HeaderParam("protocol") String protocol, - @Context HttpServletResponse response) { + public SensorRecord requestTemperature(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @Context HttpServletResponse response) { SensorRecord sensorRecord = null; - DeviceValidator deviceValidator = new DeviceValidator(); - try { - if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE))) { - response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); - } - } catch (DeviceManagementException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - } + DeviceValidator deviceValidator = new DeviceValidator(); + try { + if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, + VirtualFireAlarmConstants.DEVICE_TYPE))) { + response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); + } + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } - String protocolString = protocol.toUpperCase(); + String protocolString = protocol.toUpperCase(); if (log.isDebugEnabled()) { - log.debug("Sending request to read virtual-firealarm-temperature of device [" + deviceId + "] via " + protocolString); + log.debug( + "Sending request to read virtual-firealarm-temperature of device [" + deviceId + + "] via " + protocolString); } - try { - switch (protocolString) { - case HTTP_PROTOCOL: - String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); - if (deviceHTTPEndpoint == null) { - response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + try { + switch (protocolString) { + case HTTP_PROTOCOL: + String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); + if (deviceHTTPEndpoint == null) { + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); } - String tString = sendCommandViaHTTP(deviceHTTPEndpoint, VirtualFireAlarmConstants.TEMPERATURE_CONTEXT, false); - String temperatureValue = tString; - SensorDataManager.getInstance().setSensorRecord(deviceId, VirtualFireAlarmConstants.SENSOR_TEMPERATURE, temperatureValue, - Calendar.getInstance().getTimeInMillis()); + String tString = sendCommandViaHTTP(deviceHTTPEndpoint, + VirtualFireAlarmConstants + .TEMPERATURE_CONTEXT, + false); + String temperatureValue = tString; + SensorDataManager.getInstance().setSensorRecord(deviceId, + VirtualFireAlarmConstants + .SENSOR_TEMPERATURE, + temperatureValue, + Calendar.getInstance() + .getTimeInMillis()); break; - case MQTT_PROTOCOL: - sendCommandViaMQTT(owner, deviceId, VirtualFireAlarmConstants.TEMPERATURE_CONTEXT.replace("/", ""), ""); - break; + case MQTT_PROTOCOL: + sendCommandViaMQTT(owner, deviceId, + VirtualFireAlarmConstants.TEMPERATURE_CONTEXT.replace("/", + ""), + ""); + break; - case XMPP_PROTOCOL: - sendCommandViaXMPP(owner, deviceId, VirtualFireAlarmConstants - .TEMPERATURE_CONTEXT, ""); - break; + case XMPP_PROTOCOL: + sendCommandViaXMPP(owner, deviceId, VirtualFireAlarmConstants + .TEMPERATURE_CONTEXT, ""); + break; - default: + default: response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); } - sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, VirtualFireAlarmConstants.SENSOR_TEMPERATURE); - } catch (DeviceManagementException e) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - } catch (DeviceControllerException e){ - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - } - - response.setStatus(Response.Status.OK.getStatusCode()); + sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, + VirtualFireAlarmConstants.SENSOR_TEMPERATURE); + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } catch (DeviceControllerException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } + + response.setStatus(Response.Status.OK.getStatusCode()); return sensorRecord; } - @Path("controller/push_temperature") - @POST - @Consumes(MediaType.APPLICATION_JSON) - public void pushTemperatureData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { - boolean result; - String deviceId = dataMsg.deviceId; - String deviceIp = dataMsg.reply; - float temperature = dataMsg.value; - - 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, - VirtualFireAlarmConstants.SENSOR_TEMPERATURE, - String.valueOf(temperature), - Calendar.getInstance().getTimeInMillis()); - - if (!publishToDAS(dataMsg.owner, dataMsg.deviceId, dataMsg.value)) { - response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - } - - } - - private String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext, boolean fireAndForgot) throws DeviceManagementException { - - String responseMsg = ""; - String urlString = VirtualFireAlarmConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext; - - if (log.isDebugEnabled()) { - log.debug(urlString); - } - - if (!fireAndForgot) { - HttpURLConnection httpConnection = getHttpConnection(urlString); - - try { - httpConnection.setRequestMethod(HttpMethod.GET); - } catch (ProtocolException e) { - String errorMsg = - "Protocol specific error occurred when trying to set method to GET" + - " for:" + urlString; - log.error(errorMsg); - throw new DeviceManagementException(errorMsg, e); - } - - responseMsg = readResponseFromGetRequest(httpConnection); - - } else { - CloseableHttpAsyncClient httpclient = null; - try { - - httpclient = HttpAsyncClients.createDefault(); - httpclient.start(); - HttpGet request = new HttpGet(urlString); - final CountDownLatch latch = new CountDownLatch(1); - Future future = httpclient.execute( - request, new FutureCallback() { - @Override - public void completed(HttpResponse httpResponse) { - latch.countDown(); - } - - @Override - public void failed(Exception e) { - latch.countDown(); - } - - @Override - public void cancelled() { - latch.countDown(); - } - }); - - latch.await(); - - } catch (InterruptedException e) { - if (log.isDebugEnabled()) { - log.debug("Sync Interrupted"); - } - } finally { - try { - if (httpclient != null) { - httpclient.close(); - - } - } catch (IOException e) { - if (log.isDebugEnabled()) { - log.debug("Failed on close"); - } - } - } - } - - return responseMsg; - } - - - - private boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource, String state) throws DeviceManagementException { - - boolean result = false; - DeviceController deviceController = new DeviceController(); - - try { - result = deviceController.publishMqttControl(deviceOwner, - VirtualFireAlarmConstants.DEVICE_TYPE, - deviceId, resource, state); - } catch (DeviceControllerException e) { - String errorMsg = "Error whilst trying to publish to MQTT Queue"; - log.error(errorMsg); - throw new DeviceManagementException(errorMsg, e); - } - return result; - } - - private void sendCommandViaXMPP(String deviceOwner, String deviceId, String resource, String state) throws DeviceManagementException { - - String xmppServerDomain = XmppConfig.getInstance().getXmppEndpoint(); - int indexOfChar = xmppServerDomain.lastIndexOf(File.separator); - if (indexOfChar != -1) { - xmppServerDomain = xmppServerDomain.substring((indexOfChar + 1), xmppServerDomain.length()); - } - - indexOfChar = xmppServerDomain.indexOf(":"); - if (indexOfChar != -1) { - xmppServerDomain = xmppServerDomain.substring(0, indexOfChar); - } - - String clientToConnect = deviceId + "@" + xmppServerDomain + File.separator + deviceOwner; - String message = resource.replace("/","") + ":" + state; - - virtualFireAlarmXMPPConnector.sendXMPPMessage(clientToConnect, message, "CONTROL-REQUEST"); - } + @Path("controller/push_temperature") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushTemperatureData(final DeviceJSON dataMsg, + @Context HttpServletResponse response) { + boolean result; + String deviceId = dataMsg.deviceId; + String deviceIp = dataMsg.reply; + float temperature = dataMsg.value; + + 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, + VirtualFireAlarmConstants + .SENSOR_TEMPERATURE, + String.valueOf(temperature), + Calendar.getInstance().getTimeInMillis()); + + if (!publishToDAS(dataMsg.owner, dataMsg.deviceId, dataMsg.value)) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } + + } + + private String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext, + boolean fireAndForgot) throws DeviceManagementException { + + String responseMsg = ""; + String urlString = VirtualFireAlarmConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext; + + if (log.isDebugEnabled()) { + log.debug(urlString); + } + + if (!fireAndForgot) { + HttpURLConnection httpConnection = getHttpConnection(urlString); + + try { + httpConnection.setRequestMethod(HttpMethod.GET); + } catch (ProtocolException e) { + String errorMsg = + "Protocol specific error occurred when trying to set method to GET" + + " for:" + urlString; + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + + responseMsg = readResponseFromGetRequest(httpConnection); + + } else { + CloseableHttpAsyncClient httpclient = null; + try { + + httpclient = HttpAsyncClients.createDefault(); + httpclient.start(); + HttpGet request = new HttpGet(urlString); + final CountDownLatch latch = new CountDownLatch(1); + Future future = httpclient.execute( + request, new FutureCallback() { + @Override + public void completed(HttpResponse httpResponse) { + latch.countDown(); + } + + @Override + public void failed(Exception e) { + latch.countDown(); + } + + @Override + public void cancelled() { + latch.countDown(); + } + }); + + latch.await(); + + } catch (InterruptedException e) { + if (log.isDebugEnabled()) { + log.debug("Sync Interrupted"); + } + } finally { + try { + if (httpclient != null) { + httpclient.close(); + + } + } catch (IOException e) { + if (log.isDebugEnabled()) { + log.debug("Failed on close"); + } + } + } + } + + return responseMsg; + } + + + private boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource, + String state) throws DeviceManagementException { + + boolean result = false; + DeviceController deviceController = new DeviceController(); + + try { + result = deviceController.publishMqttControl(deviceOwner, + VirtualFireAlarmConstants.DEVICE_TYPE, + deviceId, resource, state); + } catch (DeviceControllerException e) { + String errorMsg = "Error whilst trying to publish to MQTT Queue"; + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + return result; + } + + private void sendCommandViaXMPP(String deviceOwner, String deviceId, String resource, + String state) throws DeviceManagementException { + + String xmppServerDomain = XmppConfig.getInstance().getXmppEndpoint(); + int indexOfChar = xmppServerDomain.lastIndexOf(File.separator); + if (indexOfChar != -1) { + xmppServerDomain = xmppServerDomain.substring((indexOfChar + 1), + xmppServerDomain.length()); + } + + indexOfChar = xmppServerDomain.indexOf(":"); + if (indexOfChar != -1) { + xmppServerDomain = xmppServerDomain.substring(0, indexOfChar); + } + + String clientToConnect = deviceId + "@" + xmppServerDomain + File.separator + deviceOwner; + String message = resource.replace("/", "") + ":" + state; + + virtualFireAlarmXMPPConnector.sendXMPPMessage(clientToConnect, message, "CONTROL-REQUEST"); + } /* --------------------------------------------------------------------------------------- Utility methods relevant to creating and sending http requests @@ -801,87 +854,231 @@ public class VirtualFireAlarmService { /* This methods creates and returns a http connection object */ - private HttpURLConnection getHttpConnection(String urlString) throws - DeviceManagementException { - - URL connectionUrl = null; - HttpURLConnection httpConnection = null; - - try { - connectionUrl = new URL(urlString); - httpConnection = (HttpURLConnection) connectionUrl.openConnection(); - } catch (MalformedURLException e) { - String errorMsg = - "Error occured whilst trying to form HTTP-URL from string: " + urlString; - log.error(errorMsg); - throw new DeviceManagementException(errorMsg, e); - } catch (IOException e) { - String errorMsg = "Error occured whilst trying to open a connection to: " + - connectionUrl.toString(); - log.error(errorMsg); - throw new DeviceManagementException(errorMsg, e); - } - - return httpConnection; - } + private HttpURLConnection getHttpConnection(String urlString) throws + DeviceManagementException { + + URL connectionUrl = null; + HttpURLConnection httpConnection = null; + + try { + connectionUrl = new URL(urlString); + httpConnection = (HttpURLConnection) connectionUrl.openConnection(); + } catch (MalformedURLException e) { + String errorMsg = + "Error occured whilst trying to form HTTP-URL from string: " + urlString; + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } catch (IOException e) { + String errorMsg = "Error occured whilst trying to open a connection to: " + + connectionUrl.toString(); + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + + return httpConnection; + } /* This methods reads and returns the response from the connection */ - private String readResponseFromGetRequest(HttpURLConnection httpConnection) - throws DeviceManagementException { - BufferedReader bufferedReader = null; - try { - bufferedReader = new BufferedReader(new InputStreamReader( - httpConnection.getInputStream())); - } catch (IOException e) { - String errorMsg = - "There is an issue with connecting the reader to the input stream at: " + - httpConnection.getURL(); - log.error(errorMsg); - throw new DeviceManagementException(errorMsg, e); - } - - String responseLine; - StringBuffer completeResponse = new StringBuffer(); - - try { - while ((responseLine = bufferedReader.readLine()) != null) { - completeResponse.append(responseLine); - } - } catch (IOException e) { - String errorMsg = - "Error occured whilst trying read from the connection stream at: " + - httpConnection.getURL(); - log.error(errorMsg); - throw new DeviceManagementException(errorMsg, e); - } - try { - bufferedReader.close(); - } catch (IOException e) { - log.error( - "Could not succesfully close the bufferedReader to the connection at: " + - httpConnection.getURL()); - } - - return completeResponse.toString(); - } - - public static boolean publishToDAS(String owner, String deviceId, float temperature){ - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - ctx.setTenantDomain(SUPER_TENANT, true); - DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( - DeviceAnalyticsService.class, null); - Object metdaData[] = {owner, VirtualFireAlarmConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; - Object payloadData[] = {temperature}; - - try { - deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadData); - } catch (DataPublisherConfigurationException e) { - return false; - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - return true; - } + private String readResponseFromGetRequest(HttpURLConnection httpConnection) + throws DeviceManagementException { + BufferedReader bufferedReader = null; + try { + bufferedReader = new BufferedReader(new InputStreamReader( + httpConnection.getInputStream())); + } catch (IOException e) { + String errorMsg = + "There is an issue with connecting the reader to the input stream at: " + + httpConnection.getURL(); + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + + String responseLine; + StringBuffer completeResponse = new StringBuffer(); + + try { + while ((responseLine = bufferedReader.readLine()) != null) { + completeResponse.append(responseLine); + } + } catch (IOException e) { + String errorMsg = + "Error occured whilst trying read from the connection stream at: " + + httpConnection.getURL(); + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + try { + bufferedReader.close(); + } catch (IOException e) { + log.error( + "Could not succesfully close the bufferedReader to the connection at: " + + httpConnection.getURL()); + } + + return completeResponse.toString(); + } + + public static boolean publishToDAS(String owner, String deviceId, float temperature) { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ctx.setTenantDomain(SUPER_TENANT, true); + DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( + DeviceAnalyticsService.class, null); + Object metdaData[] = {owner, VirtualFireAlarmConstants.DEVICE_TYPE, deviceId, + System.currentTimeMillis()}; + Object payloadData[] = {temperature}; + + try { + deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData, + new Object[0], payloadData); + } catch (DataPublisherConfigurationException e) { + return false; + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + return true; + } + + +// @GET +// @Path("/enrol") +// public Response scepRequest(String certificateSignRequest) { +// +// Base64 base64Encoder = new Base64(); +// String signedCertEncodedString = ""; +// +// +// CertificateManagementService certificateManagementService = null; +// try { +// certificateManagementService = VirtualFireAlarmServiceUtils.getCertificateManagementService(); +// X509Certificate signedCeritficate = certificateManagementService.getSignedCertificateFromCSR(certificateSignRequest); +// signedCertEncodedString = base64Encoder.encodeAsString(signedCeritficate.getEncoded()); +// } catch (VirtualFireAlarmEnrollmentException e) { +// e.printStackTrace(); +// } catch (KeystoreException e) { +// e.printStackTrace(); +// } catch (CertificateEncodingException e) { +// e.printStackTrace(); +// } +// +// +// Response.ResponseBuilder responseBuilder = Response.ok(signedCertEncodedString, ContentType.X_X509_CA_CERT);; +// return responseBuilder.build(); +// } + + @GET + @Path("/scep") + public Response scepRequest(@QueryParam("operation") String operation) { + + if (log.isDebugEnabled()) { + log.debug("Invoking SCEP operation " + operation); + } + + if (SCEPOperation.GET_CA_CERT.getValue().equals(operation)) { + + if (log.isDebugEnabled()) { + log.debug("Invoking GetCACert"); + } + + try { + CertificateManagementService certificateManagementService = + VirtualFireAlarmServiceUtils.getCertificateManagementService(); + SCEPResponse scepResponse = certificateManagementService.getCACertSCEP(); + Response.ResponseBuilder responseBuilder; + + switch (scepResponse.getResultCriteria()) { + case CA_CERT_FAILED: + log.error("CA cert failed"); + responseBuilder = Response.serverError(); + break; + case CA_CERT_RECEIVED: + + if (log.isDebugEnabled()) { + log.debug("CA certificate received in GetCACert"); + } + + responseBuilder = Response.ok(scepResponse.getEncodedResponse(), + ContentType.X_X509_CA_CERT); + break; + case CA_RA_CERT_RECEIVED: + + if (log.isDebugEnabled()) { + log.debug("CA and RA certificates received in GetCACert"); + } + + responseBuilder = Response.ok(scepResponse.getEncodedResponse(), + ContentType.X_X509_CA_RA_CERT); + break; + default: + log.error("Invalid SCEP request"); + responseBuilder = Response.serverError(); + break; + } + + + + + return responseBuilder.build(); + } catch (VirtualFireAlarmEnrollmentException e) { + log.error("Error occurred while enrolling the iOS device", e); + } catch (KeystoreException e) { + log.error("Keystore error occurred while enrolling the iOS device", e); + } + + } else if (SCEPOperation.GET_CA_CAPS.getValue().equals(operation)) { + + if (log.isDebugEnabled()) { + log.debug("Invoking GetCACaps"); + } + + try { + CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils. + getCertificateManagementService(); + byte caCaps[] = certificateManagementService.getCACapsSCEP(); + + return Response.ok(caCaps, MediaType.TEXT_PLAIN).build(); + } catch (VirtualFireAlarmEnrollmentException e) { + log.error("Error occurred while enrolling the iOS device", e); + } + + } else { + log.error("Invalid SCEP operation " + operation); + } + + return Response.serverError().build(); + } + + @POST + @Consumes({ContentType.X_PKI_MESSAGE}) + @Path("/scep") + public Response scepRequestPost(@QueryParam("operation") String operation, + InputStream inputStream) { + + if (log.isDebugEnabled()) { + log.debug("Invoking SCEP operation " + operation); + } + + if (SCEPOperation.PKI_OPERATION.getValue().equals(operation)) { + + if (log.isDebugEnabled()) { + log.debug("Invoking PKIOperation"); + } + + try { + CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils. + getCertificateManagementService(); + byte pkiMessage[] = certificateManagementService.getPKIMessageSCEP(inputStream); + + return Response.ok(pkiMessage, ContentType.X_PKI_MESSAGE).build(); + } catch (VirtualFireAlarmEnrollmentException e) { + log.error("Error occurred while enrolling the iOS device", e); + } catch (KeystoreException e) { + log.error("Keystore error occurred while enrolling the iOS device", e); + } + + } + + return Response.serverError().build(); + } } diff --git a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/exception/VirtualFireAlarmEnrollmentException.java b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/exception/VirtualFireAlarmEnrollmentException.java new file mode 100644 index 00000000..42364474 --- /dev/null +++ b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/exception/VirtualFireAlarmEnrollmentException.java @@ -0,0 +1,13 @@ +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.exception; + +public class VirtualFireAlarmEnrollmentException extends Exception { + private static final long serialVersionUID = 118512086957330189L; + + public VirtualFireAlarmEnrollmentException(String errorMessage) { + super(errorMessage); + } + + public VirtualFireAlarmEnrollmentException(String errorMessage, Throwable throwable) { + super(errorMessage, throwable); + } +} diff --git a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/VirtualFireAlarmMQTTSubscriber.java b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/transport/VirtualFireAlarmMQTTSubscriber.java similarity index 99% rename from modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/VirtualFireAlarmMQTTSubscriber.java rename to modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/transport/VirtualFireAlarmMQTTSubscriber.java index eef27ae7..3e4ad6c7 100644 --- a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/VirtualFireAlarmMQTTSubscriber.java +++ b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/transport/VirtualFireAlarmMQTTSubscriber.java @@ -1,4 +1,4 @@ -package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util; +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.transport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/VirtualFireAlarmXMPPConnector.java b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/transport/VirtualFireAlarmXMPPConnector.java similarity index 94% rename from modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/VirtualFireAlarmXMPPConnector.java rename to modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/transport/VirtualFireAlarmXMPPConnector.java index fcd19b5b..df3b839a 100644 --- a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/VirtualFireAlarmXMPPConnector.java +++ b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/transport/VirtualFireAlarmXMPPConnector.java @@ -1,11 +1,8 @@ -package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util; +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.transport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jivesoftware.smack.packet.Message; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException; -import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConnector; diff --git a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/ContentType.java b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/ContentType.java new file mode 100644 index 00000000..0f92eaaa --- /dev/null +++ b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/ContentType.java @@ -0,0 +1,8 @@ +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util; + +public class ContentType { + public static final String X_PKI_MESSAGE = "application/x-pki-message"; + public static final String X_X509_CA_CERT = "application/x-x509-ca-cert"; + public static final String X_X509_CA_RA_CERT = "application/x-x509-ca-ra-cert"; +} + diff --git a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/VirtualFireAlarmServiceUtils.java b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/VirtualFireAlarmServiceUtils.java new file mode 100644 index 00000000..c83c7bc0 --- /dev/null +++ b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/VirtualFireAlarmServiceUtils.java @@ -0,0 +1,29 @@ +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.exception + .VirtualFireAlarmEnrollmentException; + +public class VirtualFireAlarmServiceUtils { + private static final Log log = LogFactory.getLog(VirtualFireAlarmServiceUtils.class); + + public static CertificateManagementService getCertificateManagementService() throws + VirtualFireAlarmEnrollmentException { + + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + CertificateManagementService certificateManagementService = (CertificateManagementService) + ctx.getOSGiService(CertificateManagementService.class, null); + + if (certificateManagementService == null) { + String msg = "EnrollmentService is not initialized"; + log.error(msg); + throw new VirtualFireAlarmEnrollmentException(msg); + } + + return certificateManagementService; + } + +} diff --git a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/scep/SCEPOperation.java b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/scep/SCEPOperation.java new file mode 100644 index 00000000..e9c94aff --- /dev/null +++ b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/scep/SCEPOperation.java @@ -0,0 +1,21 @@ +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.scep; + +public enum SCEPOperation { + GET_CA_CERT("GetCACert"), + GET_CA_CAPS("GetCACaps"), + PKI_OPERATION("PKIOperation"); + + private String value; + + private SCEPOperation(String value) { + this.setValue(value); + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml index e4caa0b6..c1713862 100644 --- a/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/modules/samples/virtual_firealarm/FireAlarm/api/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -51,10 +51,10 @@ + class="org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.transport.VirtualFireAlarmMQTTSubscriber"> + class="org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.transport.VirtualFireAlarmXMPPConnector">