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

adding drone as a device type
Ruwan 9 years ago
commit 9233a6f8ff

@ -0,0 +1,106 @@
<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">
<parent>
<artifactId>device-mgt-iot-droneanalyzer</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>1.9.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl</artifactId>
<version>1.9.2-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - IoT Server Drone Analyzer Management Plugin</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.iot.device.mgt.version}</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.xml.bind.*,
javax.naming,
javax.sql,
javax.xml.bind.annotation.*,
javax.xml.parsers,
javax.net,
javax.net.ssl,
org.w3c.dom,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.context.*,
org.wso2.carbon.ndatasource.core,
org.wso2.carbon.device.mgt.iot.*,
</Import-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.internal,
org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,63 @@
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;
/**
* Created by geesara on 12/9/15.
*/
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
}
}

@ -0,0 +1,20 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants;
/**
* Created by geesara on 12/7/15.
*/
public class DroneConstants {
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 STATE_ON = "ON";
public final static String STATE_OFF = "OFF";
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 String SENSOR_TEMPERATURE = "temp";
}

@ -0,0 +1,17 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants;
public class MessageConfig {
public static final String IN_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 OUT_ACCELETOMETER_VAL = "accelerometer";
public static final String IN_GYROSCOPE_VAL = "gyroscope";
public static final String OUT_GYROSCOPE_VAL = "gyroscope";
public static final String IN_MAGNETOMETER_VAL = "magnetometer";
public static final String OUT_MAGNETOMETER_VAL = "magnetometer";
public static final String IN_BASIC_PARAM_VAL = "basicParam";
public static final String OUT_BASIC_PARAM_VAL = "basicParam";
}

@ -0,0 +1,253 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl.dao.DroneAnalyzerDAO;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dto.IotDevice;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.util.IotDeviceManagementUtil;
import java.util.ArrayList;
import java.util.List;
/**
* Created by geesara on 12/9/15.
*/
public class DroneAnalyzerManager implements DeviceManager {
private static final IotDeviceManagementDAOFactory iotDeviceManagementDAOFactory = new DroneAnalyzerDAO();
private static final Log log = LogFactory.getLog(DroneAnalyzerManager.class);
@Override
public FeatureManager getFeatureManager() {
return null;
}
@Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration)
throws DeviceManagementException {
//TODO implement this
return false;
}
@Override
public TenantConfiguration getConfiguration() throws DeviceManagementException {
//TODO implement this
return null;
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status;
IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device);
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new Virtual Firealarm device : " + device.getDeviceIdentifier());
}
DroneAnalyzerDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice(
iotDevice);
DroneAnalyzerDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while enrolling the Virtual Firealarm device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status;
IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device);
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Virtual Firealarm device enrollment data");
}
DroneAnalyzerDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO()
.updateIotDevice(iotDevice);
DroneAnalyzerDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while updating the enrollment of the Virtual Firealarm device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling Virtual Firealarm device : " + deviceId);
}
DroneAnalyzerDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO()
.deleteIotDevice(deviceId.getId());
DroneAnalyzerDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while removing the Virtual Firealarm device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Virtual Firealarm device : " + deviceId.getId());
}
IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO().getIotDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (IotDeviceManagementDAOException e) {
String msg = "Error while checking the enrollment status of Virtual Firealarm device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return isEnrolled;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return true;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Virtual Firealarm device : " + deviceId.getId());
}
IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO().
getIotDevice(deviceId.getId());
device = IotDeviceManagementUtil.convertToDevice(iotDevice);
} catch (IotDeviceManagementDAOException e) {
String msg = "Error while fetching the Virtual Firealarm device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return device;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
}
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
}
@Override
public License getLicense(String s) throws LicenseManagementException {
return null;
}
@Override
public void addLicense(License license) throws LicenseManagementException {
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
boolean status;
IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device);
try {
if (log.isDebugEnabled()) {
log.debug(
"updating the details of Virtual Firealarm device : " + deviceIdentifier);
}
DroneAnalyzerDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO()
.updateIotDevice(iotDevice);
DroneAnalyzerDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg =
"Error while updating the Virtual Firealarm device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices = null;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Virtual Firealarm devices");
}
List<IotDevice> iotDevices =
iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices();
if (iotDevices != null) {
devices = new ArrayList<Device>();
for (IotDevice iotDevice : iotDevices) {
devices.add(IotDeviceManagementUtil.convertToDevice(iotDevice));
}
}
} catch (IotDeviceManagementDAOException e) {
String msg = "Error while fetching all Virtual Firealarm devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return devices;
}
@Override
public boolean requireDeviceAuthorization() {
return true;
}
}

@ -0,0 +1,92 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants;
import java.util.List;
/**
* Created by geesara on 12/9/15.
*/
public class DroneAnalyzerManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
@Override
public String getType() {
return DroneConstants.DEVICE_TYPE;
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager = new DroneAnalyzerManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> list)
throws DeviceManagementException {
}
@Override
public Application[] getApplications(String s, int i, int i1) throws ApplicationManagementException {
return new Application[0];
}
@Override
public void updateApplicationStatus(DeviceIdentifier deviceIdentifier, Application application, String s)
throws ApplicationManagementException {
}
@Override
public String getApplicationStatus(DeviceIdentifier deviceIdentifier, Application application)
throws ApplicationManagementException {
return null;
}
@Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> list)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUsers(Operation operation, List<String> list)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUserRoles(Operation operation, List<String> list)
throws ApplicationManagementException {
}
public String getProviderTenantDomain() {
return "carbon.super";
}
public boolean isSharedWithAllTenants() {
return true;
}
public String[] getSharedTenantsDomain() {
return new String[0];
}
}

