Merge pull request #52 from GPrathap/IoTS-1.0.0-M1

Io ts 1.0.0 m1
Ruwan 9 years ago
commit af63452cf7

@ -1,21 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent> <parent>
@ -25,7 +7,7 @@
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl</artifactId> <artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.api</artifactId>
<version>1.9.2-SNAPSHOT</version> <version>1.9.2-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>WSO2 Carbon - IoT Server Drone Analyzer API</name> <name>WSO2 Carbon - IoT Server Drone Analyzer API</name>
@ -99,6 +81,12 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!--Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<!--IOT --> <!--IOT -->
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
@ -113,7 +101,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl</artifactId> <artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
@ -221,6 +209,12 @@
<artifactId>smackx</artifactId> <artifactId>smackx</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
</dependencies> </dependencies>
@ -238,10 +232,10 @@
<plugin> <plugin>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<configuration> <configuration>
<!--<webXml>src/main/webapp/WEB-INF/web.xml</webXml>--> <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
<warName>drone_analyzer</warName> <warName>drone_analyzer</warName>
<!--<outputDirectory>/home/geesara/wso2/products/wso2iot-1.0.0-SNAPSHOT/repository/deployment/server/webapps</outputDirectory> <!-- <outputDirectory>/home/geesara/wso2/products/wso2iot-1.0.0-SNAPSHOT/repository/deployment/server/webapps</outputDirectory>
--> -->
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

