From 2cf022ef550996a3e2a73cfb81c097aab571d38e Mon Sep 17 00:00:00 2001 From: Shabirmean Date: Wed, 23 Dec 2015 15:08:27 +0530 Subject: [PATCH 1/6] Deleting all active xmpp-sessions during server shutdown --- .../api/DigitalDisplayControllerService.java | 4 +- .../api/transport/CommunicationHandler.java | 15 - .../CommunicationHandlerException.java | 38 -- .../transport/MQTTCommunicationHandler.java | 345 ------------ ...igitalDisplayMqttCommunicationHandler.java | 85 +-- .../controlqueue/xmpp/XmppServerClient.java | 502 +++++++++++------- .../IotDeviceManagementServiceComponent.java | 216 ++++---- 7 files changed, 497 insertions(+), 708 deletions(-) delete mode 100644 components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/CommunicationHandler.java delete mode 100644 components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/CommunicationHandlerException.java delete mode 100644 components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/MQTTCommunicationHandler.java diff --git a/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/DigitalDisplayControllerService.java b/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/DigitalDisplayControllerService.java index 120a89b0a7..c5b8995835 100644 --- a/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/DigitalDisplayControllerService.java +++ b/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/DigitalDisplayControllerService.java @@ -26,7 +26,7 @@ import org.wso2.carbon.apimgt.annotations.device.feature.Feature; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; import org.wso2.carbon.device.mgt.iot.digitaldisplay.api.exception.DigitalDisplayException; -import org.wso2.carbon.device.mgt.iot.digitaldisplay.api.transport.CommunicationHandlerException; +import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.digitaldisplay.api.util.DigitalDisplayMqttCommunicationHandler; import org.wso2.carbon.device.mgt.iot.digitaldisplay.constants.DigitalDisplayConstants; @@ -466,7 +466,7 @@ public class DigitalDisplayControllerService { try { digitalDisplayMqttCommunicationHandler.publishToDigitalDisplay(topic, payload, 2, true); - } catch (CommunicationHandlerException e) { + } catch (TransportHandlerException e) { String errorMessage = "Error publishing data to device with ID " + deviceId; throw new DigitalDisplayException(errorMessage, e); } diff --git a/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/CommunicationHandler.java b/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/CommunicationHandler.java deleted file mode 100644 index 9c165fef62..0000000000 --- a/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/CommunicationHandler.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.wso2.carbon.device.mgt.iot.digitaldisplay.api.transport; - -public interface CommunicationHandler { - int DEFAULT_TIMEOUT_INTERVAL = 5000; // millis ~ 10 sec - - void connect(); - - boolean isConnected(); - - void processIncomingMessage(T message, String... messageParams); - - void processIncomingMessage(); - - void disconnect(); -} diff --git a/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/CommunicationHandlerException.java b/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/CommunicationHandlerException.java deleted file mode 100644 index 447ae6f1b1..0000000000 --- a/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/CommunicationHandlerException.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.wso2.carbon.device.mgt.iot.digitaldisplay.api.transport; - -public class CommunicationHandlerException extends Exception { - private static final long serialVersionUID = 2736466230451105440L; - - private String errorMessage; - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public CommunicationHandlerException(String msg, Exception nestedEx) { - super(msg, nestedEx); - setErrorMessage(msg); - } - - public CommunicationHandlerException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - public CommunicationHandlerException(String msg) { - super(msg); - setErrorMessage(msg); - } - - public CommunicationHandlerException() { - super(); - } - - public CommunicationHandlerException(Throwable cause) { - super(cause); - } -} diff --git a/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/MQTTCommunicationHandler.java b/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/MQTTCommunicationHandler.java deleted file mode 100644 index c441f892c5..0000000000 --- a/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/transport/MQTTCommunicationHandler.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.iot.digitaldisplay.api.transport; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eclipse.paho.client.mqttv3.*; - -import java.io.File; -import java.nio.charset.StandardCharsets; - -/** - * This class contains the IoT-Server specific implementation for all the MQTT functionality. - * This includes connecting to a MQTT Broker & subscribing to the appropriate MQTT-topic, action - * plan upon losing connection or successfully delivering a message to the broker and processing - * incoming messages. Makes use of the 'Paho-MQTT' library provided by Eclipse Org. - *

- * It is an abstract class that implements the common interface "CommunicationHandler" and the - * "MqttCallback". Whilst providing some methods which handle key MQTT relevant tasks, this class - * implements only the most generic methods of the "CommunicationHandler" interface. The rest of - * the methods are left for any extended concrete-class to implement as per its need. - */ -public abstract class MQTTCommunicationHandler - implements MqttCallback, CommunicationHandler { - private static final Log log = LogFactory.getLog(MQTTCommunicationHandler.class); - - public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; - - private MqttClient client; - private String clientId; - private MqttConnectOptions options; - private String clientWillTopic; - - protected String mqttBrokerEndPoint; - protected int timeoutInterval; - protected String subscribeTopic; - - /** - * Constructor for the MQTTCommunicationHandler which takes in the owner, type of the device - * and the MQTT Broker URL and the topic to subscribe. - * - * @param deviceOwner the owner of the device. - * @param deviceType the CDMF Device-Type of the device. - * @param mqttBrokerEndPoint the IP/URL of the MQTT broker endpoint. - * @param subscribeTopic the MQTT topic to which the client is to be subscribed - */ - protected MQTTCommunicationHandler(String deviceOwner, String deviceType, - String mqttBrokerEndPoint, - String subscribeTopic) { - this.clientId = deviceOwner + ":" + deviceType; - this.subscribeTopic = subscribeTopic; - this.clientWillTopic = deviceType + File.separator + "disconnection"; - this.mqttBrokerEndPoint = mqttBrokerEndPoint; - this.timeoutInterval = DEFAULT_TIMEOUT_INTERVAL; - this.initSubscriber(); - } - - /** - * Constructor for the MQTTCommunicationHandler which takes in the owner, type of the device - * and the MQTT Broker URL and the topic to subscribe. Additionally this constructor takes in - * the reconnection-time interval between successive attempts to connect to the broker. - * - * @param deviceOwner the owner of the device. - * @param deviceType the CDMF Device-Type of the device. - * @param mqttBrokerEndPoint the IP/URL of the MQTT broker endpoint. - * @param subscribeTopic the MQTT topic to which the client is to be subscribed - * @param intervalInMillis the time interval in MILLI-SECONDS between successive - * attempts to connect to the broker. - */ - protected MQTTCommunicationHandler(String deviceOwner, String deviceType, - String mqttBrokerEndPoint, String subscribeTopic, - int intervalInMillis) { - this.clientId = deviceOwner + ":" + deviceType; - this.subscribeTopic = subscribeTopic; - this.clientWillTopic = deviceType + File.separator + "disconnection"; - this.mqttBrokerEndPoint = mqttBrokerEndPoint; - this.timeoutInterval = intervalInMillis; - this.initSubscriber(); - } - - public void setTimeoutInterval(int timeoutInterval) { - this.timeoutInterval = timeoutInterval; - } - - /** - * Initializes the MQTT-Client. Creates a client using the given MQTT-broker endpoint and the - * clientId (which is constructed by a concatenation of [deviceOwner]:[deviceType]). Also sets - * the client's options parameter with the clientWillTopic (in-case of connection failure) and - * other info. Also sets the call-back this current class. - */ - private void initSubscriber() { - try { - - client = new MqttClient(this.mqttBrokerEndPoint, clientId, null); - log.info("MQTT subscriber was created with ClientID : " + clientId); - } catch (MqttException ex) { - String errorMsg = "MQTT Client Error\n" + "\tReason: " + ex.getReasonCode() + - "\n\tMessage: " + ex.getMessage() + "\n\tLocalMsg: " + - ex.getLocalizedMessage() + "\n\tCause: " + ex.getCause() + - "\n\tException: " + ex; - log.error(errorMsg); - } - - options = new MqttConnectOptions(); - options.setCleanSession(false); - options.setWill(clientWillTopic, "Connection-Lost".getBytes(StandardCharsets.UTF_8), 2, - true); - client.setCallback(this); - } - - /** - * Checks whether the connection to the MQTT-Broker persists. - * - * @return true if the client is connected to the MQTT-Broker, else false. - */ - @Override - public boolean isConnected() { - return client.isConnected(); - } - - - /** - * Connects to the MQTT-Broker and if successfully established connection. - * - * @throws CommunicationHandlerException in the event of 'Connecting to' the MQTT broker fails. - */ - protected void connectToQueue() throws CommunicationHandlerException { - try { - client.connect(options); - - if (log.isDebugEnabled()) { - log.debug("Subscriber connected to queue at: " + this.mqttBrokerEndPoint); - } - } catch (MqttSecurityException ex) { - String errorMsg = "MQTT Security Exception when connecting to queue\n" + "\tReason: " + - " " + - ex.getReasonCode() + "\n\tMessage: " + ex.getMessage() + - "\n\tLocalMsg: " + ex.getLocalizedMessage() + "\n\tCause: " + - ex.getCause() + "\n\tException: " + ex; - if (log.isDebugEnabled()) { - log.debug(errorMsg); - } - throw new CommunicationHandlerException(errorMsg, ex); - - } catch (MqttException ex) { - String errorMsg = "MQTT Exception when connecting to queue\n" + "\tReason: " + - ex.getReasonCode() + "\n\tMessage: " + ex.getMessage() + - "\n\tLocalMsg: " + ex.getLocalizedMessage() + "\n\tCause: " + - ex.getCause() + "\n\tException: " + ex; - if (log.isDebugEnabled()) { - log.debug(errorMsg); - } - throw new CommunicationHandlerException(errorMsg, ex); - } - } - - /** - * Subscribes to the MQTT-Topic specific to this MQTT Client. (The MQTT-Topic specific to the - * device is taken in as a constructor parameter of this class) . - * - * @throws CommunicationHandlerException in the event of 'Subscribing to' the MQTT broker - * fails. - */ - protected void subscribeToQueue() throws CommunicationHandlerException { - try { - client.subscribe(subscribeTopic, 0); - log.info("Subscriber '" + clientId + "' subscribed to topic: " + subscribeTopic); - } catch (MqttException ex) { - String errorMsg = "MQTT Exception when trying to subscribe to topic: " + - subscribeTopic + "\n\tReason: " + ex.getReasonCode() + - "\n\tMessage: " + ex.getMessage() + "\n\tLocalMsg: " + - ex.getLocalizedMessage() + "\n\tCause: " + ex.getCause() + - "\n\tException: " + ex; - if (log.isDebugEnabled()) { - log.debug(errorMsg); - } - - throw new CommunicationHandlerException(errorMsg, ex); - } - } - - - /** - * This method is used to publish reply-messages for the control signals received. - * Invocation of this method calls its overloaded-method with a QoS equal to that of the - * default value. - * - * @param topic the topic to which the reply message is to be published. - * @param payLoad the reply-message (payload) of the MQTT publish action. - */ - protected void publishToQueue(String topic, String payLoad) - throws CommunicationHandlerException { - publishToQueue(topic, payLoad, DEFAULT_MQTT_QUALITY_OF_SERVICE, false); - } - - /** - * This is an overloaded method that publishes MQTT reply-messages for control signals - * received form the IoT-Server. - * - * @param topic the topic to which the reply message is to be published - * @param payLoad the reply-message (payload) of the MQTT publish action. - * @param qos the Quality-of-Service of the current publish action. - * Could be 0(At-most once), 1(At-least once) or 2(Exactly once) - */ - protected void publishToQueue(String topic, String payLoad, int qos, boolean retained) - throws CommunicationHandlerException { - try { - client.publish(topic, payLoad.getBytes(StandardCharsets.UTF_8), qos, retained); - if (log.isDebugEnabled()) { - log.debug("Message: " + payLoad + " to MQTT topic [" + topic + - "] published successfully"); - } - } catch (MqttException ex) { - String errorMsg = - "MQTT Client Error" + "\n\tReason: " + ex.getReasonCode() + "\n\tMessage: " + - ex.getMessage() + "\n\tLocalMsg: " + ex.getLocalizedMessage() + - "\n\tCause: " + ex.getCause() + "\n\tException: " + ex; - log.info(ex); - throw new CommunicationHandlerException(errorMsg, ex); - } - } - - - protected void publishToQueue(String topic, MqttMessage message) - throws CommunicationHandlerException { - try { - client.publish(topic, message); - if (log.isDebugEnabled()) { - log.debug("Message: " + message.toString() + " to MQTT topic [" + topic + - "] published successfully"); - } - } catch (MqttException ex) { - String errorMsg = - "MQTT Client Error" + "\n\tReason: " + ex.getReasonCode() + "\n\tMessage: " + - ex.getMessage() + "\n\tLocalMsg: " + ex.getLocalizedMessage() + - "\n\tCause: " + ex.getCause() + "\n\tException: " + ex; - log.info(errorMsg); - throw new CommunicationHandlerException(errorMsg, ex); - } - } - - - /** - * Callback method which is triggered once the MQTT client losers its connection to the broker. - * Spawns a new thread that executes necessary actions to try and reconnect to the endpoint. - * - * @param throwable a Throwable Object containing the details as to why the failure occurred. - */ - @Override - public void connectionLost(Throwable throwable) { - log.warn("Lost Connection for client: " + this.clientId + - " to " + this.mqttBrokerEndPoint + ".\nThis was due to - " + - throwable.getMessage()); - - - Thread reconnectThread = new Thread() { - public void run() { - connect(); - } - }; - reconnectThread.setDaemon(true); - reconnectThread.start(); - } - - /** - * Callback method which is triggered upon receiving a MQTT Message from the broker. Spawns a - * new thread that executes any actions to be taken with the received message. - * - * @param topic the MQTT-Topic to which the received message was published to and the - * client was subscribed to. - * @param mqttMessage the actual MQTT-Message that was received from the broker. - */ - @Override - public void messageArrived(final String topic, final MqttMessage mqttMessage) { - if (log.isDebugEnabled()) { - log.info("Got an MQTT message '" + mqttMessage.toString() + "' for topic '" + topic + - "'."); - } - - Thread messageProcessorThread = new Thread() { - public void run() { - processIncomingMessage(mqttMessage, topic); - } - }; - messageProcessorThread.setDaemon(true); - messageProcessorThread.start(); - } - - /** - * Callback method which gets triggered upon successful completion of a message delivery to - * the broker. - * - * @param iMqttDeliveryToken the MQTT-DeliveryToken which includes the details about the - * specific message delivery. - */ - @Override - public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { - String message = ""; - try { - if (iMqttDeliveryToken.isComplete()) { - if (iMqttDeliveryToken.getMessage() != null){ - message = iMqttDeliveryToken.getMessage().toString(); - } - } else { - log.error("MQTT Message not delivered"); - } - } catch (MqttException e) { - log.error( - "Error occurred whilst trying to read the message from the MQTT delivery token."); - } - String topic = iMqttDeliveryToken.getTopics()[0]; - String client = iMqttDeliveryToken.getClient().getClientId(); - - if (log.isDebugEnabled()) { - log.debug("Message - '" + message + "' of client [" + client + "] for the topic (" + - topic + ") was delivered successfully."); - } - } - - /** - * Closes the connection to the MQTT Broker. - */ - public void closeConnection() throws MqttException { - if (client != null && isConnected()) { - client.disconnect(); - } - } -} - diff --git a/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/util/DigitalDisplayMqttCommunicationHandler.java b/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/util/DigitalDisplayMqttCommunicationHandler.java index 66529a9e0d..154c9cd207 100644 --- a/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/util/DigitalDisplayMqttCommunicationHandler.java +++ b/components/device-mgt-iot-digitaldisplay/org.wso2.carbon.device.mgt.iot.digitaldisplay.api/src/main/java/org/wso2/carbon/device/mgt/iot/digitaldisplay/api/util/DigitalDisplayMqttCommunicationHandler.java @@ -5,32 +5,35 @@ import org.apache.commons.logging.LogFactory; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; -import org.wso2.carbon.device.mgt.iot.digitaldisplay.constants.DigitalDisplayConstants; -import org.wso2.carbon.device.mgt.iot.digitaldisplay.api.transport.CommunicationHandlerException; -import org.wso2.carbon.device.mgt.iot.digitaldisplay.api.transport.MQTTCommunicationHandler; import org.wso2.carbon.device.mgt.iot.digitaldisplay.api.websocket.DigitalDisplayWebSocketServerEndPoint; +import org.wso2.carbon.device.mgt.iot.digitaldisplay.constants.DigitalDisplayConstants; +import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; +import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler; import java.io.File; import java.util.UUID; import java.util.concurrent.ScheduledFuture; +//import org.wso2.carbon.device.mgt.iot.digitaldisplay.api.transport.CommunicationHandlerException; +//import org.wso2.carbon.device.mgt.iot.digitaldisplay.api.transport.MQTTCommunicationHandler; -public class DigitalDisplayMqttCommunicationHandler extends MQTTCommunicationHandler { + +public class DigitalDisplayMqttCommunicationHandler extends MQTTTransportHandler { private static Log log = LogFactory.getLog(DigitalDisplayMqttCommunicationHandler.class); private static final String subscribeTopic = - "wso2"+ File.separator+"iot"+File.separator+"+"+File.separator+ - DigitalDisplayConstants.DEVICE_TYPE+File.separator+"+"+File.separator+ + "wso2" + File.separator + "iot" + File.separator + "+" + File.separator + + DigitalDisplayConstants.DEVICE_TYPE + File.separator + "+" + File.separator + "digital_display_publisher"; - private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0,5); + private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5); private ScheduledFuture dataPushServiceHandler; private DigitalDisplayMqttCommunicationHandler() { super(iotServerSubscriber, DigitalDisplayConstants.DEVICE_TYPE, - MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic); + MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic); } public ScheduledFuture getDataPushServiceHandler() { @@ -42,15 +45,15 @@ public class DigitalDisplayMqttCommunicationHandler extends MQTTCommunicationHan Runnable connect = new Runnable() { @Override public void run() { - while (!isConnected()){ + while (!isConnected()) { try { log.info("Trying to Connect.."); connectToQueue(); subscribeToQueue(); - } catch (CommunicationHandlerException e) { + } catch (TransportHandlerException e) { log.warn("Connection/Subscription to MQTT Broker at: " + - mqttBrokerEndPoint + " failed"); + mqttBrokerEndPoint + " failed"); try { Thread.sleep(timeoutInterval); @@ -76,36 +79,32 @@ public class DigitalDisplayMqttCommunicationHandler extends MQTTCommunicationHan String topic = messageParams[0]; - String ownerAndId = topic.replace("wso2"+File.separator+"iot"+File.separator,""); - ownerAndId = ownerAndId.replace(File.separator+ DigitalDisplayConstants.DEVICE_TYPE+File.separator,":"); - ownerAndId = ownerAndId.replace(File.separator+"digital_display_publisher",""); + String ownerAndId = topic.replace("wso2" + File.separator + "iot" + File.separator, ""); + ownerAndId = ownerAndId.replace(File.separator + DigitalDisplayConstants.DEVICE_TYPE + File.separator, ":"); + ownerAndId = ownerAndId.replace(File.separator + "digital_display_publisher", ""); String owner = ownerAndId.split(":")[0]; String deviceId = ownerAndId.split(":")[1]; - String [] messageData = message.toString().split(":"); + String[] messageData = message.toString().split(":"); log.info("Received MQTT message for: {OWNER-" + owner + "} & {DEVICE.ID-" + deviceId + "}"); - if(messageData.length == 3){ - String randomId = messageData[0]; - String requestMessage = messageData[1]; - String result = messageData[2]; - log.info("Return result " + result + " for Request " + requestMessage); - DigitalDisplayWebSocketServerEndPoint.sendMessage(randomId, result); + if (messageData.length == 3) { + String randomId = messageData[0]; + String requestMessage = messageData[1]; + String result = messageData[2]; + log.info("Return result " + result + " for Request " + requestMessage); + DigitalDisplayWebSocketServerEndPoint.sendMessage(randomId, result); } } - @Override - public void processIncomingMessage() { - - } - - public void publishToDigitalDisplay(String topic, String payLoad, int qos, boolean retained) throws CommunicationHandlerException { - log.info(topic + " " + payLoad); - publishToQueue(topic, payLoad, qos, retained); + public void publishToDigitalDisplay(String topic, String payLoad, int qos, boolean retained) + throws TransportHandlerException { + log.info(topic + " " + payLoad); + publishToQueue(topic, payLoad, qos, retained); } @Override @@ -120,7 +119,7 @@ public class DigitalDisplayMqttCommunicationHandler extends MQTTCommunicationHan } catch (MqttException e) { if (log.isDebugEnabled()) { log.warn("Unable to 'STOP' MQTT connection at broker at: " + - mqttBrokerEndPoint); + mqttBrokerEndPoint); } try { @@ -138,4 +137,30 @@ public class DigitalDisplayMqttCommunicationHandler extends MQTTCommunicationHan terminatorThread.start(); } + + @Override + public void publishDeviceData() throws TransportHandlerException { + + } + + @Override + public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException { + + } + + @Override + public void publishDeviceData(String... publishData) throws TransportHandlerException { + + } + + @Override + public void processIncomingMessage() { + + } + + @Override + public void processIncomingMessage(MqttMessage message) throws TransportHandlerException { + + } + } diff --git a/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/controlqueue/xmpp/XmppServerClient.java b/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/controlqueue/xmpp/XmppServerClient.java index 0b07b14241..8639ee392a 100644 --- a/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/controlqueue/xmpp/XmppServerClient.java +++ b/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/controlqueue/xmpp/XmppServerClient.java @@ -25,10 +25,13 @@ import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; +import org.json.JSONArray; +import org.json.JSONObject; import org.wso2.carbon.device.mgt.iot.controlqueue.ControlQueueConnector; import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; import org.wso2.carbon.device.mgt.iot.exception.IoTException; @@ -44,184 +47,323 @@ import java.util.HashMap; public class XmppServerClient implements ControlQueueConnector { - private static final Log log = LogFactory.getLog(XmppServerClient.class); - - private static final String XMPP_SERVER_API_CONTEXT = "/plugins/restapi/v1"; - private static final String USERS_API = "/users"; - @SuppressWarnings("unused") - private static final String GROUPS_API = "/groups"; - @SuppressWarnings("unused") - private static final String APPLICATION_JSON_MT = "application/json"; - - private String xmppEndpoint; - private String xmppUsername; - private String xmppPassword; - private boolean xmppEnabled = false; - - public XmppServerClient() { - } - - @Override - public void initControlQueue() { - xmppEndpoint = XmppConfig.getInstance().getXmppEndpoint(); - xmppUsername = XmppConfig.getInstance().getXmppUsername(); - xmppPassword = XmppConfig.getInstance().getXmppPassword(); - xmppEnabled = XmppConfig.getInstance().isEnabled(); - } - - @Override - public void enqueueControls(HashMap deviceControls) - throws DeviceControllerException { - if (!xmppEnabled) { - log.warn("XMPP set to false in 'devicemgt-config.xml'"); - } - } - - public boolean createXMPPAccount(XmppAccount newUserAccount) throws DeviceControllerException { - if (xmppEnabled) { - String xmppUsersAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + USERS_API; - if (log.isDebugEnabled()) { - log.debug("The API Endpoint URL of the XMPP Server is set to: " + xmppUsersAPIEndpoint); - } - - String encodedString = xmppUsername + ":" + xmppPassword; - encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8))); - String authorizationHeader = "Basic " + encodedString; - String jsonRequest ="{\n" + - " \"username\": \""+newUserAccount.getUsername()+"\"," + - " \"password\": \""+newUserAccount.getPassword()+"\"," + - " \"name\": \""+newUserAccount.getAccountName()+"\"," + - " \"email\": \""+newUserAccount.getEmail()+"\"," + - " \"properties\": {" + - " \"property\": [" + - " {" + - " \"@key\": \"console.rows_per_page\"," + - " \"@value\": \"user-summary=8\"" + - " }," + - " {" + - " \"@key\": \"console.order\"," + - " \"@value\": \"session-summary=1\"" + - " }" + - " ]" + - " }" + - "}"; - - StringEntity requestEntity; - try { - requestEntity = new StringEntity(jsonRequest, MediaType.APPLICATION_JSON , StandardCharsets.UTF_8.toString()); - } catch (UnsupportedEncodingException e) { - return false; - } - - URL xmppUserApiUrl; - try { - xmppUserApiUrl = new URL(xmppUsersAPIEndpoint); - } catch (MalformedURLException e) { - String errMsg = "Malformed XMPP URL + " + xmppUsersAPIEndpoint; - log.error(errMsg); - throw new DeviceControllerException(errMsg); - } - HttpClient httpClient; - try { - httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol()); - } catch (Exception e) { - log.error("Error on getting a http client for port :" + xmppUserApiUrl.getPort() + " protocol :" - + xmppUserApiUrl.getProtocol()); - return false; - } - - HttpPost httpPost = new HttpPost(xmppUsersAPIEndpoint); - httpPost.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); - httpPost.setEntity(requestEntity); - - try { - HttpResponse httpResponse = httpClient.execute(httpPost); - - if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { - String response = IoTUtil.getResponseString(httpResponse); - String errorMsg = "XMPP Server returned status: '" + httpResponse.getStatusLine().getStatusCode() + - "' for account creation with error:\n" + response; - log.error(errorMsg); - throw new DeviceControllerException(errorMsg); - } else { - EntityUtils.consume(httpResponse.getEntity()); - return true; - } - } catch (IOException | IoTException e) { - String errorMsg = - "Error occured whilst trying a 'POST' at : " + xmppUsersAPIEndpoint + " error: " + e.getMessage(); - log.error(errorMsg); - throw new DeviceControllerException(errorMsg, e); - } - - } else { - log.warn("XMPP set to false in 'devicemgt-config.xml'"); - return false; - } - } - - - public boolean doesXMPPUserAccountExist(String username) throws DeviceControllerException { - if (xmppEnabled) { - String xmppUsersAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + USERS_API + "/" + username; - if (log.isDebugEnabled()) { - log.debug("The API Endpoint URL of the XMPP Server is set to: " + xmppUsersAPIEndpoint); - } - - String encodedString = xmppUsername + ":" + xmppPassword; - encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8))); - String authorizationHeader = "Basic " + encodedString; - - URL xmppUserApiUrl; - try { - xmppUserApiUrl = new URL(xmppUsersAPIEndpoint); - } catch (MalformedURLException e) { - String errMsg = "Malformed XMPP URL + " + xmppUsersAPIEndpoint; - log.error(errMsg); - throw new DeviceControllerException(errMsg, e); - } - - HttpClient httpClient; - try { - httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol()); - } catch (Exception e) { - String errorMsg = "Error on getting a http client for port :" + xmppUserApiUrl.getPort() + - " protocol :" + xmppUserApiUrl.getProtocol(); - log.error(errorMsg); - throw new DeviceControllerException(errorMsg, e); - } - - HttpGet httpGet = new HttpGet(xmppUsersAPIEndpoint); - httpGet.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); - - try { - HttpResponse httpResponse = httpClient.execute(httpGet); - - if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { - String response = IoTUtil.getResponseString(httpResponse); - if (log.isDebugEnabled()) { - log.debug("XMPP Server returned status: '" + httpResponse.getStatusLine().getStatusCode() + - "' for checking existence of account [" + username + "] with message:\n" + - response + "\nProbably, an account with this username does not exist."); - } - return false; - } - - } catch (IOException | IoTException e) { - String errorMsg = "Error occured whilst trying a 'GET' at : " + xmppUsersAPIEndpoint + - "\nError: " + e.getMessage(); - log.error(errorMsg); - throw new DeviceControllerException(errorMsg, e); - } - - if (log.isDebugEnabled()) { - log.debug("XMPP Server already has an account for the username - [" + username + "]."); - } - return true; - } else { - String warnMsg = "XMPP set to false in 'devicemgt-config.xml'"; - log.warn(warnMsg); - throw new DeviceControllerException(warnMsg); - } - } + private static final Log log = LogFactory.getLog(XmppServerClient.class); + + private static final String XMPP_SERVER_API_CONTEXT = "/plugins/restapi/v1"; + private static final String XMPP_USERS_API = "/users"; + private static final String XMPP_SESSIONS_API = "/sessions"; + @SuppressWarnings("unused") + private static final String XMPP_GROUPS_API = "/groups"; + @SuppressWarnings("unused") + private static final String APPLICATION_JSON_MT = "application/json"; + private static final String DEVICEMGT_CONFIG_FILE = "devicemgt-config.xml"; + + private String xmppEndpoint; + private String xmppUsername; + private String xmppPassword; + private boolean xmppEnabled = false; + + public XmppServerClient() { + } + + @Override + public void initControlQueue() { + xmppEndpoint = XmppConfig.getInstance().getXmppEndpoint(); + xmppUsername = XmppConfig.getInstance().getXmppUsername(); + xmppPassword = XmppConfig.getInstance().getXmppPassword(); + xmppEnabled = XmppConfig.getInstance().isEnabled(); + } + + @Override + public void enqueueControls(HashMap deviceControls) + throws DeviceControllerException { + if (!xmppEnabled) { + log.warn(String.format("XMPP set to false in [%s]", DEVICEMGT_CONFIG_FILE)); + } + } + + public boolean createXMPPAccount(XmppAccount newUserAccount) throws DeviceControllerException { + if (xmppEnabled) { + String xmppUsersAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + XMPP_USERS_API; + if (log.isDebugEnabled()) { + log.debug("The Create-UserAccount Endpoint URL of the XMPP Server is set to: " + xmppUsersAPIEndpoint); + } + + String encodedString = xmppUsername + ":" + xmppPassword; + encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8))); + String authorizationHeader = "Basic " + encodedString; + String jsonRequest = "{\n" + + " \"username\": \"" + newUserAccount.getUsername() + "\"," + + " \"password\": \"" + newUserAccount.getPassword() + "\"," + + " \"name\": \"" + newUserAccount.getAccountName() + "\"," + + " \"email\": \"" + newUserAccount.getEmail() + "\"," + + " \"properties\": {" + + " \"property\": [" + + " {" + + " \"@key\": \"console.rows_per_page\"," + + " \"@value\": \"user-summary=8\"" + + " }," + + " {" + + " \"@key\": \"console.order\"," + + " \"@value\": \"session-summary=1\"" + + " }" + + " ]" + + " }" + + "}"; + + StringEntity requestEntity; + try { + requestEntity = new StringEntity(jsonRequest, MediaType.APPLICATION_JSON, + StandardCharsets.UTF_8.toString()); + } catch (UnsupportedEncodingException e) { + return false; + } + + URL xmppUserApiUrl; + try { + xmppUserApiUrl = new URL(xmppUsersAPIEndpoint); + } catch (MalformedURLException e) { + String errMsg = "Malformed XMPP URL + " + xmppUsersAPIEndpoint; + log.error(errMsg); + throw new DeviceControllerException(errMsg); + } + HttpClient httpClient; + try { + httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol()); + } catch (Exception e) { + log.error("Error on getting a http client for port :" + xmppUserApiUrl.getPort() + " protocol :" + + xmppUserApiUrl.getProtocol()); + return false; + } + + HttpPost httpPost = new HttpPost(xmppUsersAPIEndpoint); + httpPost.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); + httpPost.setEntity(requestEntity); + + try { + HttpResponse httpResponse = httpClient.execute(httpPost); + + if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { + String response = IoTUtil.getResponseString(httpResponse); + String errorMsg = "XMPP Server returned status: '" + httpResponse.getStatusLine().getStatusCode() + + "' for account creation with error:\n" + response; + log.error(errorMsg); + throw new DeviceControllerException(errorMsg); + } else { + EntityUtils.consume(httpResponse.getEntity()); + return true; + } + } catch (IOException | IoTException e) { + String errorMsg = "Error occured whilst trying a 'POST' at : " + xmppUsersAPIEndpoint; + log.error(errorMsg); + throw new DeviceControllerException(errorMsg, e); + } + + } else { + log.warn(String.format("XMPP set to false in [%s]", DEVICEMGT_CONFIG_FILE)); + return false; + } + } + + + public boolean doesXMPPUserAccountExist(String username) throws DeviceControllerException { + if (xmppEnabled) { + String xmppCheckUserAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + XMPP_USERS_API + "/" + username; + if (log.isDebugEnabled()) { + log.debug("The Check-User-Account Endpoint URL of the XMPP Server is set to: " + + xmppCheckUserAPIEndpoint); + } + + String encodedString = xmppUsername + ":" + xmppPassword; + encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8))); + String authorizationHeader = "Basic " + encodedString; + + URL xmppUserApiUrl; + try { + xmppUserApiUrl = new URL(xmppCheckUserAPIEndpoint); + } catch (MalformedURLException e) { + String errMsg = "Malformed XMPP URL + " + xmppCheckUserAPIEndpoint; + log.error(errMsg); + throw new DeviceControllerException(errMsg, e); + } + + HttpClient httpClient; + try { + httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol()); + } catch (Exception e) { + String errorMsg = "Error on getting a http client for port :" + xmppUserApiUrl.getPort() + + " protocol :" + xmppUserApiUrl.getProtocol(); + log.error(errorMsg); + throw new DeviceControllerException(errorMsg, e); + } + + HttpGet httpGet = new HttpGet(xmppCheckUserAPIEndpoint); + httpGet.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); + + try { + HttpResponse httpResponse = httpClient.execute(httpGet); + + if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { + String response = IoTUtil.getResponseString(httpResponse); + if (log.isDebugEnabled()) { + log.debug("XMPP Server returned status: '" + httpResponse.getStatusLine().getStatusCode() + + "' for checking existence of account [" + username + "] with message:\n" + + response + "\nProbably, an account with this username does not exist."); + } + return false; + } + + } catch (IOException | IoTException e) { + String errorMsg = "Error occured whilst trying a 'GET' at : " + xmppCheckUserAPIEndpoint; + log.error(errorMsg); + throw new DeviceControllerException(errorMsg, e); + } + + if (log.isDebugEnabled()) { + log.debug("XMPP Server already has an account for the username - [" + username + "]."); + } + return true; + } else { + String warnMsg = String.format("XMPP set to false in [%s]", DEVICEMGT_CONFIG_FILE); + log.warn(warnMsg); + throw new DeviceControllerException(warnMsg); + } + } + + + public JSONArray getAllCurrentUserSessions() throws DeviceControllerException { + if (xmppEnabled) { + JSONArray xmppSessions; + String xmppSessionsAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + XMPP_SESSIONS_API; + + if (log.isDebugEnabled()) { + log.debug("The Get-Sessions Endpoint URL of the XMPP Server is set to: " + xmppSessionsAPIEndpoint); + } + + String encodedString = xmppUsername + ":" + xmppPassword; + encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8))); + String authorizationHeader = "Basic " + encodedString; + + URL xmppUserApiUrl; + try { + xmppUserApiUrl = new URL(xmppSessionsAPIEndpoint); + } catch (MalformedURLException e) { + String errMsg = "Malformed XMPP URL + " + xmppSessionsAPIEndpoint; + log.error(errMsg); + throw new DeviceControllerException(errMsg, e); + } + + HttpClient httpClient; + try { + httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol()); + } catch (Exception e) { + String errorMsg = "Error on getting a http client for port :" + xmppUserApiUrl.getPort() + + " protocol :" + xmppUserApiUrl.getProtocol(); + log.error(errorMsg); + throw new DeviceControllerException(errorMsg, e); + } + + HttpGet httpGet = new HttpGet(xmppSessionsAPIEndpoint); + httpGet.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); + httpGet.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + + try { + HttpResponse httpResponse = httpClient.execute(httpGet); + + if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { + String errorMsg = "XMPP Server returned status: '" + httpResponse.getStatusLine().getStatusCode() + + "' for checking current XMPP Sessions."; + log.error(errorMsg); + throw new DeviceControllerException(errorMsg); + } + + String response = IoTUtil.getResponseString(httpResponse); + xmppSessions = new JSONObject(response).getJSONArray("session"); + return xmppSessions; + + } catch (IOException | IoTException e) { + String errorMsg = "Error occured whilst trying a 'GET' at : " + xmppSessionsAPIEndpoint; + log.error(errorMsg); + throw new DeviceControllerException(errorMsg, e); + } + + } else { + String warnMsg = String.format("XMPP set to false in [%s]", DEVICEMGT_CONFIG_FILE); + log.warn(warnMsg); + throw new DeviceControllerException(warnMsg); + } + } + + + public void deleteCurrentXmppSessions() throws DeviceControllerException { + JSONArray xmppSessionsArray; + + try { + xmppSessionsArray = getAllCurrentUserSessions(); + } catch (DeviceControllerException e) { + if (e.getMessage().contains(DEVICEMGT_CONFIG_FILE)) { + log.warn(String.format("XMPP set to false in [%s]", DEVICEMGT_CONFIG_FILE)); + return; + } else { + throw e; + } + } + + if (xmppSessionsArray.length() != 0) { + String xmppSessionsAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + XMPP_SESSIONS_API; + String encodedString = xmppUsername + ":" + xmppPassword; + encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8))); + String authorizationHeader = "Basic " + encodedString; + + if (log.isDebugEnabled()) { + log.debug("The Get-Sessions Endpoint URL of the XMPP Server is set to: " + xmppSessionsAPIEndpoint); + } + + URL xmppUserApiUrl; + try { + xmppUserApiUrl = new URL(xmppSessionsAPIEndpoint); + } catch (MalformedURLException e) { + String errMsg = "Malformed XMPP URL + " + xmppSessionsAPIEndpoint; + log.error(errMsg); + throw new DeviceControllerException(errMsg, e); + } + + HttpClient httpClient; + try { + httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol()); + } catch (Exception e) { + String errorMsg = "Error on getting a http client for port :" + xmppUserApiUrl.getPort() + + " protocol :" + xmppUserApiUrl.getProtocol(); + log.error(errorMsg); + throw new DeviceControllerException(errorMsg, e); + } + + for (int i = 0; i < xmppSessionsArray.length(); i++) { + + String sessionName = xmppSessionsArray.getJSONObject(i).getString("username"); + String xmppUserSessionsAPIEndpoint = xmppSessionsAPIEndpoint + "/" + sessionName; + + HttpDelete httpDelete = new HttpDelete(xmppUserSessionsAPIEndpoint); + httpDelete.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); + + try { + HttpResponse httpResponse = httpClient.execute(httpDelete); + + if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { + String errorMsg = + "XMPP Server returned status: '" + httpResponse.getStatusLine().getStatusCode() + + "' for checking current XMPP Sessions."; + log.error(errorMsg); + throw new DeviceControllerException(errorMsg); + } + + } catch (IOException e) { + String errorMsg = "Error occured whilst trying a 'DELETE' user-session [" + sessionName + "] " + + "at : " + xmppUserSessionsAPIEndpoint; + log.error(errorMsg); + throw new DeviceControllerException(errorMsg, e); + } + } + } + } } diff --git a/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/internal/IotDeviceManagementServiceComponent.java b/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/internal/IotDeviceManagementServiceComponent.java index 4c204abb04..068342dbb8 100644 --- a/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/internal/IotDeviceManagementServiceComponent.java +++ b/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/internal/IotDeviceManagementServiceComponent.java @@ -27,16 +27,19 @@ import org.wso2.carbon.databridge.core.DataBridgeReceiverService; import org.wso2.carbon.device.mgt.iot.DeviceController; import org.wso2.carbon.device.mgt.iot.UserManagement; import org.wso2.carbon.device.mgt.iot.analytics.statistics.IoTEventsStatisticsClient; +import org.wso2.carbon.device.mgt.iot.analytics.statistics.IoTUsageStatisticsClient; +import org.wso2.carbon.device.mgt.iot.config.devicetype.IotDeviceTypeConfigurationManager; import org.wso2.carbon.device.mgt.iot.config.devicetype.datasource.IotDeviceTypeConfig; +import org.wso2.carbon.device.mgt.iot.config.server.DeviceManagementConfigurationManager; +import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig; +import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient; +import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; import org.wso2.carbon.device.mgt.iot.service.DeviceTypeService; import org.wso2.carbon.device.mgt.iot.service.DeviceTypeServiceImpl; import org.wso2.carbon.device.mgt.iot.startup.StartupUrlPrinter; -import org.wso2.carbon.device.mgt.iot.util.iotdevice.exception.IotDeviceMgtPluginException; -import org.wso2.carbon.device.mgt.iot.config.server.DeviceManagementConfigurationManager; -import org.wso2.carbon.device.mgt.iot.analytics.statistics.IoTUsageStatisticsClient; -import org.wso2.carbon.device.mgt.iot.config.devicetype.IotDeviceTypeConfigurationManager; import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.util.IotDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.iot.util.iotdevice.exception.IotDeviceMgtPluginException; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.ConfigurationContextService; @@ -74,7 +77,8 @@ import java.util.Map; public class IotDeviceManagementServiceComponent { private static final Log log = LogFactory.getLog(IotDeviceManagementServiceComponent.class); - public static ConfigurationContextService configurationContextService; + public static ConfigurationContextService configurationContextService; + protected void activate(ComponentContext ctx) { if (log.isDebugEnabled()) { log.debug("Activating Iot Device Management Service Component"); @@ -82,69 +86,83 @@ public class IotDeviceManagementServiceComponent { try { - BundleContext bundleContext = ctx.getBundleContext(); /* Initialize the data source configuration */ - DeviceManagementConfigurationManager.getInstance().initConfig(); - IotDeviceTypeConfigurationManager.getInstance().initConfig(); - Map dsConfigMap = - IotDeviceTypeConfigurationManager.getInstance().getIotDeviceTypeConfigMap(); - - IotDeviceManagementDAOFactory.init(dsConfigMap); - - - - String setupOption = System.getProperty("setup"); - if (setupOption != null) { - if (log.isDebugEnabled()) { - log.debug( - "-Dsetup is enabled. Iot Device management repository schema initialization is about " + - "to begin"); - } - try { - for (String pluginType : dsConfigMap.keySet()){ - IotDeviceManagementDAOUtil - .setupIotDeviceManagementSchema( - IotDeviceManagementDAOFactory.getDataSourceMap - ().get(pluginType), pluginType); - } - } catch (IotDeviceMgtPluginException e) { - log.error( - "Exception occurred while initializing mobile device management database schem ", - e); - } - } - - IoTCommonDataHolder.getInstance().initialize(); + BundleContext bundleContext = ctx.getBundleContext(); /* Initialize the data source + configuration */ + DeviceManagementConfigurationManager.getInstance().initConfig(); + IotDeviceTypeConfigurationManager.getInstance().initConfig(); + Map dsConfigMap = + IotDeviceTypeConfigurationManager.getInstance().getIotDeviceTypeConfigMap(); + + IotDeviceManagementDAOFactory.init(dsConfigMap); + + + String setupOption = System.getProperty("setup"); + if (setupOption != null) { + if (log.isDebugEnabled()) { + log.debug( + "-Dsetup is enabled. Iot Device management repository schema initialization is about " + + "to begin"); + } + try { + for (String pluginType : dsConfigMap.keySet()) { + IotDeviceManagementDAOUtil + .setupIotDeviceManagementSchema( + IotDeviceManagementDAOFactory.getDataSourceMap + ().get(pluginType), pluginType); + } + } catch (IotDeviceMgtPluginException e) { + log.error( + "Exception occurred while initializing mobile device management database schem ", + e); + } + } + + IoTCommonDataHolder.getInstance().initialize(); + + //TODO: handle + + DeviceController.init(); + IoTUsageStatisticsClient.initializeDataSource(); + IoTEventsStatisticsClient.initializeDataSource(); + UserManagement.registerApiAccessRoles(); - //TODO: handle - DeviceController.init(); - IoTUsageStatisticsClient.initializeDataSource(); - IoTEventsStatisticsClient.initializeDataSource(); - UserManagement.registerApiAccessRoles(); + bundleContext.registerService(DeviceTypeService.class.getName(), + new DeviceTypeServiceImpl(), null); + if (log.isDebugEnabled()) { + log.debug("Iot Device Management Service Component has been successfully activated"); + } - bundleContext.registerService(DeviceTypeService.class.getName(), - new DeviceTypeServiceImpl(), null); + bundleContext.registerService(ServerStartupObserver.class, new StartupUrlPrinter(), null); + } catch (Throwable e) { + log.error("Error occurred while activating Iot Device Management Service Component", e); + } + } - if (log.isDebugEnabled()) { - log.debug("Iot Device Management Service Component has been successfully activated"); - } + protected void deactivate(ComponentContext ctx) { + XmppConfig xmppConfig = XmppConfig.getInstance(); - bundleContext.registerService(ServerStartupObserver.class, new StartupUrlPrinter(), null); - } catch (Throwable e) { - log.error("Error occurred while activating Iot Device Management Service Component", e); - } - } + try { + if (xmppConfig.isEnabled()) { + XmppServerClient xmppServerClient = new XmppServerClient(); + xmppServerClient.initControlQueue(); + xmppServerClient.deleteCurrentXmppSessions(); + } + } catch (DeviceControllerException e) { + String errorMsg = "An error occurred whilst trying to delete all existing XMPP login sessions at " + + "[" + xmppConfig.getXmppEndpoint() + "]."; + log.error(errorMsg, e); + } - protected void deactivate(ComponentContext ctx) { - if (log.isDebugEnabled()) { - log.debug("De-activating Iot Device Management Service Component"); - } + if (log.isDebugEnabled()) { + log.debug("De-activating Iot Device Management Service Component"); + } - } + } - protected void setDataSourceService(DataSourceService dataSourceService) { - /* This is to avoid iot device management component getting initialized before the + protected void setDataSourceService(DataSourceService dataSourceService) { + /* This is to avoid iot device management component getting initialized before the underlying datasources are registered */ if (log.isDebugEnabled()) { @@ -156,45 +174,47 @@ public class IotDeviceManagementServiceComponent { //do nothing } - protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { - if (log.isDebugEnabled()) { - log.debug("Setting ConfigurationContextService"); - } - - IotDeviceManagementServiceComponent.configurationContextService=configurationContextService; - - } - - protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { - if (log.isDebugEnabled()) { - log.debug("Un-setting ConfigurationContextService"); - } - IotDeviceManagementServiceComponent.configurationContextService=null; - } - - /** - * Sets Realm Service - * @param realmService associated realm service reference - */ - protected void setRealmService(RealmService realmService) { - if (log.isDebugEnabled()) { - log.debug("Setting Realm Service"); - - } - UserManagement.setRealmService(realmService); - - } - - /** - * Unsets Realm Service - * @param realmService associated realm service reference - */ - protected void unsetRealmService(RealmService realmService) { - if (log.isDebugEnabled()) { - log.debug("Unsetting Realm Service"); - } - UserManagement.setRealmService(realmService); - } + protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Setting ConfigurationContextService"); + } + + IotDeviceManagementServiceComponent.configurationContextService = configurationContextService; + + } + + protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Un-setting ConfigurationContextService"); + } + IotDeviceManagementServiceComponent.configurationContextService = null; + } + + /** + * Sets Realm Service + * + * @param realmService associated realm service reference + */ + protected void setRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Setting Realm Service"); + + } + UserManagement.setRealmService(realmService); + + } + + /** + * Unsets Realm Service + * + * @param realmService associated realm service reference + */ + protected void unsetRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting Realm Service"); + } + UserManagement.setRealmService(realmService); + } /** * Sets DataBridge Receiver Service From 93957a3ed0dce1908b4cead4349e2f2796d3e5aa Mon Sep 17 00:00:00 2001 From: Shabirmean Date: Wed, 23 Dec 2015 15:45:09 +0530 Subject: [PATCH 2/6] Deleted all device-type specific databases --- .../resources/database/AndroidSenseDM_DB.h2.db | Bin 16384 -> 0 bytes .../main/resources/database/ArduinoDM_DB.h2.db | Bin 16384 -> 0 bytes .../database/DigitalDisplayDM_DB.h2.db | Bin 16384 -> 0 bytes .../resources/database/DroneAnalyzerDM_DB.h2.db | Bin 16384 -> 0 bytes .../resources/database/RaspberryPiDM_DB.h2.db | Bin 16384 -> 0 bytes .../database/VirtualFireAlarmDM_DB.h2.db | Bin 16384 -> 0 bytes .../database/WSO2MobileAndroid_DB.h2.db | Bin 18432 -> 0 bytes .../database/WSO2MobileWindows_DB.h2.db | Bin 12288 -> 0 bytes 8 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/database/AndroidSenseDM_DB.h2.db delete mode 100644 features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/src/main/resources/database/ArduinoDM_DB.h2.db delete mode 100644 features/device-mgt-iot-digitaldisplay-feature/org.wso2.carbon.device.mgt.iot.digitaldisplay.feature/src/main/resources/database/DigitalDisplayDM_DB.h2.db delete mode 100644 features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/database/DroneAnalyzerDM_DB.h2.db delete mode 100644 features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/database/RaspberryPiDM_DB.h2.db delete mode 100644 features/device-mgt-iot-virtualfirealarm-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/database/VirtualFireAlarmDM_DB.h2.db delete mode 100644 features/device-mgt-mdm-android-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/database/WSO2MobileAndroid_DB.h2.db delete mode 100644 features/device-mgt-mdm-windows-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/src/main/resources/database/WSO2MobileWindows_DB.h2.db diff --git a/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/database/AndroidSenseDM_DB.h2.db b/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/database/AndroidSenseDM_DB.h2.db deleted file mode 100644 index 7e93cc95738ee811270e30a321fac0a633264d68..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16384 zcmeI$y>8P`6bJBxkhl$sst6?5I4P~|Ag5g0N$ZR^_6@P(*p)w;29T`SX$Dp*#K2T_ z;1$@}cno%)0Eroi1qrbsu#>p$P(iyiYIQ7SxHo^_bI#9}BBjxQo&sd6^`rxh29%S} zKi9e3O0H1I;e`SyfC4Ch0w{2e1%4hLf0(!b;OH8Ufvuwe3ZMWApa2S7LI8jNFM)+o z6hHwKKmioEAp)i1#={#j3XXvSD1ZVefC4CRL4oSwk2Luwxz?Rs_Ttz!cy zfC4Ch0w{n2S0+%sKTT_`+`6)gSO^7B00mG01yEqw0@c^QW-Z*#mGj)!0{5xNedM_J ztK88Y?q#L)ZLRdYTKs*t_-fgWVto`q0Tj6Y0*_&{a-64@&s^|n$6~M>bSzWfqPF2W zrV)C~_E>1JJyT~u4Fhz?_I#I`wx2~$cfuXmb@F*{>^cW4@QFl~eFXE!dg zVUi7Z>QJkUbeB;->EZN{bF<*s*?v~zY@g>876B^n@{8kjs`r@j|9Qo7@-H=H6;7sr zJ?iQ`>Wa-)9c;%3JFqNimR)3QI$$R$nUFddtV;uH9xc}eSg*WYG!u9U{m^q1ow}W5 zE-!f)ARI(8iDFfaNE}5(Rs`r#uLpwG)YNG_X-CsG8LQf)rB1h-t+pJ+B$g+w_9U7{ zS{!RC8Mn!SDn~?}PKXl4ZS6pr$YUXSh6B^)f#3I-5AzROpX(8IT(AZmihF1d~9=K1mZvE^>O3<=7t2(xn!bC8L)lE(PHz($Jw(DIH3O zK>Ho~8Tv80mVSal=0cY)UE7ming&8hmYA4FV9cHWch7S_2?Va!p{D`aZ9eTny$)sm zxpJJ#t>y}a99}4Z0w{n2D1ZWYSRnmy_I29+#;ZGg3~U_*Pyhu`00mIs1_Jp0zX29T zQ2+%{00mHBNd$^3+mDvyD0mDMKmim$0Te)iYYJ3f|H_ho__bEd74pK*lJLDOe7ojy zjG+Jupa2S>017NzptdRR^xge^g(wOmGRWe5^o%Gf07&z3pN|zyX>3&AW?h#S-a0mb z0w{n2D1ZVeaBBk9hiO)8_1>*j#6l>50w{n2D1ZWs7O1}YJ!#>7uACRn3c{Ba;jx|*n|#P8d{azqf1d=|j8ho~D`wh5|Ec0fGL<_|q9VEj(obOcR8wn6kJ zaXa+0=R%Sm&o{^rBj0+?K;3J!^(_!zWXaiiqsbE#1*0JYvI*k&|KDua=tqGyU~U+I HMhN)}k&n@8 diff --git a/features/device-mgt-iot-digitaldisplay-feature/org.wso2.carbon.device.mgt.iot.digitaldisplay.feature/src/main/resources/database/DigitalDisplayDM_DB.h2.db b/features/device-mgt-iot-digitaldisplay-feature/org.wso2.carbon.device.mgt.iot.digitaldisplay.feature/src/main/resources/database/DigitalDisplayDM_DB.h2.db deleted file mode 100644 index 48ff20b776e655bb235802bff4a6579840884086..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16384 zcmeI$KX21O6aesqkhl$sN(2%kucfseuZ{AqFNs z00SGJfzQCi&L==(uEfH^3YUNUk)o%phYt#%01BW03ZTFh7Wh01BYMIR&aOe@r5O@n@ryE98am>%!Nv@a3G# zF$@Jz00mG01yEq+0<}$fr|a+UD@0KkkwF$0qXVL-03a>KT|QPcrE$0VdQ$cJ%1g%r zPyhu`00mG01ujjXdT%_*wRYpuGGZbWKmim$0Te)iRSQ&K{hXF?Ggrj>Ul5HdwwFMgeuaXc7E(CgB?dPLBoy=(2&le3!(rYv6b`J6>!s zUz6}P39G?oWoQMAM*nTLG!}esF~2<5870U7mG}91B8yrbW}nAEF7tnd-*ejT(4<1YYdA%52TlF!5-Q{fSZuse#S*Y3$BI%QXqMDsSdx#UVeKe&}l!4cffd zkRKIDBf}hLqvntdn!CXw@glj)61qQM~pvI%1P?{BVe Pb(6^HF+Yw#BZT}0YlhvA diff --git a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/database/DroneAnalyzerDM_DB.h2.db b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/database/DroneAnalyzerDM_DB.h2.db deleted file mode 100644 index 74d44f639dedcc8f6cc9f9fae526b541fd23f65b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 16384 zcmeI$&ui0Q7zgmq+GeekSrt6`bZ$vH()s3Bmmc3H?`&wAjQrTvA%v{y1aE?fha`22h=ou91yBG5Pyhv%El_{{W75L)LUo1vQsh3Cxc40Q zuEM>!!9A&!zpj-}>g8LvOK+FmDAq>-6hMKiFR%rhwU^WhnGYfDIt=!ru49|qmhZVN zw%ERHGN6_PrsoEsPi;4xM^1O*HthNKfcit|v!S?nZ){sluw9EC&TpF~<187so6x9v zrq5`YRX#o9uUYWi`Tk;sKgx*!wb!#VO=|X-_3zQdYW6=hEFPCN4ExkKd(;;-y$P-t zf*U!GG)+!GVwVos@03hP6D+n%BWD_|HU(I(y_&TU1)1$Z;3+2cyV(dqrVT=>B|C;} zbjEs;bQD>~zpTQ#(G;2-75*}U=OrHRAg9s|+8P`6bJBxkhl$sN(2%kr=_(WKe%Df@)a%gJfNUD~T2QY; znScJd&gGVJg+dN56hHwKKmim$feS3~uK48PwEgS*7kCV89R*MT1yBG5P~Z##`1^kb zER3Q63ZMWApui;&C>7UlUy@O93=}{C6hHwKK!H;VRG)s$l0W#hQpy$b!k1;?V_Eoc z%G)u90w{n2D1ZVeuyBFes=U$hcXkw_D2&J;i}TfeqNo5M&DR~iRy1YnX7zd2_42}7 z#|BUU1yBG5PyhwaO`v*foYh*oa&8r|5DK6G3ZMWApunO9s?WYnTDY1k=Y>xN;eAnf zD+q6vg_qZaN0rj&mC~SE{C=bOc+rhweH1_e6u8I&cVVOQDo@>r1rX7e%b*vxT*ulB zXxMA9AQ<$V#AdsW#emv2SiToV0d>4+9z5Pj4Cn<;mj(mquz`H?35jFZ!0~LhH@|t7 zPk25tYOq>4umVOS-o^2Q{+I>do9~~j^Ow>xK;?CQR=}cGo7w-HSuXQ`sNrM z%p-NAX+&$7`j`yO=Ak+yBb8`oV^hzZ;$FxinD&sgV#l>X)yW2k{cOJP*Tp0|0LtZzK~NKyYip3K}c4b)<_IY2r)1r z@dX%=_zZjuR>UVjsu+=2SXjZ%AId0=RdN@U+J?}$`$g$_f_FbS@?X; z&djyHL!J0w{n2|Es`#*si?IQzv9TgtX%@*o`_4w|0iy z4a$xLj(uFnV5A3>juQP_T^cuKc2yWy!_35gaX6(`d`xB)QQUjZHY2?g8%QXo$E3f9IML~K~pNDj>-Vj8MRG}CB~ zC(2kS6MbT~%&}rl1I+_fX&vc_p&9DISV~WNz+Dl<{eXoqt0C@0+_6E?$To<3+5Dc* zLzdnRhmJreWD7)p8tz0vcBdri-eQ9cHV*hB28z*aX`3KE&LZdi#?#vuhofBvWCO(U T-@iGY)sI6yU|tl0N(lK40EObu diff --git a/features/device-mgt-mdm-android-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/database/WSO2MobileAndroid_DB.h2.db b/features/device-mgt-mdm-android-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/database/WSO2MobileAndroid_DB.h2.db deleted file mode 100644 index cf56b1e27937779dbd373b2a4cc60a607f6e5a82..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 18432 zcmeI1!EfV46vopgt+#>fDoX(&E-$;=#9^H>_?gtT=YD$8CdH!>_DRdMe)A!IhVVU%ja|WLIOwt2_OL^fCScBo}v?M>;cC5vDf5{L1wA|BceBg)kopAOR$R z1dsp{SQ`T6zkZu)E#z))NWbQ#$6L}5lJw1v^u-I(ho$Y`Zxwzn7e0O||M$!JFJIks zU)z*k-}riMx?5YJ`>ff)>;&xW#N*TL~@c9KP=ld+hLSpzDix2-^wK9_ZAEcjkFzL1mDR{%;sZKhQ$ z)9Nw%Y3k*o_%jL|TS($yv#uGr9AuB3a5ysEh(Xs6vPHsS$k`wc**g*QEEcP+j@7nW zG*+98#9G_3V}ogGY*JnAY8|^vJ60V$pMw{)nHWP9Kt7itX zrZ3if?wejo0ZK1lKXA1Wc_X29Xt;XRla%{?6pi>$O6Z_PT0V- zVsXO-EDWzvmv(#Mw4H-otk>X9>9f=jLrao}(!ZYkFsf=nd149r5((Qy86Gs7XxUE;6A>oE<7^klXF`)nAGjDFw1 zf&c^{009U|39G*=C;@yLimbpRx}-gUgK=3?(4|0SG_<0{;@QXm97^ zB$u(0R2DL)Ws$j)I3H(6RK%$wtMOV_2d(F}q6xjAwrCy~bFzfz*6pa)e%*0B(oN@c zQ3pbVj_>$kdlEHTpM+lIMOxRQ5jt|*QCEwgZNsRGI*a1zVRB@W`L>XXZaY-tGD)Z8 z`22v(<@)_HPn4{tGL4T(aK2AweiKj2Lapjr*2_N!#FM$KisYRnC-5SFkIeV$ Date: Wed, 23 Dec 2015 16:14:42 +0530 Subject: [PATCH 3/6] restructuring arduino mgt/controller api --- .../pom.xml | 2 +- .../pom.xml | 2 +- .../iot/arduino/service/ArduinoService.java | 0 .../iot/arduino/service/dto/DeviceJSON.java | 0 .../service/exception/ArduinoException.java | 0 .../transport/ArduinoMQTTSubscriber.java | 0 .../service/util/ArduinoServiceUtils.java | 0 .../webapp/META-INF/webapp-classloading.xml | 0 .../src/main/webapp/WEB-INF/cxf-servlet.xml | 0 .../src/main/webapp/WEB-INF/web.xml | 0 .../pom.xml | 171 +++++ .../iot/arduino/service/ArduinoService.java | 708 ++++++++++++++++++ .../iot/arduino/service/dto/DeviceJSON.java | 36 + .../service/exception/ArduinoException.java | 31 + .../transport/ArduinoMQTTSubscriber.java | 146 ++++ .../service/util/ArduinoServiceUtils.java | 234 ++++++ .../webapp/META-INF/webapp-classloading.xml | 33 + .../src/main/webapp/WEB-INF/cxf-servlet.xml | 48 ++ .../src/main/webapp/WEB-INF/web.xml | 55 ++ components/device-mgt-iot-arduino/pom.xml | 3 +- .../pom.xml | 2 +- .../database/AndroidSenseDM_DB.h2.db | Bin 16384 -> 16384 bytes .../pom.xml | 18 +- .../resources/database/ArduinoDM_DB.h2.db | Bin 16384 -> 16384 bytes .../database/DigitalDisplayDM_DB.h2.db | Bin 16384 -> 16384 bytes .../database/DroneAnalyzerDM_DB.h2.db | Bin 16384 -> 16384 bytes .../resources/database/RaspberryPiDM_DB.h2.db | Bin 16384 -> 16384 bytes .../database/VirtualFireAlarmDM_DB.h2.db | Bin 16384 -> 16384 bytes .../database/WSO2MobileAndroid_DB.h2.db | Bin 18432 -> 18432 bytes .../database/WSO2MobileWindows_DB.h2.db | Bin 12288 -> 12288 bytes pom.xml | 13 +- 31 files changed, 1495 insertions(+), 7 deletions(-) rename components/device-mgt-iot-arduino/{org.wso2.carbon.device.mgt.iot.arduino.service.impl => org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl}/pom.xml (98%) rename components/device-mgt-iot-arduino/{org.wso2.carbon.device.mgt.iot.arduino.service.impl => org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl}/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/ArduinoService.java (100%) rename components/device-mgt-iot-arduino/{org.wso2.carbon.device.mgt.iot.arduino.service.impl => org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl}/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/dto/DeviceJSON.java (100%) rename components/device-mgt-iot-arduino/{org.wso2.carbon.device.mgt.iot.arduino.service.impl => org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl}/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/exception/ArduinoException.java (100%) rename components/device-mgt-iot-arduino/{org.wso2.carbon.device.mgt.iot.arduino.service.impl => org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl}/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/transport/ArduinoMQTTSubscriber.java (100%) rename components/device-mgt-iot-arduino/{org.wso2.carbon.device.mgt.iot.arduino.service.impl => org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl}/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/util/ArduinoServiceUtils.java (100%) rename components/device-mgt-iot-arduino/{org.wso2.carbon.device.mgt.iot.arduino.service.impl => org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl}/src/main/webapp/META-INF/webapp-classloading.xml (100%) rename components/device-mgt-iot-arduino/{org.wso2.carbon.device.mgt.iot.arduino.service.impl => org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl}/src/main/webapp/WEB-INF/cxf-servlet.xml (100%) rename components/device-mgt-iot-arduino/{org.wso2.carbon.device.mgt.iot.arduino.service.impl => org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl}/src/main/webapp/WEB-INF/web.xml (100%) create mode 100644 components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/pom.xml create mode 100644 components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/ArduinoService.java create mode 100644 components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/dto/DeviceJSON.java create mode 100644 components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/exception/ArduinoException.java create mode 100644 components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/transport/ArduinoMQTTSubscriber.java create mode 100644 components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/util/ArduinoServiceUtils.java create mode 100644 components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/META-INF/webapp-classloading.xml create mode 100644 components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml create mode 100644 components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/WEB-INF/web.xml diff --git a/components/device-mgt-iot-androidsense/org.wso2.carbon.device.mgt.iot.androidsense.api/pom.xml b/components/device-mgt-iot-androidsense/org.wso2.carbon.device.mgt.iot.androidsense.api/pom.xml index 69bb002679..070120d25d 100644 --- a/components/device-mgt-iot-androidsense/org.wso2.carbon.device.mgt.iot.androidsense.api/pom.xml +++ b/components/device-mgt-iot-androidsense/org.wso2.carbon.device.mgt.iot.androidsense.api/pom.xml @@ -187,7 +187,7 @@ maven-war-plugin - android_sense + android_sense_war diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/pom.xml b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/pom.xml similarity index 98% rename from components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/pom.xml rename to components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/pom.xml index bc5ca940d3..6965fad463 100644 --- a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/pom.xml +++ b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/pom.xml @@ -29,7 +29,7 @@ 4.0.0 - org.wso2.carbon.device.mgt.iot.arduino.service.impl + org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl 1.9.2-SNAPSHOT war WSO2 Carbon - IoT Server Arduino API diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/ArduinoService.java b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/ArduinoService.java similarity index 100% rename from components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/ArduinoService.java rename to components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/ArduinoService.java diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/dto/DeviceJSON.java b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/dto/DeviceJSON.java similarity index 100% rename from components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/dto/DeviceJSON.java rename to components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/dto/DeviceJSON.java diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/exception/ArduinoException.java b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/exception/ArduinoException.java similarity index 100% rename from components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/exception/ArduinoException.java rename to components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/exception/ArduinoException.java diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/transport/ArduinoMQTTSubscriber.java b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/transport/ArduinoMQTTSubscriber.java similarity index 100% rename from components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/transport/ArduinoMQTTSubscriber.java rename to components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/transport/ArduinoMQTTSubscriber.java diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/util/ArduinoServiceUtils.java b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/util/ArduinoServiceUtils.java similarity index 100% rename from components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/util/ArduinoServiceUtils.java rename to components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/util/ArduinoServiceUtils.java diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/webapp/META-INF/webapp-classloading.xml b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/webapp/META-INF/webapp-classloading.xml similarity index 100% rename from components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/webapp/META-INF/webapp-classloading.xml rename to components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/webapp/META-INF/webapp-classloading.xml diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml similarity index 100% rename from components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml rename to components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/webapp/WEB-INF/web.xml b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.service.impl/src/main/webapp/WEB-INF/web.xml rename to components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl/src/main/webapp/WEB-INF/web.xml diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/pom.xml b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/pom.xml new file mode 100644 index 0000000000..2a391e7abe --- /dev/null +++ b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/pom.xml @@ -0,0 +1,171 @@ + + + + + + device-mgt-iot-arduino + org.wso2.carbon.devicemgt-plugins + 1.9.2-SNAPSHOT + ../pom.xml + + + + 4.0.0 + org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl + 1.9.2-SNAPSHOT + war + WSO2 Carbon - IoT Server Arduino API + WSO2 Carbon - Arduino Service API Implementation + http://wso2.org + + + + + org.wso2.carbon + org.wso2.carbon.utils + provided + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + provided + + + org.apache.axis2.wso2 + axis2-client + + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.analytics + provided + + + org.apache.axis2.wso2 + axis2-client + + + + + + + + org.apache.cxf + cxf-rt-frontend-jaxws + provided + + + org.apache.cxf + cxf-rt-frontend-jaxrs + provided + + + org.apache.cxf + cxf-rt-transports-http + provided + + + + + org.eclipse.paho + mqtt-client + provided + + + + + org.apache.httpcomponents + httpasyncclient + 4.1 + provided + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot + provided + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.arduino.plugin.impl + provided + + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.webapp.publisher + provided + + + + + + + + maven-compiler-plugin + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + maven-war-plugin + + arduino_mgt + + + + + + \ No newline at end of file diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/ArduinoService.java b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/ArduinoService.java new file mode 100644 index 0000000000..7a51ac6dd7 --- /dev/null +++ b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/ArduinoService.java @@ -0,0 +1,708 @@ +/* + * 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.arduino.service; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.device.DeviceType; +import org.wso2.carbon.apimgt.annotations.device.feature.Feature; +import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.iot.DeviceManagement; +import org.wso2.carbon.device.mgt.iot.DeviceValidator; +import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo; +import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient; +import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants; +import org.wso2.carbon.device.mgt.iot.arduino.service.dto.DeviceJSON; +import org.wso2.carbon.device.mgt.iot.arduino.service.transport.ArduinoMQTTSubscriber; +import org.wso2.carbon.device.mgt.iot.arduino.service.util.ArduinoServiceUtils; +import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; +import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException; +import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager; +import org.wso2.carbon.device.mgt.iot.util.ZipArchive; +import org.wso2.carbon.device.mgt.iot.util.ZipUtil; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +@API( name="arduino", version="1.0.0", context="/arduino") +@DeviceType( value = "arduino") +public class ArduinoService { + + private static Log log = LogFactory.getLog(ArduinoService.class); + + //TODO; replace this tenant domain + private static final String SUPER_TENANT = "carbon.super"; + + @Context //injected response proxy supporting multiple thread + private HttpServletResponse response; + + public static final String HTTP_PROTOCOL = "HTTP"; + public static final String MQTT_PROTOCOL = "MQTT"; + + private ArduinoMQTTSubscriber arduinoMQTTSubscriber; + private static Map> replyMsgQueue = new HashMap<>(); + private static Map> internalControlsQueue = new HashMap<>(); + private ConcurrentHashMap deviceToIpMap = new ConcurrentHashMap<>(); + + /** + * @param arduinoMQTTSubscriber an object of type "ArduinoMQTTSubscriber" specific for this ArduinoService + */ + @SuppressWarnings("unused") + public void setArduinoMQTTSubscriber( + final ArduinoMQTTSubscriber arduinoMQTTSubscriber) { + this.arduinoMQTTSubscriber = arduinoMQTTSubscriber; + + if (MqttConfig.getInstance().isEnabled()) { + Runnable xmppStarter = new Runnable() { + @Override + public void run() { + arduinoMQTTSubscriber.initConnector(); + arduinoMQTTSubscriber.connectAndSubscribe(); + } + }; + + Thread xmppStarterThread = new Thread(xmppStarter); + xmppStarterThread.setDaemon(true); + xmppStarterThread.start(); + } else { + log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, ArduinoMQTTSubscriber not started."); + } + } + + /** + * @return the "ArduinoMQTTSubscriber" object of this ArduinoService instance + */ + @SuppressWarnings("unused") + public ArduinoMQTTSubscriber getArduinoMQTTSubscriber() { + return arduinoMQTTSubscriber; + } + + /** + * @return the queue containing all the MQTT reply messages from all Arduinos communicating to this service + */ + public static Map> getReplyMsgQueue() { + return replyMsgQueue; + } + + /** + * @return the queue containing all the MQTT controls received to be sent to any Arduinos connected to this server + */ + public static Map> getInternalControlsQueue() { + return internalControlsQueue; + } + + /* --------------------------------------------------------------------------------------- + Device management specific APIs + --------------------------------------------------------------------------------------- */ + + /** + * @param deviceId + * @param name + * @param owner + * @return + */ + @Path("manager/device/register") + @PUT + public boolean register(@QueryParam("deviceId") String deviceId, + @QueryParam("name") String name, @QueryParam("owner") String owner) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE); + try { + if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + response.setStatus(Response.Status.CONFLICT.getStatusCode()); + return false; + } + Device device = new Device(); + device.setDeviceIdentifier(deviceId); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setDateOfEnrolment(new Date().getTime()); + enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + device.setName(name); + device.setType(ArduinoConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(owner); + device.setEnrolmentInfo(enrolmentInfo); + + boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); + if (added) { + response.setStatus(Response.Status.OK.getStatusCode()); + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + } + + return added; + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return false; + } finally { + deviceManagement.endTenantFlow(); + } + } + + /** + * @param deviceId + * @param response + */ + @Path("manager/device/remove/{device_id}") + @DELETE + public void removeDevice(@PathParam("device_id") String deviceId, @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE); + try { + boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( + deviceIdentifier); + if (removed) { + response.setStatus(Response.Status.OK.getStatusCode()); + + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + + } + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } finally { + deviceManagement.endTenantFlow(); + } + + } + + /** + * @param deviceId + * @param name + * @param response + * @return + */ + @Path("manager/device/update/{device_id}") + @POST + public boolean updateDevice(@PathParam("device_id") String deviceId, + @QueryParam("name") String name, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(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(Response.Status.OK.getStatusCode()); + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + + } + return updated; + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return false; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + /** + * @param deviceId + * @return + */ + @Path("manager/device/{device_id}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Device getDevice(@PathParam("device_id") String deviceId) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE); + + try { + return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); + + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return null; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + /** + * @param username + * @return + */ + @Path("manager/devices/{username}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Device[] getArduinoDevices(@PathParam("username") String username) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + try { + List userDevices = + deviceManagement.getDeviceManagementService().getDevicesOfUser(username); + ArrayList userDevicesforArduino = new ArrayList<>(); + for (Device device : userDevices) { + if (device.getType().equals(ArduinoConstants.DEVICE_TYPE) && + device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) { + userDevicesforArduino.add(device); + + } + } + + return userDevicesforArduino.toArray(new Device[]{}); + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return null; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + /** + * @param owner + * @param customDeviceName + * @param sketchType + * @return + */ + @Path("manager/device/{sketch_type}/download") + @GET + @Produces("application/octet-stream") + public Response downloadSketch(@QueryParam("owner") String owner, + @QueryParam("deviceName") String customDeviceName, + @PathParam("sketch_type") String sketchType) { + //TODO:: null check customDeviceName at UI level + try { + ZipArchive zipFile = createDownloadFile(owner, customDeviceName, sketchType); + Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); + rb.header("Content-Disposition", + "attachment; filename=\"" + zipFile.getFileName() + "\""); + return rb.build(); + } catch (IllegalArgumentException ex) { + return Response.status(400).entity(ex.getMessage()).build();//bad request + } catch (DeviceManagementException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (AccessTokenException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (DeviceControllerException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } + + } + + /** + * @param owner + * @param customDeviceName + * @param sketchType + * @return + */ + @Path("manager/device/{sketch_type}/generate_link") + @GET + public Response generateSketchLink(@QueryParam("owner") String owner, + @QueryParam("deviceName") String customDeviceName, + @PathParam("sketch_type") String sketchType) { + + try { + ZipArchive zipFile = createDownloadFile(owner, customDeviceName, sketchType); + Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); + return rb.build(); + } catch (IllegalArgumentException ex) { + return Response.status(400).entity(ex.getMessage()).build();//bad request + } catch (DeviceManagementException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (AccessTokenException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (DeviceControllerException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } + + } + + /** + * @param owner + * @param customDeviceName + * @param sketchType + * @return + * @throws DeviceManagementException + * @throws AccessTokenException + * @throws DeviceControllerException + */ + private ZipArchive createDownloadFile(String owner, String customDeviceName, String sketchType) + throws DeviceManagementException, AccessTokenException, DeviceControllerException { + if (owner == null) { + throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!"); + } + + //create new device id + String deviceId = shortUUID(); + + KeyGenerationUtil.createApplicationKeys("arduino"); + + TokenClient accessTokenClient = new TokenClient(ArduinoConstants.DEVICE_TYPE); + AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); + + //create token + String accessToken = accessTokenInfo.getAccess_token(); + String refreshToken = accessTokenInfo.getRefresh_token(); + + //Register the device with CDMF + String deviceName = customDeviceName + "_" + deviceId; + boolean status = register(deviceId, deviceName, owner); + + if (!status) { + String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner; + throw new DeviceManagementException(msg); + } + + + ZipUtil ziputil = new ZipUtil(); + ZipArchive zipFile = ziputil.createZipFile(owner, SUPER_TENANT, sketchType, deviceId, deviceName, accessToken, + refreshToken); + zipFile.setDeviceId(deviceId); + return zipFile; + } + + /** + * @return + */ + private static String shortUUID() { + UUID uuid = UUID.randomUUID(); + long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong(); + return Long.toString(l, Character.MAX_RADIX); + } + + /* --------------------------------------------------------------------------------------- + Device specific APIs - Control APIs + Data-Publishing APIs + --------------------------------------------------------------------------------------- */ + + /** + * @param owner + * @param deviceId + * @param deviceIP + * @param devicePort + * @param response + * @param request + * @return + */ + @Path("controller/register/{owner}/{deviceId}/{ip}/{port}") + @POST + public String registerDeviceIP(@PathParam("owner") String owner, + @PathParam("deviceId") String deviceId, + @PathParam("ip") String deviceIP, + @PathParam("port") String devicePort, + @Context HttpServletResponse response, + @Context HttpServletRequest request) { + + //TODO:: Need to get IP from the request itself + String result; + + if (log.isDebugEnabled()) { + log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: " + owner); + } + + String deviceHttpEndpoint = deviceIP + ":" + devicePort; + deviceToIpMap.put(deviceId, deviceHttpEndpoint); + + result = "Device-IP Registered"; + response.setStatus(Response.Status.OK.getStatusCode()); + + if (log.isDebugEnabled()) { + log.debug(result); + } + + return result; + } + + /** + * @param owner + * @param deviceId + * @param protocol + * @param state + * @param response + */ + @Path("controller/bulb") + @POST + @Feature( code="bulb", name="Control Bulb", type="operation", + description="Control Bulb on Arduino Uno") + public void switchBulb(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @PathParam("state") String state, + @Context HttpServletResponse response) { + + try { + DeviceValidator deviceValidator = new DeviceValidator(); + if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, + ArduinoConstants.DEVICE_TYPE))) { + response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); + return; + } + } catch (DeviceManagementException e) { + log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return; + } + + String switchToState = state.toUpperCase(); + + if (!switchToState.equals(ArduinoConstants.STATE_ON) && !switchToState.equals(ArduinoConstants.STATE_OFF)) { + log.error("The requested state change shoud be either - 'ON' or 'OFF'"); + response.setStatus(Response.Status.BAD_REQUEST.getStatusCode()); + return; + } + + String protocolString = protocol.toUpperCase(); + String callUrlPattern = ArduinoConstants.BULB_CONTEXT + switchToState; + + if (log.isDebugEnabled()) { + log.debug("Sending request to switch-bulb of device [" + deviceId + "] via " + + protocolString); + } + + try { + switch (protocolString) { + case HTTP_PROTOCOL: + String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); + if (deviceHTTPEndpoint == null) { + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return; + } + ArduinoServiceUtils.sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true); + break; + case MQTT_PROTOCOL: + String mqttMessage = ArduinoConstants.BULB_CONTEXT.replace("/", ""); + ArduinoServiceUtils.sendCommandViaMQTT(owner, deviceId, mqttMessage, switchToState); + break; + default: + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + return; + } + } catch (DeviceManagementException e) { + log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " + protocolString); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return; + } + response.setStatus(Response.Status.OK.getStatusCode()); + } + + + /** + * @param dataMsg + * @param response + */ + @Path("controller/pushdata") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { + + String owner = dataMsg.owner; + String deviceId = dataMsg.deviceId; + String deviceIp = dataMsg.reply; //TODO:: Get IP from request + float pinData = dataMsg.value; + + try { + DeviceValidator deviceValidator = new DeviceValidator(); + if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, + ArduinoConstants.DEVICE_TYPE))) { + response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); + log.warn("Data Received from unregistered Arduino device [" + deviceId + "] for owner [" + owner + "]"); + return; + } + + String registeredIp = deviceToIpMap.get(deviceId); + + if (registeredIp == null) { + log.warn("Unregistered IP: Arduino Pin Data Received from an un-registered IP " + deviceIp + + " for device ID - " + deviceId); + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return; + } else if (!registeredIp.equals(deviceIp)) { + log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId + + " is already registered under some other IP. Re-registration required"); + response.setStatus(Response.Status.CONFLICT.getStatusCode()); + return; + } + + if (log.isDebugEnabled()) { + log.debug("Received Pin Data Value: " + pinData + " degrees C"); + } + SensorDataManager.getInstance().setSensorRecord(deviceId, ArduinoConstants.SENSOR_TEMPERATURE, + String.valueOf(pinData), + Calendar.getInstance().getTimeInMillis()); + + if (!ArduinoServiceUtils.publishToDAS(dataMsg.owner, dataMsg.deviceId, dataMsg.value)) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + log.warn("An error occured whilst trying to publish pin data of Arduino with ID [" + deviceId + + "] of owner [" + owner + "]"); + } + + } catch (DeviceManagementException e) { + String errorMsg = "Validation attempt for deviceId [" + deviceId + "] of owner [" + owner + "] failed.\n"; + log.error(errorMsg + Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase() + "\n" + e.getErrorMessage()); + } + } + + /** + * @param owner + * @param deviceId + * @param response + * @return + */ + @Path("controller/readcontrols") + @GET + public String readControls(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @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; + } + + + /** + * @param dataMsg + * @param response + */ + @Path("controller/push_temperature") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushTemperatureData(final DeviceJSON dataMsg, + @Context HttpServletResponse response, + @Context HttpServletRequest request) { + String owner = dataMsg.owner; + String deviceId = dataMsg.deviceId; + String deviceIp = dataMsg.reply; //TODO:: Get IP from request + float temperature = dataMsg.value; + + try { + DeviceValidator deviceValidator = new DeviceValidator(); + if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, + ArduinoConstants.DEVICE_TYPE))) { + response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); + log.warn("Temperature data Received from unregistered Arduino device [" + deviceId + "] for owner [" + + owner + "]"); + return; + } + + String registeredIp = deviceToIpMap.get(deviceId); + + if (registeredIp == null) { + log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp + + " for device ID - " + deviceId); + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return; + } else if (!registeredIp.equals(deviceIp)) { + log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId + + " is already registered under some other IP. Re-registration required"); + response.setStatus(Response.Status.CONFLICT.getStatusCode()); + return; + } + + if (log.isDebugEnabled()) { + log.debug("Received Pin Data Value: " + temperature + " degrees C"); + } + SensorDataManager.getInstance().setSensorRecord(deviceId, ArduinoConstants.SENSOR_TEMPERATURE, + String.valueOf(temperature), + Calendar.getInstance().getTimeInMillis()); + + if (!ArduinoServiceUtils.publishToDAS(dataMsg.owner, dataMsg.deviceId, dataMsg.value)) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + log.warn("An error occured whilst trying to publish temperature data of Arduino with ID [" + deviceId + + "] of owner [" + owner + "]"); + } + + } catch (DeviceManagementException e) { + String errorMsg = "Validation attempt for deviceId [" + deviceId + "] of owner [" + owner + "] failed.\n"; + log.error(errorMsg + Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase() + "\n" + e.getErrorMessage()); + } + } +} diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/dto/DeviceJSON.java b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/dto/DeviceJSON.java new file mode 100644 index 0000000000..1be336bbde --- /dev/null +++ b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/dto/DeviceJSON.java @@ -0,0 +1,36 @@ +/* + * 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.arduino.service.dto; + +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 float value; +} diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/exception/ArduinoException.java b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/exception/ArduinoException.java new file mode 100644 index 0000000000..ee81f9798e --- /dev/null +++ b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/exception/ArduinoException.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.arduino.service.exception; + +public class ArduinoException extends Exception { + private static final long serialVersionUID = 118512086957330189L; + + public ArduinoException(String errorMessage) { + super(errorMessage); + } + + public ArduinoException(String errorMessage, Throwable throwable) { + super(errorMessage, throwable); + } +} diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/transport/ArduinoMQTTSubscriber.java b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/transport/ArduinoMQTTSubscriber.java new file mode 100644 index 0000000000..0edb99a16d --- /dev/null +++ b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/transport/ArduinoMQTTSubscriber.java @@ -0,0 +1,146 @@ +/* + * 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.arduino.service.transport; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants; +import org.wso2.carbon.device.mgt.iot.arduino.service.ArduinoService; +import org.wso2.carbon.device.mgt.iot.config.server.DeviceManagementConfigurationManager; +import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; +import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttSubscriber; + +import java.io.File; +import java.util.LinkedList; +import java.util.UUID; + +public class ArduinoMQTTSubscriber extends MqttSubscriber { + private static Log log = LogFactory.getLog(ArduinoMQTTSubscriber.class); + + private static final String serverName = + DeviceManagementConfigurationManager.getInstance().getDeviceManagementServerInfo().getName(); + private static final String subscribeTopic = + serverName + File.separator + "+" + File.separator + ArduinoConstants.DEVICE_TYPE + File.separator + "#"; + + + private static final String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5); + private static String mqttEndpoint; + + private ArduinoMQTTSubscriber() { + super(iotServerSubscriber, ArduinoConstants.DEVICE_TYPE, + MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic); + } + + public void initConnector() { + mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint(); + } + + public void connectAndSubscribe() { + try { + super.connectAndSubscribe(); + } catch (DeviceManagementException e) { + log.error("Subscription to MQTT Broker at: " + mqttEndpoint + " failed"); + retryMQTTSubscription(); + } + } + + @Override + protected void postMessageArrived(String topic, MqttMessage message) { + 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)) { + + if (log.isDebugEnabled()) { + log.debug("Received a control message: "); + log.debug("Control message topic: " + topic); + log.debug("Control message: " + message.toString()); + } + + synchronized (ArduinoService.getInternalControlsQueue()) { + deviceControlList = ArduinoService.getInternalControlsQueue().get(deviceId); + if (deviceControlList == null) { + ArduinoService.getInternalControlsQueue() + .put(deviceId, deviceControlList = new LinkedList()); + } + } + deviceControlList.add(message.toString()); + + } else if (msgContext.equals("OUT")) { + + if (log.isDebugEnabled()) { + log.debug("Recieved reply from a device: "); + log.debug("Reply message topic: " + topic); + log.debug("Reply message: " + message.toString().substring(0, lastIndex)); + } + + synchronized (ArduinoService.getReplyMsgQueue()) { + replyMessageList = ArduinoService.getReplyMsgQueue().get(deviceId); + if (replyMessageList == null) { + ArduinoService.getReplyMsgQueue() + .put(deviceId, replyMessageList = new LinkedList()); + } + } + replyMessageList.add(message.toString()); + } + } + + private void retryMQTTSubscription() { + Thread retryToSubscribe = new Thread() { + @Override + public void run() { + while (true) { + if (!isConnected()) { + if (log.isDebugEnabled()) { + log.debug("Subscriber re-trying to reach MQTT queue...."); + } + + try { + ArduinoMQTTSubscriber.super.connectAndSubscribe(); + } catch (DeviceManagementException e1) { + if (log.isDebugEnabled()) { + log.debug("Attempt to re-connect to MQTT-Queue failed"); + } + } + } else { + break; + } + + try { + Thread.sleep(5000); + } catch (InterruptedException e1) { + log.error("MQTT: Thread S;eep Interrupt Exception"); + } + } + } + }; + + retryToSubscribe.setDaemon(true); + retryToSubscribe.start(); + } +} diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/util/ArduinoServiceUtils.java b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/util/ArduinoServiceUtils.java new file mode 100644 index 0000000000..0747df7a04 --- /dev/null +++ b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/util/ArduinoServiceUtils.java @@ -0,0 +1,234 @@ +/* + * 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.arduino.service.util; + +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.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException; +import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.iot.DeviceController; +import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants; +import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; + +import javax.ws.rs.HttpMethod; +import java.io.BufferedReader; +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.CountDownLatch; +import java.util.concurrent.Future; + +public class ArduinoServiceUtils { + private static final Log log = LogFactory.getLog(ArduinoServiceUtils.class); + + //TODO; replace this tenant domain + private static final String SUPER_TENANT = "carbon.super"; + private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature"; + + public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext, + boolean fireAndForgot) throws DeviceManagementException { + + String responseMsg = ""; + String urlString = ArduinoConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext; + + if (log.isDebugEnabled()) { + log.debug(urlString); + } + + if (!fireAndForgot) { + HttpURLConnection httpConnection = getHttpConnection(urlString); + + try { + httpConnection.setRequestMethod(HttpMethod.GET); + } catch (ProtocolException e) { + String errorMsg = + "Protocol specific error occurred when trying to set method to GET" + + " for:" + urlString; + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + + responseMsg = readResponseFromGetRequest(httpConnection); + + } else { + CloseableHttpAsyncClient httpclient = null; + try { + + httpclient = HttpAsyncClients.createDefault(); + httpclient.start(); + HttpGet request = new HttpGet(urlString); + final CountDownLatch latch = new CountDownLatch(1); + Future future = httpclient.execute( + request, new FutureCallback() { + @Override + public void completed(HttpResponse httpResponse) { + latch.countDown(); + } + + @Override + public void failed(Exception e) { + latch.countDown(); + } + + @Override + public void cancelled() { + latch.countDown(); + } + }); + + latch.await(); + + } catch (InterruptedException e) { + if (log.isDebugEnabled()) { + log.debug("Sync Interrupted"); + } + } finally { + try { + if (httpclient != null) { + httpclient.close(); + + } + } catch (IOException e) { + if (log.isDebugEnabled()) { + log.debug("Failed on close"); + } + } + } + } + + return responseMsg; + } + + + public static boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource, + String state) throws DeviceManagementException { + + boolean result; + DeviceController deviceController = new DeviceController(); + + try { + result = deviceController.publishMqttControl(deviceOwner, ArduinoConstants.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; + } + + /* --------------------------------------------------------------------------------------- + Utility methods relevant to creating and sending http requests + --------------------------------------------------------------------------------------- */ + + /* This methods creates and returns a http connection object */ + + public static HttpURLConnection getHttpConnection(String urlString) throws + DeviceManagementException { + + URL connectionUrl = null; + HttpURLConnection httpConnection; + + 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 */ + + public static String readResponseFromGetRequest(HttpURLConnection httpConnection) + throws DeviceManagementException { + BufferedReader bufferedReader; + 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; + StringBuilder completeResponse = new StringBuilder(); + + try { + while ((responseLine = bufferedReader.readLine()) != null) { + completeResponse.append(responseLine); + } + } catch (IOException e) { + String errorMsg = + "Error occured whilst trying read from the connection stream at: " + + httpConnection.getURL(); + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + try { + bufferedReader.close(); + } catch (IOException e) { + log.error( + "Could not succesfully close the bufferedReader to the connection at: " + + httpConnection.getURL()); + } + + return completeResponse.toString(); + } + + public static boolean publishToDAS(String owner, String deviceId, float temperature) { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ctx.setTenantDomain(SUPER_TENANT, true); + DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( + DeviceAnalyticsService.class, null); + Object metdaData[] = {owner, ArduinoConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; + Object payloadData[] = {temperature}; + + try { + deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadData); + } catch (DataPublisherConfigurationException e) { + return false; + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + return true; + } +} diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/META-INF/webapp-classloading.xml b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 0000000000..fa44619195 --- /dev/null +++ b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,33 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 0000000000..1be763aa18 --- /dev/null +++ b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/WEB-INF/web.xml b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..652c3f454a --- /dev/null +++ b/components/device-mgt-iot-arduino/org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,55 @@ + + + Arduino + Arduino + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + + CXFServlet + /* + + + + isAdminService + false + + + doAuthentication + false + + + + + managed-api-enabled + true + + + managed-api-owner + admin + + + managed-api-context-template + /arduino/{version} + + + managed-api-application + arduino + + + managed-api-isSecured + true + + + + + diff --git a/components/device-mgt-iot-arduino/pom.xml b/components/device-mgt-iot-arduino/pom.xml index 42ce389a7e..25706f77ad 100644 --- a/components/device-mgt-iot-arduino/pom.xml +++ b/components/device-mgt-iot-arduino/pom.xml @@ -37,7 +37,8 @@ org.wso2.carbon.device.mgt.iot.arduino.plugin.impl - org.wso2.carbon.device.mgt.iot.arduino.service.impl + org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl + org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl diff --git a/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/pom.xml b/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/pom.xml index bc51240cc5..750a9eb2c3 100644 --- a/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/pom.xml +++ b/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/pom.xml @@ -98,7 +98,7 @@ war true ${basedir}/src/main/resources/webapps/ - android_sense.war + android_sense_mgt.war diff --git a/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/database/AndroidSenseDM_DB.h2.db b/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/database/AndroidSenseDM_DB.h2.db index 7e93cc95738ee811270e30a321fac0a633264d68..2b6bfa1fca9eca0df110ed3ed7b286506d0b563f 100644 GIT binary patch delta 53 mcmZo@U~Fh$T)@HOSQ@jK0SpvYZ5HHs&pt7L6|3MP2@L>!S`G66 delta 53 mcmZo@U~Fh$T)@HerKDvE0~km&Z5HHs&pt7L6|3MP2@L?PhYv{r diff --git a/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/pom.xml b/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/pom.xml index 9210d92e59..1f8bb9cdca 100644 --- a/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/pom.xml +++ b/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/pom.xml @@ -44,7 +44,12 @@ org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.iot.arduino.service.impl + org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl + war + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl war @@ -94,13 +99,22 @@ org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.iot.arduino.service.impl + org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl war true ${basedir}/src/main/resources/webapps/ arduino.war + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl + + war + true + ${basedir}/src/main/resources/webapps/ + arduino_mgt.war + diff --git a/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/src/main/resources/database/ArduinoDM_DB.h2.db b/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/src/main/resources/database/ArduinoDM_DB.h2.db index 2b5150d83d92c0ebac1cac9bfaad5dc8a5023888..1225be622425b5cf3aa32452237bbbbedd76f69c 100644 GIT binary patch delta 53 mcmZo@U~Fh$T)@Heu)emN0SsiOZ5HHs&pt7L6|3MP2@L?J>klaa delta 53 mcmZo@U~Fh$T)@GT)_VU80~mklaa delta 53 mcmZo@U~Fh$T)@GT)_VU80~maRCQU;;i#(3}7HLbF(1Fd-jO|tXKsXNf-bCkU|b; delta 53 mcmZpez}PT>aRCQUqw2B63}7HqxLJ_nJ^RD}R;+@HBn$wJ{|-d} diff --git a/features/device-mgt-mdm-windows-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/src/main/resources/database/WSO2MobileWindows_DB.h2.db b/features/device-mgt-mdm-windows-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/src/main/resources/database/WSO2MobileWindows_DB.h2.db index 1b6b8cb9545acaab18ce4242ab6401ebf6849ee6..45ff933f76144798564c1054eb46040241bfb6c1 100644 GIT binary patch delta 51 kcmZojXh>MV!IQ6)u$ci2WF~ADMV!SmwAp)U+zAd<0JkmEi3!~j;Tf{P?10MQl@hX4Qo diff --git a/pom.xml b/pom.xml index 025c42a107..2ebfce5d64 100644 --- a/pom.xml +++ b/pom.xml @@ -398,7 +398,18 @@ ${carbon.iot.device.mgt.version} war - + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.arduino.mgt.service.impl + ${carbon.iot.device.mgt.version} + war + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl + ${carbon.iot.device.mgt.version} + war + From 1d302f4353f993254a884720c52389309954b41b Mon Sep 17 00:00:00 2001 From: Shabirmean Date: Wed, 23 Dec 2015 16:15:49 +0530 Subject: [PATCH 4/6] Added the p2 task to create database folder --- .../device/mgt/iot/transport/mqtt/MQTTTransportHandler.java | 4 +++- .../src/main/resources/p2.inf | 1 + .../src/main/resources/p2.inf | 1 + .../src/main/resources/p2.inf | 1 + .../src/main/resources/p2.inf | 1 + .../src/main/resources/p2.inf | 1 + .../src/main/resources/p2.inf | 1 + .../src/main/resources/p2.inf | 1 + .../src/main/resources/p2.inf | 1 + 9 files changed, 11 insertions(+), 1 deletion(-) diff --git a/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/transport/mqtt/MQTTTransportHandler.java b/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/transport/mqtt/MQTTTransportHandler.java index cc8c6b46cd..ed1b454cd3 100644 --- a/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/transport/mqtt/MQTTTransportHandler.java +++ b/components/device-mgt-iot/org.wso2.carbon.device.mgt.iot/src/main/java/org/wso2/carbon/device/mgt/iot/transport/mqtt/MQTTTransportHandler.java @@ -199,7 +199,9 @@ public abstract class MQTTTransportHandler try { //TODO:: QoS Level take it from a variable client.subscribe(subscribeTopic, 0); - log.info("Subscriber '" + clientId + "' subscribed to topic: " + subscribeTopic); + if (log.isDebugEnabled()) { + log.debug("Subscriber '" + clientId + "' subscribed to topic: " + subscribeTopic); + } } catch (MqttException ex) { //TODO:: Compulsory log of errors and remove formatted error String errorMsg = "MQTT Exception when trying to subscribe to topic: " + diff --git a/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/p2.inf b/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/p2.inf index 1fc9b1bf5f..81e14433d9 100644 --- a/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/p2.inf +++ b/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/p2.inf @@ -10,5 +10,6 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/android_sense/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/android_sense/,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\ diff --git a/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/src/main/resources/p2.inf b/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/src/main/resources/p2.inf index 81f3576d03..7bdbcad9c9 100644 --- a/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/src/main/resources/p2.inf +++ b/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/src/main/resources/p2.inf @@ -10,4 +10,5 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.arduino_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.arduino_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.arduino_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\ diff --git a/features/device-mgt-iot-digitaldisplay-feature/org.wso2.carbon.device.mgt.iot.digitaldisplay.feature/src/main/resources/p2.inf b/features/device-mgt-iot-digitaldisplay-feature/org.wso2.carbon.device.mgt.iot.digitaldisplay.feature/src/main/resources/p2.inf index c2a5ee7649..28eb268339 100644 --- a/features/device-mgt-iot-digitaldisplay-feature/org.wso2.carbon.device.mgt.iot.digitaldisplay.feature/src/main/resources/p2.inf +++ b/features/device-mgt-iot-digitaldisplay-feature/org.wso2.carbon.device.mgt.iot.digitaldisplay.feature/src/main/resources/p2.inf @@ -8,4 +8,5 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.digitaldisplay_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.digitaldisplay_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.digitaldisplay_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\ diff --git a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/p2.inf b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/p2.inf index 76c663d420..b5b4a4da3f 100644 --- a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/p2.inf +++ b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/p2.inf @@ -10,4 +10,5 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\ diff --git a/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/p2.inf b/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/p2.inf index 561502c417..7c542593f6 100644 --- a/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/p2.inf +++ b/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/p2.inf @@ -10,4 +10,5 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.raspberrypi_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.raspberrypi_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.raspberrypi_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\ diff --git a/features/device-mgt-iot-virtualfirealarm-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/p2.inf b/features/device-mgt-iot-virtualfirealarm-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/p2.inf index 97090f7c6e..53bbb56f9f 100644 --- a/features/device-mgt-iot-virtualfirealarm-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/p2.inf +++ b/features/device-mgt-iot-virtualfirealarm-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/p2.inf @@ -14,4 +14,5 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\ diff --git a/features/device-mgt-mdm-android-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/p2.inf b/features/device-mgt-mdm-android-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/p2.inf index a30fb7a137..0bc0624e24 100644 --- a/features/device-mgt-mdm-android-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/p2.inf +++ b/features/device-mgt-mdm-android-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/p2.inf @@ -4,4 +4,5 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.android_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.android_${feature.version}/conf/mobile-config.xml,target:${installFolder}/../../conf/mobile-config.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.android_${feature.version}/dbscripts/plugins/,target:${installFolder}/../../../dbscripts/cdm/plugins/android,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.android_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\ diff --git a/features/device-mgt-mdm-windows-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/src/main/resources/p2.inf b/features/device-mgt-mdm-windows-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/src/main/resources/p2.inf index 9b394f853c..f7de186327 100644 --- a/features/device-mgt-mdm-windows-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/src/main/resources/p2.inf +++ b/features/device-mgt-mdm-windows-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/src/main/resources/p2.inf @@ -3,4 +3,5 @@ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../depl org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.windows_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.windows_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.windows_${feature.version}/dbscripts/plugins/,target:${installFolder}/../../../dbscripts/cdm/plugins/windows,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.windows_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\ From f68fc42f35deb38c5440995b30c65a4be50fc3e0 Mon Sep 17 00:00:00 2001 From: GPrathap Date: Wed, 23 Dec 2015 16:35:09 +0530 Subject: [PATCH 5/6] updated Raspberry Pi agent --- .../src/main/resources/agent/src/RaspberryAgent.py | 5 ++--- .../type-view.hbs | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/agent/src/RaspberryAgent.py b/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/agent/src/RaspberryAgent.py index 8242db1bbd..8e502fa251 100755 --- a/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/agent/src/RaspberryAgent.py +++ b/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/agent/src/RaspberryAgent.py @@ -73,7 +73,7 @@ if args.mode: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Endpoint specific settings to which the data is pushed # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -DC_ENDPOINT = iotUtils.APIM_EP.split(":") +DC_ENDPOINT = iotUtils.HTTPS_EP.split(":") DC_IP = DC_ENDPOINT[1].replace('//', '') DC_PORT = int(DC_ENDPOINT[2]) DC_ENDPOINT_CONTEXT = iotUtils.CONTROLLER_CONTEXT @@ -124,8 +124,7 @@ def configureLogger(loggerName): # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def registerDeviceIP(): dcConncection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT) - #dcConncection = httplib.HTTPConnection(DC_IP, DC_PORT) - + #TODO need to get server certificate when initializing https connection dcConncection.set_debuglevel(1) dcConncection.connect() diff --git a/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.type-view/type-view.hbs b/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.type-view/type-view.hbs index 719eb2aba2..d30e896d95 100644 --- a/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.type-view/type-view.hbs +++ b/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.type-view/type-view.hbs @@ -177,9 +177,9 @@

Connect (Quick Start)


Internet of Things Foundation Quickstart connection