@ -0,0 +1,109 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl.dao;
import org.apache.commons.logging.Log;
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.impl.dao.impl.DroneAnalyzerDeviceDAOImpl;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceDAO;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOFactoryInterface;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Created by geesara on 12/9/15.
*/
public class DroneAnalyzerDAO extends IotDeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface {
private static final Log log = LogFactory.getLog(DroneAnalyzerDAO.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public DroneAnalyzerDAO() {
initFireAlarmDAO();
}
public static void initFireAlarmDAO() {
dataSource = getDataSourceMap().get(DroneConstants.DEVICE_TYPE);
}
@Override
public IotDeviceDAO getIotDeviceDAO() {
return new DroneAnalyzerDeviceDAOImpl();
}
public static void beginTransaction() throws IotDeviceManagementDAOException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws IotDeviceManagementDAOException {
if (currentConnection != null && currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e);
}
}
//log.info("------>");
return currentConnection.get();
}
public static void commitTransaction() throws IotDeviceManagementDAOException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws IotDeviceManagementDAOException {
Connection con = currentConnection.get();
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
}
currentConnection.remove();
}
public static void rollbackTransaction() throws IotDeviceManagementDAOException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}
}
}

@ -0,0 +1,210 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl.dao.impl;
import org.apache.commons.logging.Log;
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.impl.dao.DroneAnalyzerDAO;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceDAO;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.util.IotDeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dto.IotDevice;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by geesara on 12/9/15.
*/
public class DroneAnalyzerDeviceDAOImpl implements IotDeviceDAO {
private static final Log log = LogFactory.getLog(DroneAnalyzerDeviceDAOImpl.class);
@Override
public IotDevice getIotDevice(String iotDeviceId) throws IotDeviceManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
IotDevice iotDevice = null;
ResultSet resultSet = null;
try {
conn = DroneAnalyzerDAO.getConnection();
String selectDBQuery =
"SELECT VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME" +
" FROM VIRTUAL_FIREALARM_DEVICE WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, iotDeviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
iotDevice = new IotDevice();
iotDevice.setIotDeviceName(resultSet.getString(
DroneConstants.DEVICE_PLUGIN_DEVICE_NAME));
Map<String, String> propertyMap = new HashMap<String, String>();
iotDevice.setDeviceProperties(propertyMap);
if (log.isDebugEnabled()) {
log.debug("Drone device " + iotDeviceId + " data has been fetched from " +
"Drone database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching Drone device : '" + iotDeviceId + "'";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet);
DroneAnalyzerDAO.closeConnection();
}
return iotDevice;
}
@Override
public boolean addIotDevice(IotDevice iotDevice) throws IotDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DroneAnalyzerDAO.getConnection();
String createDBQuery =
"INSERT INTO VIRTUAL_FIREALARM_DEVICE(VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, iotDevice.getIotDeviceId());
stmt.setString(2,iotDevice.getIotDeviceName());
if (iotDevice.getDeviceProperties() == null) {
iotDevice.setDeviceProperties(new HashMap<String, String>());
}
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Virtual Firealarm device " + iotDevice.getIotDeviceId() + " data has been" +
" added to the Virtual Firealarm database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the Virtual Firealarm device '" +
iotDevice.getIotDeviceId() + "' to the Virtual Firealarm db.";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean updateIotDevice(IotDevice iotDevice)
throws IotDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DroneAnalyzerDAO.getConnection();
String updateDBQuery =
"UPDATE VIRTUAL_FIREALARM_DEVICE SET DEVICE_NAME = ? WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
if (iotDevice.getDeviceProperties() == null) {
iotDevice.setDeviceProperties(new HashMap<String, String>());
}
stmt.setString(1, iotDevice.getIotDeviceName());
stmt.setString(2, iotDevice.getIotDeviceId());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Drone device " + iotDevice.getIotDeviceId() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Drone device '" +
iotDevice.getIotDeviceId() + "' data.";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean deleteIotDevice(String iotDeviceId)
throws IotDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DroneAnalyzerDAO.getConnection();
System.out.println("delete device ");
/* String deleteDBQuery =
"DELETE FROM VIRTUAL_FIREALARM_DEVICE WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, iotDeviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Drone device " + iotDeviceId + " data has deleted" +
" from the Virtual Drone database.");
}
}*/
} /*catch (SQLException e) {
String msg = "Error occurred while deleting Virtual Firealarm device " + iotDeviceId;
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
}*/ finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public List<IotDevice> getAllIotDevices()
throws IotDeviceManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
IotDevice iotDevice;
List<IotDevice> iotDevices = new ArrayList<IotDevice>();
try {
conn = DroneAnalyzerDAO.getConnection();
String selectDBQuery =
"SELECT VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME " +
"FROM VIRTUAL_FIREALARM_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
iotDevice = new IotDevice();
iotDevice.setIotDeviceId(resultSet.getString(DroneConstants.DEVICE_PLUGIN_DEVICE_ID));
iotDevice.setIotDeviceName(resultSet.getString(DroneConstants.DEVICE_PLUGIN_DEVICE_NAME));
Map<String, String> propertyMap = new HashMap<String, String>();
iotDevice.setDeviceProperties(propertyMap);
iotDevices.add(iotDevice);
}
if (log.isDebugEnabled()) {
log.debug("All Virtual Firealarm device details have fetched from Firealarm database.");
}
return iotDevices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all Virtual Firealarm device data'";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet);
DroneAnalyzerDAO.closeConnection();
}
}
}