@ -20,45 +20,32 @@ package org.wso2.carbon.device.mgt.iot.droneanalyzer.service;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants; import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport.DroneAnalyzerXMPPConnector;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport.DroneXMPPConnector; import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport.DroneXMPPConnector;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.trasformer.MessageTransformer; import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.trasformer.MessageTransformer;
import javax.websocket.OnClose; import javax.websocket.*;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint; import javax.websocket.server.ServerEndpoint;
import java.io.IOException; import java.io.IOException;
import java.nio.channels.ClosedChannelException;
@ServerEndpoint("/datastream/drone_status") @ServerEndpoint("/datastream/drone_status")
public class DroneRealTimeService { public class DroneRealTimeService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneRealTimeService.class); private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneRealTimeService.class);
public MessageTransformer messageController; private MessageTransformer messageController;
public DroneXMPPConnector xmppConn; private DroneAnalyzerXMPPConnector xmppConnector;
Thread mqttStarterThread;
public DroneRealTimeService(){ public DroneRealTimeService(){
messageController = new MessageTransformer(); messageController = new MessageTransformer();
xmppConn = new DroneXMPPConnector(messageController); xmppConnector = new DroneAnalyzerXMPPConnector(messageController);
Runnable mqttStarter = new Runnable() { xmppConnector.connectLoginAndSetFilterOnReceiver();
@Override
public void run() {
try {
xmppConn.run();
} catch (Exception e) {
log.error(e.getMessage()+ "\n", e);
}
}
};
mqttStarterThread = new Thread(mqttStarter);
//mqttStarterThread.setDaemon(true);
mqttStarterThread.start();
} }
@OnOpen @OnOpen
public void onOpen(Session session){ public void onOpen(Session session){
log.info(session.getId() + " has opened a connection"); log.info(session.getId() + " has opened a connection");
System.out.println(session.getId() + " has opened a connection");
try { try {
session.getBasicRemote().sendText("Connection Established"); session.getBasicRemote().sendText("Connection Established");
} catch (IOException e) { } catch (IOException e) {
@ -70,33 +57,50 @@ public class DroneRealTimeService {
public void onMessage(String message, Session session){ public void onMessage(String message, Session session){
try { try {
while(true){ while(true){
if(!messageController.isEmptyQueue()){ if((messageController !=null) && (!messageController.isEmptyQueue())){
String message1 = messageController.getMessage(); String message1 = messageController.getMessage();
System.out.println("Out going message :"+ message1);
session.getBasicRemote().sendText(message1); session.getBasicRemote().sendText(message1);
} }
/*if((current_message = messageController.getCurrentMessage())!= null){
session.getBasicRemote().sendText( current_message );
}*/
Thread.sleep(DroneConstants.MINIMUM_TIME_DURATION); Thread.sleep(DroneConstants.MINIMUM_TIME_DURATION);
} }
} catch (IOException ex) { } catch (IOException ex) {
log.error(ex.getMessage() + "\n" + ex); log.error(ex.getMessage() + "\n" + ex);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); log.error(e.getMessage(), e);
System.out.println(e.getMessage()+" "+ e);
} }
} }
@OnClose @OnClose
public void onClose(Session session){ public void onClose(Session session){
try {
xmppConnector.disconnect();
log.info("XMPP connection is disconnected");
System.out.println("XMPP connection is disconnected");
}
catch (Exception e) {
log.error(e.getMessage() + "\n" + e);
System.out.println(e.getMessage()+"\n"+ e);
}
log.info("Session " + session.getId() + " has ended");
System.out.println("Session " + session.getId() + " has ended");
}
@OnError
public void onError(Session session, Throwable t) {
try { try {
session.getBasicRemote().sendText("Connection closed"); session.getBasicRemote().sendText("Connection closed");
xmppConn.disconnect(); xmppConnector.disconnect();
log.info("XMPP connection is disconnected"); log.info("XMPP connection is disconnected");
System.out.println("00XMPP connection is disconnected");
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage()+"\n"+ e); log.error(e.getMessage()+"\n"+ e);
System.out.println("00"+ e.getMessage()+"\n"+ e);
} }
log.info("Session " + session.getId() + " has ended"); log.info("Session " + session.getId() + " has ended");
System.out.println("00 Session " + session.getId() + " has ended");
} }
} }

@ -15,22 +15,30 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service; package org.wso2.carbon.device.mgt.iot.droneanalyzer.service;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
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.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.DeviceManagement; import org.wso2.carbon.device.mgt.iot.DeviceManagement;
import org.wso2.carbon.device.mgt.iot.DeviceValidator;
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo; import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient; import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppAccount; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppAccount;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants; import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport.DroneAnalyzerXMPPConnector; import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.controller.DroneController;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.controller.impl.DroneControllerImpl;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.exception.DroneAnalyzerException;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.util.DroneAnalyzerServiceUtils;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.util.scep.ContentType;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.util.scep.SCEPOperation;
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException; import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive; import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
@ -40,7 +48,9 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.Context; import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
@ -49,16 +59,15 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@Path("/DroneAnalyzerServiceUnitManager")
public class DroneService { public class DroneService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneService.class); private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneService.class);
//TODO; replace this tenant domain
private static final String SUPER_TENANT = "carbon.super"; private static final String SUPER_TENANT = "carbon.super";
@Context //injected response proxy supporting multiple thread @Context //injected response proxy supporting multiple thread
private HttpServletResponse response; private HttpServletResponse response;
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
//private DroneAnalyzerXMPPConnector xmppConnector; private DroneController droneController = new DroneControllerImpl();
/* --------------------------------------------------------------------------------------- /* ---------------------------------------------------------------------------------------
Device management specific APIs Device management specific APIs
@ -68,9 +77,6 @@ public class DroneService {
@PUT @PUT
public boolean register(@QueryParam("deviceId") String deviceId, public boolean register(@QueryParam("deviceId") String deviceId,
@QueryParam("name") String name, @QueryParam("owner") String owner) { @QueryParam("name") String name, @QueryParam("owner") String owner) {
log.info( deviceId + name + owner);
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
@ -80,7 +86,6 @@ public class DroneService {
response.setStatus(Response.Status.CONFLICT.getStatusCode()); response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false; return false;
} }
Device device = new Device(); Device device = new Device();
device.setDeviceIdentifier(deviceId); device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
@ -95,13 +100,11 @@ public class DroneService {
enrolmentInfo.setOwner(owner); enrolmentInfo.setOwner(owner);
device.setEnrolmentInfo(enrolmentInfo); device.setEnrolmentInfo(enrolmentInfo);
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device);
if (added) { if (added) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
} else { } else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
} }
return added; return added;
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
@ -114,9 +117,6 @@ public class DroneService {
@Path("manager/device/remove/{device_id}") @Path("manager/device/remove/{device_id}")
@DELETE @DELETE
public void removeDevice(@PathParam("device_id") String deviceId, @Context HttpServletResponse response) { public void removeDevice(@PathParam("device_id") String deviceId, @Context HttpServletResponse response) {
log.info(deviceId );
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
@ -141,21 +141,15 @@ public class DroneService {
@Path("manager/device/update/{device_id}") @Path("manager/device/update/{device_id}")
@POST @POST
public boolean updateDevice(@PathParam("device_id") String deviceId, public boolean updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name,
@QueryParam("name") String name,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
log.info(deviceId + name );
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE); deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
try { try {
Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId); device.setDeviceIdentifier(deviceId);
// device.setDeviceTypeId(deviceTypeId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name); device.setName(name);
device.setType(DroneConstants.DEVICE_TYPE); device.setType(DroneConstants.DEVICE_TYPE);
@ -179,14 +173,10 @@ public class DroneService {
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Device getDevice(@PathParam("device_id") String deviceId) { public Device getDevice(@PathParam("device_id") String deviceId) {
log.info(deviceId);
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE); deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
try { try {
return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
@ -203,10 +193,6 @@ public class DroneService {
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Device[] getDroneDevices(@PathParam("username") String username) { public Device[] getDroneDevices(@PathParam("username") String username) {
/*@QueryParam("action") String action, @QueryParam("duration") String duration,
@QueryParam("speed") String speed*/
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
try { try {
List<Device> userDevices = deviceManagement.getDeviceManagementService().getDevicesOfUser(username); List<Device> userDevices = deviceManagement.getDeviceManagementService().getDevicesOfUser(username);
@ -225,16 +211,13 @@ public class DroneService {
} finally { } finally {
deviceManagement.endTenantFlow(); deviceManagement.endTenantFlow();
} }
} }
@Path("manager/device/{sketch_type}/download") @Path("manager/device/{sketch_type}/download")
@GET @GET
@Produces("application/octet-stream") @Produces("application/octet-stream")
public Response downloadSketch(@QueryParam("owner") String owner, public Response downloadSketch(@QueryParam("owner") String owner, @QueryParam("deviceName") String customDeviceName,
@QueryParam("deviceName") String customDeviceName,
@PathParam("sketch_type") String sketchType) { @PathParam("sketch_type") String sketchType) {
log.info(owner + customDeviceName + sketchType);
try { try {
ZipArchive zipFile = createDownloadFile(owner, customDeviceName, sketchType); ZipArchive zipFile = createDownloadFile(owner, customDeviceName, sketchType);
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
@ -257,14 +240,12 @@ public class DroneService {
public Response generateSketchLink(@QueryParam("owner") String owner, public Response generateSketchLink(@QueryParam("owner") String owner,
@QueryParam("deviceName") String customDeviceName, @QueryParam("deviceName") String customDeviceName,
@PathParam("sketch_type") String sketchType) { @PathParam("sketch_type") String sketchType) {
log.info(owner + customDeviceName + sketchType);
try { try {
ZipArchive zipFile = createDownloadFile(owner, customDeviceName, sketchType); ZipArchive zipFile = createDownloadFile(owner, customDeviceName, sketchType);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
return rb.build(); return rb.build();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request return Response.status(400).entity(ex.getMessage()).build();
} catch (DeviceManagementException ex) { } catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build(); return Response.status(500).entity(ex.getMessage()).build();
} catch (AccessTokenException ex) { } catch (AccessTokenException ex) {
@ -279,24 +260,19 @@ public class DroneService {
if (owner == null) { if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!"); throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
} }
//create new device id //create new device id
String deviceId = shortUUID(); String deviceId = shortUUID();
TokenClient accessTokenClient = new TokenClient(DroneConstants.DEVICE_TYPE); TokenClient accessTokenClient = new TokenClient(DroneConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
//create token //create token
String accessToken = accessTokenInfo.getAccess_token(); String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token(); String refreshToken = accessTokenInfo.getRefresh_token();
//adding registering data //adding registering data
XmppAccount newXmppAccount = new XmppAccount(); XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(owner + "_" + deviceId); newXmppAccount.setAccountName(owner + "_" + deviceId);
newXmppAccount.setUsername(deviceId); newXmppAccount.setUsername(deviceId);
newXmppAccount.setPassword(accessToken); newXmppAccount.setPassword(accessToken);
newXmppAccount.setEmail(deviceId + "@wso2.com"); newXmppAccount.setEmail(deviceId + "@wso2.com");
XmppServerClient xmppServerClient = new XmppServerClient(); XmppServerClient xmppServerClient = new XmppServerClient();
xmppServerClient.initControlQueue(); xmppServerClient.initControlQueue();
boolean status; boolean status;
@ -313,23 +289,19 @@ public class DroneService {
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
} }
//Register the device with CDMF //Register the device with CDMF
String deviceName = customDeviceName + "_" + deviceId; String deviceName = customDeviceName + "_" + deviceId;
status = register(deviceId, deviceName, owner); status = register(deviceId, deviceName, owner);
if (!status) { if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId String msg = "Error occurred while registering the device with " + "id: " + deviceId
+ " owner:" + owner; + " owner:" + owner;
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
ZipUtil ziputil = new ZipUtil(); ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.downloadSketch(owner, SUPER_TENANT, sketchType, deviceId, deviceName, ZipArchive zipFile = ziputil.downloadSketch(owner, SUPER_TENANT, sketchType, deviceId, deviceName,
accessToken, refreshToken); accessToken, refreshToken);
zipFile.setDeviceId(deviceId); zipFile.setDeviceId(deviceId);
return null; return zipFile;
} }
private static String shortUUID() { private static String shortUUID() {
@ -344,25 +316,18 @@ public class DroneService {
--------------------------------------------------------------------------------------- */ --------------------------------------------------------------------------------------- */
@Path("controller/register/{owner}/{deviceId}/{ip}/{port}") @Path("controller/register/{owner}/{deviceId}/{ip}/{port}")
@POST @POST
public String registerDeviceIP(@PathParam("owner") String owner, public String registerDeviceIP(@PathParam("owner") String owner, @PathParam("deviceId") String deviceId,
@PathParam("deviceId") String deviceId,
@PathParam("ip") String deviceIP, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort, @PathParam("port") String devicePort,
@Context HttpServletResponse response, @Context HttpServletResponse response,
@Context HttpServletRequest request) { @Context HttpServletRequest request) {
//TODO:: Need to get IP from the request itself
String result; String result;
log.info("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + log.info("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId +
" of owner: " + owner); " of owner: " + owner);
String deviceHttpEndpoint = deviceIP + ":" + devicePort; String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint); deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered"; result = "Device-IP Registered";
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug(result); log.debug(result);
} }
@ -371,289 +336,47 @@ public class DroneService {
} }
/* Service to switch "ON" and "OFF" the Virtual FireAlarm bulb
Called by an external client intended to control the Virtual FireAlarm bulb */
@Path("controller/send_command") @Path("controller/send_command")
@POST @POST
public void droneController(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, public Response droneController(@QueryParam("owner") String owner, @QueryParam("deviceId") String deviceId,
@QueryParam("action") String action, @QueryParam("action") String action, @QueryParam("duration") String duration,
@QueryParam("duration") String duration, @QueryParam("speed") String speed){
@QueryParam("speed") String speed,
@Context HttpServletResponse response) {
/*
try { try {
DeviceValidator deviceValidator = new DeviceValidator(); DeviceValidator deviceValidator = new DeviceValidator();
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId,
VirtualFireAlarmConstants DroneConstants.DEVICE_TYPE))) {
.DEVICE_TYPE))) { return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
return;
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner); log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
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 switch-bulb of device [" + deviceId + "] via " +
protocolString);
}
try { try {
switch (protocolString) { DroneAnalyzerServiceUtils.sendControlCommand(droneController, deviceId, action, Double.valueOf(speed),
case HTTP_PROTOCOL: Double.valueOf(duration));
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); return Response.status(Response.Status.ACCEPTED).build();
if (deviceHTTPEndpoint == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
}
VirtualFireAlarmServiceUtils.sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true);
break;
case MQTT_PROTOCOL:
String mqttMessage = VirtualFireAlarmConstants.BULB_CONTEXT.replace("/", "");
VirtualFireAlarmServiceUtils.sendCommandViaMQTT(owner, deviceId, mqttMessage, switchToState);
break;
case XMPP_PROTOCOL:
VirtualFireAlarmServiceUtils.sendCommandViaXMPP(owner, deviceId,
VirtualFireAlarmConstants.BULB_CONTEXT,
switchToState, virtualFireAlarmXMPPConnector);
break;
default:
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return;
}
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " + protocolString); log.error("Drone command didn't success. Try again, \n"+ e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
return;
} }
response.setStatus(Response.Status.OK.getStatusCode());*/
} }
@Path("controller/readsonar")
@GET @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 = VirtualFireAlarmServiceUtils.sendCommandViaHTTP(deviceHTTPEndpoint,
VirtualFireAlarmConstants.SONAR_CONTEXT,
false);
break;
case MQTT_PROTOCOL:
String mqttMessage = VirtualFireAlarmConstants.BULB_CONTEXT.replace("/", "");
VirtualFireAlarmServiceUtils.sendCommandViaMQTT(owner, deviceId, mqttMessage, "");
break;
case XMPP_PROTOCOL:
VirtualFireAlarmServiceUtils.sendCommandViaXMPP(owner, deviceId,
VirtualFireAlarmConstants.SONAR_CONTEXT, "",
virtualFireAlarmXMPPConnector);
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;*/
return null;
}
@Path("controller/readtemperature")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response 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());
}
String protocolString = protocol.toUpperCase();
if (log.isDebugEnabled()) {
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());
}
String temperatureValue = VirtualFireAlarmServiceUtils.sendCommandViaHTTP(deviceHTTPEndpoint,
VirtualFireAlarmConstants.TEMPERATURE_CONTEXT,
false);
*//* SensorDataManager.getInstance().setSensorRecord(deviceId,
VirtualFireAlarmConstants.SENSOR_TEMPERATURE,
temperatureValue,
Calendar.getInstance().getTimeInMillis());*//*
break;
case MQTT_PROTOCOL:
String mqttMessage = VirtualFireAlarmConstants.BULB_CONTEXT.replace("/", "");
VirtualFireAlarmServiceUtils.sendCommandViaMQTT(owner, deviceId, mqttMessage, "");
break;
case XMPP_PROTOCOL:
VirtualFireAlarmServiceUtils.sendCommandViaXMPP(owner, deviceId,
VirtualFireAlarmConstants.TEMPERATURE_CONTEXT, "",
virtualFireAlarmXMPPConnector);
break;
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());
}
response.setStatus(Response.Status.OK.getStatusCode());*/
return null;
}
/*@Path("controller/push_temperature")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void pushTemperatureData(final DeviceJSON dataMsg,
@Context HttpServletResponse response) {
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 (!VirtualFireAlarmServiceUtils.publishToDAS(dataMsg.owner, dataMsg.deviceId, dataMsg.value)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
}*/
/*@GET
@Path("controller/scep") @Path("controller/scep")
public Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message) { public Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Invoking SCEP operation " + operation); log.debug("Invoking SCEP operation " + operation);
} }
if (SCEPOperation.GET_CA_CERT.getValue().equals(operation)) { if (SCEPOperation.GET_CA_CERT.getValue().equals(operation)) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Invoking GetCACert"); log.debug("Invoking GetCACert");
} }
try { try {
CertificateManagementService certificateManagementService = CertificateManagementService certificateManagementService =
VirtualFireAlarmServiceUtils.getCertificateManagementService(); DroneAnalyzerServiceUtils.getCertificateManagementService();
SCEPResponse scepResponse = certificateManagementService.getCACertSCEP(); SCEPResponse scepResponse = certificateManagementService.getCACertSCEP();
Response.ResponseBuilder responseBuilder; Response.ResponseBuilder responseBuilder;
switch (scepResponse.getResultCriteria()) { switch (scepResponse.getResultCriteria()) {
case CA_CERT_FAILED: case CA_CERT_FAILED:
log.error("CA cert failed"); log.error("CA cert failed");
@ -664,16 +387,13 @@ public class DroneService {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("CA certificate received in GetCACert"); log.debug("CA certificate received in GetCACert");
} }
responseBuilder = Response.ok(scepResponse.getEncodedResponse(), responseBuilder = Response.ok(scepResponse.getEncodedResponse(),
ContentType.X_X509_CA_CERT); ContentType.X_X509_CA_CERT);
break; break;
case CA_RA_CERT_RECEIVED: case CA_RA_CERT_RECEIVED:
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("CA and RA certificates received in GetCACert"); log.debug("CA and RA certificates received in GetCACert");
} }
responseBuilder = Response.ok(scepResponse.getEncodedResponse(), responseBuilder = Response.ok(scepResponse.getEncodedResponse(),
ContentType.X_X509_CA_RA_CERT); ContentType.X_X509_CA_RA_CERT);
break; break;
@ -682,12 +402,11 @@ public class DroneService {
responseBuilder = Response.serverError(); responseBuilder = Response.serverError();
break; break;
} }
return responseBuilder.build(); return responseBuilder.build();
} catch (VirtualFireAlarmException e) { } catch (DroneAnalyzerException e) {
log.error("Error occurred while enrolling the iOS device", e); log.error("Error occurred while enrolling the drone device", e);
} catch (KeystoreException e) { } catch (KeystoreException e) {
log.error("Keystore error occurred while enrolling the iOS device", e); log.error("Keystore error occurred while enrolling the drone device", e);
} }
} else if (SCEPOperation.GET_CA_CAPS.getValue().equals(operation)) { } else if (SCEPOperation.GET_CA_CAPS.getValue().equals(operation)) {
@ -697,13 +416,11 @@ public class DroneService {
} }
try { try {
CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils. CertificateManagementService certificateManagementService = DroneAnalyzerServiceUtils.
getCertificateManagementService(); getCertificateManagementService();
byte caCaps[] = certificateManagementService.getCACapsSCEP(); byte caCaps[] = certificateManagementService.getCACapsSCEP();
return Response.ok(caCaps, MediaType.TEXT_PLAIN).build(); return Response.ok(caCaps, MediaType.TEXT_PLAIN).build();
} catch (DroneAnalyzerException e) {
} catch (VirtualFireAlarmException e) {
log.error("Error occurred while enrolling the device", e); log.error("Error occurred while enrolling the device", e);
} }
@ -712,9 +429,9 @@ public class DroneService {
} }
return Response.serverError().build(); return Response.serverError().build();
}*/ }
/*@POST @POST
@Path("controller/scep") @Path("controller/scep")
public Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream) { public Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream) {
@ -727,20 +444,18 @@ public class DroneService {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Invoking PKIOperation"); log.debug("Invoking PKIOperation");
} }
try { try {
CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils. CertificateManagementService certificateManagementService = DroneAnalyzerServiceUtils.
getCertificateManagementService(); getCertificateManagementService();
byte pkiMessage[] = certificateManagementService.getPKIMessageSCEP(inputStream); byte pkiMessage[] = certificateManagementService.getPKIMessageSCEP(inputStream);
return Response.ok(pkiMessage, ContentType.X_PKI_MESSAGE).build(); return Response.ok(pkiMessage, ContentType.X_PKI_MESSAGE).build();
} catch (VirtualFireAlarmException e) { } catch (DroneAnalyzerException e) {
log.error("Error occurred while enrolling the device", e); log.error("Error occurred while enrolling the device", e);
} catch (KeystoreException e) { } catch (KeystoreException e) {
log.error("Keystore error occurred while enrolling the device", e); log.error("Keystore error occurred while enrolling the device", e);
} }
} }
return Response.serverError().build(); return Response.serverError().build();
}*/ }
} }

