diff --git a/.DS_Store b/.DS_Store index b5c87da2..a0d9a9dd 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/modules/distribution/pom.xml b/modules/distribution/pom.xml index e796fb97..b4aecb89 100644 --- a/modules/distribution/pom.xml +++ b/modules/distribution/pom.xml @@ -178,177 +178,177 @@ - - - create-firealarm-schema - package - - run - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + + + + - - - create-sensebot-schema - package - - run - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + + + + - - - create-arduino-schema - package - - run - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + + + + - - - create-android-sense-schema - package - - run - - - - - - - + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + + + + - - - create-raspberrypi-schema - package - - run - - - - - - - + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + + + + - - - create-digitaldisply-schema - package - - run - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + + + + diff --git a/modules/distribution/src/assembly/bin.xml b/modules/distribution/src/assembly/bin.xml index 952ab49f..860ca20a 100644 --- a/modules/distribution/src/assembly/bin.xml +++ b/modules/distribution/src/assembly/bin.xml @@ -278,12 +278,6 @@ ${pom.artifactId}-${pom.version}/repository/deployment/server/webapps devicecloud.war - firealarm.war - arduino.war - android_sense.war - sensebot.war - raspberrypi.war - digitaldisplay.war @@ -618,7 +612,7 @@ ../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/mobile-config.xml - ${pom.artifactId}-${pom.version}/repository/conf/etc/device-mgt-plugin-configs/mobile + ${pom.artifactId}-${pom.version}/repository/conf/etc/device-mgt-plugin-org.wso2.carbon.device.mgt.iot.common.config.server.configs/mobile true 644 diff --git a/modules/distribution/src/repository/jaggeryapps/iotserver/lib/handlebars-helpers.js b/modules/distribution/src/repository/jaggeryapps/iotserver/lib/handlebars-helpers.js index f303d0e0..e8c801fa 100644 --- a/modules/distribution/src/repository/jaggeryapps/iotserver/lib/handlebars-helpers.js +++ b/modules/distribution/src/repository/jaggeryapps/iotserver/lib/handlebars-helpers.js @@ -12,7 +12,7 @@ var getScope = function (unit,configs) { var cbResult; if (jsFile.isExists()) { script = require(jsFile.getPath()); - //Eagerly make the viewModel the template configs + //Eagerly make the viewModel the template org.wso2.carbon.device.mgt.iot.common.config.server.configs viewModel = templateConfigs; //Check if the unit author has specified an onRequest //callback @@ -24,7 +24,7 @@ var getScope = function (unit,configs) { }; onRequestCb = script.onRequest; cbResult = onRequestCb(templateConfigs); - log.debug("passing configs to unit "+unit+" configs: "+stringify(templateConfigs)); + log.debug("passing org.wso2.carbon.device.mgt.iot.common.config.server.configs to unit "+unit+" org.wso2.carbon.device.mgt.iot.common.config.server.configs: "+stringify(templateConfigs)); //If the execution does not yield an object we will print //a warning as the unit author may have forgotten to return a data object if(cbResult===undefined){ @@ -157,7 +157,7 @@ Handlebars.registerHelper('unit', function (unitName,options) { //TODO warn when unspecified decencies are included. fuseState.currentZone.push('main'); var template = fuse.getFile(baseUnit, '', '.hbs'); - //log.debug('[' + requestId + '] including "' + baseUnit + '"'+" with configs "+stringify(templateConfigs)); + //log.debug('[' + requestId + '] including "' + baseUnit + '"'+" with org.wso2.carbon.device.mgt.iot.common.config.server.configs "+stringify(templateConfigs)); var result = new Handlebars.SafeString(Handlebars.compileFile(template)(getScope(baseUnit,templateConfigs))); fuseState.currentZone.pop(); return result; diff --git a/modules/distribution/src/samples/android_sense/dbscripts/h2_android_sense.sql b/modules/distribution/src/samples/android_sense/dbscripts/h2_android_sense.sql new file mode 100644 index 00000000..218cdbf0 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/dbscripts/h2_android_sense.sql @@ -0,0 +1,11 @@ + +-- ----------------------------------------------------- +-- Table `ANDROID_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `ANDROID_SENSE_DEVICE` ( + `ANDROID_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`ANDROID_DEVICE_ID`) ); + + + diff --git a/modules/distribution/src/samples/android_sense/dbscripts/mysql_android_sense.sql b/modules/distribution/src/samples/android_sense/dbscripts/mysql_android_sense.sql new file mode 100644 index 00000000..4637b4da --- /dev/null +++ b/modules/distribution/src/samples/android_sense/dbscripts/mysql_android_sense.sql @@ -0,0 +1,12 @@ +-- ----------------------------------------------------- +-- Table `ANDROID_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `ANDROID_SENSE_DEVICE` ( + `ANDROID_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`ANDROID_DEVICE_ID`) ) +ENGINE = InnoDB; + + + + diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/pom.xml b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/pom.xml new file mode 100644 index 00000000..0bebd287 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/pom.xml @@ -0,0 +1,141 @@ + + + + + + + devicecloud-mgt + org.wso2.carbon.device.mgt.iot + 1.0.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.iot.android.sense.impl + 1.0.0-SNAPSHOT + bundle + WSO2 Carbon - Android Sense Management Impl + WSO2 Carbon - Android Sense Management and Control Implementation + http://wso2.org + + + + + 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} + Device Cloud Impl Bundle + org.wso2.carbon.device.mgt.iot.android.sense.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.common.* + + + + !org.wso2.carbon.device.mgt.iot.android.sense.internal, + org.wso2.carbon.device.mgt.iot.android.sense.* + + + + + + + + + + + + + + + + + + + + + + + + + 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.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + + + + + diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/constants/AndroidSenseConstants.java b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/constants/AndroidSenseConstants.java new file mode 100644 index 00000000..572f74e7 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/constants/AndroidSenseConstants.java @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.constants; + +public class AndroidSenseConstants { + + public final static String DEVICE_TYPE = "android_sense"; + public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; + public final static String DEVICE_PLUGIN_DEVICE_ID = "ANDROID_DEVICE_ID"; + +} diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/AndroidSenseManager.java b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/AndroidSenseManager.java new file mode 100644 index 00000000..7e18284d --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/AndroidSenseManager.java @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl; + + +import org.apache.commons.logging.Log; +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.DeviceManager; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; +import org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl.dao.AndroidSenseDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.util.IotDeviceManagementUtil; + +import java.util.ArrayList; +import java.util.List; + + +/** + * This represents the Android implementation of DeviceManagerService. + */ +public class AndroidSenseManager implements DeviceManager { + + private static final IotDeviceManagementDAOFactory iotDeviceManagementDAOFactory = new AndroidSenseDAO(); + private static final Log log = LogFactory.getLog(AndroidSenseManager.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 Android device : " + device.getDeviceIdentifier()); + } + AndroidSenseDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice( + iotDevice); + AndroidSenseDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + AndroidSenseDAO.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 Android 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 Android device enrollment data"); + } + AndroidSenseDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + AndroidSenseDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + AndroidSenseDAO.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 Android 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 Android device : " + deviceId); + } + AndroidSenseDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .deleteIotDevice(deviceId.getId()); + AndroidSenseDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + AndroidSenseDAO.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 Android 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 Android 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 Android 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 Android device : " + deviceId.getId()); + } + IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO(). + getIotDevice(deviceId.getId()); + device = IotDeviceManagementUtil.convertToDevice(iotDevice); + } catch (IotDeviceManagementDAOException e) { + String msg = "Error while fetching the Android 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 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 Android device : " + deviceIdentifier); + } + AndroidSenseDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + AndroidSenseDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + AndroidSenseDAO.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 Android 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 Android 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 Android devices."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return devices; + } + +} \ No newline at end of file diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/AndroidSenseManagerService.java b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/AndroidSenseManagerService.java new file mode 100644 index 00000000..d33dddc7 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/AndroidSenseManagerService.java @@ -0,0 +1,60 @@ +package org.wso2.carbon.device.mgt.iot.sample.android.sense.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.sample.android.sense.plugin.constants.AndroidSenseConstants; + +import java.util.List; + +public class AndroidSenseManagerService implements DeviceManagementService { + private DeviceManager deviceManager; + @Override + public String getType() { + return AndroidSenseConstants.DEVICE_TYPE; + } + + @Override + public void init() throws DeviceManagementException { + deviceManager=new AndroidSenseManager(); + } + + @Override + public DeviceManager getDeviceManager() { + return deviceManager; + } + + @Override + public ApplicationManager getApplicationManager() { + return null; + } + + @Override + public Application[] getApplications(String domain, int pageNumber, int size) + throws ApplicationManagementException { + return new Application[0]; + } + + @Override + public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, + String status) throws ApplicationManagementException { + + } + + @Override + public String getApplicationStatus(DeviceIdentifier deviceId, Application application) + throws ApplicationManagementException { + return null; + } + + @Override + public void installApplication(Operation operation, List deviceIdentifiers) + throws ApplicationManagementException { + + } +} diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/dao/AndroidSenseDAO.java b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/dao/AndroidSenseDAO.java new file mode 100644 index 00000000..14b56e8b --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/dao/AndroidSenseDAO.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.constants.AndroidSenseConstants; +import org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl.dao.impl.AndroidSenseDAOImpl; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactoryInterface; + + + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class AndroidSenseDAO extends IotDeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface { + + private static final Log log = LogFactory.getLog(AndroidSenseDAO.class); + static DataSource dataSource; + private static ThreadLocal currentConnection = new ThreadLocal(); + + public AndroidSenseDAO() { + initAndroidDAO(); + } + + public static void initAndroidDAO() { + dataSource = getDataSourceMap().get(AndroidSenseConstants.DEVICE_TYPE); + } + + @Override public IotDeviceDAO getIotDeviceDAO() { + return new AndroidSenseDAOImpl(); + } + + 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.get() == null) { + try { + currentConnection.set(dataSource.getConnection()); + } catch (SQLException e) { + throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e); + } + } + 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(); + } + } +} \ No newline at end of file diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/dao/impl/AndroidSenseDAOImpl.java b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/dao/impl/AndroidSenseDAOImpl.java new file mode 100644 index 00000000..aa8bf1d7 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/dao/impl/AndroidSenseDAOImpl.java @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.constants.AndroidSenseConstants; +import org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl.dao.AndroidSenseDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.util.IotDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.iot.common.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; + +/** + * Implements IotDeviceDAO for android Devices. + */ +public class AndroidSenseDAOImpl implements IotDeviceDAO{ + + + private static final Log log = LogFactory.getLog(AndroidSenseDAOImpl.class); + + @Override + public IotDevice getIotDevice(String iotDeviceId) + throws IotDeviceManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + IotDevice iotDevice = null; + ResultSet resultSet = null; + try { + conn = AndroidSenseDAO.getConnection(); + String selectDBQuery = + "SELECT ANDROID_DEVICE_ID, DEVICE_NAME" + + " FROM ANDROID_SENSE_DEVICE WHERE ANDROID_DEVICE_ID = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setString(1, iotDeviceId); + resultSet = stmt.executeQuery(); + + if (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceName(resultSet.getString( + AndroidSenseConstants.DEVICE_PLUGIN_DEVICE_NAME)); + Map propertyMap = new HashMap(); + + + + iotDevice.setDeviceProperties(propertyMap); + + if (log.isDebugEnabled()) { + log.debug("Android device " + iotDeviceId + " data has been fetched from " + + "Android database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while fetching Android device : '" + iotDeviceId + "'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + AndroidSenseDAO.closeConnection(); + } + + return iotDevice; + } + + @Override + public boolean addIotDevice(IotDevice iotDevice) + throws IotDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = AndroidSenseDAO.getConnection(); + String createDBQuery = + "INSERT INTO ANDROID_SENSE_DEVICE(ANDROID_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("Android device " + iotDevice.getIotDeviceId() + " data has been" + + " added to the Android database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while adding the Android device '" + + iotDevice.getIotDeviceId() + "' to the Android 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 = AndroidSenseDAO.getConnection(); + String updateDBQuery = + "UPDATE ANDROID_SENSE_DEVICE SET DEVICE_NAME = ? WHERE ANDROID_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("Android device " + iotDevice.getIotDeviceId() + " data has been" + + " modified."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while modifying the Android 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 = AndroidSenseDAO.getConnection(); + String deleteDBQuery = + "DELETE FROM ANDROID_SENSE_DEVICE WHERE ANDROID_DEVICE_ID = ?"; + stmt = conn.prepareStatement(deleteDBQuery); + stmt.setString(1, iotDeviceId); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Android device " + iotDeviceId + " data has deleted" + + " from the Android database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while deleting Android 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 = AndroidSenseDAO.getConnection(); + String selectDBQuery = + "SELECT ANDROID_DEVICE_ID, DEVICE_NAME " + + "FROM ANDROID_SENSE_DEVICE"; + stmt = conn.prepareStatement(selectDBQuery); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceId(resultSet.getString(AndroidSenseConstants.DEVICE_PLUGIN_DEVICE_ID)); + iotDevice.setIotDeviceName(resultSet.getString(AndroidSenseConstants.DEVICE_PLUGIN_DEVICE_NAME)); + + Map propertyMap = new HashMap(); + + iotDevice.setDeviceProperties(propertyMap); + iotDevices.add(iotDevice); + } + if (log.isDebugEnabled()) { + log.debug("All Android device details have fetched from Android database."); + } + return iotDevices; + } catch (SQLException e) { + String msg = "Error occurred while fetching all Android device data'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + AndroidSenseDAO.closeConnection(); + } + + } + + } \ No newline at end of file diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/util/AndroidSenseUtils.java b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/util/AndroidSenseUtils.java new file mode 100644 index 00000000..f84c19f7 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/impl/util/AndroidSenseUtils.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Map; + +/** + * Contains utility methods used by Android plugin. + */ +public class AndroidSenseUtils { + + private static Log log = LogFactory.getLog(AndroidSenseUtils.class); + + public static String getDeviceProperty(Map deviceProperties, String property) { + + String deviceProperty = deviceProperties.get(property); + + if (deviceProperty == null) { + return ""; + } + + return deviceProperty; + } + + +} diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/internal/AndroidSenseManagementServiceComponent.java b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/internal/AndroidSenseManagementServiceComponent.java new file mode 100644 index 00000000..166844d0 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/plugin/internal/AndroidSenseManagementServiceComponent.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.android.sense.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.sample.android.sense.plugin.impl.AndroidSenseManagerService; +import org.wso2.carbon.device.mgt.iot.common.service.DeviceTypeService; + + + +/** + * @scr.component name="org.wso2.carbon.device.mgt.iot.android.internal.AndroidSenseManagementServiceComponent" + * immediate="true" + * @scr.reference name="wso2.carbon.device.mgt.iot.common.DeviceTypeService" + * interface="org.wso2.carbon.device.mgt.iot.common.service.DeviceTypeService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDeviceTypeService" + * unbind="unsetDeviceTypeService" + */ +public class AndroidSenseManagementServiceComponent { + + + private ServiceRegistration androidServiceRegRef; + + + + private static final Log log = LogFactory.getLog(AndroidSenseManagementServiceComponent.class); + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating Android Device Management Service Component"); + } + try { + BundleContext bundleContext = ctx.getBundleContext(); + + + androidServiceRegRef = + bundleContext.registerService(DeviceManagementService.class.getName(), new + AndroidSenseManagerService(), null); + + + + if (log.isDebugEnabled()) { + log.debug("Android Device Management Service Component has been successfully activated"); + } + } catch (Throwable e) { + log.error("Error occurred while activating Android Device Management Service Component", e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating Android Device Management Service Component"); + } + try { + if (androidServiceRegRef != null) { + androidServiceRegRef.unregister(); + } + + if (log.isDebugEnabled()) { + log.debug( + "Android Device Management Service Component has been successfully de-activated"); + } + } catch (Throwable e) { + log.error("Error occurred while de-activating Android 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/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/pom.xml b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/pom.xml new file mode 100644 index 00000000..ed516635 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/pom.xml @@ -0,0 +1,105 @@ + + + + devicecloud-api + org.wso2.carbon.device.mgt.iot + 1.0.0 + ../pom.xml + + 4.0.0 + + org.wso2.carbon.device.mgt.iot.android.sense.api + 1.0.0 + + war + WSO2 Carbon - Device Cloud API - Android SenseAPI + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + + + + 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.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + provided + + + org.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.android.sense.impl + 1.0.0-SNAPSHOT + provided + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + + + + + + maven-compiler-plugin + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + maven-war-plugin + + android_sense + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/service/impl/AndroidSenseControllerService.java b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/service/impl/AndroidSenseControllerService.java new file mode 100644 index 00000000..71e79e94 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/service/impl/AndroidSenseControllerService.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl.util.DeviceJSON; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +public class AndroidSenseControllerService { + + private static Log log = LogFactory.getLog(AndroidSenseControllerService.class); + + + /* Service to push all the sensor data collected by the Android + Called by the Android device */ + @Path("/sensordata") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushSensorData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { + + + + + String temperature = dataMsg.value; //TEMP + log.info("Recieved Sensor Data Values: " + temperature); + + if (log.isDebugEnabled()) { + log.debug("Recieved Temperature Data Value: " + temperature + " degrees C"); + } + //try { + boolean result = false; +// result=DeviceController.pushBamData(dataMsg.owner, AndroidSenseConstants.DEVICE_TYPE, +// dataMsg.deviceId, +// System.currentTimeMillis(), "DeviceData", +// temperature, "TEMPERATURE"); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + //return result; +// } catch (UnauthorizedException e) { +// response.setStatus(HttpStatus.SC_UNAUTHORIZED); +// +// } + } +} diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/service/impl/AndroidSenseManagerService.java b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/service/impl/AndroidSenseManagerService.java new file mode 100644 index 00000000..63b3a127 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/service/impl/AndroidSenseManagerService.java @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +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.sample.android.sense.plugin.constants.AndroidSenseConstants; +import org.wso2.carbon.device.mgt.iot.common.DeviceManagement; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.FormParam; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import java.util.Date; + +public class AndroidSenseManagerService { + + private static Log log = LogFactory.getLog(AndroidSenseManagerService.class); + + @Path("/device") + @PUT + public boolean register(@FormParam("deviceId") String deviceId, + @FormParam("owner") String owner) { + + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE); + try { + if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + return true; + } + + 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.setEnrolmentInfo(enrolmentInfo); + + String name = "android_sense" + deviceId; + device.setName(name); + device.setType(AndroidSenseConstants.DEVICE_TYPE); + boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); + if (added) { + Response.status(HttpStatus.SC_OK).build(); + + + } else { + Response.status(HttpStatus.SC_EXPECTATION_FAILED).build(); + + + } + + return added; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + } + + @Path("/device/{device_id}") + @DELETE + public void removeDevice(@PathParam("device_id") String deviceId, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE); + try { + boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(deviceIdentifier); + if (removed) { + response.setStatus(HttpStatus.SC_OK); + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + } + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + + } + + + } + + @Path("/device/{device_id}") + @POST + public boolean updateDevice(@PathParam("device_id") String deviceId, + @FormParam("name") String name, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(AndroidSenseConstants.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(AndroidSenseConstants.DEVICE_TYPE); + + boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device); + + + if (updated) { + response.setStatus(HttpStatus.SC_OK); + + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + + } + return updated; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + + } + + @Path("/device/{device_id}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device getDevice(@PathParam("device_id") String deviceId) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE); + + try { + return deviceManagement.getDeviceManagementService().getDevice( + deviceIdentifier); + + } catch (DeviceManagementException ex) { + log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex); + return null; + } + + } + +} diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/service/impl/util/DeviceJSON.java b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/service/impl/util/DeviceJSON.java new file mode 100644 index 00000000..3e99dfd0 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/android/sense/service/impl/util/DeviceJSON.java @@ -0,0 +1,18 @@ +package org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl.util; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement + +@JsonIgnoreProperties(ignoreUnknown = true) +public class DeviceJSON { + @XmlElement(required = true) public String owner; + @XmlElement(required = true) public String deviceId; + @XmlElement(required = true) public String reply; + @XmlElement public Long time; + @XmlElement public String key; + @XmlElement public String value; +} diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/webapp/META-INF/webapp-classloading.xml b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 00000000..fa446191 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,33 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 00000000..b5024a3a --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/webapp/WEB-INF/web.xml b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/webapp/WEB-INF/web.xml new file mode 100755 index 00000000..f4864580 --- /dev/null +++ b/modules/distribution/src/samples/android_sense/src/org.wso2.carbon.device.mgt.iot.sample.android.sense.service.impl/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,23 @@ + + + Android Sense + Android Sense + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + + CXFServlet + /* + + + + diff --git a/modules/distribution/src/samples/arduino/dbscripts/h2_arduino.sql b/modules/distribution/src/samples/arduino/dbscripts/h2_arduino.sql new file mode 100644 index 00000000..09ce397f --- /dev/null +++ b/modules/distribution/src/samples/arduino/dbscripts/h2_arduino.sql @@ -0,0 +1,11 @@ + +-- ----------------------------------------------------- +-- Table `ARDUINO_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `ARDUINO_DEVICE` ( + `ARDUINO_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`ARDUINO_DEVICE_ID`) ); + + + diff --git a/modules/distribution/src/samples/arduino/dbscripts/mysql_arduino.sql b/modules/distribution/src/samples/arduino/dbscripts/mysql_arduino.sql new file mode 100644 index 00000000..837412b3 --- /dev/null +++ b/modules/distribution/src/samples/arduino/dbscripts/mysql_arduino.sql @@ -0,0 +1,12 @@ +-- ----------------------------------------------------- +-- Table `ARDUINO_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `ARDUINO_DEVICE` ( + `ARDUINO_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`ARDUINO_DEVICE_ID`) ) +ENGINE = InnoDB; + + + + diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/pom.xml b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/pom.xml new file mode 100644 index 00000000..df04156c --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/pom.xml @@ -0,0 +1,141 @@ + + + + + + + devicecloud-mgt + org.wso2.carbon.device.mgt.iot + 1.0.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.iot.arduino.impl + 1.0.0-SNAPSHOT + bundle + WSO2 Carbon - Arduino Management Impl + WSO2 Carbon - Arduino Management and Control Implementation + http://wso2.org + + + + + 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} + Device Cloud Impl Bundle + org.wso2.carbon.device.mgt.iot.arduino.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.common.* + + + + !org.wso2.carbon.device.mgt.iot.arduino.internal, + org.wso2.carbon.device.mgt.iot.arduino.* + + + + + + + + + + + + + + + + + + + + + + + + + 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.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + + + + + diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/constants/ArduinoConstants.java b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/constants/ArduinoConstants.java new file mode 100644 index 00000000..50061bb5 --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/constants/ArduinoConstants.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.constants; + +public class ArduinoConstants { + + public final static String DEVICE_TYPE = "arduino"; + public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; + public final static String DEVICE_PLUGIN_DEVICE_ID = "ARDUINO_DEVICE_ID"; + public final static String STATE_ON = "ON"; + public final static String STATE_OFF = "OFF"; +} diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/ArduinoManager.java b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/ArduinoManager.java new file mode 100644 index 00000000..938606c0 --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/ArduinoManager.java @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl; + + +import org.apache.commons.logging.Log; +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.DeviceManager; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.util.IotDeviceManagementUtil; +import org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl.dao.ArduinoDAO; + +import java.util.ArrayList; +import java.util.List; + + +/** + * This represents the Arduino implementation of DeviceManagerService. + */ +public class ArduinoManager implements DeviceManager { + + private static final IotDeviceManagementDAOFactory iotDeviceManagementDAOFactory = new ArduinoDAO(); + private static final Log log = LogFactory.getLog(ArduinoManager.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 Arduino device : " + device.getDeviceIdentifier()); + } + ArduinoDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice( + iotDevice); + ArduinoDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + ArduinoDAO.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 Arduino 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 Arduino device enrollment data"); + } + ArduinoDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + ArduinoDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + ArduinoDAO.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 Arduino 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 Arduino device : " + deviceId); + } + ArduinoDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .deleteIotDevice(deviceId.getId()); + ArduinoDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + ArduinoDAO.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 Arduino 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 Arduino 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 Arduino 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 Arduino device : " + deviceId.getId()); + } + IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO(). + getIotDevice(deviceId.getId()); + device = IotDeviceManagementUtil.convertToDevice(iotDevice); + } catch (IotDeviceManagementDAOException e) { + String msg = "Error while fetching the Arduino 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 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 Arduino device : " + deviceIdentifier); + } + ArduinoDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + ArduinoDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + ArduinoDAO.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 Arduino 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 Arduino 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 Arduino devices."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return devices; + } + +} \ No newline at end of file diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/ArduinoManagerService.java b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/ArduinoManagerService.java new file mode 100644 index 00000000..2bf8ed58 --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/ArduinoManagerService.java @@ -0,0 +1,62 @@ +package org.wso2.carbon.device.mgt.iot.sample.arduino.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.sample.arduino.plugin.constants.ArduinoConstants; + +import java.util.List; + +public class ArduinoManagerService implements DeviceManagementService { + private DeviceManager deviceManager; + + @Override + public String getType() { + return ArduinoConstants.DEVICE_TYPE; + } + + @Override + public void init() throws DeviceManagementException { + deviceManager=new ArduinoManager(); + + } + + @Override + public DeviceManager getDeviceManager() { + return deviceManager; + } + + @Override + public ApplicationManager getApplicationManager() { + return null; + } + + @Override + public Application[] getApplications(String domain, int pageNumber, int size) + throws ApplicationManagementException { + return new Application[0]; + } + + @Override + public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, + String status) throws ApplicationManagementException { + + } + + @Override + public String getApplicationStatus(DeviceIdentifier deviceId, Application application) + throws ApplicationManagementException { + return null; + } + + @Override + public void installApplication(Operation operation, List deviceIdentifiers) + throws ApplicationManagementException { + + } +} diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/dao/ArduinoDAO.java b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/dao/ArduinoDAO.java new file mode 100644 index 00000000..a28a61cf --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/dao/ArduinoDAO.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactoryInterface; +import org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.constants.ArduinoConstants; +import org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl.dao.impl.ArduinoDeviceDAOImpl; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class ArduinoDAO extends IotDeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface { + + private static final Log log = LogFactory.getLog(ArduinoDAO.class); + static DataSource dataSource; + private static ThreadLocal currentConnection = new ThreadLocal(); + + public ArduinoDAO() { + initArduinoDAO(); + } + + public static void initArduinoDAO() { + dataSource = getDataSourceMap().get(ArduinoConstants.DEVICE_TYPE); + } + + @Override public IotDeviceDAO getIotDeviceDAO() { + return new ArduinoDeviceDAOImpl(); + } + + 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.get() == null) { + try { + currentConnection.set(dataSource.getConnection()); + } catch (SQLException e) { + throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e); + } + } + 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(); + } + } +} \ No newline at end of file diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/dao/impl/ArduinoDeviceDAOImpl.java b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/dao/impl/ArduinoDeviceDAOImpl.java new file mode 100644 index 00000000..3ba599b6 --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/dao/impl/ArduinoDeviceDAOImpl.java @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.util.IotDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.constants.ArduinoConstants; +import org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl.dao.ArduinoDAO; + +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; + +/** + * Implements IotDeviceDAO for arduino Devices. + */ +public class ArduinoDeviceDAOImpl implements IotDeviceDAO{ + + + private static final Log log = LogFactory.getLog(ArduinoDeviceDAOImpl.class); + + @Override + public IotDevice getIotDevice(String iotDeviceId) + throws IotDeviceManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + IotDevice iotDevice = null; + ResultSet resultSet = null; + try { + conn = ArduinoDAO.getConnection(); + String selectDBQuery = + "SELECT ARDUINO_DEVICE_ID, DEVICE_NAME" + + " FROM ARDUINO_DEVICE WHERE ARDUINO_DEVICE_ID = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setString(1, iotDeviceId); + resultSet = stmt.executeQuery(); + + if (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceName(resultSet.getString( + ArduinoConstants.DEVICE_PLUGIN_DEVICE_NAME)); + Map propertyMap = new HashMap(); + + + + iotDevice.setDeviceProperties(propertyMap); + + if (log.isDebugEnabled()) { + log.debug("Arduino device " + iotDeviceId + " data has been fetched from " + + "Arduino database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while fetching Arduino device : '" + iotDeviceId + "'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + ArduinoDAO.closeConnection(); + } + + return iotDevice; + } + + @Override + public boolean addIotDevice(IotDevice iotDevice) + throws IotDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = ArduinoDAO.getConnection(); + String createDBQuery = + "INSERT INTO ARDUINO_DEVICE(ARDUINO_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("Arduino device " + iotDevice.getIotDeviceId() + " data has been" + + " added to the Arduino database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while adding the Arduino device '" + + iotDevice.getIotDeviceId() + "' to the Arduino 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 = ArduinoDAO.getConnection(); + String updateDBQuery = + "UPDATE ARDUINO_DEVICE SET DEVICE_NAME = ? WHERE ARDUINO_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("Arduino device " + iotDevice.getIotDeviceId() + " data has been" + + " modified."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while modifying the Arduino 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 = ArduinoDAO.getConnection(); + String deleteDBQuery = + "DELETE FROM ARDUINO_DEVICE WHERE ARDUINO_DEVICE_ID = ?"; + stmt = conn.prepareStatement(deleteDBQuery); + stmt.setString(1, iotDeviceId); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Arduino device " + iotDeviceId + " data has deleted" + + " from the Arduino database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while deleting Arduino 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 = ArduinoDAO.getConnection(); + String selectDBQuery = + "SELECT ARDUINO_DEVICE_ID, DEVICE_NAME " + + "FROM ARDUINO_DEVICE"; + stmt = conn.prepareStatement(selectDBQuery); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceId(resultSet.getString(ArduinoConstants.DEVICE_PLUGIN_DEVICE_ID)); + iotDevice.setIotDeviceName(resultSet.getString(ArduinoConstants.DEVICE_PLUGIN_DEVICE_NAME)); + + Map propertyMap = new HashMap(); + + iotDevice.setDeviceProperties(propertyMap); + iotDevices.add(iotDevice); + } + if (log.isDebugEnabled()) { + log.debug("All Arduino device details have fetched from Arduino database."); + } + return iotDevices; + } catch (SQLException e) { + String msg = "Error occurred while fetching all Arduino device data'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + ArduinoDAO.closeConnection(); + } + + } + + } \ No newline at end of file diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/util/ArduinoUtils.java b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/util/ArduinoUtils.java new file mode 100644 index 00000000..ba189562 --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/impl/util/ArduinoUtils.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Map; + +/** + * Contains utility methods used by Arduino plugin. + */ +public class ArduinoUtils { + + private static Log log = LogFactory.getLog(ArduinoUtils.class); + + public static String getDeviceProperty(Map deviceProperties, String property) { + + String deviceProperty = deviceProperties.get(property); + + if (deviceProperty == null) { + return ""; + } + + return deviceProperty; + } + + +} diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/internal/ArduinoManagementServiceComponent.java b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/internal/ArduinoManagementServiceComponent.java new file mode 100644 index 00000000..86e03c0d --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/plugin/internal/ArduinoManagementServiceComponent.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.arduino.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.sample.arduino.plugin.impl.ArduinoManagerService; +import org.wso2.carbon.device.mgt.iot.common.service.DeviceTypeService; + + +/** + * @scr.component name="org.wso2.carbon.device.mgt.iot.arduino.internal.ArduinoManagementServiceComponent" + * immediate="true" + * @scr.reference name="wso2.carbon.device.mgt.iot.common.DeviceTypeService" + * interface="org.wso2.carbon.device.mgt.iot.common.service.DeviceTypeService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDeviceTypeService" + * unbind="unsetDeviceTypeService" + */ +public class ArduinoManagementServiceComponent { + + + private ServiceRegistration arduinoServiceRegRef; + + + + private static final Log log = LogFactory.getLog(ArduinoManagementServiceComponent.class); + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating Arduino Device Management Service Component"); + } + try { + BundleContext bundleContext = ctx.getBundleContext(); + + + arduinoServiceRegRef = + bundleContext.registerService(DeviceManagementService.class.getName(), new + ArduinoManagerService(), null); + + + + if (log.isDebugEnabled()) { + log.debug("Arduino Device Management Service Component has been successfully activated"); + } + } catch (Throwable e) { + log.error("Error occurred while activating Arduino Device Management Service Component", e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating Arduino Device Management Service Component"); + } + try { + if (arduinoServiceRegRef != null) { + arduinoServiceRegRef.unregister(); + } + + if (log.isDebugEnabled()) { + log.debug( + "Arduino Device Management Service Component has been successfully de-activated"); + } + } catch (Throwable e) { + log.error("Error occurred while de-activating Arduino 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/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/pom.xml b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/pom.xml new file mode 100644 index 00000000..f44efe61 --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/pom.xml @@ -0,0 +1,104 @@ + + + + devicecloud-api + org.wso2.carbon.device.mgt.iot + 1.0.0 + ../pom.xml + + 4.0.0 + + org.wso2.carbon.device.mgt.iot.arduino.api + 1.0.0 + + war + WSO2 Carbon - Device Cloud API - Arduiono API + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + + + + 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.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + provided + + + org.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.arduino.impl + provided + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + + + + + + maven-compiler-plugin + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + maven-war-plugin + + arduino + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/ArduinoControllerService.java b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/ArduinoControllerService.java new file mode 100644 index 00000000..926113ff --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/ArduinoControllerService.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl.util.DeviceJSON; +import org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl.util.MqttArduinoSubscriber; +import org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.constants.ArduinoConstants; +import org.wso2.carbon.device.mgt.iot.common.DeviceController; +import org.wso2.carbon.device.mgt.iot.common.datastore.impl.DataStreamDefinitions; +import org.wso2.carbon.device.mgt.iot.common.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.iot.common.exception.UnauthorizedException; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.*; + +public class ArduinoControllerService { + + private static Log log = LogFactory.getLog(ArduinoControllerService.class); + + private static Map> replyMsgQueue = new HashMap<>(); + private static Map> internalControlsQueue = new HashMap<>(); + private static MqttArduinoSubscriber mqttArduinoSubscriber; + + + public void setMqttArduinoSubscriber(MqttArduinoSubscriber mqttArduinoSubscriber) { + ArduinoControllerService.mqttArduinoSubscriber = mqttArduinoSubscriber; + try { + mqttArduinoSubscriber.subscribe(); + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + } + } + + public MqttArduinoSubscriber getMqttArduinoSubscriber() { + return mqttArduinoSubscriber; + } + + public static Map> getReplyMsgQueue() { + return replyMsgQueue; + } + + public static Map> getInternalControlsQueue() { + return internalControlsQueue; + } + + /* Service to switch arduino bulb (pin 13) between "ON" and "OFF" + Called by an external client intended to control the Arduino */ + @Path("/bulb/{deviceId}/{state}") + @POST + public void switchBulb(@QueryParam("owner") String owner, + @PathParam("deviceId") String deviceId, + @PathParam("state") String state, + @Context HttpServletResponse response) { + + String switchToState = state.toUpperCase(); + + if (!switchToState.equals(ArduinoConstants.STATE_ON) && !switchToState.equals( + ArduinoConstants.STATE_OFF)) { + log.error("The requested state change shoud be either - 'ON' or 'OFF'"); + response.setStatus(HttpStatus.SC_BAD_REQUEST); + return; + } + + try { + DeviceController deviceController = new DeviceController(); + boolean result = deviceController.publishMqttControl(owner, + ArduinoConstants.DEVICE_TYPE, + deviceId, "BULB", switchToState); + if (result) { + response.setStatus(HttpStatus.SC_ACCEPTED); + + } else { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + + } + + } catch (DeviceControllerException e) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + + } + + } + + /* Service to poll the control-queue for the controls sent to the Arduino + Called by the Arduino device */ + @Path("/readcontrols/{deviceId}") + @GET + public String readControls(@QueryParam("owner") String owner, + @PathParam("deviceId") String deviceId, + @Context HttpServletResponse response) { + String result; + LinkedList deviceControlList = internalControlsQueue.get(deviceId); + + if (deviceControlList == null) { + result = "No controls have been set for device " + deviceId + " of owner " + owner; + response.setStatus(HttpStatus.SC_NO_CONTENT); + } else { + try { + result = deviceControlList.remove(); //returns the head value + response.setStatus(HttpStatus.SC_ACCEPTED); + + } catch (NoSuchElementException ex) { + result = "There are no more controls for device " + deviceId + " of owner " + + owner; + response.setStatus(HttpStatus.SC_NO_CONTENT); + } + } + if (log.isDebugEnabled()) { + log.debug(result); + } + + return result; + } + + + /* Service to push all the sensor data collected by the Arduino + Called by the Arduino device */ + @Path("/pushdata") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { + + String temperature = dataMsg.value; //TEMP + log.info("Recieved Sensor Data Values: " + temperature); + + if (log.isDebugEnabled()) { + log.debug("Recieved Temperature Data Value: " + temperature + " degrees C"); + } + try { + DeviceController deviceController = new DeviceController(); + boolean result = deviceController.pushBamData(dataMsg.owner, + ArduinoConstants.DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + temperature, + DataStreamDefinitions.StreamTypeLabel + .TEMPERATURE); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + + } catch (UnauthorizedException e) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + + } + } +} diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/ArduinoManagerService.java b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/ArduinoManagerService.java new file mode 100644 index 00000000..73ed8d84 --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/ArduinoManagerService.java @@ -0,0 +1,251 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +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.sample.arduino.plugin.constants.ArduinoConstants; +import org.wso2.carbon.device.mgt.iot.common.DeviceManagement; +import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; +import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; + +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.Date; +import java.util.UUID; + +public class ArduinoManagerService { + + private static Log log = LogFactory.getLog(ArduinoManagerService.class); + + @Path("/device/register") + @PUT + public boolean register(@QueryParam("deviceId") String deviceId, + @QueryParam("name") String name, @QueryParam("owner") String owner) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE); + try { + if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + Response.status(HttpStatus.SC_CONFLICT).build(); + 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(ArduinoConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(owner); + device.setEnrolmentInfo(enrolmentInfo); + boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); + if (added) { + Response.status(HttpStatus.SC_OK).build(); + + + } else { + Response.status(HttpStatus.SC_EXPECTATION_FAILED).build(); + + + } + + return added; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + } + + @Path("/device/remove/{device_id}") + @DELETE + public void removeDevice(@PathParam("device_id") String deviceId, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE); + try { + boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(deviceIdentifier); + if (removed) { + response.setStatus(HttpStatus.SC_OK); + + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + + } + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + + } + + + } + + @Path("/device/update/{device_id}") + @POST + public boolean updateDevice(@PathParam("device_id") String deviceId, + @QueryParam("name") String name, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(ArduinoConstants.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(ArduinoConstants.DEVICE_TYPE); + + boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device); + + + if (updated) { + response.setStatus(HttpStatus.SC_OK); + + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + + } + return updated; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + + } + + @Path("/device/{device_id}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device getDevice(@PathParam("device_id") String deviceId) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE); + + try { + Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); + + return device; + } catch (DeviceManagementException ex) { + log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex); + return null; + } + + } + + @Path("/device/{sketch_type}/download") + @GET + @Produces("application/octet-stream") + public Response downloadSketch(@QueryParam("owner") String owner, @PathParam("sketch_type") String + sketchType) { + + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, 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(); + } + + } + + @Path("/device/{sketch_type}/generate_link") + @GET + public Response generateSketchLink(@QueryParam("owner") String owner, @PathParam("sketch_type") String + sketchType) { + + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, 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(); + } + + } + + private ZipArchive createDownloadFile(String owner, String sketchType) throws DeviceManagementException{ + if (owner == null) { + throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!"); + } + + //create new device id + String deviceId = shortUUID(); + + //create token + String token = UUID.randomUUID().toString(); + String refreshToken = UUID.randomUUID().toString(); + //adding registering data + + boolean status = register(deviceId, owner + "s_" + sketchType + "_" + deviceId.substring(0, + 3), + owner); + if (!status) { + String msg = "Error occurred while registering the device with " + "id: " + deviceId + + " owner:" + owner; + throw new DeviceManagementException(msg); + } + + ZipUtil ziputil = new ZipUtil(); + ZipArchive zipFile = null; + + zipFile = ziputil.downloadSketch(owner, sketchType, deviceId, token, refreshToken); + zipFile.setDeviceId(deviceId); + return zipFile; + } + + private static String shortUUID() { + UUID uuid = UUID.randomUUID(); + long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong(); + return Long.toString(l, Character.MAX_RADIX); + } + +} diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/util/DeviceJSON.java b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/util/DeviceJSON.java new file mode 100644 index 00000000..86c739e4 --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/util/DeviceJSON.java @@ -0,0 +1,18 @@ +package org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl.util; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement + +@JsonIgnoreProperties(ignoreUnknown = true) +public class DeviceJSON { + @XmlElement(required = true) public String owner; + @XmlElement(required = true) public String deviceId; + @XmlElement(required = true) public String reply; + @XmlElement public Long time; + @XmlElement public String key; + @XmlElement public String value; +} diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/util/MqttArduinoSubscriber.java b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/util/MqttArduinoSubscriber.java new file mode 100644 index 00000000..f465c7b0 --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/arduino/service/impl/util/MqttArduinoSubscriber.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl.ArduinoControllerService; +import org.wso2.carbon.device.mgt.iot.sample.arduino.plugin.constants.ArduinoConstants; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.mqtt.MqttConfig; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.mqtt.MqttSubscriber; + +import java.io.File; +import java.util.LinkedList; + +public class MqttArduinoSubscriber extends MqttSubscriber { + + private static Log log = LogFactory.getLog(MqttArduinoSubscriber.class); + private static final String subscribetopic = + "wso2" + File.separator + "iot" + File.separator + "+" + File.separator + + ArduinoConstants.DEVICE_TYPE + File.separator + "#"; + + + //make it singleton + private MqttArduinoSubscriber() { + + super("Subscriber", ArduinoConstants.DEVICE_TYPE, MqttConfig.getInstance().getMqttQueueEndpoint(), + subscribetopic); + } + + @Override protected void postMessageArrived(final String topic, final MqttMessage message) { + int lastIndex = topic.lastIndexOf("/"); + String deviceId = topic.substring(lastIndex + 1); + + lastIndex = message.toString().lastIndexOf(":"); + String msgContext = message.toString().substring(lastIndex + 1); + + LinkedList deviceControlList = null; + LinkedList replyMessageList = null; + + if (msgContext.equals("IN") || msgContext.equals(ArduinoConstants.STATE_ON) || msgContext + .equals(ArduinoConstants.STATE_OFF)) { + log.info("Recieved a control message: "); + log.info("Control message topic: " + topic); + log.info("Control message: " + message.toString()); + synchronized (ArduinoControllerService.getInternalControlsQueue()) { + deviceControlList = ArduinoControllerService.getInternalControlsQueue().get(deviceId); + if (deviceControlList == null) { + ArduinoControllerService.getInternalControlsQueue() + .put(deviceId, deviceControlList = new LinkedList()); + } + } + deviceControlList.add(message.toString()); + } else if (msgContext.equals("OUT")) { + log.info("Recieved reply from a device: "); + log.info("Reply message topic: " + topic); + log.info("Reply message: " + message.toString().substring(0, lastIndex)); + synchronized (ArduinoControllerService.getReplyMsgQueue()) { + replyMessageList = ArduinoControllerService.getReplyMsgQueue().get(deviceId); + if (replyMessageList == null) { + ArduinoControllerService.getReplyMsgQueue() + .put(deviceId, replyMessageList = new LinkedList()); + } + } + replyMessageList.add(message.toString()); + } + + } +} diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/webapp/META-INF/webapp-classloading.xml b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 00000000..fa446191 --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,33 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 00000000..958931b7 --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/webapp/WEB-INF/web.xml b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/webapp/WEB-INF/web.xml new file mode 100755 index 00000000..7dbfdaaa --- /dev/null +++ b/modules/distribution/src/samples/arduino/src/org.wso2.carbon.device.mgt.iot.sample.arduino.service.impl/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,23 @@ + + + DigitalDisplay + DigitalDisplay + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + + CXFServlet + /* + + + + diff --git a/modules/distribution/src/samples/digital_display/dbscripts/h2_digital_display.sql b/modules/distribution/src/samples/digital_display/dbscripts/h2_digital_display.sql new file mode 100644 index 00000000..4be5ef35 --- /dev/null +++ b/modules/distribution/src/samples/digital_display/dbscripts/h2_digital_display.sql @@ -0,0 +1,11 @@ + +-- ----------------------------------------------------- +-- Table `DIGITALDISPLAY_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `DIGITAL_DISPLAY_DEVICE` ( + `DIGITAL_DISPLAY_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`DIGITAL_DISPLAY_DEVICE_ID`) ); + + + diff --git a/modules/distribution/src/samples/digital_display/dbscripts/mysql_digital_display.sql b/modules/distribution/src/samples/digital_display/dbscripts/mysql_digital_display.sql new file mode 100644 index 00000000..3ff0ddf7 --- /dev/null +++ b/modules/distribution/src/samples/digital_display/dbscripts/mysql_digital_display.sql @@ -0,0 +1,12 @@ +-- ----------------------------------------------------- +-- Table `DIGITALDISPLAY_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `DIGITAL_DISPLAY_DEVICE` ( + `DIGITAL_DISPLAY_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`DIGITAL_DISPLAY_DEVICE_ID`) ) +ENGINE = InnoDB; + + + + diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/pom.xml b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/pom.xml new file mode 100644 index 00000000..fce18856 --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/pom.xml @@ -0,0 +1,141 @@ + + + + + + + devicecloud-mgt + org.wso2.carbon.device.mgt.iot + 1.0.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.iot.digitaldisplay.impl + 1.0.0-SNAPSHOT + bundle + WSO2 Carbon - Digital Display Management Impl + WSO2 Carbon - digitaldisplay Management and Control Implementation + http://wso2.org + + + + + 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} + Device Cloud Impl Bundle + org.wso2.carbon.device.mgt.iot.digitaldisplay.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.common.* + + + + !org.wso2.carbon.device.mgt.iot.digitaldisplay.internal, + org.wso2.carbon.device.mgt.iot.digitaldisplay.* + + + + + + + + + + + + + + + + + + + + + + + + + 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.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + + + + + diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/constants/DigitalDisplayConstants.java b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/constants/DigitalDisplayConstants.java new file mode 100644 index 00000000..dc233c24 --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/constants/DigitalDisplayConstants.java @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.constants; + +public class DigitalDisplayConstants { + + public final static String DEVICE_TYPE = "digital_display"; + public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; + public final static String DEVICE_PLUGIN_DEVICE_ID = "DIGITAL_DISPLAY_DEVICE_ID"; + +} diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/DigitalDisplayManager.java b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/DigitalDisplayManager.java new file mode 100644 index 00000000..ca57eedf --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/DigitalDisplayManager.java @@ -0,0 +1,266 @@ +/* + * 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.sample.digitaldisplay.plugin.impl; + + +import org.apache.commons.logging.Log; +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.DeviceManager; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.util.IotDeviceManagementUtil; +import org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl.dao.DigitalDisplayDAO; + +import java.util.ArrayList; +import java.util.List; + + +/** + * This represents the DigitalDisplay implementation of DeviceManagerService. + */ +public class DigitalDisplayManager implements DeviceManager +{ + + private static final IotDeviceManagementDAOFactory iotDeviceManagementDAOFactory = new DigitalDisplayDAO(); + private static final Log log = LogFactory.getLog(DigitalDisplayManager.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 DigitalDisplay device : " + device.getDeviceIdentifier()); + } + DigitalDisplayDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice( + iotDevice); + DigitalDisplayDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + DigitalDisplayDAO.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 DigitalDisplay 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 DigitalDisplay device enrollment data"); + } + DigitalDisplayDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + DigitalDisplayDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + DigitalDisplayDAO.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 DigitalDisplay 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 DigitalDisplay device : " + deviceId); + } + DigitalDisplayDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .deleteIotDevice(deviceId.getId()); + DigitalDisplayDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + DigitalDisplayDAO.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 DigitalDisplay 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 DigitalDisplay 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 DigitalDisplay 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 DigitalDisplay device : " + deviceId.getId()); + } + IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO(). + getIotDevice(deviceId.getId()); + device = IotDeviceManagementUtil.convertToDevice(iotDevice); + } catch (IotDeviceManagementDAOException e) { + String msg = "Error while fetching the DigitalDisplay 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 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 DigitalDisplay device : " + deviceIdentifier); + } + DigitalDisplayDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + DigitalDisplayDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + DigitalDisplayDAO.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 DigitalDisplay 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 DigitalDisplay 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 DigitalDisplay devices."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return devices; + } + +} \ No newline at end of file diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/DigitalDisplayManagerService.java b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/DigitalDisplayManagerService.java new file mode 100644 index 00000000..9c29010f --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/DigitalDisplayManagerService.java @@ -0,0 +1,60 @@ +package org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.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.sample.digitaldisplay.plugin.constants.DigitalDisplayConstants; + +import java.util.List; + +public class DigitalDisplayManagerService implements DeviceManagementService{ + private DeviceManager deviceManager; + @Override + public String getType() { + return DigitalDisplayConstants.DEVICE_TYPE; + } + + @Override + public void init() throws DeviceManagementException { + deviceManager= new DigitalDisplayManager(); + } + + @Override + public DeviceManager getDeviceManager() { + return deviceManager; + } + + @Override + public ApplicationManager getApplicationManager() { + return null; + } + + @Override + public Application[] getApplications(String domain, int pageNumber, int size) + throws ApplicationManagementException { + return new Application[0]; + } + + @Override + public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, + String status) throws ApplicationManagementException { + + } + + @Override + public String getApplicationStatus(DeviceIdentifier deviceId, Application application) + throws ApplicationManagementException { + return null; + } + + @Override + public void installApplication(Operation operation, List deviceIdentifiers) + throws ApplicationManagementException { + + } +} diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/dao/DigitalDisplayDAO.java b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/dao/DigitalDisplayDAO.java new file mode 100644 index 00000000..5e64a8c6 --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/dao/DigitalDisplayDAO.java @@ -0,0 +1,126 @@ +/* + * 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.sample.digitaldisplay.plugin.impl.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactoryInterface; +import org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.constants.DigitalDisplayConstants; +import org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl.dao.impl.DigitalDisplayDeviceDAOImpl; + + + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class DigitalDisplayDAO extends IotDeviceManagementDAOFactory + implements IotDeviceManagementDAOFactoryInterface { + + private static final Log log = LogFactory.getLog(DigitalDisplayDAO.class); + static DataSource dataSource; // package local variable + private static ThreadLocal currentConnection = new ThreadLocal(); + + public DigitalDisplayDAO() { + initDigitalDisplayDAO(); + } + + @Override + public IotDeviceDAO getIotDeviceDAO() { + return new DigitalDisplayDeviceDAOImpl(); + } + + public static void initDigitalDisplayDAO(){ + dataSource = getDataSourceMap().get(DigitalDisplayConstants.DEVICE_TYPE); + } + + 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.get() == null) { + try { + currentConnection.set(dataSource.getConnection()); + } catch (SQLException e) { + throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", + e); + } + } + 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(); + } + } +} \ No newline at end of file diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/dao/impl/DigitalDisplayDeviceDAOImpl.java b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/dao/impl/DigitalDisplayDeviceDAOImpl.java new file mode 100644 index 00000000..20b51d43 --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/dao/impl/DigitalDisplayDeviceDAOImpl.java @@ -0,0 +1,238 @@ +/* + * 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.sample.digitaldisplay.plugin.impl.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.util.IotDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.constants.DigitalDisplayConstants; +import org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl.dao.DigitalDisplayDAO; + +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; + +/** + * Implements IotDeviceDAO for digital display Devices. + */ +public class DigitalDisplayDeviceDAOImpl implements IotDeviceDAO{ + + + private static final Log log = LogFactory.getLog(DigitalDisplayDeviceDAOImpl.class); + + @Override + public IotDevice getIotDevice(String iotDeviceId) + throws IotDeviceManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + IotDevice iotDevice = null; + ResultSet resultSet = null; + try { + conn = DigitalDisplayDAO.getConnection(); + String selectDBQuery = + "SELECT DIGITAL_DISPLAY_DEVICE_ID, DEVICE_NAME" + + " FROM DIGITAL_DISPLAY_DEVICE WHERE DIGITAL_DISPLAY_DEVICE_ID = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setString(1, iotDeviceId); + resultSet = stmt.executeQuery(); + + if (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceName(resultSet.getString( + DigitalDisplayConstants.DEVICE_PLUGIN_DEVICE_NAME)); + Map propertyMap = new HashMap(); + + + + iotDevice.setDeviceProperties(propertyMap); + + if (log.isDebugEnabled()) { + log.debug("Digital Display device " + iotDeviceId + " data has been fetched from " + + "Digital Display database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while fetching Digital Display device : '" + iotDeviceId + "'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + DigitalDisplayDAO.closeConnection(); + } + + return iotDevice; + } + + @Override + public boolean addIotDevice(IotDevice iotDevice) + throws IotDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = DigitalDisplayDAO.getConnection(); + String createDBQuery = + "INSERT INTO DIGITAL_DISPLAY_DEVICE(DIGITAL_DISPLAY_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("Digital Display device " + iotDevice.getIotDeviceId() + " data has been" + + " added to the Digital Display database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while adding the Digital Display device '" + + iotDevice.getIotDeviceId() + "' to the Digital Display 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 = DigitalDisplayDAO.getConnection(); + String updateDBQuery = + "UPDATE DIGITAL_DISPLAY_DEVICE SET DEVICE_NAME = ? WHERE DIGITAL_DISPLAY_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("Digital Display device " + iotDevice.getIotDeviceId() + " data has been" + + " modified."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while modifying the Digital Display 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 = DigitalDisplayDAO.getConnection(); + String deleteDBQuery = + "DELETE FROM DIGITAL_DISPLAY_DEVICE WHERE DIGITAL_DISPLAY_DEVICE_ID = ?"; + stmt = conn.prepareStatement(deleteDBQuery); + stmt.setString(1, iotDeviceId); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Digital Display device " + iotDeviceId + " data has deleted" + + " from the Digital Display database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while deleting Digital Display 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 = DigitalDisplayDAO.getConnection(); + String selectDBQuery = + "SELECT DIGITAL_DISPLAY_DEVICE_ID, DEVICE_NAME " + + "FROM DIGITAL_DISPLAY_DEVICE"; + stmt = conn.prepareStatement(selectDBQuery); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceId(resultSet.getString(DigitalDisplayConstants.DEVICE_PLUGIN_DEVICE_ID)); + iotDevice.setIotDeviceName(resultSet.getString(DigitalDisplayConstants.DEVICE_PLUGIN_DEVICE_NAME)); + + Map propertyMap = new HashMap(); + + iotDevice.setDeviceProperties(propertyMap); + iotDevices.add(iotDevice); + } + if (log.isDebugEnabled()) { + log.debug("All Digital Display device details have fetched from Digital Display database."); + } + return iotDevices; + } catch (SQLException e) { + String msg = "Error occurred while fetching all Digital Display device data'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + DigitalDisplayDAO.closeConnection(); + } + + } + + } \ No newline at end of file diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/util/DigitalDisplayUtils.java b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/util/DigitalDisplayUtils.java new file mode 100644 index 00000000..b8113ea6 --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/impl/util/DigitalDisplayUtils.java @@ -0,0 +1,45 @@ +/* + * 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.sample.digitaldisplay.plugin.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Map; + +/** + * Contains utility methods used by Digital Display plugin. + */ +public class DigitalDisplayUtils { + + private static Log log = LogFactory.getLog(DigitalDisplayUtils.class); + + public static String getDeviceProperty(Map deviceProperties, String property) { + + String deviceProperty = deviceProperties.get(property); + + if (deviceProperty == null) { + return ""; + } + + return deviceProperty; + } + + +} diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/internal/DigitalDisplayManagementServiceComponent.java b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/internal/DigitalDisplayManagementServiceComponent.java new file mode 100644 index 00000000..46daeb45 --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/plugin/internal/DigitalDisplayManagementServiceComponent.java @@ -0,0 +1,110 @@ +/* + * 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.sample.digitaldisplay.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.common.service.DeviceTypeService; +import org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.impl.DigitalDisplayManagerService; + + + +/** + * @scr.component name="org.wso2.carbon.device.mgt.iot.digitaldisplay.internal.DigitalDisplayManagementServiceComponent" + * immediate="true" + * @scr.reference name="wso2.carbon.device.mgt.iot.common.DeviceTypeService" + * interface="org.wso2.carbon.device.mgt.iot.common.service.DeviceTypeService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDeviceTypeService" + * unbind="unsetDeviceTypeService" + */ + +public class DigitalDisplayManagementServiceComponent { + + + private ServiceRegistration digitalDisplayServiceRegRef; + + + + private static final Log log = LogFactory.getLog(DigitalDisplayManagementServiceComponent.class); + + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating Digital Display Management Service Component"); + } + try { + BundleContext bundleContext = ctx.getBundleContext(); + + + digitalDisplayServiceRegRef = + bundleContext.registerService(DeviceManagementService.class.getName(), new + DigitalDisplayManagerService(), + null); + + + + if (log.isDebugEnabled()) { + log.debug("Digital Display Management Service Component has been successfully activated"); + } + } catch (Throwable e) { + log.error("Error occurred while activating Digital Display Management Service Component", e); + } + } + + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating DigitalDisplay Management Service Component"); + } + try { + if (digitalDisplayServiceRegRef != null) { + digitalDisplayServiceRegRef.unregister(); + } + + if (log.isDebugEnabled()) { + log.debug( + "DigitalDisplay Management Service Component has been successfully de-activated"); + } + } catch (Throwable e) { + log.error("Error occurred while de-activating Iot 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/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/pom.xml b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/pom.xml new file mode 100644 index 00000000..3d86d927 --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/pom.xml @@ -0,0 +1,100 @@ + + + + devicecloud-api + org.wso2.carbon.device.mgt.iot + 1.0.0 + ../pom.xml + + 4.0.0 + + org.wso2.carbon.device.mgt.iot.digitaldisplay.api + 1.0.0 + + war + WSO2 Carbon - Device Cloud API - Digital Display API + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + + + 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.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + provided + + + org.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.digitaldisplay.impl + provided + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + + + + + + maven-compiler-plugin + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + maven-war-plugin + + digitaldisplay + + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/service/impl/DigitalDisplayManagerService.java b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/service/impl/DigitalDisplayManagerService.java new file mode 100644 index 00000000..8a98ee39 --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/digitaldisplay/service/impl/DigitalDisplayManagerService.java @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +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.common.DeviceManagement; +import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; +import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; +import org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.plugin.constants.DigitalDisplayConstants; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import java.util.UUID; + +public class DigitalDisplayManagerService { + + private static Log log = LogFactory.getLog(DigitalDisplayManagerService.class); + + @Path("/device/register") + @PUT + public boolean register(@QueryParam("deviceId") String deviceId, + @QueryParam("name") String name, @QueryParam("owner") String owner) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE); + try { + if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + Response.status(HttpStatus.SC_CONFLICT).build(); + return false; + } + + Device device = new Device(); + device.setDeviceIdentifier(deviceId); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setDateOfEnrolment(new Date().getTime()); + enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + device.setName(name); + device.setType(DigitalDisplayConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(owner); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); + if (added) { + Response.status(HttpStatus.SC_OK).build(); + + + } else { + Response.status(HttpStatus.SC_EXPECTATION_FAILED).build(); + + + } + + return added; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + } + + @Path("/device/remove/{device_id}") + @DELETE + public void removeDevice(@PathParam("device_id") String deviceId, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE); + try { + boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( + deviceIdentifier); + if (removed) { + response.setStatus(HttpStatus.SC_OK); + + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + + } + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + + } + + + } + + @Path("/device/update/{device_id}") + @POST + public boolean updateDevice(@PathParam("device_id") String deviceId, + @QueryParam("name") String name, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(DigitalDisplayConstants.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(DigitalDisplayConstants.DEVICE_TYPE); + + boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device); + + + if (updated) { + response.setStatus(HttpStatus.SC_OK); + + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + + } + return updated; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + + } + + @Path("/device/{device_id}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device getDevice(@PathParam("device_id") String deviceId) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE); + + try { + Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); + + return device; + } catch (DeviceManagementException ex) { + log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex); + return null; + } + + } + + @Path("/device/{sketch_type}/download") + @GET + @Produces("application/octet-stream") + public Response downloadSketch(@QueryParam("owner") String owner, + @PathParam("sketch_type") String + sketchType) { + + if (owner == null) { + return Response.status(400).build();//bad request + } + + //create new device id + String deviceId = shortUUID(); + + //create token + String token = UUID.randomUUID().toString(); + String refreshToken = UUID.randomUUID().toString(); + //adding registering data + + boolean status = register(deviceId, + owner + "s_" + sketchType + "_" + deviceId.substring(0, 3), + owner); + if (!status) { + return Response.status(500).entity( + "Error occurred while registering the device with " + "id: " + deviceId + + " owner:" + owner).build(); + + } + + ZipUtil ziputil = new ZipUtil(); + ZipArchive zipFile = null; + try { + zipFile = ziputil.downloadSketch(owner, sketchType, deviceId, + token, refreshToken); + } catch (DeviceManagementException ex) { + return Response.status(500).entity("Error occurred while creating zip file").build(); + } + + Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); + rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); + return rb.build(); + } + + 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); + } + +} diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/webapp/META-INF/webapp-classloading.xml b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 00000000..fa446191 --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,33 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 00000000..deff291d --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/webapp/WEB-INF/web.xml b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/webapp/WEB-INF/web.xml new file mode 100755 index 00000000..7dbfdaaa --- /dev/null +++ b/modules/distribution/src/samples/digital_display/src/org.wso2.carbon.device.mgt.iot.sample.digitaldisplay.service.impl/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,23 @@ + + + DigitalDisplay + DigitalDisplay + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + + CXFServlet + /* + + + + diff --git a/modules/distribution/src/samples/firealarm/dbscripts/h2_firealarm.sql b/modules/distribution/src/samples/firealarm/dbscripts/h2_firealarm.sql new file mode 100644 index 00000000..3f637c25 --- /dev/null +++ b/modules/distribution/src/samples/firealarm/dbscripts/h2_firealarm.sql @@ -0,0 +1,11 @@ + +-- ----------------------------------------------------- +-- Table `FIREALARM_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `FIREALARM_DEVICE` ( + `FIREALARM_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`FIREALARM_DEVICE_ID`) ); + + + diff --git a/modules/distribution/src/samples/firealarm/dbscripts/mysql_firealarm.sql b/modules/distribution/src/samples/firealarm/dbscripts/mysql_firealarm.sql new file mode 100644 index 00000000..f358db29 --- /dev/null +++ b/modules/distribution/src/samples/firealarm/dbscripts/mysql_firealarm.sql @@ -0,0 +1,12 @@ +-- ----------------------------------------------------- +-- Table `FIREALARM_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `FIREALARM_DEVICE` ( + `FIREALARM_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`FIREALARM_DEVICE_ID`) ) +ENGINE = InnoDB; + + + + diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/pom.xml b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/pom.xml new file mode 100644 index 00000000..647fbe92 --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/pom.xml @@ -0,0 +1,152 @@ + + + + + + + devicecloud-mgt + org.wso2.carbon.device.mgt.iot + 1.0.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.iot.firealarm.impl + 1.0.0-SNAPSHOT + bundle + WSO2 Carbon - Firealarm Management Impl + WSO2 Carbon - Firealarm Management and Control Implementation + http://wso2.org + + + + + 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} + Device Cloud Impl Bundle + org.wso2.carbon.device.mgt.iot.firealarm.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.common.*, + + + + !org.wso2.carbon.device.mgt.iot.firealarm.internal, + org.wso2.carbon.device.mgt.iot.firealarm.* + + + + + + + + + + + + + + + + + + + + + + + + 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.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/constants/FireAlarmConstants.java b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/constants/FireAlarmConstants.java new file mode 100644 index 00000000..8725e4df --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/constants/FireAlarmConstants.java @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants; + +public class FireAlarmConstants { + public final static String DEVICE_TYPE = "firealarm"; + public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; + public final static String DEVICE_PLUGIN_DEVICE_ID = "FIREALARM_DEVICE_ID"; + public final static String STATE_ON = "ON"; + public final static String STATE_OFF = "OFF"; +} diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/FireAlarmManager.java b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/FireAlarmManager.java new file mode 100644 index 00000000..9a6d0b1b --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/FireAlarmManager.java @@ -0,0 +1,261 @@ +/* + * 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.sample.firealarm.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.iot.sample.firealarm.plugin.impl.dao.FireAlarmDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.util.IotDeviceManagementUtil; +import java.util.ArrayList; +import java.util.List; + + +/** + * This represents the FireAlarm implementation of DeviceManagerService. + */ +public class FireAlarmManager implements DeviceManager { + + private static final IotDeviceManagementDAOFactory iotDeviceManagementDAOFactory = new FireAlarmDAO(); + private static final Log log = LogFactory.getLog(FireAlarmManager.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 Firealarm device : " + device.getDeviceIdentifier()); + } + FireAlarmDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice( + iotDevice); + FireAlarmDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + FireAlarmDAO.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 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 Firealarm device enrollment data"); + } + FireAlarmDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + FireAlarmDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + FireAlarmDAO.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 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 Firealarm device : " + deviceId); + } + FireAlarmDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .deleteIotDevice(deviceId.getId()); + FireAlarmDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + FireAlarmDAO.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 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 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 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 Firealarm device : " + deviceId.getId()); + } + IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO(). + getIotDevice(deviceId.getId()); + device = IotDeviceManagementUtil.convertToDevice(iotDevice); + } catch (IotDeviceManagementDAOException e) { + String msg = "Error while fetching the 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 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 Firealarm device : " + deviceIdentifier); + } + FireAlarmDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + FireAlarmDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + FireAlarmDAO.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 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 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 Firealarm devices."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return devices; + } + + + +} \ No newline at end of file diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/FireAlarmManagerService.java b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/FireAlarmManagerService.java new file mode 100644 index 00000000..3853a021 --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/FireAlarmManagerService.java @@ -0,0 +1,60 @@ +package org.wso2.carbon.device.mgt.iot.sample.firealarm.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.sample.firealarm.plugin.constants.FireAlarmConstants; + +import java.util.List; + +public class FireAlarmManagerService implements DeviceManagementService{ + private DeviceManager deviceManager; + @Override + public String getType() { + return FireAlarmConstants.DEVICE_TYPE; + } + + @Override + public void init() throws DeviceManagementException { + this.deviceManager=new FireAlarmManager(); + } + + @Override + public DeviceManager getDeviceManager() { + return deviceManager; + } + + @Override + public ApplicationManager getApplicationManager() { + return null; + } + + @Override + public Application[] getApplications(String domain, int pageNumber, int size) + throws ApplicationManagementException { + return new Application[0]; + } + + @Override + public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, + String status) throws ApplicationManagementException { + + } + + @Override + public String getApplicationStatus(DeviceIdentifier deviceId, Application application) + throws ApplicationManagementException { + return null; + } + + @Override + public void installApplication(Operation operation, List deviceIdentifiers) + throws ApplicationManagementException { + + } +} diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/dao/FireAlarmDAO.java b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/dao/FireAlarmDAO.java new file mode 100644 index 00000000..ea47c0aa --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/dao/FireAlarmDAO.java @@ -0,0 +1,121 @@ +/* + * 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.sample.firealarm.plugin.impl.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactoryInterface; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants.FireAlarmConstants; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl.dao.impl.FireAlarmDeviceDAOImpl; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class FireAlarmDAO extends IotDeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface { + + private static final Log log = LogFactory.getLog(FireAlarmDAO.class); + static DataSource dataSource; + private static ThreadLocal currentConnection = new ThreadLocal(); + + public FireAlarmDAO() { + initFireAlarmDAO(); + } + + public static void initFireAlarmDAO() { + dataSource = getDataSourceMap().get(FireAlarmConstants.DEVICE_TYPE); + } + + @Override public IotDeviceDAO getIotDeviceDAO() { + return new FireAlarmDeviceDAOImpl(); + } + + 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.get() == null) { + try { + currentConnection.set(dataSource.getConnection()); + } catch (SQLException e) { + throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e); + } + } + 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(); + } + } +} \ No newline at end of file diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/dao/impl/FireAlarmDeviceDAOImpl.java b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/dao/impl/FireAlarmDeviceDAOImpl.java new file mode 100644 index 00000000..987f36a2 --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/dao/impl/FireAlarmDeviceDAOImpl.java @@ -0,0 +1,238 @@ +/* + * 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.sample.firealarm.plugin.impl.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants.FireAlarmConstants; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl.dao.FireAlarmDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.util.IotDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.iot.common.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; + +/** + * Implements IotDeviceDAO for firealarm Devices. + */ +public class FireAlarmDeviceDAOImpl implements IotDeviceDAO{ + + + private static final Log log = LogFactory.getLog(FireAlarmDeviceDAOImpl.class); + + @Override + public IotDevice getIotDevice(String iotDeviceId) + throws IotDeviceManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + IotDevice iotDevice = null; + ResultSet resultSet = null; + try { + conn = FireAlarmDAO.getConnection(); + String selectDBQuery = + "SELECT FIREALARM_DEVICE_ID, DEVICE_NAME" + + " FROM FIREALARM_DEVICE WHERE FIREALARM_DEVICE_ID = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setString(1, iotDeviceId); + resultSet = stmt.executeQuery(); + + if (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceName(resultSet.getString( + FireAlarmConstants.DEVICE_PLUGIN_DEVICE_NAME)); + Map propertyMap = new HashMap(); + + + + iotDevice.setDeviceProperties(propertyMap); + + if (log.isDebugEnabled()) { + log.debug("Firealarm device " + iotDeviceId + " data has been fetched from " + + "Firealarm database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while fetching Firealarm device : '" + iotDeviceId + "'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + FireAlarmDAO.closeConnection(); + } + + return iotDevice; + } + + @Override + public boolean addIotDevice(IotDevice iotDevice) + throws IotDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = FireAlarmDAO.getConnection(); + String createDBQuery = + "INSERT INTO FIREALARM_DEVICE(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("Firealarm device " + iotDevice.getIotDeviceId() + " data has been" + + " added to the Firealarm database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while adding the Firealarm device '" + + iotDevice.getIotDeviceId() + "' to the 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 = FireAlarmDAO.getConnection(); + String updateDBQuery = + "UPDATE FIREALARM_DEVICE SET DEVICE_NAME = ? WHERE 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("Firealarm device " + iotDevice.getIotDeviceId() + " data has been" + + " modified."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while modifying the Firealarm 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 = FireAlarmDAO.getConnection(); + String deleteDBQuery = + "DELETE FROM FIREALARM_DEVICE WHERE 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("Firealarm device " + iotDeviceId + " data has deleted" + + " from the Firealarm database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while deleting 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 = FireAlarmDAO.getConnection(); + String selectDBQuery = + "SELECT FIREALARM_DEVICE_ID, DEVICE_NAME " + + "FROM FIREALARM_DEVICE"; + stmt = conn.prepareStatement(selectDBQuery); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceId(resultSet.getString(FireAlarmConstants.DEVICE_PLUGIN_DEVICE_ID)); + iotDevice.setIotDeviceName(resultSet.getString(FireAlarmConstants.DEVICE_PLUGIN_DEVICE_NAME)); + + Map propertyMap = new HashMap(); + + iotDevice.setDeviceProperties(propertyMap); + iotDevices.add(iotDevice); + } + if (log.isDebugEnabled()) { + log.debug("All Firealarm device details have fetched from Firealarm database."); + } + return iotDevices; + } catch (SQLException e) { + String msg = "Error occurred while fetching all Firealarm device data'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + FireAlarmDAO.closeConnection(); + } + + } + + } \ No newline at end of file diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/util/FireAlarmUtils.java b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/util/FireAlarmUtils.java new file mode 100644 index 00000000..d1e6688f --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/impl/util/FireAlarmUtils.java @@ -0,0 +1,45 @@ +/* + * 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.sample.firealarm.plugin.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Map; + +/** + * Contains utility methods used by FireAlarm plugin. + */ +public class FireAlarmUtils { + + private static Log log = LogFactory.getLog(FireAlarmUtils.class); + + public static String getDeviceProperty(Map deviceProperties, String property) { + + String deviceProperty = deviceProperties.get(property); + + if (deviceProperty == null) { + return ""; + } + + return deviceProperty; + } + + +} diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/internal/FirealarmManagementServiceComponent.java b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/internal/FirealarmManagementServiceComponent.java new file mode 100644 index 00000000..21221caf --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/plugin/internal/FirealarmManagementServiceComponent.java @@ -0,0 +1,104 @@ +/* + * 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.sample.firealarm.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.common.service.DeviceTypeService; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.impl.FireAlarmManagerService; + + +/** + * @scr.component name="org.wso2.carbon.device.mgt.iot.firealarm.internal.FirealarmManagementServiceComponent" + * immediate="true" + * @scr.reference name="wso2.carbon.device.mgt.iot.common.DeviceTypeService" + * interface="org.wso2.carbon.device.mgt.iot.common.service.DeviceTypeService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDeviceTypeService" + * unbind="unsetDeviceTypeService" + */ +public class FirealarmManagementServiceComponent { + + + private ServiceRegistration firealarmServiceRegRef; + + + + private static final Log log = LogFactory.getLog(FirealarmManagementServiceComponent.class); + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating Firealarm Device Management Service Component"); + } + try { + BundleContext bundleContext = ctx.getBundleContext(); + + + firealarmServiceRegRef = + bundleContext.registerService(DeviceManagementService.class.getName(), + new FireAlarmManagerService(), + null); + + + + if (log.isDebugEnabled()) { + log.debug("Firealarm Device Management Service Component has been successfully activated"); + } + } catch (Throwable e) { + log.error("Error occurred while activating Firealarm Device Management Service Component", e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating Firealarm Device Management Service Component"); + } + try { + if (firealarmServiceRegRef != null) { + firealarmServiceRegRef.unregister(); + } + + if (log.isDebugEnabled()) { + log.debug( + "Firealarm Device Management Service Component has been successfully de-activated"); + } + } catch (Throwable e) { + log.error("Error occurred while de-activating 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/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/pom.xml b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/pom.xml new file mode 100644 index 00000000..e5618c76 --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/pom.xml @@ -0,0 +1,107 @@ + + + + devicecloud-api + org.wso2.carbon.device.mgt.iot + 1.0.0 + ../pom.xml + + 4.0.0 + + org.wso2.carbon.device.mgt.iot.firealarm.api + 1.0.0 + + war + WSO2 Carbon - Device Cloud API - Firealarm API + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + + + 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 + + + org.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + provided + + + org.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.firealarm.impl + provided + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + + + + + + maven-compiler-plugin + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + maven-war-plugin + + firealarm + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/log4j.properties b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/log4j.properties new file mode 100755 index 00000000..c271582f --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/log4j.properties @@ -0,0 +1,8 @@ +# Root logger option +log4j.rootLogger=INFO, stdout + +# Direct log messages to stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%-5p %d{yyyy-MM-dd HH:mm:ss} %c{1}:%L - %m%n \ No newline at end of file diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmControllerService.java b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmControllerService.java new file mode 100644 index 00000000..a04729fc --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmControllerService.java @@ -0,0 +1,676 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.concurrent.FutureCallback; +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClients; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.iot.common.DeviceController; +import org.wso2.carbon.device.mgt.iot.common.DeviceValidator; +import org.wso2.carbon.device.mgt.iot.common.datastore.impl.DataStreamDefinitions; +import org.wso2.carbon.device.mgt.iot.common.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.iot.common.exception.UnauthorizedException; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.util.DeviceJSON; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants.FireAlarmConstants; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; +import java.net.URL; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; + +public class FireAlarmControllerService { + + private static Log log = LogFactory.getLog(FireAlarmControllerService.class); + + private static final String URL_PREFIX = "http://"; + private static final String BULB_CONTEXT = "/BULB/"; + private static final String FAN_CONTEXT = "/FAN/"; + private static final String TEMPERATURE_CONTEXT = "/TEMP/"; + + public static final String XMPP_PROTOCOL = "XMPP"; + public static final String HTTP_PROTOCOL = "HTTP"; + public static final String MQTT_PROTOCOL = "MQTT"; + + + private static ConcurrentHashMap deviceToIpMap = + new ConcurrentHashMap(); + + @Path("/register/{owner}/{deviceId}/{ip}") + @POST + public String registerDeviceIP(@PathParam("owner") String owner, + @PathParam("deviceId") String deviceId, + @PathParam("ip") String deviceIP, + @Context HttpServletResponse response) { + String result; + + log.info("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + + " of owner: " + owner); + + deviceToIpMap.put(deviceId, deviceIP); + + result = "Device-IP Registered"; + response.setStatus(HttpStatus.SC_OK); + + if (log.isDebugEnabled()) { + log.debug(result); + } + + return result; + } + + + /* Service to switch "ON" and "OFF" the FireAlarm bulb + Called by an external client intended to control the FireAlarm bulb */ + @Path("/bulb/{state}") + @POST + public void switchBulb(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @PathParam("state") String state, + @Context HttpServletResponse response) { + + try { + DeviceValidator deviceValidator = new DeviceValidator(); + if (!deviceValidator.isExist(owner, new DeviceIdentifier(deviceId, + FireAlarmConstants + .DEVICE_TYPE))) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + return; + } + } catch (DeviceManagementException e) { + log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner); + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + return; + } + + String switchToState = state.toUpperCase(); + + if (!switchToState.equals(FireAlarmConstants.STATE_ON) && !switchToState.equals( + FireAlarmConstants.STATE_OFF)) { + log.error("The requested state change shoud be either - 'ON' or 'OFF'"); + response.setStatus(HttpStatus.SC_BAD_REQUEST); + return; + } + + String deviceIP = deviceToIpMap.get(deviceId); + if (deviceIP == null) { + response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); + return; + } + + String protocolString = protocol.toUpperCase(); + String callUrlPattern = BULB_CONTEXT + switchToState; + + log.info("Sending command: '" + callUrlPattern + "' to firealarm at: " + deviceIP + " " + + "via" + " " + protocol); + + try { + switch (protocolString) { + case HTTP_PROTOCOL: + sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true); + break; + case MQTT_PROTOCOL: + callUrlPattern = BULB_CONTEXT.replace("/", ""); + sendCommandViaMQTT(owner, deviceId, callUrlPattern, switchToState); + break; + default: + if (protocolString == null) { + sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true); + } else { + response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED); + return; + } + break; + } + } catch (DeviceManagementException e) { + log.error("Failed to send command '" + callUrlPattern + "' to: " + deviceIP + " via" + + " " + protocol); + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + return; + } + + response.setStatus(HttpStatus.SC_OK); + } + + + @Path("/fan/{state}") + @POST + public void switchFan(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @PathParam("state") String state, + @Context HttpServletResponse response) { + + try { + DeviceValidator deviceValidator = new DeviceValidator(); + if (!deviceValidator.isExist(owner, new DeviceIdentifier(deviceId, + FireAlarmConstants + .DEVICE_TYPE))) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + return; + } + } catch (DeviceManagementException e) { + log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner); + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + return; + } + + String switchToState = state.toUpperCase(); + + if (!switchToState.equals(FireAlarmConstants.STATE_ON) && !switchToState.equals( + FireAlarmConstants.STATE_OFF)) { + log.error("The requested state change shoud be either - 'ON' or 'OFF'"); + response.setStatus(HttpStatus.SC_BAD_REQUEST); + return; + } + + String deviceIP = deviceToIpMap.get(deviceId); + + if (deviceIP == null) { + response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); + return; + } + + String protocolString = protocol.toUpperCase(); + String callUrlPattern = FAN_CONTEXT + switchToState; + + log.info("Sending command: '" + callUrlPattern + "' to firealarm at: " + deviceIP + " " + + "via" + " " + protocol); + + try { + switch (protocolString) { + case HTTP_PROTOCOL: + sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true); + break; + case MQTT_PROTOCOL: + callUrlPattern = FAN_CONTEXT.replace("/", ""); + sendCommandViaMQTT(owner, deviceId, callUrlPattern, switchToState); + break; + default: + if (protocolString == null) { + sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true); + } else { + response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED); + return; + } + break; + } + } catch (DeviceManagementException e) { + log.error("Failed to send command '" + callUrlPattern + "' to: " + deviceIP + " via" + + " " + protocol); + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + return; + } + + response.setStatus(HttpStatus.SC_OK); + } + + + @Path("/readtemperature") + @GET + public String requestTemperature(@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, new DeviceIdentifier(deviceId, + FireAlarmConstants + .DEVICE_TYPE))) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + return "Unauthorized Access"; + } + } catch (DeviceManagementException e) { + replyMsg = e.getErrorMessage(); + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + return replyMsg; + } + + String deviceIp = deviceToIpMap.get(deviceId); + + if (deviceIp == null) { + replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner; + response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); + return replyMsg; + } + + try { + switch (protocol) { + case HTTP_PROTOCOL: + log.info("Sending request to read firealarm-temperature at : " + deviceIp + + " via " + HTTP_PROTOCOL); + + replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false); + break; + + case XMPP_PROTOCOL: + log.info("Sending request to read firealarm-temperature at : " + deviceIp + + " via " + + XMPP_PROTOCOL); + replyMsg = requestTemperatureViaXMPP(deviceIp, response); + break; + + default: + if (protocol == null) { + log.info("Sending request to read firealarm-temperature at : " + deviceIp + + " via " + HTTP_PROTOCOL); + + replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false); + } else { + replyMsg = "Requested protocol '" + protocol + "' is not supported"; + response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED); + return replyMsg; + } + break; + } + } catch (DeviceManagementException e) { + replyMsg = e.getErrorMessage(); + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + return replyMsg; + } + + response.setStatus(HttpStatus.SC_OK); + replyMsg = "The current temperature of the device is " + replyMsg; + return replyMsg; + } + + + public String requestTemperatureViaXMPP(String deviceIp, + @Context HttpServletResponse response) { + String replyMsg = ""; + + String sep = File.separator; + String scriptsFolder = "repository" + sep + "resources" + sep + "scripts"; + String scriptPath = CarbonUtils.getCarbonHome() + sep + scriptsFolder + sep + + "xmpp_client.py"; + String command = "python " + scriptPath; + + replyMsg = executeCommand(command); + + response.setStatus(HttpStatus.SC_OK); + return replyMsg; + } + + + private String executeCommand(String command) { + StringBuffer output = new StringBuffer(); + + Process p; + try { + p = Runtime.getRuntime().exec(command); + p.waitFor(); + BufferedReader reader = + new BufferedReader(new InputStreamReader(p.getInputStream())); + + String line = ""; + while ((line = reader.readLine()) != null) { + output.append(line + "\n"); + } + + } catch (Exception e) { + log.info(e.getMessage(), e); + } + + return output.toString(); + + } + + + @Path("/push_temperature") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushTemperatureData( + final DeviceJSON dataMsg, @Context HttpServletResponse response) { + boolean result; + String deviceId = dataMsg.deviceId; + String deviceIp = dataMsg.reply; + String 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(HttpStatus.SC_PRECONDITION_FAILED); + 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(HttpStatus.SC_CONFLICT); + return; + } + + try { + DeviceController deviceController = new DeviceController(); + result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants + .DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + temperature, + DataStreamDefinitions.StreamTypeLabel + .TEMPERATURE); + + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + } catch (UnauthorizedException e) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + log.error("Data Push Attempt Failed for BAM Publisher: " + e.getMessage()); + } + + try { + DeviceController deviceController = new DeviceController(); + result = deviceController.pushCepData(dataMsg.owner, FireAlarmConstants + .DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + temperature, + DataStreamDefinitions.StreamTypeLabel + .TEMPERATURE); + + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + } catch (UnauthorizedException e) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + log.error("Data Push Attempt Failed for CEP Publisher: " + e.getMessage()); + } + } + + + /* Service to push all the sensor data collected by the FireAlarm + Called by the FireAlarm device */ + + @Path("/pushalarmdata") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushAlarmData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { + boolean result; + String sensorValues = dataMsg.value; + log.info("Recieved Sensor Data Values: " + sensorValues); + + String sensors[] = sensorValues.split(":"); + try { + if (sensors.length == 3) { + String temperature = sensors[0]; + String bulb = sensors[1]; + String fan = sensors[2]; + + sensorValues = "Temperature:" + temperature + "C\tBulb Status:" + bulb + + "\t\tFan Status:" + fan; + log.info(sensorValues); + DeviceController deviceController = new DeviceController(); + result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants + .DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + temperature, "TEMPERATURE"); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + log.error("Error whilst pushing temperature: " + sensorValues); + return; + } + + result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants + .DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + bulb, + "BULB"); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + log.error("Error whilst pushing Bulb data: " + sensorValues); + return; + } + + result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants + .DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + fan, + "FAN"); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + log.error("Error whilst pushing Fan data: " + sensorValues); + } + + } else { + DeviceController deviceController = new DeviceController(); + result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants + .DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + dataMsg.value, dataMsg.reply); + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + log.error("Error whilst pushing sensor data: " + sensorValues); + } + } + + } catch (UnauthorizedException e) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + log.error("Data Push Attempt Failed at Publisher: " + e.getMessage()); + } + } + + + private boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource, + String state) throws DeviceManagementException { + + boolean result = false; + DeviceController deviceController = new DeviceController(); + + try { + result = deviceController.publishMqttControl(deviceOwner, + FireAlarmConstants.DEVICE_TYPE, + deviceId, resource, state); + } catch (DeviceControllerException e) { + String errorMsg = "Error whilst trying to publish to MQTT Queue"; + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + return result; + } + + + private String sendCommandViaHTTP(final String deviceIp, int deviceServerPort, + String callUrlPattern, + boolean fireAndForgot) + throws DeviceManagementException { + + if (deviceServerPort == 0) { + deviceServerPort = 80; + } + + String responseMsg = ""; + String urlString = URL_PREFIX + deviceIp + ":" + deviceServerPort + callUrlPattern; + + if (log.isDebugEnabled()) { + log.debug(urlString); + } + + if (!fireAndForgot) { + HttpURLConnection httpConnection = getHttpConnection(urlString); + + try { + httpConnection.setRequestMethod(HttpMethod.GET); + } catch (ProtocolException e) { + String errorMsg = + "Protocol specific error occurred when trying to set method to GET" + + " for:" + urlString; + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + + responseMsg = readResponseFromGetRequest(httpConnection); + + } else { + CloseableHttpAsyncClient httpclient = null; + try { + + httpclient = HttpAsyncClients.createDefault(); + httpclient.start(); + HttpGet request = new HttpGet(urlString); + final CountDownLatch latch = new CountDownLatch(1); + Future future = httpclient.execute( + request, new FutureCallback() { + @Override + public void completed(HttpResponse httpResponse) { + latch.countDown(); + } + + @Override + public void failed(Exception e) { + latch.countDown(); + } + + @Override + public void cancelled() { + latch.countDown(); + } + }); + + latch.await(); + + } catch (InterruptedException e) { + if (log.isDebugEnabled()) { + log.debug("Sync Interrupted"); + } + } finally { + try { + if (httpclient != null) { + httpclient.close(); + + } + } catch (IOException e) { + if (log.isDebugEnabled()) { + log.debug("Failed on close"); + } + } + } + + } + + return responseMsg; + } + + /* Utility methods relevant to creating and sending http requests */ + + /* This methods creates and returns a http connection object */ + + private HttpURLConnection getHttpConnection(String urlString) throws + DeviceManagementException { + + URL connectionUrl = null; + HttpURLConnection httpConnection = null; + + try { + connectionUrl = new URL(urlString); + httpConnection = (HttpURLConnection) connectionUrl.openConnection(); + } catch (MalformedURLException e) { + String errorMsg = + "Error occured whilst trying to form HTTP-URL from string: " + urlString; + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } catch (IOException e) { + String errorMsg = "Error occured whilst trying to open a connection to: " + + connectionUrl.toString(); + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + + return httpConnection; + } + + /* This methods reads and returns the response from the connection */ + + private String readResponseFromGetRequest(HttpURLConnection httpConnection) + throws DeviceManagementException { + BufferedReader bufferedReader = null; + try { + bufferedReader = new BufferedReader(new InputStreamReader( + httpConnection.getInputStream())); + } catch (IOException e) { + String errorMsg = + "There is an issue with connecting the reader to the input stream at: " + + httpConnection.getURL(); + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + + String responseLine; + StringBuffer completeResponse = new StringBuffer(); + + try { + while ((responseLine = bufferedReader.readLine()) != null) { + completeResponse.append(responseLine); + } + } catch (IOException e) { + String errorMsg = + "Error occured whilst trying read from the connection stream at: " + + httpConnection.getURL(); + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + try { + bufferedReader.close(); + } catch (IOException e) { + log.error( + "Could not succesfully close the bufferedReader to the connection at: " + + httpConnection.getURL()); + } + + return completeResponse.toString(); + } + +} diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmManagerService.java b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmManagerService.java new file mode 100644 index 00000000..fe7d0426 --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/FireAlarmManagerService.java @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +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.common.DeviceManagement; +import org.wso2.carbon.device.mgt.iot.common.apimgt.AccessTokenInfo; +import org.wso2.carbon.device.mgt.iot.common.apimgt.TokenClient; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppAccount; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppServerClient; +import org.wso2.carbon.device.mgt.iot.common.exception.AccessTokenException; +import org.wso2.carbon.device.mgt.iot.common.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; +import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; +import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants.FireAlarmConstants; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.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; + +//@Path("/FireAlarmDeviceManager") +public class FireAlarmManagerService { + + private static Log log = LogFactory.getLog(FireAlarmManagerService.class); + + @Path("/device/register") + @PUT + public boolean register(@QueryParam("deviceId") String deviceId, + @QueryParam("name") String name, @QueryParam("owner") String owner) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(FireAlarmConstants.DEVICE_TYPE); + try { + if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + Response.status(HttpStatus.SC_CONFLICT).build(); + 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(FireAlarmConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(owner); + device.setEnrolmentInfo(enrolmentInfo); + boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); + + if (added) { + Response.status(HttpStatus.SC_OK).build(); + } else { + Response.status(HttpStatus.SC_EXPECTATION_FAILED).build(); + } + + return added; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + } + + @Path("/device/remove/{device_id}") + @DELETE + public void removeDevice(@PathParam("device_id") String deviceId, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(FireAlarmConstants.DEVICE_TYPE); + try { + boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( + deviceIdentifier); + if (removed) { + response.setStatus(HttpStatus.SC_OK); + + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + + } + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + + } + + } + + @Path("/device/update/{device_id}") + @POST + public boolean updateDevice(@PathParam("device_id") String deviceId, + @QueryParam("name") String name, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(FireAlarmConstants.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(FireAlarmConstants.DEVICE_TYPE); + + boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment( + device); + + if (updated) { + response.setStatus(HttpStatus.SC_OK); + + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + + } + return updated; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + + } + + @Path("/device/{device_id}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device getDevice(@PathParam("device_id") String deviceId) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(FireAlarmConstants.DEVICE_TYPE); + + try { + return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); + + } catch (DeviceManagementException ex) { + log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex); + return null; + } + + } + + @Path("/devices/{username}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device[] getFirealarmDevices(@PathParam("username") String username) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + try { + List userDevices = + deviceManagement.getDeviceManagementService().getDevicesOfUser( + username); + ArrayList userDevicesforFirealarm = new ArrayList(); + for (Device device : userDevices) { + + if (device.getType().equals(FireAlarmConstants.DEVICE_TYPE) && + device.getEnrolmentInfo().getStatus().equals( + EnrolmentInfo.Status.ACTIVE)) { + userDevicesforFirealarm.add(device); + + } + } + + return userDevicesforFirealarm.toArray(new Device[]{}); + } catch (DeviceManagementException ex) { + log.error("Error occurred while retrieving devices for " + username); + return null; + } + + } + + @Path("/device/{sketch_type}/download") + @GET + @Produces("application/octet-stream") + public Response downloadSketch(@QueryParam("owner") String owner, + @PathParam("sketch_type") String sketchType) { + + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, 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("/device/{sketch_type}/generate_link") + @GET + public Response generateSketchLink(@QueryParam("owner") String owner, + @PathParam("sketch_type") String sketchType) { + + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, 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 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(FireAlarmConstants.DEVICE_TYPE); + AccessTokenInfo accessTokenInfo = null; + + accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); + + //create token + String accessToken = accessTokenInfo.getAccess_token(); + String refreshToken = accessTokenInfo.getRefresh_token(); + //adding registering data + + + + XmppAccount newXmppAccount = new XmppAccount(); + newXmppAccount.setAccountName(owner + "_" + deviceId); + newXmppAccount.setUsername(deviceId); + newXmppAccount.setPassword(accessToken); + + String xmppEndPoint = XmppConfig.getInstance().getXmppControlQueue().getServerURL(); + + int indexOfChar = xmppEndPoint.lastIndexOf('/'); + + if (indexOfChar != -1) { + xmppEndPoint = xmppEndPoint.substring((indexOfChar + 1), xmppEndPoint.length()); + } + + 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); + } + } + status = register(deviceId, owner + "s_" + sketchType + "_" + deviceId.substring(0, + 3), + owner); + if (!status) { + String msg = "Error occurred while registering the device with " + "id: " + deviceId + + " owner:" + owner; + throw new DeviceManagementException(msg); + } + + + ZipUtil ziputil = new ZipUtil(); + ZipArchive zipFile = null; + + zipFile = ziputil.downloadSketch(owner, sketchType, deviceId, accessToken, refreshToken); + zipFile.setDeviceId(deviceId); + return zipFile; + } + + private static String shortUUID() { + UUID uuid = UUID.randomUUID(); + long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong(); + return Long.toString(l, Character.MAX_RADIX); + } + +} diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/DeviceJSON.java b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/DeviceJSON.java new file mode 100644 index 00000000..2fe4cb31 --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/DeviceJSON.java @@ -0,0 +1,18 @@ +package org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.util; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement + +@JsonIgnoreProperties(ignoreUnknown = true) +public class DeviceJSON { + @XmlElement(required = true) public String owner; + @XmlElement(required = true) public String deviceId; + @XmlElement(required = true) public String reply; + @XmlElement public Long time; + @XmlElement public String key; + @XmlElement public String value; +} diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/MQTTFirealarmSubscriber.java b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/MQTTFirealarmSubscriber.java new file mode 100644 index 00000000..b941a95c --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/firealarm/service/impl/util/MQTTFirealarmSubscriber.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *//* + + +package org.wso2.carbon.device.mgt.iot.firealarm.api.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.mqtt.MqttSubscriber; +import org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService; +import org.wso2.carbon.device.mgt.iot.firealarm.constants.FireAlarmConstants; + +import java.io.File; +import java.util.LinkedList; + +public class MQTTFirealarmSubscriber extends MqttSubscriber { + + private static Log log = LogFactory.getLog(MQTTFirealarmSubscriber.class); + private static final String subscribetopic = + "wso2" + File.separator + "iot" + File.separator + "+" + File.separator + + FireAlarmConstants.DEVICE_TYPE + File.separator + "#"; + + private MQTTFirealarmSubscriber() { + super("Subscriber", FireAlarmConstants.DEVICE_TYPE, FireAlarmControllerService.CONTROL_QUEUE_ENDPOINT, + subscribetopic); + } + + @Override protected void postMessageArrived(final String topic, final MqttMessage message) { + + int lastIndex = topic.lastIndexOf("/"); + String deviceId = topic.substring(lastIndex + 1); + + lastIndex = message.toString().lastIndexOf(":"); + String msgContext = message.toString().substring(lastIndex + 1); + + LinkedList deviceControlList = null; + LinkedList replyMessageList = null; + + if (msgContext.equals("IN") || msgContext.equals(FireAlarmConstants.STATE_ON) || msgContext + .equals(FireAlarmConstants.STATE_OFF)) { + log.info("Recieved a control message: "); + log.info("Control message topic: " + topic); + log.info("Control message: " + message.toString()); + // synchronized (FireAlarmControllerService.internalControlsQueue) { + // deviceControlList = FireAlarmControllerService.internalControlsQueue.get(deviceId); + synchronized (FireAlarmControllerService.getInternalControlsQueue()) { + deviceControlList = FireAlarmControllerService.getInternalControlsQueue().get(deviceId); + if (deviceControlList == null) { + // FireAlarmControllerService.internalControlsQueue + FireAlarmControllerService.getInternalControlsQueue() + .put(deviceId, deviceControlList = new LinkedList()); + } + } + deviceControlList.add(message.toString()); + } else if (msgContext.equals("OUT")) { + log.info("Recieved reply from a device: "); + log.info("Reply message topic: " + topic); + log.info("Reply message: " + message.toString().substring(0, lastIndex)); + // synchronized (FireAlarmControllerService.replyMsgQueue) { + // replyMessageList = FireAlarmControllerService.replyMsgQueue.get(deviceId); + synchronized (FireAlarmControllerService.getReplyMsgQueue()) { + replyMessageList = FireAlarmControllerService.getReplyMsgQueue().get(deviceId); + if (replyMessageList == null) { + // FireAlarmControllerService.replyMsgQueue + FireAlarmControllerService.getReplyMsgQueue() + .put(deviceId, replyMessageList = new LinkedList()); + } + } + replyMessageList.add(message.toString()); + } + + } + +} +*/ diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/META-INF/webapp-classloading.xml b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 00000000..fa446191 --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,33 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 00000000..69cc179b --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml new file mode 100755 index 00000000..5cc402a9 --- /dev/null +++ b/modules/distribution/src/samples/firealarm/src/org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,23 @@ + + + WSO2 Device Cloud + WSO2 Device Cloud + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + + CXFServlet + /* + + + + diff --git a/modules/distribution/src/samples/raspberrypi/dbscripts/h2_raspberrypi.sql b/modules/distribution/src/samples/raspberrypi/dbscripts/h2_raspberrypi.sql new file mode 100644 index 00000000..aead055a --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/dbscripts/h2_raspberrypi.sql @@ -0,0 +1,11 @@ + +-- ----------------------------------------------------- +-- Table `RASPBERRYPI_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `RASPBERRYPI_DEVICE` ( + `RASPBERRYPI_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`RASPBERRYPI_DEVICE_ID`) ); + + + diff --git a/modules/distribution/src/samples/raspberrypi/dbscripts/mysql_raspberrypi.sql b/modules/distribution/src/samples/raspberrypi/dbscripts/mysql_raspberrypi.sql new file mode 100644 index 00000000..ad0ec54b --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/dbscripts/mysql_raspberrypi.sql @@ -0,0 +1,12 @@ +-- ----------------------------------------------------- +-- Table `RASPBERRYPI_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `RASPBERRYPI_DEVICE` ( + `RASPBERRYPI_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`RASPBERRYPI_DEVICE_ID`) ) +ENGINE = InnoDB; + + + + diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/pom.xml b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/pom.xml new file mode 100644 index 00000000..db36fd67 --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/pom.xml @@ -0,0 +1,140 @@ + + + + + + + devicecloud-mgt + org.wso2.carbon.device.mgt.iot + 1.0.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.iot.raspberrypi.impl + 1.0.0-SNAPSHOT + bundle + WSO2 Carbon - RaspberryPi Management Impl + WSO2 Carbon - Raspberrypi Management and Control Implementation + http://wso2.org + + + + + 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} + Device Cloud Impl Bundle + org.wso2.carbon.device.mgt.iot.raspberrypi.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.common.*, + + + + !org.wso2.carbon.device.mgt.iot.raspberrypi.internal, + org.wso2.carbon.device.mgt.iot.raspberrypi.* + + + + + + + + + + + + + + + + + + + + + + + + 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.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + + + + + + diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/constants/RaspberrypiConstants.java b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/constants/RaspberrypiConstants.java new file mode 100644 index 00000000..4945e611 --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/constants/RaspberrypiConstants.java @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.constants; + +public class RaspberrypiConstants { + + public final static String DEVICE_TYPE = "raspberrypi"; + public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; + public final static String DEVICE_PLUGIN_DEVICE_ID = "RASPBERRYPI_DEVICE_ID"; + +} diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/RaspberrypiManager.java b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/RaspberrypiManager.java new file mode 100644 index 00000000..540ec899 --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/RaspberrypiManager.java @@ -0,0 +1,264 @@ +/* + * 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.sample.raspberrypi.plugin.impl; + + +import org.apache.commons.logging.Log; +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.DeviceManager; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.util.IotDeviceManagementUtil; +import org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl.dao.RaspberrypiDAO; + +import java.util.ArrayList; +import java.util.List; + + +/** + * This represents the Raspberrypi implementation of DeviceManagerService. + */ +public class RaspberrypiManager implements DeviceManager { + + private static final IotDeviceManagementDAOFactory iotDeviceManagementDAOFactory = new RaspberrypiDAO(); + private static final Log log = LogFactory.getLog(RaspberrypiManager.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 Raspberrypi device : " + device.getDeviceIdentifier()); + } + RaspberrypiDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice( + iotDevice); + RaspberrypiDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + RaspberrypiDAO.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 Raspberrypi 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 Raspberrypi device enrollment data"); + } + RaspberrypiDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + RaspberrypiDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + RaspberrypiDAO.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 Raspberrypi 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 Raspberrypi device : " + deviceId); + } + RaspberrypiDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .deleteIotDevice(deviceId.getId()); + RaspberrypiDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + RaspberrypiDAO.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 Raspberrypi 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 Raspberrypi 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 Raspberrypi 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 Raspberrypi device : " + deviceId.getId()); + } + IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO(). + getIotDevice(deviceId.getId()); + device = IotDeviceManagementUtil.convertToDevice(iotDevice); + } catch (IotDeviceManagementDAOException e) { + String msg = "Error while fetching the Raspberrypi 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 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 Raspberrypi device : " + deviceIdentifier); + } + RaspberrypiDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + RaspberrypiDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + RaspberrypiDAO.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 Raspberrypi 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 Raspberrypi 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 Raspberrypi devices."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return devices; + } +} \ No newline at end of file diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/RaspberrypiManagerService.java b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/RaspberrypiManagerService.java new file mode 100644 index 00000000..0f0cddaa --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/RaspberrypiManagerService.java @@ -0,0 +1,63 @@ +package org.wso2.carbon.device.mgt.iot.sample.raspberrypi.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.sample.raspberrypi.plugin.constants.RaspberrypiConstants; + +import java.util.List; + +public class RaspberrypiManagerService implements DeviceManagementService { + + private DeviceManager deviceManager; + + @Override + public String getType() { + return RaspberrypiConstants.DEVICE_TYPE; + } + + @Override + public void init() throws DeviceManagementException { + deviceManager = new RaspberrypiManager(); + } + + @Override + public DeviceManager getDeviceManager() { + return deviceManager; + } + + @Override + public ApplicationManager getApplicationManager() { + return null; + } + + @Override + public Application[] getApplications(String domain, int pageNumber, int size) + throws ApplicationManagementException { + return new Application[0]; + } + + @Override + public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, + String status) throws ApplicationManagementException { + + } + + @Override + public String getApplicationStatus(DeviceIdentifier deviceId, Application application) + throws ApplicationManagementException { + return null; + } + + @Override + public void installApplication(Operation + operation, List deviceIdentifiers) + throws ApplicationManagementException { + + } +} diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/dao/RaspberrypiDAO.java b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/dao/RaspberrypiDAO.java new file mode 100644 index 00000000..9eeb1987 --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/dao/RaspberrypiDAO.java @@ -0,0 +1,123 @@ +/* + * 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.sample.raspberrypi.plugin.impl.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactoryInterface; +import org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.constants.RaspberrypiConstants; +import org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl.dao.impl.RaspberrypiDeviceDAOImpl; + + + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class RaspberrypiDAO extends IotDeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface { + + private static final Log log = LogFactory.getLog(RaspberrypiDAO.class); + static DataSource dataSource; + private static ThreadLocal currentConnection = new ThreadLocal(); + + public RaspberrypiDAO() { + initRaspberrypiDAO(); + } + + @Override public IotDeviceDAO getIotDeviceDAO() { + return new RaspberrypiDeviceDAOImpl(); + } + + public static void initRaspberrypiDAO() { + dataSource = getDataSourceMap().get(RaspberrypiConstants.DEVICE_TYPE); + } + + 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.get() == null) { + try { + currentConnection.set(dataSource.getConnection()); + } catch (SQLException e) { + throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e); + } + } + 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(); + } + } +} \ No newline at end of file diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/dao/impl/RaspberrypiDeviceDAOImpl.java b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/dao/impl/RaspberrypiDeviceDAOImpl.java new file mode 100644 index 00000000..a698e71a --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/dao/impl/RaspberrypiDeviceDAOImpl.java @@ -0,0 +1,238 @@ +/* + * 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.sample.raspberrypi.plugin.impl.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.util.IotDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.constants.RaspberrypiConstants; +import org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl.dao.RaspberrypiDAO; + +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; + +/** + * Implements IotDeviceDAO for Raspberrypi Devices. + */ +public class RaspberrypiDeviceDAOImpl implements IotDeviceDAO{ + + + private static final Log log = LogFactory.getLog(RaspberrypiDeviceDAOImpl.class); + + @Override + public IotDevice getIotDevice(String iotDeviceId) + throws IotDeviceManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + IotDevice iotDevice = null; + ResultSet resultSet = null; + try { + conn = RaspberrypiDAO.getConnection(); + String selectDBQuery = + "SELECT RASPBERRYPI_DEVICE_ID, DEVICE_NAME" + + " FROM RASPBERRYPI_DEVICE WHERE RASPBERRYPI_DEVICE_ID = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setString(1, iotDeviceId); + resultSet = stmt.executeQuery(); + + if (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceName(resultSet.getString( + RaspberrypiConstants.DEVICE_PLUGIN_DEVICE_NAME)); + Map propertyMap = new HashMap(); + + + + iotDevice.setDeviceProperties(propertyMap); + + if (log.isDebugEnabled()) { + log.debug("Raspberrypi device " + iotDeviceId + " data has been fetched from " + + "Raspberrypi database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while fetching Raspberrypi device : '" + iotDeviceId + "'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + RaspberrypiDAO.closeConnection(); + } + + return iotDevice; + } + + @Override + public boolean addIotDevice(IotDevice iotDevice) + throws IotDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = RaspberrypiDAO.getConnection(); + String createDBQuery = + "INSERT INTO RASPBERRYPI_DEVICE(RASPBERRYPI_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("Raspberrypi device " + iotDevice.getIotDeviceId() + " data has been" + + " added to the Raspberrypi database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while adding the Raspberrypi device '" + + iotDevice.getIotDeviceId() + "' to the Raspberrypi 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 = RaspberrypiDAO.getConnection(); + String updateDBQuery = + "UPDATE RASPBERRYPI_DEVICE SET DEVICE_NAME = ? WHERE RASPBERRYPI_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("Raspberrypi device " + iotDevice.getIotDeviceId() + " data has been" + + " modified."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while modifying the Raspberrypi 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 = RaspberrypiDAO.getConnection(); + String deleteDBQuery = + "DELETE FROM RASPBERRYPI_DEVICE WHERE RASPBERRYPI_DEVICE_ID = ?"; + stmt = conn.prepareStatement(deleteDBQuery); + stmt.setString(1, iotDeviceId); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Raspberrypi device " + iotDeviceId + " data has deleted" + + " from the Raspberrypi database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while deleting Raspberrypi 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 = RaspberrypiDAO.getConnection(); + String selectDBQuery = + "SELECT RASPBERRYPI_DEVICE_ID, DEVICE_NAME " + + "FROM RASPBERRYPI_DEVICE"; + stmt = conn.prepareStatement(selectDBQuery); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceId(resultSet.getString(RaspberrypiConstants.DEVICE_PLUGIN_DEVICE_ID)); + iotDevice.setIotDeviceName(resultSet.getString(RaspberrypiConstants.DEVICE_PLUGIN_DEVICE_NAME)); + + Map propertyMap = new HashMap(); + + iotDevice.setDeviceProperties(propertyMap); + iotDevices.add(iotDevice); + } + if (log.isDebugEnabled()) { + log.debug("All Raspberrypi device details have fetched from Raspberrypi database."); + } + return iotDevices; + } catch (SQLException e) { + String msg = "Error occurred while fetching all Raspberrypi device data'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + RaspberrypiDAO.closeConnection(); + } + + } + + } \ No newline at end of file diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/util/RaspberrypiUtils.java b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/util/RaspberrypiUtils.java new file mode 100644 index 00000000..c4142ed2 --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/impl/util/RaspberrypiUtils.java @@ -0,0 +1,45 @@ +/* + * 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.sample.raspberrypi.plugin.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Map; + +/** + * Contains utility methods used by Raspberrypi plugin. + */ +public class RaspberrypiUtils { + + private static Log log = LogFactory.getLog(RaspberrypiUtils.class); + + public static String getDeviceProperty(Map deviceProperties, String property) { + + String deviceProperty = deviceProperties.get(property); + + if (deviceProperty == null) { + return ""; + } + + return deviceProperty; + } + + +} diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/internal/RaspberrypiManagementServiceComponent.java b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/internal/RaspberrypiManagementServiceComponent.java new file mode 100644 index 00000000..02c07961 --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/plugin/internal/RaspberrypiManagementServiceComponent.java @@ -0,0 +1,104 @@ +/* + * 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.sample.raspberrypi.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.common.service.DeviceTypeService; +import org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.impl.RaspberrypiManagerService; + + +/** + * @scr.component name="org.wso2.carbon.device.mgt.iot.raspberrypi.internal.RaspberrypiManagementServiceComponent" + * immediate="true" + * @scr.reference name="wso2.carbon.device.mgt.iot.common.DeviceTypeService" + * interface="org.wso2.carbon.device.mgt.iot.common.service.DeviceTypeService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDeviceTypeService" + * unbind="unsetDeviceTypeService" + */ +public class RaspberrypiManagementServiceComponent { + + + private ServiceRegistration raspberrypiServiceRegRef; + + + private static final Log log = LogFactory.getLog(RaspberrypiManagementServiceComponent.class); + + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating Raspberrypi Device Management Service Component"); + } + try { + BundleContext bundleContext = ctx.getBundleContext(); + raspberrypiServiceRegRef = + bundleContext.registerService(DeviceManagementService.class.getName(), + new RaspberrypiManagerService(), null); + if (log.isDebugEnabled()) { + log.debug( + "Raspberrypi Device Management Service Component has been successfully " + + "activated"); + } + } catch (Throwable e) { + log.error( + "Error occurred while activating Raspberrypi Device Management Service " + + "Component", + e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating Raspberrypi Device Management Service Component"); + } + try { + if (raspberrypiServiceRegRef != null) { + raspberrypiServiceRegRef.unregister(); + } + + if (log.isDebugEnabled()) { + log.debug( + "Raspberrypi Device Management Service Component has been successfully " + + "de-activated"); + } + } catch (Throwable e) { + log.error("Error occurred while de-activating Raspberrypi 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/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/pom.xml b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/pom.xml new file mode 100644 index 00000000..c9e7024d --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/pom.xml @@ -0,0 +1,101 @@ + + + + devicecloud-api + org.wso2.carbon.device.mgt.iot + 1.0.0 + ../pom.xml + + 4.0.0 + + org.wso2.carbon.device.mgt.iot.raspberrypi.api + 1.0.0 + + war + WSO2 Carbon - Device Cloud API - Raspberrypi API + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + + + 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.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + provided + + + org.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.raspberrypi.impl + provided + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + + + + + + + maven-compiler-plugin + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + maven-war-plugin + + raspberrypi + + + + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/service/impl/RaspberrypiControllerService.java b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/service/impl/RaspberrypiControllerService.java new file mode 100644 index 00000000..7a3029ce --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/service/impl/RaspberrypiControllerService.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.datastore.impl.DataStreamDefinitions; +import org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl.util.DeviceJSON; +import org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.constants.RaspberrypiConstants; +import org.wso2.carbon.device.mgt.iot.common.DeviceController; + +import org.wso2.carbon.device.mgt.iot.common.exception.UnauthorizedException; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +public class RaspberrypiControllerService { + + private static Log log = LogFactory.getLog(RaspberrypiControllerService.class); + + /* Service to push all the sensor data collected by the Arduino + Called by the Arduino device */ + @Path("/pushdata") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { + + String temperature = dataMsg.value; //TEMP + log.info("Recieved Sensor Data Values: " + temperature); + + if (log.isDebugEnabled()) { + log.debug("Recieved Temperature Data Value: " + temperature + " degrees C"); + } + try { + + DeviceController deviceController = new DeviceController(); + boolean result = deviceController.pushBamData(dataMsg.owner, + RaspberrypiConstants.DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + temperature, + DataStreamDefinitions.StreamTypeLabel.TEMPERATURE); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + + } catch (UnauthorizedException e) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + + } + } +} diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/service/impl/RaspberrypiManagerService.java b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/service/impl/RaspberrypiManagerService.java new file mode 100644 index 00000000..68dbdef7 --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/service/impl/RaspberrypiManagerService.java @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +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.common.DeviceManagement; +import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; +import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; +import org.wso2.carbon.device.mgt.iot.sample.raspberrypi.plugin.constants.RaspberrypiConstants; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import java.util.UUID; + +public class RaspberrypiManagerService { + + private static Log log = LogFactory.getLog(RaspberrypiManagerService.class); + + @Path("/device/register") + @PUT + public boolean register(@QueryParam("deviceId") String deviceId, + @QueryParam("name") String name, @QueryParam("owner") String owner) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE); + try { + if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + Response.status(HttpStatus.SC_CONFLICT).build(); + 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(RaspberrypiConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(owner); + boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); + if (added) { + Response.status(HttpStatus.SC_OK).build(); + + + } else { + Response.status(HttpStatus.SC_EXPECTATION_FAILED).build(); + + + } + + return added; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + } + + @Path("/device/remove/{device_id}") + @DELETE + public void removeDevice(@PathParam("device_id") String deviceId, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE); + try { + boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(deviceIdentifier); + if (removed) { + response.setStatus(HttpStatus.SC_OK); + + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + + } + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + + } + + + } + + @Path("/device/update/{device_id}") + @POST + public boolean updateDevice(@PathParam("device_id") String deviceId, + @QueryParam("name") String name, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(RaspberrypiConstants.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(RaspberrypiConstants.DEVICE_TYPE); + + boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device); + + + if (updated) { + response.setStatus(HttpStatus.SC_OK); + + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + + } + return updated; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + + } + + @Path("/device/{device_id}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device getDevice(@PathParam("device_id") String deviceId) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE); + + try { + Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); + + return device; + } catch (DeviceManagementException ex) { + log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex); + return null; + } + + } + + @Path("/device/{sketch_type}/download") + @GET + @Produces("application/octet-stream") + public Response downloadSketch(@QueryParam("owner") String owner, @PathParam("sketch_type") String + sketchType) { + + if (owner == null) { + return Response.status(400).build();//bad request + } + + //create new device id + String deviceId = shortUUID(); + + //create token + String token = UUID.randomUUID().toString(); + String refreshToken = UUID.randomUUID().toString(); + //adding registering data + + boolean status = register(deviceId, + owner + "s_" + sketchType + "_" + deviceId.substring(0, 3), + owner); + if (!status) { + return Response.status(500).entity( + "Error occurred while registering the device with " + "id: " + deviceId + + " owner:" + owner).build(); + + } + + ZipUtil ziputil = new ZipUtil(); + ZipArchive zipFile = null; + try { + zipFile = ziputil.downloadSketch(owner, sketchType, deviceId, + token,refreshToken); + } catch (DeviceManagementException ex) { + return Response.status(500).entity("Error occurred while creating zip file").build(); + } + + Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); + rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); + return rb.build(); + } + + 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); + } + +} diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/service/impl/util/DeviceJSON.java b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/service/impl/util/DeviceJSON.java new file mode 100644 index 00000000..c44de244 --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/raspberrypi/service/impl/util/DeviceJSON.java @@ -0,0 +1,18 @@ +package org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl.util; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement + +@JsonIgnoreProperties(ignoreUnknown = true) +public class DeviceJSON { + @XmlElement(required = true) public String owner; + @XmlElement(required = true) public String deviceId; + @XmlElement(required = true) public String reply; + @XmlElement public Long time; + @XmlElement public String key; + @XmlElement public String value; +} diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/webapp/META-INF/webapp-classloading.xml b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 00000000..fa446191 --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,33 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 00000000..b529740b --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/webapp/WEB-INF/web.xml b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/webapp/WEB-INF/web.xml new file mode 100755 index 00000000..7dbfdaaa --- /dev/null +++ b/modules/distribution/src/samples/raspberrypi/src/org.wso2.carbon.device.mgt.iot.sample.raspberrypi.service.impl/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,23 @@ + + + DigitalDisplay + DigitalDisplay + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + + CXFServlet + /* + + + + diff --git a/modules/distribution/src/samples/sensebot/dbscripts/h2_sensebot.sql b/modules/distribution/src/samples/sensebot/dbscripts/h2_sensebot.sql new file mode 100644 index 00000000..11e28f77 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/dbscripts/h2_sensebot.sql @@ -0,0 +1,11 @@ + +-- ----------------------------------------------------- +-- Table `SENSEBOT_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `SENSEBOT_DEVICE` ( + `SENSEBOT_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`SENSEBOT_DEVICE_ID`) ); + + + diff --git a/modules/distribution/src/samples/sensebot/dbscripts/mysql_sensebot.sql b/modules/distribution/src/samples/sensebot/dbscripts/mysql_sensebot.sql new file mode 100644 index 00000000..a06eac87 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/dbscripts/mysql_sensebot.sql @@ -0,0 +1,12 @@ +-- ----------------------------------------------------- +-- Table `SENSEBOT_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `SENSEBOT_DEVICE` ( + `SENSEBOT_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`SENSEBOT_DEVICE_ID`) ) +ENGINE = InnoDB; + + + + diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/pom.xml b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/pom.xml new file mode 100644 index 00000000..9387190f --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/pom.xml @@ -0,0 +1,140 @@ + + + + + + + devicecloud-mgt + org.wso2.carbon.device.mgt.iot + 1.0.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.iot.sensebot.impl + 1.0.0-SNAPSHOT + bundle + WSO2 Carbon - Sensebot Management Impl + WSO2 Carbon - Sensebot Management and Control Implementation + http://wso2.org + + + + + 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} + Device Cloud Impl Bundle + org.wso2.carbon.device.mgt.iot.sensebot.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.common.*, + + + + !org.wso2.carbon.device.mgt.iot.sensebot.internal, + org.wso2.carbon.device.mgt.iot.sensebot.* + + + + + + + + + + + + + + + + + + + + + + + + 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.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + + + + + + diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/constants/SensebotConstants.java b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/constants/SensebotConstants.java new file mode 100644 index 00000000..c9b012e1 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/constants/SensebotConstants.java @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +package org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.constants; + +public class SensebotConstants { + + public final static String DEVICE_TYPE = "sensebot"; + public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; + public final static String DEVICE_PLUGIN_DEVICE_ID = "SENSEBOT_DEVICE_ID"; + +} diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/SensebotManager.java b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/SensebotManager.java new file mode 100644 index 00000000..8145c855 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/SensebotManager.java @@ -0,0 +1,262 @@ +/* + * 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.sample.sensebot.plugin.impl; + + +import org.apache.commons.logging.Log; +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.DeviceManager; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.util.IotDeviceManagementUtil; +import org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl.dao.SensebotDAO; + +import java.util.ArrayList; +import java.util.List; + + +/** + * This represents the Sensebot implementation of DeviceManagerService. + */ +public class SensebotManager implements DeviceManager { + + private static final IotDeviceManagementDAOFactory iotDeviceManagementDAOFactory = new SensebotDAO(); + private static final Log log = LogFactory.getLog(SensebotManager.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 Sensebot device : " + device.getDeviceIdentifier()); + } + SensebotDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice( + iotDevice); + SensebotDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + SensebotDAO.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 Sensebot 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 Sensebot device enrollment data"); + } + SensebotDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + SensebotDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + SensebotDAO.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 Sensebot 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 Sensebot device : " + deviceId); + } + SensebotDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .deleteIotDevice(deviceId.getId()); + SensebotDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + SensebotDAO.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 Sensebot 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 Sensebot 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 Sensebot 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 Sensebot device : " + deviceId.getId()); + } + IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO(). + getIotDevice(deviceId.getId()); + device = IotDeviceManagementUtil.convertToDevice(iotDevice); + } catch (IotDeviceManagementDAOException e) { + String msg = "Error while fetching the Sensebot 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 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 Sensebot device : " + deviceIdentifier); + } + SensebotDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + SensebotDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + SensebotDAO.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 Sensebot 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 Sensebot 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 Sensebot devices."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return devices; + } +} \ No newline at end of file diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/SensebotManagerService.java b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/SensebotManagerService.java new file mode 100644 index 00000000..323ecbf7 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/SensebotManagerService.java @@ -0,0 +1,60 @@ +package org.wso2.carbon.device.mgt.iot.sample.sensebot.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.sample.sensebot.plugin.constants.SensebotConstants; + +import java.util.List; + +public class SensebotManagerService implements DeviceManagementService { + private DeviceManager deviceManager; + @Override + public String getType() { + return SensebotConstants.DEVICE_TYPE; + } + + @Override + public void init() throws DeviceManagementException { + deviceManager=new SensebotManager(); + } + + @Override + public DeviceManager getDeviceManager() { + return deviceManager; + } + + @Override + public ApplicationManager getApplicationManager() { + return null; + } + + @Override + public Application[] getApplications(String domain, int pageNumber, int size) + throws ApplicationManagementException { + return new Application[0]; + } + + @Override + public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, + String status) throws ApplicationManagementException { + + } + + @Override + public String getApplicationStatus(DeviceIdentifier deviceId, Application application) + throws ApplicationManagementException { + return null; + } + + @Override + public void installApplication(Operation operation, List deviceIdentifiers) + throws ApplicationManagementException { + + } +} diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/dao/SensebotDAO.java b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/dao/SensebotDAO.java new file mode 100644 index 00000000..5413acaa --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/dao/SensebotDAO.java @@ -0,0 +1,122 @@ +/* + * 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.sample.sensebot.plugin.impl.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactoryInterface; + +import org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.constants.SensebotConstants; +import org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl.dao.impl.SensebotDeviceDAOImpl; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class SensebotDAO extends IotDeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface { + + private static final Log log = LogFactory.getLog(SensebotDAO.class); + static DataSource dataSource; + private static ThreadLocal currentConnection = new ThreadLocal(); + + public SensebotDAO() { + initSensebotDAO(); + } + + @Override public IotDeviceDAO getIotDeviceDAO() { + return new SensebotDeviceDAOImpl(); + } + + public static void initSensebotDAO() { + dataSource = getDataSourceMap().get(SensebotConstants.DEVICE_TYPE); + } + + 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.get() == null) { + try { + currentConnection.set(dataSource.getConnection()); + } catch (SQLException e) { + throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e); + } + } + 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(); + } + } +} \ No newline at end of file diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/dao/impl/SensebotDeviceDAOImpl.java b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/dao/impl/SensebotDeviceDAOImpl.java new file mode 100644 index 00000000..61ca6f21 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/dao/impl/SensebotDeviceDAOImpl.java @@ -0,0 +1,238 @@ +/* + * 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.sample.sensebot.plugin.impl.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.util.IotDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.constants.SensebotConstants; +import org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl.dao.SensebotDAO; + +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; + +/** + * Implements IotDeviceDAO for sensebot Devices. + */ +public class SensebotDeviceDAOImpl implements IotDeviceDAO{ + + + private static final Log log = LogFactory.getLog(SensebotDeviceDAOImpl.class); + + @Override + public IotDevice getIotDevice(String iotDeviceId) + throws IotDeviceManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + IotDevice iotDevice = null; + ResultSet resultSet = null; + try { + conn = SensebotDAO.getConnection(); + String selectDBQuery = + "SELECT SENSEBOT_DEVICE_ID, DEVICE_NAME" + + " FROM SENSEBOT_DEVICE WHERE SENSEBOT_DEVICE_ID = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setString(1, iotDeviceId); + resultSet = stmt.executeQuery(); + + if (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceName(resultSet.getString( + SensebotConstants.DEVICE_PLUGIN_DEVICE_NAME)); + Map propertyMap = new HashMap(); + + + + iotDevice.setDeviceProperties(propertyMap); + + if (log.isDebugEnabled()) { + log.debug("Sensebot device " + iotDeviceId + " data has been fetched from " + + "Sensebot database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while fetching Sensebot device : '" + iotDeviceId + "'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + SensebotDAO.closeConnection(); + } + + return iotDevice; + } + + @Override + public boolean addIotDevice(IotDevice iotDevice) + throws IotDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = SensebotDAO.getConnection(); + String createDBQuery = + "INSERT INTO SENSEBOT_DEVICE(SENSEBOT_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("Sensebot device " + iotDevice.getIotDeviceId() + " data has been" + + " added to the Sensebot database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while adding the Sensebot device '" + + iotDevice.getIotDeviceId() + "' to the Sensebot 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 = SensebotDAO.getConnection(); + String updateDBQuery = + "UPDATE SENSEBOT_DEVICE SET DEVICE_NAME = ? WHERE SENSEBOT_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("Sensebot device " + iotDevice.getIotDeviceId() + " data has been" + + " modified."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while modifying the Sensebot 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 = SensebotDAO.getConnection(); + String deleteDBQuery = + "DELETE FROM SENSEBOT_DEVICE WHERE SENSEBOT_DEVICE_ID = ?"; + stmt = conn.prepareStatement(deleteDBQuery); + stmt.setString(1, iotDeviceId); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Sensebot device " + iotDeviceId + " data has deleted" + + " from the Sensebot database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while deleting Sensebot 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 = SensebotDAO.getConnection(); + String selectDBQuery = + "SELECT SENSEBOT_DEVICE_ID, DEVICE_NAME " + + "FROM SENSEBOT_DEVICE"; + stmt = conn.prepareStatement(selectDBQuery); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceId(resultSet.getString(SensebotConstants.DEVICE_PLUGIN_DEVICE_ID)); + iotDevice.setIotDeviceName(resultSet.getString(SensebotConstants.DEVICE_PLUGIN_DEVICE_NAME)); + + Map propertyMap = new HashMap(); + + iotDevice.setDeviceProperties(propertyMap); + iotDevices.add(iotDevice); + } + if (log.isDebugEnabled()) { + log.debug("All Sensebot device details have fetched from Sensebot database."); + } + return iotDevices; + } catch (SQLException e) { + String msg = "Error occurred while fetching all Sensebot device data'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + SensebotDAO.closeConnection(); + } + + } + + } \ No newline at end of file diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/util/SensebotUtils.java b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/util/SensebotUtils.java new file mode 100644 index 00000000..7a445a26 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/impl/util/SensebotUtils.java @@ -0,0 +1,45 @@ +/* + * 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.sample.sensebot.plugin.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Map; + +/** + * Contains utility methods used by Sensebot plugin. + */ +public class SensebotUtils { + + private static Log log = LogFactory.getLog(SensebotUtils.class); + + public static String getDeviceProperty(Map deviceProperties, String property) { + + String deviceProperty = deviceProperties.get(property); + + if (deviceProperty == null) { + return ""; + } + + return deviceProperty; + } + + +} diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/internal/SensebotManagementServiceComponent.java b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/internal/SensebotManagementServiceComponent.java new file mode 100644 index 00000000..c8c03b56 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/plugin/internal/SensebotManagementServiceComponent.java @@ -0,0 +1,101 @@ +/* + * 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.sample.sensebot.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.common.service.DeviceTypeService; +import org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.impl.SensebotManagerService; + + +/** + * @scr.component name="org.wso2.carbon.device.mgt.iot.sensebot.internal.SensebotManagementServiceComponent" + * immediate="true" + * @scr.reference name="wso2.carbon.device.mgt.iot.common.DeviceTypeService" + * interface="org.wso2.carbon.device.mgt.iot.common.service.DeviceTypeService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDeviceTypeService" + * unbind="unsetDeviceTypeService" + */ +public class SensebotManagementServiceComponent { + + private ServiceRegistration sensebotServiceRegRef; + + private static final Log log = LogFactory.getLog(SensebotManagementServiceComponent.class); + + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating Sensebot Device Management Service Component"); + } + try { + BundleContext bundleContext = ctx.getBundleContext(); + + sensebotServiceRegRef = bundleContext + .registerService(DeviceManagementService.class.getName(), + new SensebotManagerService(), null); + + if (log.isDebugEnabled()) { + log.debug( + "Sensebot Device Management Service Component has been successfully " + + "activated"); + } + } catch (Throwable e) { + log.error( + "Error occurred while activating Sensebot Device Management Service Component", + e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating Sensebot Device Management Service Component"); + } + try { + if (sensebotServiceRegRef != null) { + sensebotServiceRegRef.unregister(); + } + + if (log.isDebugEnabled()) { + log.debug( + "Sensebot Device Management Service Component has been successfully " + + "de-activated"); + } + } catch (Throwable e) { + log.error("Error occurred while de-activating Sensebot 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/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/pom.xml b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/pom.xml new file mode 100644 index 00000000..87449a37 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/pom.xml @@ -0,0 +1,114 @@ + + + + devicecloud-api + org.wso2.carbon.device.mgt.iot + 1.0.0 + ../pom.xml + + 4.0.0 + + + org.wso2.carbon.device.mgt.iot.sensebot.api + 1.0.0 + + war + WSO2 Carbon - Device Cloud API - Sensebot API + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + + + + org.apache.httpcomponents + httpasyncclient + 4.1 + + + org.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + provided + + + org.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.sensebot.impl + provided + + + + 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.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + + + + Eclipse Paho Repo + http://repo.spring.io/plugins-release/ + + + + + + + maven-compiler-plugin + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + maven-war-plugin + + sensebot + + + + + + \ No newline at end of file diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/log4j.properties b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/log4j.properties new file mode 100755 index 00000000..c271582f --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/log4j.properties @@ -0,0 +1,8 @@ +# Root logger option +log4j.rootLogger=INFO, stdout + +# Direct log messages to stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%-5p %d{yyyy-MM-dd HH:mm:ss} %c{1}:%L - %m%n \ No newline at end of file diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/service/impl/SensebotControllerService.java b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/service/impl/SensebotControllerService.java new file mode 100644 index 00000000..30d90b7b --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/service/impl/SensebotControllerService.java @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClients; +import org.wso2.carbon.device.mgt.iot.common.DeviceController; +import org.wso2.carbon.device.mgt.iot.common.datastore.impl.DataStreamDefinitions; +import org.wso2.carbon.device.mgt.iot.common.exception.UnauthorizedException; +import org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl.util.DeviceJSON; +import org.wso2.carbon.device.mgt.iot.sample.sensebot.plugin.constants.SensebotConstants; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Future; + +public class SensebotControllerService { + + private static Log log = LogFactory.getLog(SensebotControllerService.class); + + private static final Map deviceIPList = new HashMap<>(); + + private static final String URL_PREFIX = "http://"; + private static final String FORWARD_URL = "/move/F"; + private static final String BACKWARD_URL = "/move/B"; + private static final String LEFT_URL = "/move/L"; + private static final String RIGHT_URL = "/move/R"; + private static final String STOP_URL = "/move/S"; + private static CloseableHttpAsyncClient httpclient; + + static { + httpclient = HttpAsyncClients.createDefault(); + httpclient.start(); + } + + @Path("/forward") + @POST + public void moveForward(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @FormParam("ip") String deviceIp, + @FormParam("port") int deviceServerPort) { + + sendCommand(deviceIp, deviceServerPort, FORWARD_URL); + } + + @Path("/backward") + @POST + public void moveBackward(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @FormParam("ip") String deviceIp, + @FormParam("port") int deviceServerPort) { + + sendCommand(deviceIp, deviceServerPort, BACKWARD_URL); + } + + @Path("/left") + @POST + public void turnLeft(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, @FormParam("ip") String + deviceIp, + @FormParam("port") int deviceServerPort) { + + sendCommand(deviceIp, deviceServerPort, LEFT_URL); + } + + @Path("/right") + @POST + public void turnRight(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @FormParam("ip") String deviceIp, + @FormParam("port") int deviceServerPort) { + + sendCommand(deviceIp, deviceServerPort, RIGHT_URL); + } + + @Path("/stop") + @POST + public void stop(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, + @FormParam("ip") String deviceIp, @FormParam("port") int deviceServerPort) { + + sendCommand(deviceIp, deviceServerPort, STOP_URL); + } + + @Path("/pushsensordata") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushSensorData( + final DeviceJSON dataMsg, @Context HttpServletResponse response) { + boolean result = false; + + String sensorValues = dataMsg.value; //TEMP-PIR-SONAR-LDR + log.info("Recieved Sensor Data Values: " + sensorValues); + + String sensors[] = sensorValues.split(":"); + try { + if (sensors.length == 4) { + String temperature = sensors[0]; + String motion = sensors[1]; + String sonar = sensors[2]; + String light = sensors[3]; + + if (sonar.equals("-1")) { + sonar = "No Object"; + } + + sensorValues = "Temperature:" + temperature + "C\t\tMotion:" + motion + + "\tSonar:" + + sonar + "\tLight:" + + light; + + if (log.isDebugEnabled()) { + log.debug(sensorValues); + } + DeviceController deviceController = new DeviceController(); + result = deviceController.pushBamData(dataMsg.owner, SensebotConstants.DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + temperature, + DataStreamDefinitions.StreamTypeLabel.TEMPERATURE); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + return; + } + + result = deviceController.pushBamData(dataMsg.owner, SensebotConstants.DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + motion, + DataStreamDefinitions.StreamTypeLabel.MOTION); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + return; + } + + if (!sonar.equals("No Object")) { + result = deviceController.pushBamData(dataMsg.owner, + SensebotConstants.DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + sonar, + DataStreamDefinitions.StreamTypeLabel.SONAR); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + return; + } + + } + + result = deviceController.pushBamData(dataMsg.owner, SensebotConstants.DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + light, + DataStreamDefinitions.StreamTypeLabel.LIGHT); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + + } else { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + + } catch (UnauthorizedException e) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + } + + } + + @Path("/pushtempdata") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushTempData( + final DeviceJSON dataMsg, @Context HttpServletResponse response) { + + String temperature = dataMsg.value; //TEMP + log.info("Recieved Sensor Data Values: " + temperature); + + if (log.isDebugEnabled()) { + log.debug("Recieved Temperature Data Value: " + temperature + " degrees C"); + } + try { + DeviceController deviceController = new DeviceController(); + boolean result = deviceController.pushBamData(dataMsg.owner, + SensebotConstants.DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + temperature, + DataStreamDefinitions.StreamTypeLabel.TEMPERATURE); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + + } catch (UnauthorizedException e) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + + } + } + + @Path("/pushpirdata") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushPIRData(final DeviceJSON dataMsg, + @Context HttpServletResponse response) { + + String motion = dataMsg.value; //PIR + log.info("Recieved Sensor Data Values: " + motion); + + if (log.isDebugEnabled()) { + log.debug("Recieved PIR (Motion) Sensor Data Value: " + motion); + } + try { + DeviceController deviceController = new DeviceController(); + boolean result = deviceController.pushBamData(dataMsg.owner, + SensebotConstants.DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + motion, + DataStreamDefinitions.StreamTypeLabel.MOTION); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + + } catch (UnauthorizedException e) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + + } + + } + + @Path("/pushsonardata") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushSonarData( + final DeviceJSON dataMsg, @Context HttpServletResponse response) { + + String sonar = dataMsg.value; //SONAR + log.info("Recieved Sensor Data Values: " + sonar); + + if (sonar.equals("-1")) { + if (log.isDebugEnabled()) { + log.debug("Recieved a 'No Obstacle' Sonar value. (Means there are no abstacles " + + "within 30cm)"); + } + } else { + if (log.isDebugEnabled()) { + log.debug("Recieved Sonar Sensor Data Value: " + sonar + " cm"); + } + try { + + DeviceController deviceController = new DeviceController(); + boolean result = deviceController.pushBamData(dataMsg.owner, + SensebotConstants.DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), + "DeviceData", sonar, + DataStreamDefinitions.StreamTypeLabel.SONAR); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + + } catch (UnauthorizedException e) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + + } + + } + + } + + @Path("/pushlightdata") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushlightData( + final DeviceJSON dataMsg, @Context HttpServletResponse response) { + + String light = dataMsg.value; //LDR + log.info("Recieved Sensor Data Values: " + light); + + if (log.isDebugEnabled()) { + log.debug("Recieved LDR (Light) Sensor Data Value: " + light); + } + + try { + DeviceController deviceController = new DeviceController(); + boolean result = deviceController.pushBamData(dataMsg.owner, + SensebotConstants.DEVICE_TYPE, + dataMsg.deviceId, + System.currentTimeMillis(), "DeviceData", + light, + DataStreamDefinitions.StreamTypeLabel.LIGHT); + + if (!result) { + response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + + } catch (UnauthorizedException e) { + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + + } + + } + + private void sendCommand(String deviceIp, int deviceServerPort, String motionType) { + + if (deviceServerPort == 0) { + deviceServerPort = 80; + } + + String urlString = URL_PREFIX + deviceIp + ":" + deviceServerPort + motionType; + if (log.isDebugEnabled()) { + log.debug(urlString); + } + HttpGet request = new HttpGet(urlString); + Future future = httpclient.execute(request, null); + } + +} diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/service/impl/SensebotManagerService.java b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/service/impl/SensebotManagerService.java new file mode 100644 index 00000000..7c465c29 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/service/impl/SensebotManagerService.java @@ -0,0 +1,225 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +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.sample.sensebot.plugin.constants.SensebotConstants; +import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; +import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; +import org.wso2.carbon.device.mgt.iot.common.DeviceManagement; + +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.Date; +import java.util.UUID; + +public class SensebotManagerService { + + private static Log log = LogFactory.getLog(SensebotManagerService.class); + + @Path("/device/register") + @PUT + public boolean register(@QueryParam("deviceId") String deviceId, + @QueryParam("name") String name, @QueryParam("owner") String owner) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(SensebotConstants.DEVICE_TYPE); + try { + if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + Response.status(HttpStatus.SC_CONFLICT).build(); + return false; + } + + Device device = new Device(); + device.setDeviceIdentifier(deviceId); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setDateOfEnrolment(new Date().getTime()); + enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + + device.setName(name); + device.setType(SensebotConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(owner); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + device.setEnrolmentInfo(enrolmentInfo); + boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); + if (added) { + Response.status(HttpStatus.SC_OK).build(); + + + } else { + Response.status(HttpStatus.SC_EXPECTATION_FAILED).build(); + + + } + + return added; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + } + + @Path("/device/remove/{device_id}") + @DELETE + public void removeDevice(@PathParam("device_id") String deviceId, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(SensebotConstants.DEVICE_TYPE); + try { + boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(deviceIdentifier); + if (removed) { + response.setStatus(HttpStatus.SC_OK); + + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + + } + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + + } + + + } + + @Path("/device/update/{device_id}") + @POST + public boolean updateDevice(@PathParam("device_id") String deviceId, + @QueryParam("name") String name, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(SensebotConstants.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(SensebotConstants.DEVICE_TYPE); + + boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device); + + + if (updated) { + response.setStatus(HttpStatus.SC_OK); + + } else { + response.setStatus(HttpStatus.SC_EXPECTATION_FAILED); + + } + return updated; + } catch (DeviceManagementException e) { + log.error(e.getErrorMessage()); + return false; + } + + } + + @Path("/device/{device_id}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device getDevice(@PathParam("device_id") String deviceId) { + + DeviceManagement deviceManagement = new DeviceManagement(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(SensebotConstants.DEVICE_TYPE); + + try { + Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); + + return device; + } catch (DeviceManagementException ex) { + log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex); + return null; + } + + } + + @Path("/device/{sketch_type}/download") + @GET + @Produces("application/octet-stream") + public Response downloadSketch(@QueryParam("owner") String owner, @PathParam("sketch_type") String + sketchType) { + + if (owner == null) { + return Response.status(400).build();//bad request + } + + //create new device id + String deviceId = shortUUID(); + + //create token + String token = UUID.randomUUID().toString(); + String refreshToken = UUID.randomUUID().toString(); + //adding registering data + + boolean status = register(deviceId, + owner + "s_" + sketchType + "_" + deviceId.substring(0, 3), + owner); + if (!status) { + return Response.status(500).entity( + "Error occurred while registering the device with " + "id: " + deviceId + + " owner:" + owner).build(); + + } + + ZipUtil ziputil = new ZipUtil(); + ZipArchive zipFile = null; + try { + zipFile = ziputil.downloadSketch(owner, sketchType, deviceId, + token,refreshToken); + } catch (DeviceManagementException ex) { + return Response.status(500).entity("Error occurred while creating zip file").build(); + } + + Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); + rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); + return rb.build(); + } + + 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); + } + +} diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/service/impl/util/DeviceJSON.java b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/service/impl/util/DeviceJSON.java new file mode 100644 index 00000000..17d71d50 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/sensebot/service/impl/util/DeviceJSON.java @@ -0,0 +1,18 @@ +package org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl.util; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement + +@JsonIgnoreProperties(ignoreUnknown = true) +public class DeviceJSON { + @XmlElement(required = true) public String owner; + @XmlElement(required = true) public String deviceId; + @XmlElement(required = true) public String reply; + @XmlElement public Long time; + @XmlElement public String key; + @XmlElement public String value; +} diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/webapp/META-INF/webapp-classloading.xml b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 00000000..fa446191 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,33 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 00000000..cabb4472 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/webapp/WEB-INF/web.xml b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/webapp/WEB-INF/web.xml new file mode 100755 index 00000000..5cc402a9 --- /dev/null +++ b/modules/distribution/src/samples/sensebot/src/org.wso2.carbon.device.mgt.iot.sample.sensebot.service.impl/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,23 @@ + + + WSO2 Device Cloud + WSO2 Device Cloud + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + + CXFServlet + /* + + + + diff --git a/pom.xml b/pom.xml index 85abfeb9..22e2cdf1 100644 --- a/pom.xml +++ b/pom.xml @@ -364,38 +364,6 @@ - - - org.wso2.carbon.iot - org.wso2.carbon.device.mgt.iot.firealarm.impl - ${carbon.iot.device.mgt.version} - - - org.wso2.carbon.iot - org.wso2.carbon.device.mgt.iot.arduino.impl - ${carbon.iot.device.mgt.version} - - - org.wso2.carbon.iot - org.wso2.carbon.device.mgt.iot.android.sense.impl - ${carbon.iot.device.mgt.version} - - - org.wso2.carbon.iot - org.wso2.carbon.device.mgt.iot.digitaldisplay.impl - ${carbon.iot.device.mgt.version} - - - org.wso2.carbon.iot - org.wso2.carbon.device.mgt.iot.sensebot.impl - ${carbon.iot.device.mgt.version} - - - org.wso2.carbon.iot - org.wso2.carbon.device.mgt.iot.raspberrypi.impl - ${carbon.iot.device.mgt.version} - - org.eclipse.osgi