@ -0,0 +1,21 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Map;
/**
* Created by geesara on 12/9/15.
*/
public class DroneAnalyzerUtils {
private static Log log = LogFactory.getLog(DroneAnalyzerUtils.class);
public static String getDeviceProperty(Map<String, String> deviceProperties, String property) {
String deviceProperty = deviceProperties.get(property);
if (deviceProperty == null) {
return "";
}
return deviceProperty;
}
}

@ -0,0 +1,106 @@
/*
* 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.internal;
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;
/**
* @scr.component name="org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal
* .VirtualFirealarmManagementServiceComponent"
* immediate="true"
* @scr.reference name="org.wso2.carbon.device.mgt.iot.service.DeviceTypeServiceImpl"
* interface="org.wso2.carbon.device.mgt.iot.service.DeviceTypeService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDeviceTypeService"
* unbind="unsetDeviceTypeService"
*/
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 Virtual Firealarm Device Management Service Component");
}
try {
BundleContext bundleContext = ctx.getBundleContext();
firealarmServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(),
new DroneAnalyzerManagerService(), null);
if (log.isDebugEnabled()) {
log.debug(
"Virtual Firealarm Device Management Service Component has been " +
"successfully activated");
}
} catch (Throwable e) {
log.error(
"Error occurred while activating Virtual Firealarm 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) {
/* This is to avoid this component getting initialized before the common registered */
if (log.isDebugEnabled()) {
log.debug("Data source service set to mobile service component");
}
}
protected void unsetDeviceTypeService(DeviceTypeService deviceTypeService) {
//do nothing
}
}

@ -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();
}
}
}