@ -15,33 +15,33 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport; package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Message;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConnector; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConnector;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants; import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.util.DroneAnalyzerServiceUtils; import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.trasformer.MessageTransformer;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import java.util.Calendar;
public class DroneAnalyzerXMPPConnector extends XmppConnector { public class DroneAnalyzerXMPPConnector extends XmppConnector {
private static Log log = LogFactory.getLog(DroneAnalyzerXMPPConnector.class); private static Log log = LogFactory.getLog(DroneAnalyzerXMPPConnector.class);
private static String xmppServerIP; private static String xmppServerIP;
// private static int xmppServerPort; private static int xmppServerPort;
private static String xmppAdminUsername; private static String xmppAdminUsername;
private static String xmppAdminPassword; private static String xmppAdminPassword;
private static String xmppAdminAccountJID; private static String xmppAdminAccountJID;
private MessageTransformer messageTransformer;
private DroneAnalyzerXMPPConnector() { public DroneAnalyzerXMPPConnector(MessageTransformer messageTransformer) {
super(XmppConfig.getInstance().getXmppServerIP(), super(XmppConfig.getInstance().getXmppServerIP(),
XmppConfig.getInstance().getSERVER_CONNECTION_PORT()); XmppConfig.getInstance().getSERVER_CONNECTION_PORT());
this.messageTransformer = messageTransformer;
} }
public void initConnector() { public void initConnector() {
@ -61,39 +61,56 @@ public class DroneAnalyzerXMPPConnector extends XmppConnector {
} }
} }
public void setMessageFilterOnReceiver(String receiver){
super.setMessageFilterOnReceiver( receiver+ "@" + xmppServerIP);
}
public void connectLoginAndSetFilterOnReceiver(){
initConnector();
connectAndLogin();
setMessageFilterOnReceiver(DroneConstants.DEVICE_ID);
}
public void disconnect(){
super.closeConnection();
}
/*public void printRoster(XmppConnector xmppConnection) throws Exception {
if(xmppConnection != null){
Roster roster = xmppConnection.getRoster();
if(roster !=null && roster.getEntries() != null){
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
System.out.println(String.format("Buddy:%1$s - Status:%2$s",
entry.getName(), entry.getStatus()));
}
}
}else{
System.out.println("There are no users");
}
}*/
@Override @Override
protected void processXMPPMessage(Message xmppMessage) { protected void processXMPPMessage(Message xmppMessage) {
String from = xmppMessage.getFrom(); String from = xmppMessage.getFrom();
String subject = xmppMessage.getSubject(); String subject = xmppMessage.getSubject();
String message = xmppMessage.getBody(); String inbound_message = xmppMessage.getBody();
//System.out.println("inbound message :"+inbound_message);
int indexOfAt = from.indexOf("@"); int indexOfAt = from.indexOf("@");
int indexOfSlash = from.indexOf("/"); int indexOfSlash = from.indexOf("/");
String deviceId = from.substring(0, indexOfAt); String deviceId = from.substring(0, indexOfAt);
String owner = from.substring(indexOfSlash + 1, from.length()); String resource = 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 ((inbound_message != null)&&(resource.equals(DroneConstants.MESSAGE_RESOURCE)) ){
if(!DroneAnalyzerServiceUtils.publishToDAS(owner, deviceId, temperature)) { messageTransformer.messageTranslater(inbound_message);
log.error("XMPP Connector: Publishing data to DAS failed.");
} }
else {
if(log.isDebugEnabled()) { log.error("Message is empty or it is not belongs to "+ DroneConstants.DEVICE_ID);
log.debug("XMPP Connector: Published data to DAS successfully."); System.out.println("Message is empty or it is not belongs to "+ DroneConstants.DEVICE_ID);
} }
} else if(subject.equals("CONTROL-REPLY")) {
log.info("XMPP: Reply Message [" + message + "] from [" + from + "]");
String temperature = message.split(":")[1];
SensorDataManager.getInstance().setSensorRecord(deviceId, DroneConstants.SENSOR_TEMPERATURE, temperature, Calendar.getInstance().getTimeInMillis());
} else {
log.info("SOME XMPP Message [" + message + "] from " + from + "]");
}
} }
private void retryXMPPConnection() { private void retryXMPPConnection() {

@ -15,7 +15,6 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport; package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -32,6 +31,9 @@ import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.trasformer.MessageTr
import java.util.Collection; import java.util.Collection;
/**
* Created by geesara on 12/7/15.
*/
public class DroneXMPPConnector { public class DroneXMPPConnector {
private static Log log = LogFactory.getLog(DroneXMPPConnector.class); private static Log log = LogFactory.getLog(DroneXMPPConnector.class);

@ -0,0 +1,142 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.trasformer;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.MessageConfig;
import java.io.IOException;
public class MessageTransformer {
private Log log = LogFactory.getLog(MessageTransformer.class);
private CircularFifoQueue<String> sharedQueue;
private String outbound_message_format_for_simulator = "{\"quatanium_val\":[%f, %f, %f, %f]," +
"\"basicParam\":{\"velocity\":[%f, %f, %f], \"global_location\":[%f, %f, %f]},\"battery_level\":%f, \"device_type\":\"IRIS_DRONE\"}";
private String outbound_message_format_for_iris_drone = "{\"quatanium_val\":[%f, %f, %f]," +
"\"basicParam\":{\"velocity\":[%f, %f, %f], \"global_location\":[%f, %f, %f]},\"battery_level\":%f," +
"\"device_type\":\"SIMULATOR\"}";
public MessageTransformer(){
sharedQueue = new CircularFifoQueue<String>(DroneConstants.MAXIMUM_BUFFERE_SIZE_OF_SHARED_QUEUE);
}
private void messageTranslaterForSimulator(JsonNode inbound_message){
JsonNode node = inbound_message;
String outbound_message;
try {
JsonNode velocity = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(MessageConfig.OUT_BASIC_PARAM_VELOCITY);
JsonNode global_location = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(
MessageConfig.OUT_BASIC_PARAM_GLOBAL_LOCATION);
JsonNode quatanium_vals = node.get(MessageConfig.OUT_QUATANNIM_VAL);
JsonNode battery_level = node.get(MessageConfig.OUT_BATTERY_LEVEL);
outbound_message = String.format(outbound_message_format_for_simulator, sTd(quatanium_vals.get(0)),
sTd(quatanium_vals.get(1)), sTd(quatanium_vals.get(2)), sTd(quatanium_vals.get(0)),
sTd(velocity.get(0)), sTd(velocity.get(1)), sTd(velocity.get(2)), sTd(global_location.get(0)),
sTd(global_location.get(1)), sTd(global_location.get(2)), sTd(battery_level));
sharedQueue.add(outbound_message);
} catch (Exception e) {
log.error(e.getMessage()+",\n"+ e);
}
}
private void messageTranslaterForIRISDrone(JsonNode inbound_message){
JsonNode node = inbound_message;
String outbound_message;
try {
JsonNode velocity = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(MessageConfig.OUT_BASIC_PARAM_VELOCITY);
System.out.println("-------1----------");
JsonNode global_location = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(
MessageConfig.OUT_BASIC_PARAM_GLOBAL_LOCATION);
System.out.println("-------2----------");
JsonNode quatanium_vals = node.get(MessageConfig.OUT_QUATANNIM_VAL);
JsonNode battery_level = node.get(MessageConfig.OUT_BATTERY_LEVEL);
System.out.println("-------3----------");
outbound_message = String.format(outbound_message_format_for_iris_drone, sTd(quatanium_vals.get(0)),
sTd(quatanium_vals.get(1)), sTd(quatanium_vals.get(2)), sTd(velocity.get(0)),
sTd(velocity.get(1)), sTd(velocity.get(2)), sTd(global_location.get(0)),
sTd(global_location.get(1)), sTd(global_location.get(2)), sTd(battery_level));
System.out.println("-----------------IRIS_DRONE---------------------"+ outbound_message);
sharedQueue.add(outbound_message);
}catch (Exception e) {
log.error(e.getMessage()+",\n"+ e);
System.out.println( e.getMessage());
}
}
public void messageTranslater(String inbound_message){
JsonNode actualMessage = null;
ObjectMapper objectMapper = new ObjectMapper();
try {
actualMessage = objectMapper.readValue(inbound_message, JsonNode.class);
JsonNode deviceType = actualMessage.get(MessageConfig.IN_DEVICE_TYPE);
switch (deviceType.getTextValue()) {
case MessageConfig.IN_IRIS_DRONE:
System.out.println("incomming message :" + inbound_message);
messageTranslaterForIRISDrone(actualMessage);
break;
case MessageConfig.IN_SIMULATOR:
messageTranslaterForSimulator(actualMessage);
break;
}
} catch (JsonProcessingException e) {
log.error("Incoming message might be corrupted, "+ e);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
private double sTd(JsonNode s)
{
return Double.parseDouble(s.toString());
}
public String getMessage() {
try{
if(sharedQueue.isEmpty() || sharedQueue == null){
return "";
}
return sharedQueue.remove();
}catch(Exception e) {
log.error("There is no more messages to send or internal server error has been occurred, \n"+ e );
return "";
}
}
public boolean isEmptyQueue(){
return sharedQueue != null? sharedQueue.isEmpty():false;
}
}

@ -1,3 +1,4 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
@ -15,24 +16,31 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.util; package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.util;
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.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService; import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants; import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.controller.DroneController;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.controller.impl.DroneControllerImpl;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.exception.DroneAnalyzerException;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport.DroneAnalyzerXMPPConnector; import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport.DroneAnalyzerXMPPConnector;
import java.io.File; import java.io.File;
/**
* Created by geesara on 12/9/15.
*/
public class DroneAnalyzerServiceUtils { public class DroneAnalyzerServiceUtils {
private static final String SUPER_TENANT = "carbon.super"; private static final String SUPER_TENANT = "carbon.super";
private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature"; private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature";
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneAnalyzerServiceUtils.class);
public static void sendCommandViaXMPP(String deviceOwner, String deviceId, String resource, public static void sendCommandViaXMPP(String deviceOwner, String deviceId, String resource,
String state, DroneAnalyzerXMPPConnector droneXMPPConnector) String state, DroneAnalyzerXMPPConnector droneXMPPConnector)
@ -44,16 +52,53 @@ public class DroneAnalyzerServiceUtils {
xmppServerDomain = xmppServerDomain.substring((indexOfChar + 1), xmppServerDomain = xmppServerDomain.substring((indexOfChar + 1),
xmppServerDomain.length()); xmppServerDomain.length());
} }
indexOfChar = xmppServerDomain.indexOf(":"); indexOfChar = xmppServerDomain.indexOf(":");
if (indexOfChar != -1) { if (indexOfChar != -1) {
xmppServerDomain = xmppServerDomain.substring(0, indexOfChar); xmppServerDomain = xmppServerDomain.substring(0, indexOfChar);
} }
String clientToConnect = deviceId + "@" + xmppServerDomain + File.separator + deviceOwner; String clientToConnect = deviceId + "@" + xmppServerDomain + File.separator + deviceOwner;
String message = resource.replace("/", "") + ":" + state; String message = resource.replace("/", "") + ":" + state;
droneXMPPConnector.sendXMPPMessage(clientToConnect, message, "CONTROL-REQUEST"); droneXMPPConnector.sendXMPPMessage(clientToConnect, message, "CONTROL-REQUEST");
}
public static boolean sendControlCommand(DroneController controller, String deviceId, String action, double speed, double duration)
throws DeviceManagementException {
boolean control_state = false;
try{
switch (action){
case DroneConstants.TAKE_OFF:
control_state = controller.takeoff();
break;
case DroneConstants.LAND:
control_state = controller.land();
break;
case DroneConstants.BACK:
control_state = controller.back(speed, duration);
break;
case DroneConstants.CLOCK_WISE:
control_state = controller.clockwise(speed, duration);
break;
case DroneConstants.COUNTER_CLOCKWISE:
control_state = controller.conterClockwise(speed, duration);
break;
case DroneConstants.DOWN:
control_state = controller.down(speed, duration);
break;
case DroneConstants.FRONT:
control_state = controller.back(speed, duration);
break;
case DroneConstants.FORWARD:
control_state = controller.clockwise(speed, duration);
break;
case DroneConstants.UP:
control_state = controller.up(speed, duration);
break;
}
}catch(Exception e){
log.error(e.getMessage()+ "\n"+ e);
}
return control_state;
} }
public static boolean publishToDAS(String owner, String deviceId, float temperature) { public static boolean publishToDAS(String owner, String deviceId, float temperature) {
@ -76,4 +121,21 @@ public class DroneAnalyzerServiceUtils {
} }
return true; return true;
} }
public static CertificateManagementService getCertificateManagementService() throws
DroneAnalyzerException {
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 DroneAnalyzerException(msg);
}
return certificateManagementService;
}
} }

