diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/pom.xml b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/pom.xml new file mode 100644 index 0000000000..8c923a3468 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/pom.xml @@ -0,0 +1,106 @@ + + + device-mgt-iot-droneanalyzer + org.wso2.carbon.devicemgt-plugins + 1.9.2-SNAPSHOT + ../pom.xml + + 4.0.0 + + org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl + 1.9.2-SNAPSHOT + bundle + + WSO2 Carbon - IoT Server Drone Analyzer Management Plugin + http://maven.apache.org + + + UTF-8 + + + + + + org.apache.felix + maven-scr-plugin + + + maven-compiler-plugin + + 1.7 + 1.7 + + 2.3.2 + + + org.apache.felix + maven-bundle-plugin + 1.4.0 + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.iot.device.mgt.version} + IoT Server Impl Bundle + org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.internal + + 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.*, + + + + !org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.internal, + org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.* + + + + + + + + + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + + org.wso2.carbon + org.wso2.carbon.logging + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + + + org.wso2.carbon + org.wso2.carbon.ndatasource.core + + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot + + + diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/DroneAnalyzerManagementServiceComponent.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/DroneAnalyzerManagementServiceComponent.java new file mode 100644 index 0000000000..ed7923889c --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/DroneAnalyzerManagementServiceComponent.java @@ -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 + } +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/constants/DroneConstants.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/constants/DroneConstants.java new file mode 100644 index 0000000000..76a811277c --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/constants/DroneConstants.java @@ -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"; + +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/constants/MessageConfig.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/constants/MessageConfig.java new file mode 100644 index 0000000000..6a1cab5684 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/constants/MessageConfig.java @@ -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"; + +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/DroneAnalyzerManager.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/DroneAnalyzerManager.java new file mode 100644 index 0000000000..8c719d038e --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/DroneAnalyzerManager.java @@ -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 getAllDevices() throws DeviceManagementException { + List devices = null; + try { + if (log.isDebugEnabled()) { + log.debug("Fetching the details of all Virtual Firealarm devices"); + } + List iotDevices = + iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices(); + if (iotDevices != null) { + devices = new ArrayList(); + 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; + } +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/DroneAnalyzerManagerService.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/DroneAnalyzerManagerService.java new file mode 100644 index 0000000000..a6f755900a --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/DroneAnalyzerManagerService.java @@ -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 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 list) + throws ApplicationManagementException { + + } + + @Override + public void installApplicationForUsers(Operation operation, List list) + throws ApplicationManagementException { + + } + + @Override + public void installApplicationForUserRoles(Operation operation, List list) + throws ApplicationManagementException { + + } + + public String getProviderTenantDomain() { + return "carbon.super"; + } + + public boolean isSharedWithAllTenants() { + return true; + } + + public String[] getSharedTenantsDomain() { + return new String[0]; + } +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/dao/DroneAnalyzerDAO.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/dao/DroneAnalyzerDAO.java new file mode 100644 index 0000000000..bff989063b --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/dao/DroneAnalyzerDAO.java @@ -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 currentConnection = new ThreadLocal(); + + 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(); + } + } +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/dao/impl/DroneAnalyzerDeviceDAOImpl.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/dao/impl/DroneAnalyzerDeviceDAOImpl.java new file mode 100644 index 0000000000..0f297ab503 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/dao/impl/DroneAnalyzerDeviceDAOImpl.java @@ -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 propertyMap = new HashMap(); + 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()); + } + + + 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()); + } + 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 getAllIotDevices() + throws IotDeviceManagementDAOException { + + Connection conn = null; + PreparedStatement stmt = null; + ResultSet resultSet = null; + IotDevice iotDevice; + List iotDevices = new ArrayList(); + + 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 propertyMap = new HashMap(); + + 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(); + } + + } +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/util/DroneAnalyzerUtils.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/util/DroneAnalyzerUtils.java new file mode 100644 index 0000000000..3304219892 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/util/DroneAnalyzerUtils.java @@ -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 deviceProperties, String property) { + String deviceProperty = deviceProperties.get(property); + if (deviceProperty == null) { + return ""; + } + return deviceProperty; + } +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/internal/DroneAnalyzerManagementServiceComponent.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/internal/DroneAnalyzerManagementServiceComponent.java new file mode 100644 index 0000000000..87acba1b0a --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/internal/DroneAnalyzerManagementServiceComponent.java @@ -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 + } + + +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/test/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/dao/impl/DroneAnalyzerDeviceDAOImplTest.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/test/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/dao/impl/DroneAnalyzerDeviceDAOImplTest.java new file mode 100644 index 0000000000..32b36fe49b --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl/src/test/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/plugin/impl/dao/impl/DroneAnalyzerDeviceDAOImplTest.java @@ -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(); + } + } +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/pom.xml b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/pom.xml new file mode 100644 index 0000000000..a22b66a295 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/pom.xml @@ -0,0 +1,231 @@ + + + device-mgt-iot-droneanalyzer + org.wso2.carbon.devicemgt-plugins + 1.9.2-SNAPSHOT + ../pom.xml + + 4.0.0 + org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl + 1.9.2-SNAPSHOT + war + WSO2 Carbon - IoT Server Drone Analyzer API + http://maven.apache.org + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + provided + + + org.apache.axis2.wso2 + axis2-client + + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.analytics + provided + + + org.apache.axis2.wso2 + axis2-client + + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.certificate.mgt.core + provided + + + commons-codec.wso2 + commons-codec + + + + + + + + org.apache.cxf + cxf-rt-frontend-jaxws + provided + + + org.apache.cxf + cxf-rt-frontend-jaxrs + provided + + + org.apache.cxf + cxf-rt-transports-http + provided + + + + + org.eclipse.paho + mqtt-client + provided + + + + + org.apache.httpcomponents + httpasyncclient + 4.1 + provided + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot + provided + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl + provided + + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + commons-httpclient.wso2 + commons-httpclient + provided + + + + org.wso2.carbon + org.wso2.carbon.utils + provided + + + org.bouncycastle.wso2 + bcprov-jdk15on + + + org.wso2.carbon + org.wso2.carbon.user.api + + + org.wso2.carbon + org.wso2.carbon.queuing + + + org.wso2.carbon + org.wso2.carbon.base + + + org.apache.axis2.wso2 + axis2 + + + org.igniterealtime.smack.wso2 + smack + + + org.igniterealtime.smack.wso2 + smackx + + + jaxen + jaxen + + + commons-fileupload.wso2 + commons-fileupload + + + org.apache.ant.wso2 + ant + + + org.apache.ant.wso2 + ant + + + commons-httpclient.wso2 + commons-httpclient + + + org.eclipse.equinox + javax.servlet + + + org.wso2.carbon + org.wso2.carbon.registry.api + + + + + + commons-codec + commons-codec + + + + org.igniterealtime.smack.wso2 + smack + provided + + + org.igniterealtime.smack.wso2 + smackx + provided + + + + + + + + + maven-compiler-plugin + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + maven-war-plugin + + + drone_analyzer + + + + + + diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/DroneRealTimeService.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/DroneRealTimeService.java new file mode 100644 index 0000000000..efbf2e6181 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/DroneRealTimeService.java @@ -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"); + } + +} \ No newline at end of file diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/DroneService.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/DroneService.java new file mode 100644 index 0000000000..7b40e255db --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/DroneService.java @@ -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 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 userDevices = deviceManagement.getDeviceManagementService().getDevicesOfUser(username); + ArrayList 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(); + }*/ +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/exception/DroneAnalyzerException.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/exception/DroneAnalyzerException.java new file mode 100644 index 0000000000..c3eb321d90 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/exception/DroneAnalyzerException.java @@ -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); + } +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/transport/DroneAnalyzerXMPPConnector.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/transport/DroneAnalyzerXMPPConnector.java new file mode 100644 index 0000000000..03f00bbbe3 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/transport/DroneAnalyzerXMPPConnector.java @@ -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(); + } +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/transport/DroneXMPPConnector.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/transport/DroneXMPPConnector.java new file mode 100644 index 0000000000..af68d8f296 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/transport/DroneXMPPConnector.java @@ -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 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(); + }*/ + +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/trasformer/MessageTransformer.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/trasformer/MessageTransformer.java new file mode 100644 index 0000000000..2eab8ba3a5 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/trasformer/MessageTransformer.java @@ -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 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(); + } + + 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(); + } + +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/util/DroneAnalyzerServiceUtils.java b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/util/DroneAnalyzerServiceUtils.java new file mode 100644 index 0000000000..d7ff522641 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/droneanalyzer/service/util/DroneAnalyzerServiceUtils.java @@ -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; + } +} diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/META-INF/resources.xml b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/META-INF/resources.xml new file mode 100644 index 0000000000..84e3e53e82 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/META-INF/resources.xml @@ -0,0 +1,105 @@ + + + + + + + + Any + PUT + http://localhost:9763/drone_analyzer/manager/device/register + /manager/device/register/* + + + Any + DELETE + http://localhost:9763/drone_analyzer/manager/device/remove + /manager/device/remove/* + + + Any + POST + http://localhost:9763/drone_analyzer/manager/device/update + /manager/device/update/* + + + Any + GET + http://localhost:9763/drone_analyzer/manager/device + /manager/device/* + + + Any + GET + http://localhost:9763/drone_analyzer/manager/devices + /manager/devices/* + + + Any + GET + http://localhost:9763/drone_analyzer/manager/device/{sketch_type}/download + /manager/device/{sketch_type}/download + + + Any + GET + http://localhost:9763/drone_analyzer/manager/device/{sketch_type}/generate_link + /manager/device/{sketch_type}/generate_link + + + + Any + POST + http://localhost:9763/drone_analyzer/controller/register/{owner}/{deviceId}/{ip}/{port} + /controller/register/{owner}/{deviceId}/{ip}/{port} + + + Any + POST + http://localhost:9763/drone_analyzer/controller/controller/bulb/{state} + /controller/bulb/{state} + + + Any + GET + http://localhost:9763/drone_analyzer/controller/send_command + /controller/send_command + + + Any + GET + http://localhost:9763/drone_analyzer/controller/controller/readtemperature + /controller/readtemperature + + + Any + POST + http://localhost:9763/drone_analyzer/controller/controller/push_temperature + /controller/push_temperature + + \ No newline at end of file diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/META-INF/webapp-classloading.xml b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 0000000000..fa44619195 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,33 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 0000000000..152012d0af --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/WEB-INF/web.xml b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..e251f0db57 --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,81 @@ + + + WSO2 IoT Server + WSO2 IoT Server + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + + CXFServlet + /* + + + + isAdminService + false + + + doAuthentication + false + + + + + managed-api-enabled + false + + + managed-api-owner + admin + + + managed-api-name + drone_analyzer + + + managed-api-endpoint + http://localhost:9763/drone_analyzer + + + managed-api-version + 1.0.0 + + + managed-api-context + /drone_analyzer + + + managed-api-context-template + /drone_analyzer/{version} + + + managed-api-application + drone_analyzer + + + managed-api-isSecured + true + + + + + + + + + + + + + + + diff --git a/components/device-mgt-iot-droneanalyzer/pom.xml b/components/device-mgt-iot-droneanalyzer/pom.xml new file mode 100644 index 0000000000..fbbeef1c0e --- /dev/null +++ b/components/device-mgt-iot-droneanalyzer/pom.xml @@ -0,0 +1,62 @@ + + + + + + + org.wso2.carbon.devicemgt-plugins + carbon-device-mgt-plugins-parent + 1.9.2-SNAPSHOT + ../../pom.xml + + + 4.0.0 + device-mgt-iot-droneanalyzer + 1.9.2-SNAPSHOT + + org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl + org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl + + pom + WSO2 Carbon - IoT Device Drone Analyzer Management Component + http://wso2.org + + + + + + org.apache.felix + maven-scr-plugin + 1.7.2 + + + generate-scr-scrdescriptor + + scr + + + + + + + + + \ No newline at end of file diff --git a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/pom.xml b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/pom.xml new file mode 100644 index 0000000000..d364098abb --- /dev/null +++ b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/pom.xml @@ -0,0 +1,124 @@ + + + org.wso2.carbon.devicemgt-plugins + device-mgt-iot-droneanalyzer-feature + 1.9.2-SNAPSHOT + ../pom.xml + + 4.0.0 + + org.wso2.carbon.device.mgt.iot.droneanalyzer.feature + pom + 1.9.2-SNAPSHOT + WSO2 Carbon - IoT Server Drone Analyzer Feature + http://maven.apache.org + This feature contains the Drone Device type specific implementations for the IoT Server + + + + UTF-8 + + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl + war + + + + + + maven-resources-plugin + + + copy-resources + generate-resources + + copy-resources + + + src/main/resources + + + resources + + build.properties + p2.inf + + + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-jaxrs-war + package + + copy + + + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl + + war + true + ${basedir}/src/main/resources/webapps/ + drone_analyzer.war + + + + + + + + + org.wso2.maven + carbon-p2-plugin + + + p2-feature-generation + package + + p2-feature-gen + + + org.wso2.carbon.device.mgt.iot.droneanalyzer + ../../../features/etc/feature.properties + + + org.wso2.carbon.p2.category.type:server + org.eclipse.equinox.p2.type.group:false + + + + + org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl:${carbon.iot.device.mgt.version} + + + + org.wso2.carbon.core.server:${carbon.kernel.version} + + org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version} + + + + + + + + + + diff --git a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/build.properties b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/build.properties new file mode 100644 index 0000000000..9c86577d76 --- /dev/null +++ b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/build.properties @@ -0,0 +1 @@ +custom = true diff --git a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/configs/drone_analyzer.xml b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/configs/drone_analyzer.xml new file mode 100644 index 0000000000..f997831fe4 --- /dev/null +++ b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/configs/drone_analyzer.xml @@ -0,0 +1,23 @@ + + + + + + + diff --git a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/dbscripts/h2.sql b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/dbscripts/h2.sql new file mode 100644 index 0000000000..340ba6a70c --- /dev/null +++ b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/dbscripts/h2.sql @@ -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`) ); + + + diff --git a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/dbscripts/mysql.sql b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/dbscripts/mysql.sql new file mode 100644 index 0000000000..432ecbb0ef --- /dev/null +++ b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/dbscripts/mysql.sql @@ -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; + + + + diff --git a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/jaggeryapps/devicemgt/app/units/iot.unit.device.droneanalyzer-overview/droneanalyzer-overview.hbs b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/jaggeryapps/devicemgt/app/units/iot.unit.device.droneanalyzer-overview/droneanalyzer-overview.hbs new file mode 100644 index 0000000000..b86c76db90 --- /dev/null +++ b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/jaggeryapps/devicemgt/app/units/iot.unit.device.droneanalyzer-overview/droneanalyzer-overview.hbs @@ -0,0 +1,36 @@ +
+
+ {{unit "cdmf.unit.device.overview.droneanalyzer-display-image"}} +
+
+
Device Overview - Virtual Firealarm
+ {{#defineZone "device-detail-properties"}} + + + + + + {{#if device.viewModel.udid}} + + {{/if}} + {{#if device.viewModel.phoneNumber}} + + {{/if}} + + + + + +
Device{{device.viewModel.vendor}} {{device.properties.model}}
Model{{device.viewModel.model}}
IMEI{{device.viewModel.imei}}
UDID{{device.viewModel.udid}}
Phone Number{{device.viewModel.phoneNumber}}
Status + {{#equal device.status "ACTIVE"}} Active{{/equal}} + {{#equal device.status "INACTIVE"}} Inactive{{/equal}} + {{#equal device.status "BLOCKED"}} Blocked{{/equal}} + {{#equal device.status "REMOVED"}} Removed{{/equal}} +
+ {{/defineZone}} +
Operations
+
+ {{unit "cdmf.unit.device.iot-operation" deviceType=device.type}} +
+
+
\ No newline at end of file diff --git a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/jaggeryapps/devicemgt/app/units/iot.unit.device.droneanalyzer-overview/droneanalyzer-overview.js b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/jaggeryapps/devicemgt/app/units/iot.unit.device.droneanalyzer-overview/droneanalyzer-overview.js new file mode 100644 index 0000000000..4db0045b5e --- /dev/null +++ b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/jaggeryapps/devicemgt/app/units/iot.unit.device.droneanalyzer-overview/droneanalyzer-overview.js @@ -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; + } +} \ No newline at end of file diff --git a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/jaggeryapps/devicemgt/app/units/iot.unit.device.droneanalyzer-overview/droneanalyzer-overview.json b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/jaggeryapps/devicemgt/app/units/iot.unit.device.droneanalyzer-overview/droneanalyzer-overview.json new file mode 100644 index 0000000000..688e939808 --- /dev/null +++ b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/jaggeryapps/devicemgt/app/units/iot.unit.device.droneanalyzer-overview/droneanalyzer-overview.json @@ -0,0 +1,3 @@ +{ + "version": "1.0.0" +} \ No newline at end of file diff --git a/features/device-mgt-iot-droneanalyzer-feature/pom.xml b/features/device-mgt-iot-droneanalyzer-feature/pom.xml new file mode 100644 index 0000000000..818bfdfee2 --- /dev/null +++ b/features/device-mgt-iot-droneanalyzer-feature/pom.xml @@ -0,0 +1,41 @@ + + + + + + + org.wso2.carbon.devicemgt-plugins + carbon-device-mgt-plugins-parent + 1.9.2-SNAPSHOT + ../../pom.xml + + + 4.0.0 + device-mgt-iot-droneanalyzer-feature + 1.9.2-SNAPSHOT + pom + WSO2 Carbon - IoT Server Drone Device Feature + http://wso2.org + + + org.wso2.carbon.device.mgt.iot.droneanalyzer.feature + + + diff --git a/pom.xml b/pom.xml index d65066782b..bece7c29fd 100644 --- a/pom.xml +++ b/pom.xml @@ -49,6 +49,7 @@ components/device-mgt-iot-virtualfirealarm components/device-mgt-iot-androidsense + components/device-mgt-iot-droneanalyzer features/device-mgt-iot-feature @@ -61,6 +62,7 @@ features/device-mgt-iot-virtualfirealarm-feature features/device-mgt-iot-androidsense-feature + features/device-mgt-iot-droneanalyzer-feature @@ -401,6 +403,22 @@ war + + + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.impl + ${carbon.iot.device.mgt.version} + + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl + ${carbon.iot.device.mgt.version} + war + + org.json.wso2