@ -0,0 +1,231 @@
<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">
<parent>
<artifactId>device-mgt-iot-droneanalyzer</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>1.9.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl</artifactId>
<version>1.9.2-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 Carbon - IoT Server Drone Analyzer API</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>mqtt-client</artifactId>
<scope>provided</scope>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<!--<webXml>src/main/webapp/WEB-INF/web.xml</webXml>-->
<warName>drone_analyzer</warName>
<!--<outputDirectory>/home/geesara/wso2/products/wso2iot-1.0.0-SNAPSHOT/repository/deployment/server/webapps</outputDirectory>
-->
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,85 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service;
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.service.transport.DroneXMPPConnector;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.trasformer.MessageTransformer;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@ServerEndpoint("/datastream/drone_status")
public class DroneRealTimeService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneRealTimeService.class);
public MessageTransformer messageController;
public DroneXMPPConnector xmppConn;
Thread mqttStarterThread;
public DroneRealTimeService(){
messageController = new MessageTransformer();
xmppConn = new DroneXMPPConnector(messageController);
Runnable mqttStarter = new Runnable() {
@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
public void onOpen(Session session){
log.info(session.getId() + " has opened a connection");
try {
session.getBasicRemote().sendText("Connection Established");
} catch (IOException e) {
log.error( e.getMessage()+"\n"+ e);
}
}
@OnMessage
public void onMessage(String message, Session session){
try {
while(true){
if(!messageController.isEmptyQueue()){
String message1 = messageController.getMessage();
session.getBasicRemote().sendText(message1);
}
/*if((current_message = messageController.getCurrentMessage())!= null){
session.getBasicRemote().sendText( current_message );
}*/
Thread.sleep(DroneConstants.MINIMUM_TIME_DURATION);
}
} catch (IOException ex) {
log.error(ex.getMessage() + "\n" + ex);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@OnClose
public void onClose(Session session){
try {
session.getBasicRemote().sendText("Connection closed");
xmppConn.disconnect();
log.info("XMPP connection is disconnected");
} catch (Exception e) {
log.error(e.getMessage()+"\n"+ e);
}
log.info("Session " + session.getId() + " has ended");
}
}

@ -0,0 +1,744 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service;/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
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.controlqueue.xmpp.XmppAccount;
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.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport.DroneAnalyzerXMPPConnector;
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.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class DroneService {
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";
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
//private DroneAnalyzerXMPPConnector xmppConnector;
/* ---------------------------------------------------------------------------------------
Device management specific APIs
Also contains utility methods required for the execution of these APIs
--------------------------------------------------------------------------------------- */
@Path("manager/device/register")
@PUT
public boolean register(@QueryParam("deviceId") String deviceId,
@QueryParam("name") String name, @QueryParam("owner") String owner) {
log.info( deviceId + name + owner);
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
try {
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name);
device.setType(DroneConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(owner);
device.setEnrolmentInfo(enrolmentInfo);
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device);
if (added) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return added;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("manager/device/remove/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId, @Context HttpServletResponse response) {
log.info(deviceId );
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
try {
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("manager/device/update/{device_id}")
@POST
public boolean updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name,
@Context HttpServletResponse response) {
log.info(deviceId + name );
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
try {
Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
// device.setDeviceTypeId(deviceTypeId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DroneConstants.DEVICE_TYPE);
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return updated;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("manager/device/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Device getDevice(@PathParam("device_id") String deviceId) {
log.info(deviceId);
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
try {
return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null;
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("manager/devices/{username}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Device[] getDroneDevices(@PathParam("username") String username) {
/*@QueryParam("action") String action, @QueryParam("duration") String duration,
@QueryParam("speed") String speed*/
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
try {
List<Device> userDevices = deviceManagement.getDeviceManagementService().getDevicesOfUser(username);
ArrayList<Device> userDevicesforDrone = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(DroneConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(
EnrolmentInfo.Status.ACTIVE)) {
userDevicesforDrone.add(device);
}
}
return userDevicesforDrone.toArray(new Device[]{});
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null;
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("manager/device/{sketch_type}/download")
@GET
@Produces("application/octet-stream")
public Response downloadSketch(@QueryParam("owner") String owner,
@QueryParam("deviceName") String customDeviceName,
@PathParam("sketch_type") String sketchType) {
log.info(owner + customDeviceName + sketchType);
try {
ZipArchive zipFile = createDownloadFile(owner, customDeviceName, sketchType);
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
rb.header("Content-Disposition",
"attachment; filename=\"" + zipFile.getFileName() + "\"");
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (AccessTokenException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
@Path("manager/device/{sketch_type}/generate_link")
@GET
public Response generateSketchLink(@QueryParam("owner") String owner,
@QueryParam("deviceName") String customDeviceName,
@PathParam("sketch_type") String sketchType) {
log.info(owner + customDeviceName + sketchType);
try {
ZipArchive zipFile = createDownloadFile(owner, customDeviceName, sketchType);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (AccessTokenException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String owner, String customDeviceName, String sketchType)
throws DeviceManagementException, AccessTokenException, DeviceControllerException {
if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
TokenClient accessTokenClient = new TokenClient(DroneConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
//adding registering data
XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(owner + "_" + deviceId);
newXmppAccount.setUsername(deviceId);
newXmppAccount.setPassword(accessToken);
newXmppAccount.setEmail(deviceId + "@wso2.com");
XmppServerClient xmppServerClient = new XmppServerClient();
xmppServerClient.initControlQueue();
boolean status;
if (XmppConfig.getInstance().isEnabled()) {
status = xmppServerClient.createXMPPAccount(newXmppAccount);
if (!status) {
String msg =
"XMPP Account was not created for device - " + deviceId + " of owner - " +
owner +
".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot" +
".common.config.server.configs";
log.warn(msg);
throw new DeviceManagementException(msg);
}
}
//Register the device with CDMF
String deviceName = customDeviceName + "_" + deviceId;
status = register(deviceId, deviceName, owner);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId
+ " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.downloadSketch(owner, SUPER_TENANT, sketchType, deviceId, deviceName,
accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return null;
}
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
/* ---------------------------------------------------------------------------------------
Device specific APIs - Control APIs + Data-Publishing APIs
Also contains utility methods required for the execution of these APIs
--------------------------------------------------------------------------------------- */
@Path("controller/register/{owner}/{deviceId}/{ip}/{port}")
@POST
public String registerDeviceIP(@PathParam("owner") String owner,
@PathParam("deviceId") String deviceId,
@PathParam("ip") String deviceIP,
@PathParam("port") String devicePort,
@Context HttpServletResponse response,
@Context HttpServletRequest request) {
//TODO:: Need to get IP from the request itself
String result;
log.info("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId +
" of owner: " + owner);
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
response.setStatus(Response.Status.OK.getStatusCode());
if (log.isDebugEnabled()) {
log.debug(result);
}
log.info(owner + deviceId + deviceIP + devicePort );
return result;
}
/* Service to switch "ON" and "OFF" the Virtual FireAlarm bulb
Called by an external client intended to control the Virtual FireAlarm bulb */
@Path("controller/send_command")
@POST
public void droneController(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
@QueryParam("action") String action,
@QueryParam("duration") String duration,
@QueryParam("speed") String speed,
@Context HttpServletResponse response) {
/*
try {
DeviceValidator deviceValidator = new DeviceValidator();
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId,
VirtualFireAlarmConstants
.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
return;
}
} catch (DeviceManagementException e) {
log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return;
}
String switchToState = state.toUpperCase();
if (!switchToState.equals(VirtualFireAlarmConstants.STATE_ON) && !switchToState.equals(
VirtualFireAlarmConstants.STATE_OFF)) {
log.error("The requested state change shoud be either - 'ON' or 'OFF'");
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
return;
}
String protocolString = protocol.toUpperCase();
String callUrlPattern = VirtualFireAlarmConstants.BULB_CONTEXT + switchToState;
if (log.isDebugEnabled()) {
log.debug("Sending request to switch-bulb of device [" + deviceId + "] via " +
protocolString);
}
try {
switch (protocolString) {
case HTTP_PROTOCOL:
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
if (deviceHTTPEndpoint == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
}
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) {
log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " + protocolString);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return;
}
response.setStatus(Response.Status.OK.getStatusCode());*/
}
@Path("controller/readsonar")
@GET
public String requestSonarReading(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) {
/*String replyMsg = "";
DeviceValidator deviceValidator = new DeviceValidator();
try {
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId,
VirtualFireAlarmConstants
.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
return "Unauthorized Access";
}
} catch (DeviceManagementException e) {
replyMsg = e.getErrorMessage();
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return replyMsg;
}
String protocolString = protocol.toUpperCase();
if (log.isDebugEnabled()) {
log.debug("Sending request to read sonar value of device [" + deviceId + "] via " +
protocolString);
}
try {
switch (protocolString) {
case HTTP_PROTOCOL:
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
if (deviceHTTPEndpoint == null) {
replyMsg =
"IP not registered for device: " + deviceId + " of owner: " + owner;
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return replyMsg;
}
replyMsg = 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")
public Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message) {
if (log.isDebugEnabled()) {
log.debug("Invoking SCEP operation " + operation);
}
if (SCEPOperation.GET_CA_CERT.getValue().equals(operation)) {
if (log.isDebugEnabled()) {
log.debug("Invoking GetCACert");
}
try {
CertificateManagementService certificateManagementService =
VirtualFireAlarmServiceUtils.getCertificateManagementService();
SCEPResponse scepResponse = certificateManagementService.getCACertSCEP();
Response.ResponseBuilder responseBuilder;
switch (scepResponse.getResultCriteria()) {
case CA_CERT_FAILED:
log.error("CA cert failed");
responseBuilder = Response.serverError();
break;
case CA_CERT_RECEIVED:
if (log.isDebugEnabled()) {
log.debug("CA certificate received in GetCACert");
}
responseBuilder = Response.ok(scepResponse.getEncodedResponse(),
ContentType.X_X509_CA_CERT);
break;
case CA_RA_CERT_RECEIVED:
if (log.isDebugEnabled()) {
log.debug("CA and RA certificates received in GetCACert");
}
responseBuilder = Response.ok(scepResponse.getEncodedResponse(),
ContentType.X_X509_CA_RA_CERT);
break;
default:
log.error("Invalid SCEP request");
responseBuilder = Response.serverError();
break;
}
return responseBuilder.build();
} catch (VirtualFireAlarmException e) {
log.error("Error occurred while enrolling the iOS device", e);
} catch (KeystoreException e) {
log.error("Keystore error occurred while enrolling the iOS device", e);
}
} else if (SCEPOperation.GET_CA_CAPS.getValue().equals(operation)) {
if (log.isDebugEnabled()) {
log.debug("Invoking GetCACaps");
}
try {
CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils.
getCertificateManagementService();
byte caCaps[] = certificateManagementService.getCACapsSCEP();
return Response.ok(caCaps, MediaType.TEXT_PLAIN).build();
} catch (VirtualFireAlarmException e) {
log.error("Error occurred while enrolling the device", e);
}
} else {
log.error("Invalid SCEP operation " + operation);
}
return Response.serverError().build();
}*/
/*@POST
@Path("controller/scep")
public Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream) {
if (log.isDebugEnabled()) {
log.debug("Invoking SCEP operation " + operation);
}
if (SCEPOperation.PKI_OPERATION.getValue().equals(operation)) {
if (log.isDebugEnabled()) {
log.debug("Invoking PKIOperation");
}
try {
CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils.
getCertificateManagementService();
byte pkiMessage[] = certificateManagementService.getPKIMessageSCEP(inputStream);
return Response.ok(pkiMessage, ContentType.X_PKI_MESSAGE).build();
} catch (VirtualFireAlarmException e) {
log.error("Error occurred while enrolling the device", e);
} catch (KeystoreException e) {
log.error("Keystore error occurred while enrolling the device", e);
}
}
return Response.serverError().build();
}*/
}

@ -0,0 +1,31 @@
/*
* 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.exception;
public class DroneAnalyzerException extends Exception {
private static final long serialVersionUID = 118512086958330189L;
public DroneAnalyzerException(String errorMessage) {
super(errorMessage);
}
public DroneAnalyzerException(String errorMessage, Throwable throwable) {
super(errorMessage, throwable);
}
}

@ -0,0 +1,116 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.packet.Message;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
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.service.util.DroneAnalyzerServiceUtils;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import java.util.Calendar;
/**
* Created by geesara on 12/9/15.
*/
public class DroneAnalyzerXMPPConnector extends XmppConnector {
private static Log log = LogFactory.getLog(DroneAnalyzerXMPPConnector.class);
private static String xmppServerIP;
// private static int xmppServerPort;
private static String xmppAdminUsername;
private static String xmppAdminPassword;
private static String xmppAdminAccountJID;
private DroneAnalyzerXMPPConnector() {
super(XmppConfig.getInstance().getXmppServerIP(),
XmppConfig.getInstance().getSERVER_CONNECTION_PORT());
}
public void initConnector() {
xmppServerIP = XmppConfig.getInstance().getXmppServerIP();
xmppAdminUsername = XmppConfig.getInstance().getXmppUsername();
xmppAdminPassword = XmppConfig.getInstance().getXmppPassword();
xmppAdminAccountJID = xmppAdminUsername + "@" + xmppServerIP;
}
public void connectAndLogin() {
try {
super.connectAndLogin(xmppAdminUsername, xmppAdminPassword, null);
super.setMessageFilterOnReceiver(xmppAdminAccountJID);
} catch (DeviceManagementException e) {
log.error("Connect/Login attempt to XMPP Server at: " + xmppServerIP + " failed");
retryXMPPConnection();
}
}
@Override
protected void processXMPPMessage(Message xmppMessage) {
String from = xmppMessage.getFrom();
String subject = xmppMessage.getSubject();
String message = xmppMessage.getBody();
int indexOfAt = from.indexOf("@");
int indexOfSlash = from.indexOf("/");
String deviceId = from.substring(0, indexOfAt);
String owner = from.substring(indexOfSlash + 1, from.length());
log.info("Received XMPP message for: {OWNER-" + owner + "} & {DEVICE.ID-" + deviceId + "}");
if (subject.equals("PUBLISHER")) {
log.info("XMPP: Publisher Message [" + message + "] from [" + from + "]");
float temperature = Float.parseFloat(message.split(":")[1]);
if(!DroneAnalyzerServiceUtils.publishToDAS(owner, deviceId, temperature)) {
log.error("XMPP Connector: Publishing data to DAS failed.");
}
if(log.isDebugEnabled()) {
log.debug("XMPP Connector: Published data to DAS successfully.");
}
} else if(subject.equals("CONTROL-REPLY")) {
log.info("XMPP: Reply Message [" + message + "] from [" + from + "]");
String temperature = message.split(":")[1];
SensorDataManager.getInstance().setSensorRecord(deviceId, DroneConstants.SENSOR_TEMPERATURE, temperature, Calendar.getInstance().getTimeInMillis());
} else {
log.info("SOME XMPP Message [" + message + "] from " + from + "]");
}
}
private void retryXMPPConnection() {
Thread retryToConnect = new Thread() {
@Override
public void run() {
while (true) {
if (!isConnected()) {
if (log.isDebugEnabled()) {
log.debug("Re-trying to reach XMPP Server....");
}
try {
DroneAnalyzerXMPPConnector.super.connectAndLogin(xmppAdminUsername, xmppAdminPassword, null);
DroneAnalyzerXMPPConnector.super.setMessageFilterOnReceiver(xmppAdminAccountJID);
} catch (DeviceManagementException e1) {
if (log.isDebugEnabled()) {
log.debug("Attempt to re-connect to XMPP-Server failed");
}
}
} else {
break;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
log.error("XMPP: Thread Sleep Interrupt Exception");
}
}
}
};
retryToConnect.setDaemon(true);
retryToConnect.start();
}
}

@ -0,0 +1,175 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.trasformer.MessageTransformer;
import java.util.Collection;
/**
* Created by geesara on 12/7/15.
*/
public class DroneXMPPConnector {
private static Log log = LogFactory.getLog(DroneXMPPConnector.class);
// XmppManager xmppManager;
private MessageTransformer messageController;
private static String xmppServerIP;
private static int xmppServerPort;
private static String xmppAdminUsername;
private static String xmppAdminPassword;
private static String xmppAdminAccountJID;
public DroneXMPPConnector(MessageTransformer messageController) {
this.messageController = messageController;
initConnector();
}
public void initConnector() {
/* xmppServerIP = XmppConfig.getInstance().getXmppServerIP();
xmppAdminUsername = XmppConfig.getInstance().getXmppUsername();
xmppAdminPassword = XmppConfig.getInstance().getXmppPassword();
xmppAdminAccountJID = xmppAdminUsername + "@" + xmppServerIP;*/
xmppServerPort = 5222;
xmppServerIP = "localhost";
xmppAdminUsername = "admin";
xmppAdminPassword = "admin";
xmppAdminAccountJID = xmppAdminUsername + "@" + xmppServerIP;
}
/*public void connectAndLogin() {
try {
super.connectAndLogin(xmppAdminUsername, xmppAdminPassword, null);
super.setMessageFilterOnReceiver(xmppAdminAccountJID);
} catch (DeviceManagementException e) {
log.error("Connect/Login attempt to XMPP Server at: " + xmppServerIP + " failed");
retryXMPPConnection();
}
}*/
private XMPPConnection xmppConnection;
public void connect(String server, int port) throws Exception {
if(xmppConnection == null){
xmppConnection = new XMPPConnection(new ConnectionConfiguration(server, port));
xmppConnection.connect();
}else{
System.out.println("Already user is connected");
}
/*xmppConnection = new XMPPConnection(new ConnectionConfiguration(server, port));
xmppConnection.connect();*/
}
public void disconnect(){
if(xmppConnection != null){
xmppConnection.disconnect();
//interrupt();
}
}
public void login(String username, String password) throws Exception{
printRoster();
connect( xmppServerIP, xmppServerPort);
xmppConnection.login(username, password);
}
public void run(){
try {
System.out.println(xmppAdminAccountJID+xmppAdminPassword);
login(xmppAdminAccountJID, xmppAdminPassword);
System.out.println("Login successful");
listeningForMessages();
} catch (Exception e) {
e.printStackTrace();
}
}
private void listeningForMessages() {
PacketFilter filter = new AndFilter(new PacketTypeFilter(Message.class));
PacketCollector collector = xmppConnection.createPacketCollector(filter);
while (true) {
System.out.println("waiting ...");
Packet packet = collector.nextResult();
if (packet instanceof Message) {
Message inbound_message = (Message) packet;
if (inbound_message != null && inbound_message.getBody() != null){
System.out.println(inbound_message.getBody());
messageController.messageTranslater(inbound_message.getBody());
}
} else {
log.error("Message has been corrupted");
}
}
}
public void printRoster() 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");
}
}
/* private void retryXMPPConnection() {
Thread retryToConnect = new Thread() {
@Override
public void run() {
while (true) {
if (!isConnected()) {
if (log.isDebugEnabled()) {
log.debug("Re-trying to reach XMPP Server....");
}
try {
VirtualFireAlarmXMPPConnector.super.connectAndLogin(xmppAdminUsername,
xmppAdminPassword,
null);
VirtualFireAlarmXMPPConnector.super.setMessageFilterOnReceiver(
xmppAdminAccountJID);
} catch (DeviceManagementException e1) {
if (log.isDebugEnabled()) {
log.debug("Attempt to re-connect to XMPP-Server failed");
}
}
} else {
break;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
log.error("XMPP: Thread Sleep Interrupt Exception");
}
}
}
};
retryToConnect.setDaemon(true);
retryToConnect.start();
}*/
}

@ -0,0 +1,93 @@
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();
}
}

@ -0,0 +1,63 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.util;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport.DroneAnalyzerXMPPConnector;
import java.io.File;
/**
* Created by geesara on 12/9/15.
*/
public class DroneAnalyzerServiceUtils {
private static final String SUPER_TENANT = "carbon.super";
private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature";
public static void sendCommandViaXMPP(String deviceOwner, String deviceId, String resource,
String state, DroneAnalyzerXMPPConnector droneXMPPConnector)
throws DeviceManagementException {
String xmppServerDomain = XmppConfig.getInstance().getXmppEndpoint();
int indexOfChar = xmppServerDomain.lastIndexOf(File.separator);
if (indexOfChar != -1) {
xmppServerDomain = xmppServerDomain.substring((indexOfChar + 1),
xmppServerDomain.length());
}
indexOfChar = xmppServerDomain.indexOf(":");
if (indexOfChar != -1) {
xmppServerDomain = xmppServerDomain.substring(0, indexOfChar);
}
String clientToConnect = deviceId + "@" + xmppServerDomain + File.separator + deviceOwner;
String message = resource.replace("/", "") + ":" + state;
droneXMPPConnector.sendXMPPMessage(clientToConnect, message, "CONTROL-REQUEST");
}
public static boolean publishToDAS(String owner, String deviceId, float temperature) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true);
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null);
Object metdaData[] = {owner, DroneConstants.DEVICE_TYPE, deviceId,
System.currentTimeMillis()};
Object payloadData[] = {temperature};
try {
deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return true;
}
}

@ -0,0 +1,105 @@
<?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.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
For ex:
Actual API endpoint: mdm-admin/1.0.0/devices/{device-id}
URL to be represented here: /devices/*
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<ResourceConfiguration>
<!-- Device related APIs -->
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>PUT</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/manager/device/register</Uri>
<UriTemplate>/manager/device/register/*</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>DELETE</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/manager/device/remove</Uri>
<UriTemplate>/manager/device/remove/*</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>POST</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/manager/device/update</Uri>
<UriTemplate>/manager/device/update/*</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/manager/device</Uri>
<UriTemplate>/manager/device/*</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/manager/devices</Uri>
<UriTemplate>/manager/devices/*</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/manager/device/{sketch_type}/download</Uri>
<UriTemplate>/manager/device/{sketch_type}/download</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/manager/device/{sketch_type}/generate_link</Uri>
<UriTemplate>/manager/device/{sketch_type}/generate_link</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>POST</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/controller/register/{owner}/{deviceId}/{ip}/{port}</Uri>
<UriTemplate>/controller/register/{owner}/{deviceId}/{ip}/{port}</UriTemplate>
</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>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/drone_analyzer/controller/send_command</Uri>
<UriTemplate>/controller/send_command</UriTemplate>
</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>

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright 2005-2013 WSO2, Inc. (http://wso2.com)
~
~ 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.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -0,0 +1,59 @@
<?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.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
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">
<!--<jaxrs:server id="VirtualFireAlarmController" address="/controller">-->
<!--<jaxrs:serviceBeans>-->
<!--<bean id="VirtualFireAlarmControllerService"-->
<!--class="org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.VirtualFireAlarmControllerService">-->
<!--<property name="virtualFireAlarmMQTTSubscriber" ref="mqttSubscriberBean"/>-->
<!--<property name="virtualFireAlarmXMPPConnector" ref="xmppConnectorBean"/>-->
<!--</bean>-->
<!--</jaxrs:serviceBeans>-->
<!--<jaxrs:providers>-->
<!--<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />-->
<!--</jaxrs:providers>-->
<!--</jaxrs:server>-->
<jaxrs:server id="VirtualFireAlarm" address="/">
<jaxrs:serviceBeans>
<bean id="DroneService"
class="org.wso2.carbon.device.mgt.iot.droneanalyzer.service.DroneService">
<!--<property name="DroneXMPPConnector" ref="xmppConnectorBean"/>-->
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
<!--<bean id="xmppConnectorBean"
class="org.wso2.carbon.device.mgt.iot.droneanalyzer.service.transport.DroneAnalyzerXMPPConnector">
</bean>-->
</beans>

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="utf-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
metadata-complete="true">
<display-name>WSO2 IoT Server</display-name>
<description>WSO2 IoT Server</description>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>false</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-name</param-name>
<param-value>drone_analyzer</param-value>
</context-param>
<context-param>
<param-name>managed-api-endpoint</param-name>
<param-value>http://localhost:9763/drone_analyzer</param-value>
</context-param>
<context-param>
<param-name>managed-api-version</param-name>
<param-value>1.0.0</param-value>
</context-param>
<context-param>
<param-name>managed-api-context</param-name>
<param-value>/drone_analyzer</param-value>
</context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/drone_analyzer/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>drone_analyzer</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
<!-- Below configuration is used to redirect http requests to https -->
<!--<security-constraint>-->
<!--<web-resource-collection>-->
<!--<web-resource-name>IoT</web-resource-name>-->
<!--<url-pattern>/*</url-pattern>-->
<!--</web-resource-collection>-->
<!--<user-data-constraint>-->
<!--<transport-guarantee>CONFIDENTIAL</transport-guarantee>-->
<!--</user-data-constraint>-->
<!--</security-constraint>-->
</web-app>

@ -0,0 +1,62 @@
<?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"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>carbon-device-mgt-plugins-parent</artifactId>
<version>1.9.2-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>device-mgt-iot-droneanalyzer</artifactId>
<version>1.9.2-SNAPSHOT</version>
<modules>
<module>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl</module>
<module>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl</module>
</modules>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Device Drone Analyzer Management Component</name>
<url>http://wso2.org</url>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<version>1.7.2</version>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

@ -0,0 +1,124 @@
<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">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device-mgt-iot-droneanalyzer-feature</artifactId>
<version>1.9.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.feature</artifactId>
<packaging>pom</packaging>
<version>1.9.2-SNAPSHOT</version>
<name>WSO2 Carbon - IoT Server Drone Analyzer Feature</name>
<url>http://maven.apache.org</url>
<description>This feature contains the Drone Device type specific implementations for the IoT Server
</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl</artifactId>
<type>war</type>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${basedir}/src/main/resources/webapps/</outputDirectory>
<destFileName>drone_analyzer.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.device.mgt.iot.droneanalyzer</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl:${carbon.iot.device.mgt.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,23 @@
<?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.
-->
<DeviceTypeConfigurations>
</DeviceTypeConfigurations>

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

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

@ -0,0 +1,36 @@
<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>

@ -0,0 +1,25 @@
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,41 @@
<?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"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>carbon-device-mgt-plugins-parent</artifactId>
<version>1.9.2-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>device-mgt-iot-droneanalyzer-feature</artifactId>
<version>1.9.2-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server Drone Device Feature</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.iot.droneanalyzer.feature</module>
</modules>
</project>

@ -49,6 +49,7 @@
<!--Device Specific IoT Components--> <!--Device Specific IoT Components-->
<module>components/device-mgt-iot-virtualfirealarm</module> <module>components/device-mgt-iot-virtualfirealarm</module>
<module>components/device-mgt-iot-androidsense</module> <module>components/device-mgt-iot-androidsense</module>
<module>components/device-mgt-iot-droneanalyzer</module>
<!--Core MDM and IoT Features--> <!--Core MDM and IoT Features-->
<module>features/device-mgt-iot-feature</module> <module>features/device-mgt-iot-feature</module>
@ -61,6 +62,7 @@
<!--Device specific IoT Features--> <!--Device specific IoT Features-->
<module>features/device-mgt-iot-virtualfirealarm-feature</module> <module>features/device-mgt-iot-virtualfirealarm-feature</module>
<module>features/device-mgt-iot-androidsense-feature</module> <module>features/device-mgt-iot-androidsense-feature</module>
<module>features/device-mgt-iot-droneanalyzer-feature</module>
</modules> </modules>
<dependencyManagement> <dependencyManagement>
@ -401,6 +403,22 @@
<type>war</type> <type>war</type>
</dependency> </dependency>
<!--+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-->
<!--Drone DeviceType Impl, API and Agent-->
<!--+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-->
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl</artifactId>
<version>${carbon.iot.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl</artifactId>
<version>${carbon.iot.device.mgt.version}</version>
<type>war</type>
</dependency>
<!--+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--> <!--+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-->
<dependency> <dependency>
<groupId>org.json.wso2</groupId> <groupId>org.json.wso2</groupId>

Loading…
Cancel
Save