@ -0,0 +1,26 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.util.scep;
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";
}

@ -15,25 +15,25 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl.dao.impl;
import org.junit.Before; package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.util.scep;
import org.junit.Test;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException;
public class DroneAnalyzerDeviceDAOImplTest { public enum SCEPOperation {
DroneAnalyzerDeviceDAOImpl dao; GET_CA_CERT("GetCACert"),
@Before GET_CA_CAPS("GetCACaps"),
public void init(){ PKI_OPERATION("PKIOperation");
dao = new DroneAnalyzerDeviceDAOImpl();
private String value;
private SCEPOperation(String value) {
this.setValue(value);
} }
//@Test public String getValue() {
public void testDBConnenction(){ return value;
try {
dao.deleteIotDevice("device1");
} catch (IotDeviceManagementDAOException e) {
e.printStackTrace();
} }
public void setValue(String value) {
this.value = value;
} }
} }

@ -78,28 +78,10 @@
<Uri>http://localhost:9763/drone_analyzer/controller/register/{owner}/{deviceId}/{ip}/{port}</Uri> <Uri>http://localhost:9763/drone_analyzer/controller/register/{owner}/{deviceId}/{ip}/{port}</Uri>
<UriTemplate>/controller/register/{owner}/{deviceId}/{ip}/{port}</UriTemplate> <UriTemplate>/controller/register/{owner}/{deviceId}/{ip}/{port}</UriTemplate>
</Resource> </Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>POST</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/controller/controller/bulb/{state}</Uri>
<UriTemplate>/controller/bulb/{state}</UriTemplate>
</Resource>
<Resource> <Resource>
<AuthType>Any</AuthType> <AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb> <HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/controller/send_command</Uri> <Uri>http://localhost:9763/drone_analyzer/controller/send_command</Uri>
<UriTemplate>/controller/send_command</UriTemplate> <UriTemplate>/controller/send_command</UriTemplate>
</Resource> </Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/controller/controller/readtemperature</Uri>
<UriTemplate>/controller/readtemperature</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>POST</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/controller/controller/push_temperature</Uri>
<UriTemplate>/controller/push_temperature</UriTemplate>
</Resource>
</ResourceConfiguration> </ResourceConfiguration>

@ -1,21 +1,19 @@
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml version="1.0" encoding="ISO-8859-1"?>
<!-- <!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ Copyright 2005-2013 WSO2, Inc. (http://wso2.com)
~ ~
~ WSO2 Inc. licenses this file to you under the Apache License, ~ Licensed under the Apache License, Version 2.0 (the "License");
~ Version 2.0 (the "License"); you may not use this file except ~ you may not use this file except in compliance with the License.
~ in compliance with the License. ~ You may obtain a copy of the License at
~ you may obtain a copy of the License at
~ ~
~ http://www.apache.org/licenses/LICENSE-2.0 ~ http://www.apache.org/licenses/LICENSE-2.0
~ ~
~ Unless required by applicable law or agreed to in writing, ~ Unless required by applicable law or agreed to in writing, software
~ software distributed under the License is distributed on an ~ distributed under the License is distributed on an "AS IS" BASIS,
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ KIND, either express or implied. See the License for the ~ See the License for the specific language governing permissions and
~ specific language governing permissions and limitations ~ limitations under the License.
~ under the License.
--> -->
<!-- <!--

@ -20,9 +20,10 @@
<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
<!--<jaxrs:server id="VirtualFireAlarmController" address="/controller">--> <!--<jaxrs:server id="VirtualFireAlarmController" address="/controller">-->
@ -38,11 +39,12 @@
<!--</jaxrs:providers>--> <!--</jaxrs:providers>-->
<!--</jaxrs:server>--> <!--</jaxrs:server>-->
<jaxrs:server id="VirtualFireAlarm" address="/"> <jaxrs:server id="DroneAnalyzer" address="/">
<jaxrs:features>
<cxf:logging/>
</jaxrs:features>
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<bean id="DroneService" <bean id="DroneService" class="org.wso2.carbon.device.mgt.iot.droneanalyzer.service.DroneService">
class="org.wso2.carbon.device.mgt.iot.droneanalyzer.service.DroneService">
<!--<property name="DroneXMPPConnector" ref="xmppConnectorBean"/>--> <!--<property name="DroneXMPPConnector" ref="xmppConnectorBean"/>-->
</bean> </bean>
</jaxrs:serviceBeans> </jaxrs:serviceBeans>
@ -50,10 +52,8 @@
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/> <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers> </jaxrs:providers>
</jaxrs:server> </jaxrs:server>
<!--<bean id="xmppConnectorBean" <!--<bean id="xmppConnectorBean"
class="org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport.DroneAnalyzerXMPPConnector"> class="org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport.DroneAnalyzerXMPPConnector">
</bean>--> </bean>-->
</beans> </beans>

@ -1,21 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<web-app version="2.5" <web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
@ -48,7 +31,7 @@
<!--publish to apim--> <!--publish to apim-->
<context-param> <context-param>
<param-name>managed-api-enabled</param-name> <param-name>managed-api-enabled</param-name>
<param-value>false</param-value> <param-value>true</param-value>
</context-param> </context-param>
<context-param> <context-param>
<param-name>managed-api-owner</param-name> <param-name>managed-api-owner</param-name>
@ -83,6 +66,8 @@
<param-value>true</param-value> <param-value>true</param-value>
</context-param> </context-param>
<!-- Below configuration is used to redirect http requests to https --> <!-- Below configuration is used to redirect http requests to https -->
<!--<security-constraint>--> <!--<security-constraint>-->
<!--<web-resource-collection>--> <!--<web-resource-collection>-->

@ -0,0 +1,116 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.jaxrs.client.WebClient;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.wso2.carbon.device.mgt.common.Device;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Collection;
import java.util.Iterator;
/**
* Created by geesara on 12/10/15.
*/
public class DroneServiceTest {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneServiceTest.class);
ApplicationContext context;
WebClient client;
@Before
public void init(){
context = new ClassPathXmlApplicationContext("spring-cxf-client.xml");
client = context.getBean("droneClient", WebClient.class);
}
//@Test
public void registerDevice(){
client.path("manager/device/register").accept(MediaType.APPLICATION_JSON_TYPE);
client.query("deviceId", "device7");
client.query("name", "dronetypeOne");
client.query("owner", "DroneOwner");
Response res = client.put(null);
log.info("Response status :"+ res.getStatus());
System.out.println("Response status :"+ res.getStatus());
}
//@Test
public void removeDevice(){
client.path("manager/device/remove/").accept(MediaType.APPLICATION_JSON_TYPE);
client.path("device7");
Response res = client.delete();
log.info("Response status :"+ res.getStatus());
}
//@Test
public void updateDevice(){
client.path("manager/device/update/").accept(MediaType.APPLICATION_JSON_TYPE);
client.path("device2");
client.query("name", "ARDrone");
Response res = client.post(null);
log.info("Response status :"+ res.getStatus());
}
//@Test
public void getDevice(){
client.path("manager/device/").accept(MediaType.APPLICATION_JSON_TYPE);
client.path("device2");
Device res = client.get(Device.class);
log.info("Device name :"+ res.getName());
log.info("Device type :"+ res.getType());
}
//@Test
public void getDroneDevices(){
client.path("manager/devices/").accept(MediaType.APPLICATION_JSON_TYPE);
client.path("DroneOwner");
Collection<? extends Device> res = client.getCollection(Device.class);
Iterator<? extends Device> iterator = res.iterator();
while (iterator.hasNext()) {
Device device = iterator.next();
log.info("Device name :" + device.getName());
log.info("Device type :"+ device.getType());
iterator.remove();
}
}
//@Test
public void downloadSketch(){
client.path("manager/devices/");
client.path("type1");
client.path("download").accept(MediaType.APPLICATION_OCTET_STREAM);
Response res = client.get();
log.info(res.getStatus());
}
//@Test
public void droneController(){
client.path("controller/send_command");
client.query("owner", "DroneOwner");
client.query("deviceId", "device2");
client.query("action", "takeoff");
client.query("speed", 5);
client.query("duration", 56);
client.accept(MediaType.APPLICATION_JSON);
Response res = client.post(null);
System.out.println(res.getStatus());
}
public void generateSketchLink(){
client.path("manager/devices/");
client.path("type1");
client.path("download").accept(MediaType.APPLICATION_OCTET_STREAM);
Response res = client.get();
log.info(res.getStatus());
}
}

@ -0,0 +1,33 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.BeforeClass;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.utils.CarbonUtils;
/**
* Created by geesara on 12/10/15.
*/
public class DroneAnalyzerXMPPConnectorTest {
private static Log log = LogFactory.getLog(DroneAnalyzerXMPPConnectorTest.class);
public DroneAnalyzerXMPPConnector droneAnalyzerXMPPConnector;
@BeforeClass
public void setup(){
//droneAnalyzerXMPPConnector = new DroneAnalyzerXMPPConnector();
//droneAnalyzerXMPPConnector.initConnector();
}
//@Test
public void login(){
// droneAnalyzerXMPPConnector.connectAndLogin();
// log.info("ip address "+XmppConfig.getInstance().getXmppServerIP());
//log.info("path "+ CarbonUtils.getCarbonConfigDirPath());
// log.info("path "+ CarbonUtils.getCarbonHome());
//System.out.println(System.getProperty("carbon.home"));
System.out.println(System.getenv("CARBON_HOME"));
}
}

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="jacksonJsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"></bean>
<util:list id="webClientProviders">
<ref bean="jacksonJsonProvider"/>
</util:list>
<bean id="droneClient" class="org.apache.cxf.jaxrs.client.WebClient"
factory-method="create">
<constructor-arg type="java.lang.String" value="http://localhost:9763/drone_analyzer/DroneAnalyzerServiceUnitManager/"/>
<constructor-arg ref="webClientProviders" />
</bean>
</beans>

@ -1,77 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl.DroneAnalyzerManagerService;
import org.wso2.carbon.device.mgt.iot.service.DeviceTypeService;
public class DroneAnalyzerManagementServiceComponent {
private ServiceRegistration firealarmServiceRegRef;
private static final Log log = LogFactory.getLog(DroneAnalyzerManagementServiceComponent.class);
protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("Activating Drone Device Management Service Component");
}
try {
BundleContext bundleContext = ctx.getBundleContext();
firealarmServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(),
new DroneAnalyzerManagerService(), null);
if (log.isDebugEnabled()) {
log.debug("Drone Device Management Service Component has been successfully activated");
}
} catch (Throwable e) {
log.error("Error occurred while activating Drone Device Management Service Component", e);
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating Virtual Firealarm Device Management Service Component");
}
try {
if (firealarmServiceRegRef != null) {
firealarmServiceRegRef.unregister();
}
if (log.isDebugEnabled()) {
log.debug(
"Virtual Firealarm Device Management Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error("Error occurred while de-activating Virtual Firealarm Device Management bundle", e);
}
}
protected void setDeviceTypeService(DeviceTypeService deviceTypeService) {
if (log.isDebugEnabled()) {
log.debug("Data source service set to mobile service component");
}
}
protected void unsetDeviceTypeService(DeviceTypeService deviceTypeService) {
//do nothing
}
}

@ -1,111 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.trasformer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.MessageConfig;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
public class MessageTransformer {
private Log log = LogFactory.getLog(MessageTransformer.class);
private Queue<String> sharedQueue;
private String current_message = "";
ObjectMapper mapper;
boolean isOld = true;
private String inbound_message_format = "{\"quatanium_val\":[%d, %d, %d, %d],\"accelerometer\":[%d, %d, %d]," +
"\"gyroscope\":[%d, %d, %d],\"magnetometer\":[%d, %d, %d],\"basicParam\":[%d, %d, %d]}";
private String outbound_message_format = "{\"quatanium_val\":[%f, %f, %f, %f],\"accelerometer\":[%f, %f, %f]," +
"\"gyroscope\":[%f, %f, %f],\"magnetometer\":[%f, %f, %f],\"basicParam\":[%f, %f, %f]}";
public MessageTransformer(){
mapper = new ObjectMapper();
sharedQueue = new LinkedList<String>();
}
public void messageTranslater(String inbound_message){
JsonNode actualObj = null;
String outbound_message;
try {
actualObj = mapper.readTree(inbound_message);
ArrayNode quatannim_vals = (ArrayNode) actualObj.path(MessageConfig.IN_QUATANNIM_VAL);
ArrayNode accelerometer_vals = (ArrayNode) actualObj.path(MessageConfig.IN_ACCELETOMETER_VAL);
ArrayNode gyroscope_vals = (ArrayNode) actualObj.path(MessageConfig.IN_GYROSCOPE_VAL);
ArrayNode magnetometer_vals = (ArrayNode) actualObj.path(MessageConfig.IN_GYROSCOPE_VAL);
ArrayNode basicParam_vals = (ArrayNode) actualObj.path(MessageConfig.IN_BASIC_PARAM_VAL);
outbound_message = String.format(outbound_message_format, sTd(quatannim_vals.get(0)), sTd(quatannim_vals.get(1)),
sTd(quatannim_vals.get(2)), sTd(quatannim_vals.get(3)), sTd(accelerometer_vals.get(0)),
sTd(accelerometer_vals.get(1)), sTd(accelerometer_vals.get(2)), sTd(gyroscope_vals.get(0)),
sTd(gyroscope_vals.get(1)), sTd(gyroscope_vals.get(2)), sTd(magnetometer_vals.get(0)),
sTd(magnetometer_vals.get(1)), sTd(magnetometer_vals.get(2)), sTd(basicParam_vals.get(0)),
sTd(basicParam_vals.get(1)), sTd(basicParam_vals.get(2)));
synchronized(current_message){
isOld = false;
current_message = outbound_message;
}
sharedQueue.add(outbound_message);
} catch (IOException e) {
log.error(e.getMessage()+",\n"+ e);
}catch (Exception e) {
log.error(e.getMessage()+",\n"+ e);
}
}
private double sTd(JsonNode s)
{
return Double.parseDouble(s.toString());
}
public String getMessage() {
if(sharedQueue.isEmpty()){
return null;
}
else{
return sharedQueue.remove();
}
}
public String getCurrentMessage(){
synchronized(current_message) {
current_message = isOld == false ? current_message : null;
isOld = true;
}
return current_message;
}
public boolean isCurrentMessageEmpty()
{
return isOld;
}
public boolean isEmptyQueue(){
return sharedQueue.isEmpty();
}
}

@ -1,21 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
@ -26,7 +8,7 @@
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl</artifactId> <artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer</artifactId>
<version>1.9.2-SNAPSHOT</version> <version>1.9.2-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>

@ -15,20 +15,26 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants; package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants;
public class DroneConstants { public class DroneConstants {
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "DRONE_DEVICE_ID"; public final static String DEVICE_PLUGIN_DEVICE_ID = "DRONE_DEVICE_ID";
public final static String STATE_ON = "ON"; public final static String MESSAGE_RESOURCE = "drone_current_status";
public final static String STATE_OFF = "OFF"; public static final String DEVICE_TYPE = "drone_analyzer";
public static final String DEVICE_TYPE = "drone";
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 int MINIMUM_TIME_DURATION = 150; public static final int MINIMUM_TIME_DURATION = 150;
public static final String SENSOR_TEMPERATURE = "temp"; public static final int MAXIMUM_BUFFERE_SIZE_OF_SHARED_QUEUE = 100;
public static final String DEVICE_ID = "drone_type1";
public final static String TAKE_OFF = "takeoff";
public final static String LAND = "land";
public final static String UP = "up";
public final static String DOWN = "down";
public final static String BACK = "back";
public final static String FORWARD = "forward";
public final static String FRONT = "front";
public final static String CLOCK_WISE = "clockwise";
public final static String COUNTER_CLOCKWISE = "counterClockwise";
} }

@ -15,12 +15,15 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants;
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants;
public class MessageConfig { public class MessageConfig {
public static final String IN_QUATANNIM_VAL = "quatanium_val"; public static final String IN_QUATANNIM_VAL = "quatanium_val";
public static final String IN_DEVICE_TYPE = "device_type";
public static final String IN_IRIS_DRONE = "IRIS_DRONE";
public static final String IN_SIMULATOR = "SIMULATOR";
public static final String OUT_QUATANNIM_VAL = "quatanium_val"; public static final String OUT_QUATANNIM_VAL = "quatanium_val";
public static final String IN_ACCELETOMETER_VAL = "accelerometer"; public static final String IN_ACCELETOMETER_VAL = "accelerometer";
public static final String OUT_ACCELETOMETER_VAL = "accelerometer"; public static final String OUT_ACCELETOMETER_VAL = "accelerometer";
@ -30,5 +33,8 @@ public class MessageConfig {
public static final String OUT_MAGNETOMETER_VAL = "magnetometer"; public static final String OUT_MAGNETOMETER_VAL = "magnetometer";
public static final String IN_BASIC_PARAM_VAL = "basicParam"; public static final String IN_BASIC_PARAM_VAL = "basicParam";
public static final String OUT_BASIC_PARAM_VAL = "basicParam"; public static final String OUT_BASIC_PARAM_VAL = "basicParam";
public static final String OUT_BASIC_PARAM_VELOCITY = "velocity";
public static final String OUT_BASIC_PARAM_GLOBAL_LOCATION = "global_location";
public static final String OUT_BATTERY_LEVEL = "battery_level";
} }

@ -0,0 +1,32 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.controller;
public interface DroneController {
boolean takeoff();
boolean land();
boolean up(double speed, double duration);
boolean down(double speed, double duration);
boolean left(double speed, double duration);
boolean right(double speed, double duration);
boolean front(double speed, double duration);
boolean back(double speed, double duration);
boolean clockwise(double speed, double duration);
boolean conterClockwise(double speed, double duration);
}

@ -0,0 +1,73 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.controller.impl;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.controller.DroneController;
public class DroneControllerImpl implements DroneController{
@Override
public boolean takeoff() {
return false;
}
@Override
public boolean land() {
return false;
}
@Override
public boolean up(double speed, double duration) {
return false;
}
@Override
public boolean down(double speed, double duration) {
return false;
}
@Override
public boolean left(double speed, double duration) {
return false;
}
@Override
public boolean right(double speed, double duration) {
return false;
}
@Override
public boolean front(double speed, double duration) {
return false;
}
@Override
public boolean back(double speed, double duration) {
return false;
}
@Override
public boolean clockwise(double speed, double duration) {
return false;
}
@Override
public boolean conterClockwise(double speed, double duration) {
return false;
}
}

@ -15,6 +15,7 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl; package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -32,6 +33,9 @@ import org.wso2.carbon.device.mgt.iot.util.iotdevice.util.IotDeviceManagementUti
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/**
* This represents the Drone Analyzer service implementation of DeviceManagerService.
*/
public class DroneAnalyzerManager implements DeviceManager { public class DroneAnalyzerManager implements DeviceManager {
private static final IotDeviceManagementDAOFactory iotDeviceManagementDAOFactory = new DroneAnalyzerDAO(); private static final IotDeviceManagementDAOFactory iotDeviceManagementDAOFactory = new DroneAnalyzerDAO();
@ -61,7 +65,7 @@ public class DroneAnalyzerManager implements DeviceManager {
IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device); IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device);
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Enrolling a new Virtual Firealarm device : " + device.getDeviceIdentifier()); log.debug("Enrolling a new drone device : " + device.getDeviceIdentifier());
} }
DroneAnalyzerDAO.beginTransaction(); DroneAnalyzerDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice( status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice(
@ -74,7 +78,7 @@ public class DroneAnalyzerManager implements DeviceManager {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString(); String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, iotDAOEx); log.warn(msg, iotDAOEx);
} }
String msg = "Error while enrolling the Virtual Firealarm device : " + device.getDeviceIdentifier(); String msg = "Error while enrolling the drone device : " + device.getDeviceIdentifier();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} }
@ -100,7 +104,7 @@ public class DroneAnalyzerManager implements DeviceManager {
String msg = "Error occurred while roll back the update device transaction :" + device.toString(); String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx); log.warn(msg, iotDAOEx);
} }
String msg = "Error while updating the enrollment of the Virtual Firealarm device : " + String msg = "Error while updating the enrollment of the drone device : " +
device.getDeviceIdentifier(); device.getDeviceIdentifier();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
@ -113,7 +117,7 @@ public class DroneAnalyzerManager implements DeviceManager {
boolean status; boolean status;
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Dis-enrolling Virtual Firealarm device : " + deviceId); log.debug("Dis-enrolling drone device : " + deviceId);
} }
DroneAnalyzerDAO.beginTransaction(); DroneAnalyzerDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO() status = iotDeviceManagementDAOFactory.getIotDeviceDAO()
@ -126,7 +130,7 @@ public class DroneAnalyzerManager implements DeviceManager {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString(); String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx); log.warn(msg, iotDAOEx);
} }
String msg = "Error while removing the Virtual Firealarm device : " + deviceId.getId(); String msg = "Error while removing the drone device : " + deviceId.getId();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} }
@ -138,14 +142,14 @@ public class DroneAnalyzerManager implements DeviceManager {
boolean isEnrolled = false; boolean isEnrolled = false;
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Virtual Firealarm device : " + deviceId.getId()); log.debug("Checking the enrollment of Drone device : " + deviceId.getId());
} }
IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO().getIotDevice(deviceId.getId()); IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO().getIotDevice(deviceId.getId());
if (iotDevice != null) { if (iotDevice != null) {
isEnrolled = true; isEnrolled = true;
} }
} catch (IotDeviceManagementDAOException e) { } catch (IotDeviceManagementDAOException e) {
String msg = "Error while checking the enrollment status of Virtual Firealarm device : " + String msg = "Error while checking the enrollment status of Drone device : " +
deviceId.getId(); deviceId.getId();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
@ -169,13 +173,13 @@ public class DroneAnalyzerManager implements DeviceManager {
Device device; Device device;
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the details of Virtual Firealarm device : " + deviceId.getId()); log.debug("Getting the details of Drone device : " + deviceId.getId());
} }
IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO(). IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO().
getIotDevice(deviceId.getId()); getIotDevice(deviceId.getId());
device = IotDeviceManagementUtil.convertToDevice(iotDevice); device = IotDeviceManagementUtil.convertToDevice(iotDevice);
} catch (IotDeviceManagementDAOException e) { } catch (IotDeviceManagementDAOException e) {
String msg = "Error while fetching the Virtual Firealarm device : " + deviceId.getId(); String msg = "Error while fetching the Drone device : " + deviceId.getId();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} }
@ -215,7 +219,7 @@ public class DroneAnalyzerManager implements DeviceManager {
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug( log.debug(
"updating the details of Virtual Firealarm device : " + deviceIdentifier); "updating the details of Drone device : " + deviceIdentifier);
} }
DroneAnalyzerDAO.beginTransaction(); DroneAnalyzerDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO() status = iotDeviceManagementDAOFactory.getIotDeviceDAO()
@ -229,7 +233,7 @@ public class DroneAnalyzerManager implements DeviceManager {
log.warn(msg, iotDAOEx); log.warn(msg, iotDAOEx);
} }
String msg = String msg =
"Error while updating the Virtual Firealarm device : " + deviceIdentifier; "Error while updating the Drone device : " + deviceIdentifier;
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} }
@ -241,7 +245,7 @@ public class DroneAnalyzerManager implements DeviceManager {
List<Device> devices = null; List<Device> devices = null;
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Virtual Firealarm devices"); log.debug("Fetching the details of all Drone devices");
} }
List<IotDevice> iotDevices = List<IotDevice> iotDevices =
iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices(); iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices();
@ -252,14 +256,13 @@ public class DroneAnalyzerManager implements DeviceManager {
} }
} }
} catch (IotDeviceManagementDAOException e) { } catch (IotDeviceManagementDAOException e) {
String msg = "Error while fetching all Virtual Firealarm devices."; String msg = "Error while fetching all Drone devices.";
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} }
return devices; return devices;
} }
@Override @Override
public boolean requireDeviceAuthorization() { public boolean requireDeviceAuthorization() {
return true; return true;

@ -29,6 +29,7 @@ import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConsta
import java.util.List; import java.util.List;
public class DroneAnalyzerManagerService implements DeviceManagementService { public class DroneAnalyzerManagerService implements DeviceManagementService {
private DeviceManager deviceManager; private DeviceManager deviceManager;
@Override @Override

@ -15,6 +15,7 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl.dao; package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl.dao;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -30,6 +31,7 @@ import javax.sql.DataSource;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
public class DroneAnalyzerDAO extends IotDeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface { public class DroneAnalyzerDAO extends IotDeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface {
private static final Log log = LogFactory.getLog(DroneAnalyzerDAO.class); private static final Log log = LogFactory.getLog(DroneAnalyzerDAO.class);
@ -37,10 +39,10 @@ public class DroneAnalyzerDAO extends IotDeviceManagementDAOFactory implements I
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>(); private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public DroneAnalyzerDAO() { public DroneAnalyzerDAO() {
initFireAlarmDAO(); initDroneAnalyzerDAO();
} }
public static void initFireAlarmDAO() { public static void initDroneAnalyzerDAO() {
dataSource = getDataSourceMap().get(DroneConstants.DEVICE_TYPE); dataSource = getDataSourceMap().get(DroneConstants.DEVICE_TYPE);
} }
@ -68,7 +70,6 @@ public class DroneAnalyzerDAO extends IotDeviceManagementDAOFactory implements I
throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e); throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e);
} }
} }
//log.info("------>");
return currentConnection.get(); return currentConnection.get();
} }

@ -15,6 +15,7 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl.dao.impl; package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl.dao.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -34,7 +35,9 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/**
* Implements IotDeviceDAO for drone analyzer.
*/
public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO { public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO {
private static final Log log = LogFactory.getLog(DroneAnalyzerDeviceDAOImpl.class); private static final Log log = LogFactory.getLog(DroneAnalyzerDeviceDAOImpl.class);
@ -47,9 +50,12 @@ public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO {
ResultSet resultSet = null; ResultSet resultSet = null;
try { try {
conn = DroneAnalyzerDAO.getConnection(); conn = DroneAnalyzerDAO.getConnection();
if(conn == null){
log.error("Database connection hasn't been created");
}
String selectDBQuery = String selectDBQuery =
"SELECT VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME" + "SELECT DRONE_DEVICE_ID, DEVICE_NAME" +
" FROM VIRTUAL_FIREALARM_DEVICE WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?"; " FROM DRONE_DEVICE WHERE DRONE_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery); stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, iotDeviceId); stmt.setString(1, iotDeviceId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
@ -66,7 +72,7 @@ public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while fetching Drone device : '" + iotDeviceId + "'"; String msg = "Error occurred while fetching drone device : '" + iotDeviceId + "'";
log.error(msg, e); log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e); throw new IotDeviceManagementDAOException(msg, e);
} finally { } finally {
@ -84,7 +90,7 @@ public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO {
try { try {
conn = DroneAnalyzerDAO.getConnection(); conn = DroneAnalyzerDAO.getConnection();
String createDBQuery = String createDBQuery =
"INSERT INTO VIRTUAL_FIREALARM_DEVICE(VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)"; "INSERT INTO DRONE_DEVICE(DRONE_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery); stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, iotDevice.getIotDeviceId()); stmt.setString(1, iotDevice.getIotDeviceId());
@ -98,13 +104,13 @@ public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO {
if (rows > 0) { if (rows > 0) {
status = true; status = true;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Virtual Firealarm device " + iotDevice.getIotDeviceId() + " data has been" + log.debug("drone device " + iotDevice.getIotDeviceId() + " data has been" +
" added to the Virtual Firealarm database."); " added to the drone database.");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while adding the Virtual Firealarm device '" + String msg = "Error occurred while adding the drone device '" +
iotDevice.getIotDeviceId() + "' to the Virtual Firealarm db."; iotDevice.getIotDeviceId() + "' to the drone db.";
log.error(msg, e); log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e); throw new IotDeviceManagementDAOException(msg, e);
} finally { } finally {
@ -122,7 +128,7 @@ public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO {
try { try {
conn = DroneAnalyzerDAO.getConnection(); conn = DroneAnalyzerDAO.getConnection();
String updateDBQuery = String updateDBQuery =
"UPDATE VIRTUAL_FIREALARM_DEVICE SET DEVICE_NAME = ? WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?"; "UPDATE DRONE_DEVICE SET DEVICE_NAME = ? WHERE DRONE_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery); stmt = conn.prepareStatement(updateDBQuery);
if (iotDevice.getDeviceProperties() == null) { if (iotDevice.getDeviceProperties() == null) {
iotDevice.setDeviceProperties(new HashMap<String, String>()); iotDevice.setDeviceProperties(new HashMap<String, String>());
@ -157,8 +163,8 @@ public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO {
try { try {
conn = DroneAnalyzerDAO.getConnection(); conn = DroneAnalyzerDAO.getConnection();
System.out.println("delete device "); System.out.println("delete device ");
/* String deleteDBQuery = String deleteDBQuery =
"DELETE FROM VIRTUAL_FIREALARM_DEVICE WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?"; "DELETE FROM DRONE_DEVICE WHERE DRONE_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery); stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, iotDeviceId); stmt.setString(1, iotDeviceId);
int rows = stmt.executeUpdate(); int rows = stmt.executeUpdate();
@ -166,14 +172,14 @@ public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO {
status = true; status = true;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Drone device " + iotDeviceId + " data has deleted" + log.debug("Drone device " + iotDeviceId + " data has deleted" +
" from the Virtual Drone database."); " from the drone database.");
} }
}*/ }
} /*catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while deleting Virtual Firealarm device " + iotDeviceId; String msg = "Error occurred while deleting drone device " + iotDeviceId;
log.error(msg, e); log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e); throw new IotDeviceManagementDAOException(msg, e);
}*/ finally { } finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null); IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
} }
return status; return status;
@ -193,8 +199,8 @@ public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO {
try { try {
conn = DroneAnalyzerDAO.getConnection(); conn = DroneAnalyzerDAO.getConnection();
String selectDBQuery = String selectDBQuery =
"SELECT VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME " + "SELECT DRONE_DEVICE_ID, DEVICE_NAME " +
"FROM VIRTUAL_FIREALARM_DEVICE"; "FROM DRONE_DEVICE";
stmt = conn.prepareStatement(selectDBQuery); stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
@ -208,11 +214,11 @@ public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO {
iotDevices.add(iotDevice); iotDevices.add(iotDevice);
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("All Virtual Firealarm device details have fetched from Firealarm database."); log.debug("All drone device details have fetched from drone database.");
} }
return iotDevices; return iotDevices;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while fetching all Virtual Firealarm device data'"; String msg = "Error occurred while fetching all drone device data'";
log.error(msg, e); log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e); throw new IotDeviceManagementDAOException(msg, e);
} finally { } finally {

@ -22,6 +22,9 @@ import org.apache.commons.logging.LogFactory;
import java.util.Map; import java.util.Map;
/**
* Contains utility methods used by Drone Analyzer plugin.
*/
public class DroneAnalyzerUtils { public class DroneAnalyzerUtils {
private static Log log = LogFactory.getLog(DroneAnalyzerUtils.class); private static Log log = LogFactory.getLog(DroneAnalyzerUtils.class);

@ -30,8 +30,8 @@ import org.wso2.carbon.device.mgt.iot.service.DeviceTypeService;
/** /**
* @scr.component name="org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal * @scr.component name="org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.internal
* .VirtualFirealarmManagementServiceComponent" * .DroneAnalyzerManagementServiceComponent"
* immediate="true" * immediate="true"
* @scr.reference name="org.wso2.carbon.device.mgt.iot.service.DeviceTypeServiceImpl" * @scr.reference name="org.wso2.carbon.device.mgt.iot.service.DeviceTypeServiceImpl"
* interface="org.wso2.carbon.device.mgt.iot.service.DeviceTypeService" * interface="org.wso2.carbon.device.mgt.iot.service.DeviceTypeService"
@ -48,7 +48,7 @@ public class DroneAnalyzerManagementServiceComponent {
protected void activate(ComponentContext ctx) { protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Activating Virtual Firealarm Device Management Service Component"); log.debug("Activating Drone Analyzer Management Service Component");
} }
try { try {
BundleContext bundleContext = ctx.getBundleContext(); BundleContext bundleContext = ctx.getBundleContext();
@ -58,12 +58,12 @@ public class DroneAnalyzerManagementServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug( log.debug(
"Virtual Firealarm Device Management Service Component has been " + "Drone Analyzer Device Management Service Component has been " +
"successfully activated"); "successfully activated");
} }
} catch (Throwable e) { } catch (Throwable e) {
log.error( log.error(
"Error occurred while activating Virtual Firealarm Device Management Service " + "Error occurred while activating Drone Analyzer Device Management Service " +
"Component", "Component",
e); e);
} }
@ -71,7 +71,7 @@ public class DroneAnalyzerManagementServiceComponent {
protected void deactivate(ComponentContext ctx) { protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("De-activating Virtual Firealarm Device Management Service Component"); log.debug("De-activating Drone Analyzer Device Management Service Component");
} }
try { try {
if (firealarmServiceRegRef != null) { if (firealarmServiceRegRef != null) {
@ -80,12 +80,12 @@ public class DroneAnalyzerManagementServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug( log.debug(
"Virtual Firealarm Device Management Service Component has been " + "Drone Analyzer Device Management Service Component has been " +
"successfully de-activated"); "successfully de-activated");
} }
} catch (Throwable e) { } catch (Throwable e) {
log.error( log.error(
"Error occurred while de-activating Virtual Firealarm Device Management " + "Error occurred while de-activating Drone Analyzer Device Management " +
"bundle", "bundle",
e); e);
} }

@ -0,0 +1,25 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl.dao.impl;
import org.junit.Before;
import org.junit.Test;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException;
/**
* Created by geesara on 12/9/15.
*/
public class DroneAnalyzerDeviceDAOImplTest {
DroneAnalyzerDeviceDAOImpl dao;
@Before
public void init(){
dao = new DroneAnalyzerDeviceDAOImpl();
}
//@Test
public void testDBConnenction(){
try {
dao.deleteIotDevice("device1");
} catch (IotDeviceManagementDAOException e) {
e.printStackTrace();
}
}
}

@ -32,8 +32,8 @@
<artifactId>device-mgt-iot-droneanalyzer</artifactId> <artifactId>device-mgt-iot-droneanalyzer</artifactId>
<version>1.9.2-SNAPSHOT</version> <version>1.9.2-SNAPSHOT</version>
<modules> <modules>
<module>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl</module> <module>org.wso2.carbon.device.mgt.iot.droneanalyzer</module>
<module>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl</module> <module>org.wso2.carbon.device.mgt.iot.droneanalyzer.api</module>
</modules> </modules>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>WSO2 Carbon - IoT Device Drone Analyzer Management Component</name> <name>WSO2 Carbon - IoT Device Drone Analyzer Management Component</name>

@ -22,11 +22,11 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl</artifactId> <artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl</artifactId> <artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.api</artifactId>
<type>war</type> <type>war</type>
</dependency> </dependency>
</dependencies> </dependencies>
@ -71,7 +71,7 @@
<artifactItems> <artifactItems>
<artifactItem> <artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl <artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.api
</artifactId> </artifactId>
<type>war</type> <type>war</type>
<overWrite>true</overWrite> <overWrite>true</overWrite>
@ -105,7 +105,7 @@
</adviceFile> </adviceFile>
<bundles> <bundles>
<bundleDef> <bundleDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl:${carbon.iot.device.mgt.version} org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.droneanalyzer:${carbon.iot.device.mgt.version}
</bundleDef> </bundleDef>
</bundles> </bundles>
<importFeatures> <importFeatures>

@ -0,0 +1,33 @@
#
# Copyright (c) 2015, 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.
#
#
#[Device-Configurations]
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/drone_analyzer/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}
push-interval=15

@ -17,6 +17,14 @@
~ under the License. ~ under the License.
--> -->
<!--<IoTDeviceTypeConfigManager>
<IotDeviceTypeConfig type="drone_analyzer">
<DatasourceName>jdbc/DroneAnalyzerDM_DB</DatasourceName>
&lt;!&ndash;ApiApplicationName>firealarm</ApiApplicationName&ndash;&gt;
</IotDeviceTypeConfig>
</IoTDeviceTypeConfigManager>-->
<DeviceTypeConfigurations> <DeviceTypeConfigurations>

@ -0,0 +1,48 @@
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>
<datasources>
<datasource>
<name>VirtualFireAlarmDM_DB</name>
<description>The datasource used for the Virtual-Firealarm database</description>
<jndiConfig>
<name>jdbc/VirtualFireAlarmDM_DB</name>
</jndiConfig>
<definition type="RDBMS">
<configuration>
<url>jdbc:h2:repository/database/VirtualFireAlarmDM_DB;DB_CLOSE_ON_EXIT=FALSE
</url>
<username>wso2carbon</username>
<password>wso2carbon</password>
<driverClassName>org.h2.Driver</driverClassName>
<maxActive>50</maxActive>
<maxWait>60000</maxWait>
<testOnBorrow>true</testOnBorrow>
<validationQuery>SELECT 1</validationQuery>
<validationInterval>30000</validationInterval>
</configuration>
</definition>
</datasource>
</datasources>
</datasources-configuration>

@ -1,11 +1,11 @@
-- ----------------------------------------------------- -- -----------------------------------------------------
-- Table `FIREALARM_DEVICE` -- Table `DRONE_DEVICE`
-- ----------------------------------------------------- -- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `VIRTUAL_FIREALARM_DEVICE` ( CREATE TABLE IF NOT EXISTS `DRONE_DEVICE` (
`VIRTUAL_FIREALARM_DEVICE_ID` VARCHAR(45) NOT NULL , `DRONE_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`VIRTUAL_FIREALARM_DEVICE_ID`) ); PRIMARY KEY (`DRONE_DEVICE_ID`) );

@ -1,10 +1,10 @@
-- ----------------------------------------------------- -- -----------------------------------------------------
-- Table `FIREALARM_DEVICE` -- Table `DRONE_DEVICE`
-- ----------------------------------------------------- -- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `VIRTUAL_FIREALARM_DEVICE` ( CREATE TABLE IF NOT EXISTS `DRONE_DEVICE` (
`VIRTUAL_FIREALARM_DEVICE_ID` VARCHAR(45) NOT NULL , `DRONE_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`VIRTUAL_FIREALARM_DEVICE_ID`) ) PRIMARY KEY (`DRONE_DEVICE_ID`) )
ENGINE = InnoDB; ENGINE = InnoDB;

@ -1,36 +0,0 @@
<div id="device_overview">
<div class="media-left media-middle asset-image col-xs-2 col-sm-2 col-md-2 col-lg-2">
{{unit "cdmf.unit.device.overview.droneanalyzer-display-image"}}
</div>
<div class="media-body asset-desc add-padding-left-5x">
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">Device Overview - Virtual Firealarm</div>
{{#defineZone "device-detail-properties"}}
<table class="table table-responsive table-striped" id="members">
<tbody>
<tr role="row" class="even"><td class="sorting_1" style="padding:10px 15px; width: 1%;;">Device</td><td style="padding:10px 15px;">{{device.viewModel.vendor}} {{device.properties.model}}</td></tr>
<tr role="row" class="odd"><td class="sorting_1" style="padding:10px 15px;">Model</td><td style="padding:10px 15px;">{{device.viewModel.model}}</td></tr>
<tr role="row" class="even"><td class="sorting_1" style="padding:10px 15px;">IMEI</td><td style="padding:10px 15px;">{{device.viewModel.imei}}</td></tr>
{{#if device.viewModel.udid}}
<tr role="row" class="even"><td class="sorting_1" style="padding:10px 15px;">UDID</td><td style="padding:10px 15px;">{{device.viewModel.udid}}</td></tr>
{{/if}}
{{#if device.viewModel.phoneNumber}}
<tr role="row" class="even"><td class="sorting_1" style="padding:10px 15px;">Phone Number</td><td style="padding:10px 15px;">{{device.viewModel.phoneNumber}}</td></tr>
{{/if}}
<tr role="row" class="even">
<td class="sorting_1" style="padding:10px 15px;">Status</td>
<td style="padding:10px 15px;">
{{#equal device.status "ACTIVE"}}<span><i class="fw fw-ok icon-success"></i> Active</span>{{/equal}}
{{#equal device.status "INACTIVE"}}<span><i class="fw fw-warning icon-warning"></i> Inactive</span>{{/equal}}
{{#equal device.status "BLOCKED"}}<span><i class="fw fw-remove icon-danger"></i> Blocked</span>{{/equal}}
{{#equal device.status "REMOVED"}}<span><i class="fw fw-delete icon-danger"></i> Removed</span>{{/equal}}
</td>
</tr>
</tbody>
</table>
{{/defineZone}}
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">Operations</div>
<div class="add-margin-top-4x">
{{unit "cdmf.unit.device.iot-operation" deviceType=device.type}}
</div>
</div>
</div>

@ -1,25 +0,0 @@
function onRequest (context) {
var log = new Log("detail.js");
var deviceType = request.getParameter("type");
var deviceId = request.getParameter("id");
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/modules/device.js").deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId);
if (device) {
var viewModel = {};
var deviceInfo = device.properties.DEVICE_INFO;
if (deviceInfo != undefined && String(deviceInfo.toString()).length > 0) {
deviceInfo = parse(stringify(deviceInfo));
viewModel.system = device.properties.IMEI;
viewModel.machine = "Virtual Firealarm";
viewModel.vendor = device.properties.VENDOR;
}
device.viewModel = viewModel;
}
context.device = device;
return context;
}
}

@ -0,0 +1,10 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../conf/devicetype-conf/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/configs/,target:${installFolder}/../../conf/devicetype-conf/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/drone_analyzer/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/drone_analyzer,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\

@ -412,13 +412,13 @@
<!--+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--> <!--+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-->
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl</artifactId> <artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer</artifactId>
<version>${carbon.iot.device.mgt.version}</version> <version>${carbon.iot.device.mgt.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl</artifactId> <artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.api</artifactId>
<version>${carbon.iot.device.mgt.version}</version> <version>${carbon.iot.device.mgt.version}</version>
<type>war</type> <type>war</type>
</dependency> </dependency>

Loading…
Cancel
Save