diff --git a/.gitignore b/.gitignore
index 717de4fa5a..c469f7d058 100644
--- a/.gitignore
+++ b/.gitignore
@@ -24,4 +24,7 @@ target
hs_err_pid*
# Ignore generated capps
-carbonapps
\ No newline at end of file
+carbonapps
+
+# Ignore generated device-type DBs
+*.h2.db
\ No newline at end of file
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/pom.xml b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/pom.xml
index 6cc5fb57fd..ec4d562bcb 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/pom.xml
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/pom.xml
@@ -163,10 +163,10 @@
${slf4j.version}
-
-
-
-
+
+ org.json.wso2
+ json
+
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/http/FireAlarmHTTPCommunicator.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/http/FireAlarmHTTPCommunicator.java
index 24b3b1f378..bc4a7bfb77 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/http/FireAlarmHTTPCommunicator.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/http/FireAlarmHTTPCommunicator.java
@@ -23,12 +23,12 @@ import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
-import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportHandlerException;
-import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportUtils;
-import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.http.HTTPTransportHandler;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core.AgentConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core.AgentManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.exception.AgentCoreOperationException;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportHandlerException;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportUtils;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.http.HTTPTransportHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -80,13 +80,13 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
processIncomingMessage();
server.start();
registerThisDevice();
- publishDeviceData(AgentManager.getInstance().getPushInterval());
+ publishDeviceData();
log.info("HTTP Server started at port: " + port);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.warn("Unable to 'START' HTTP server. Will retry after " +
- timeoutInterval / 1000 + " seconds.");
+ timeoutInterval / 1000 + " seconds.");
}
}
}
@@ -111,7 +111,7 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
AgentManager agentManager = AgentManager.getInstance();
String pathContext = request.getPathInfo();
- String separator = (File.separatorChar == '\\') ? ("\\\\") : (File.separator);
+ String separator = (File.separatorChar == '\\') ? ("\\\\") : (File.separator);
if (pathContext.toUpperCase().contains(
separator + AgentConstants.TEMPERATURE_CONTROL)) {
@@ -130,7 +130,7 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
if (pathVariables.length != 3) {
httpServletResponse.getWriter().println(
"Invalid BULB-control received by the device. Need to be in " +
- "'{host}:{port}/BULB/{ON|OFF}' format.");
+ "'{host}:{port}/BULB/{ON|OFF}' format.");
return;
}
@@ -144,7 +144,7 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
AgentConstants.CONTROL_ON);
agentManager.changeAlarmStatus(status);
httpServletResponse.getWriter().println("Bulb is " + (status ?
- AgentConstants.CONTROL_ON : AgentConstants.CONTROL_OFF));
+ AgentConstants.CONTROL_ON : AgentConstants.CONTROL_OFF));
}
} else {
httpServletResponse.getWriter().println(
@@ -155,8 +155,9 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
}
@Override
- public void publishDeviceData(int publishInterval) {
+ public void publishDeviceData() {
final AgentManager agentManager = AgentManager.getInstance();
+ int publishInterval = agentManager.getPushInterval();
final String deviceOwner = agentManager.getAgentConfigs().getDeviceOwner();
final String deviceID = agentManager.getAgentConfigs().getDeviceId();
boolean simulationMode = false;
@@ -187,6 +188,7 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
}
}
+
private void executeDataPush(String pushDataPayload) {
AgentManager agentManager = AgentManager.getInstance();
int responseCode = -1;
@@ -197,7 +199,7 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
httpConnection = TransportUtils.getHttpConnection(agentManager.getPushDataAPIEP());
httpConnection.setRequestMethod(AgentConstants.HTTP_POST);
httpConnection.setRequestProperty("Authorization", "Bearer " +
- agentManager.getAgentConfigs().getAuthToken());
+ agentManager.getAgentConfigs().getAuthToken());
httpConnection.setRequestProperty("Content-Type",
AgentConstants.APPLICATION_JSON_TYPE);
@@ -212,50 +214,50 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
httpConnection.disconnect();
log.info(AgentConstants.LOG_APPENDER + "Message - '" + pushDataPayload +
- "' was published to server at: " + httpConnection.getURL());
+ "' was published to server at: " + httpConnection.getURL());
} catch (ProtocolException exception) {
String errorMsg =
"Protocol specific error occurred when trying to set method to " +
- AgentConstants.HTTP_POST + " for:" + pushDataEndPointURL;
+ AgentConstants.HTTP_POST + " for:" + pushDataEndPointURL;
log.error(AgentConstants.LOG_APPENDER + errorMsg);
} catch (IOException exception) {
String errorMsg =
"An IO error occurred whilst trying to get the response code from: " +
- pushDataEndPointURL + " for a " + AgentConstants.HTTP_POST +
- " " + "method.";
+ pushDataEndPointURL + " for a " + AgentConstants.HTTP_POST +
+ " " + "method.";
log.error(AgentConstants.LOG_APPENDER + errorMsg);
} catch (TransportHandlerException exception) {
log.error(AgentConstants.LOG_APPENDER +
- "Error encountered whilst trying to create HTTP-Connection " +
- "to IoT-Server EP at: " +
- pushDataEndPointURL);
+ "Error encountered whilst trying to create HTTP-Connection " +
+ "to IoT-Server EP at: " +
+ pushDataEndPointURL);
}
if (responseCode == HttpStatus.CONFLICT_409 ||
- responseCode == HttpStatus.PRECONDITION_FAILED_412) {
+ responseCode == HttpStatus.PRECONDITION_FAILED_412) {
log.warn(AgentConstants.LOG_APPENDER +
- "DeviceIP is being Re-Registered due to Push-Data failure " +
- "with response code: " +
- responseCode);
+ "DeviceIP is being Re-Registered due to Push-Data failure " +
+ "with response code: " +
+ responseCode);
registerThisDevice();
} else if (responseCode != HttpStatus.NO_CONTENT_204) {
if (log.isDebugEnabled()) {
log.error(AgentConstants.LOG_APPENDER + "Status Code: " + responseCode +
- " encountered whilst trying to Push-Device-Data to IoT " +
- "Server at: " +
- agentManager.getPushDataAPIEP());
+ " encountered whilst trying to Push-Device-Data to IoT " +
+ "Server at: " +
+ agentManager.getPushDataAPIEP());
}
agentManager.updateAgentStatus(AgentConstants.SERVER_NOT_RESPONDING);
}
if (log.isDebugEnabled()) {
log.debug(AgentConstants.LOG_APPENDER + "Push-Data call with payload - " +
- pushDataPayload + ", to IoT Server returned status " +
- responseCode);
+ pushDataPayload + ", to IoT Server returned status " +
+ responseCode);
}
}
@@ -271,15 +273,15 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.warn(AgentConstants.LOG_APPENDER +
- "Unable to 'STOP' HTTP server at port: " + port);
+ "Unable to 'STOP' HTTP server at port: " + port);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
log.error(AgentConstants.LOG_APPENDER +
- "HTTP-Termination: Thread Sleep Interrupt " +
- "Exception");
+ "HTTP-Termination: Thread Sleep Interrupt " +
+ "Exception");
}
}
}
@@ -296,6 +298,10 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
}
+ @Override
+ public void publishDeviceData(String... publishData) {
+
+ }
public void registerThisDevice() {
final AgentManager agentManager = AgentManager.getInstance();
@@ -315,19 +321,19 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
break;
} else {
log.error(AgentConstants.LOG_APPENDER +
- "Device Registration with IoT Server at:" + " " +
- agentManager.getIpRegistrationEP() +
- " failed with response - '" + responseCode + ":" +
- HttpStatus.getMessage(responseCode) + "'");
+ "Device Registration with IoT Server at:" + " " +
+ agentManager.getIpRegistrationEP() +
+ " failed with response - '" + responseCode + ":" +
+ HttpStatus.getMessage(responseCode) + "'");
agentManager.updateAgentStatus(AgentConstants.RETRYING_TO_REGISTER);
}
} catch (AgentCoreOperationException exception) {
log.error(AgentConstants.LOG_APPENDER +
- "Error encountered whilst trying to register the " +
- "Device's IP at: " +
- agentManager.getIpRegistrationEP() +
- ".\nCheck whether the network-interface provided is " +
- "accurate");
+ "Error encountered whilst trying to register the " +
+ "Device's IP at: " +
+ agentManager.getIpRegistrationEP() +
+ ".\nCheck whether the network-interface provided is " +
+ "accurate");
agentManager.updateAgentStatus(AgentConstants.REGISTRATION_FAILED);
}
@@ -335,7 +341,7 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
log.error(AgentConstants.LOG_APPENDER +
- "Device Registration: Thread Sleep Interrupt Exception");
+ "Device Registration: Thread Sleep Interrupt Exception");
}
}
}
@@ -370,7 +376,7 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
if (deviceIPAddress == null) {
throw new AgentCoreOperationException(
"An IP address could not be retrieved for the selected network interface - '" +
- networkInterface + ".");
+ networkInterface + ".");
}
agentManager.setDeviceIP(deviceIPAddress);
@@ -379,11 +385,11 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
String deviceIPRegistrationEP = agentManager.getIpRegistrationEP();
String registerEndpointURLString =
deviceIPRegistrationEP + File.separator + deviceOwner + File.separator + deviceID +
- File.separator + deviceIPAddress + File.separator + port;
+ File.separator + deviceIPAddress + File.separator + port;
if (log.isDebugEnabled()) {
log.debug(AgentConstants.LOG_APPENDER + "DeviceIP Registration EndPoint: " +
- registerEndpointURLString);
+ registerEndpointURLString);
}
HttpURLConnection httpConnection;
@@ -392,8 +398,8 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
} catch (TransportHandlerException e) {
String errorMsg =
"Protocol specific error occurred when trying to fetch an HTTPConnection to:" +
- " " +
- registerEndpointURLString;
+ " " +
+ registerEndpointURLString;
log.error(AgentConstants.LOG_APPENDER + errorMsg);
throw new AgentCoreOperationException();
}
@@ -401,36 +407,36 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
try {
httpConnection.setRequestMethod(AgentConstants.HTTP_POST);
httpConnection.setRequestProperty("Authorization", "Bearer " +
- agentManager.getAgentConfigs().getAuthToken());
+ agentManager.getAgentConfigs().getAuthToken());
httpConnection.setDoOutput(true);
responseCode = httpConnection.getResponseCode();
} catch (ProtocolException exception) {
String errorMsg = "Protocol specific error occurred when trying to set method to " +
- AgentConstants.HTTP_POST + " for:" + registerEndpointURLString;
+ AgentConstants.HTTP_POST + " for:" + registerEndpointURLString;
log.error(AgentConstants.LOG_APPENDER + errorMsg);
throw new AgentCoreOperationException(errorMsg, exception);
} catch (IOException exception) {
String errorMsg = "An IO error occurred whilst trying to get the response code from:" +
- " " +
- registerEndpointURLString + " for a " + AgentConstants.HTTP_POST + " method.";
+ " " +
+ registerEndpointURLString + " for a " + AgentConstants.HTTP_POST + " method.";
log.error(AgentConstants.LOG_APPENDER + errorMsg);
throw new AgentCoreOperationException(errorMsg, exception);
}
log.info(AgentConstants.LOG_APPENDER + "DeviceIP - " + deviceIPAddress +
- ", registration with IoT Server at : " +
- agentManager.getAgentConfigs().getHTTPS_ServerEndpoint() +
- " returned status " +
- responseCode);
+ ", registration with IoT Server at : " +
+ agentManager.getAgentConfigs().getHTTPS_ServerEndpoint() +
+ " returned status " +
+ responseCode);
return responseCode;
}
/*------------------------------------------------------------------------------------------*/
/* Utility methods relevant to creating and sending HTTP requests to the Iot-Server */
- /*------------------------------------------------------------------------------------------*/
+ /*------------------------------------------------------------------------------------------*/
/**
* This method is used to get the IP of the device in which the agent is run on.
@@ -477,8 +483,8 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler {
} catch (SocketException | NullPointerException exception) {
String errorMsg =
"Error encountered whilst trying to get IP Addresses of the network interface: " +
- networkInterfaceName +
- ".\nPlease check whether the name of the network interface used is correct";
+ networkInterfaceName +
+ ".\nPlease check whether the name of the network interface used is correct";
log.error(AgentConstants.LOG_APPENDER + errorMsg);
throw new AgentCoreOperationException(errorMsg, exception);
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java
index 255f71adb2..7ce6622f8c 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java
@@ -25,10 +25,11 @@ 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.virtualfirealarm.agent.advanced.core.AgentConstants;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core.AgentManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core.AgentUtilOperations;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.exception.AgentCoreOperationException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.mqtt.MQTTTransportHandler;
-import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core.AgentManager;
import java.io.File;
import java.io.FileOutputStream;
@@ -52,6 +53,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
super(deviceOwner, deviceType, mqttBrokerEndPoint, subscribeTopic);
}
+ @SuppressWarnings("unused")
public FireAlarmMQTTCommunicator(String deviceOwner, String deviceType,
String mqttBrokerEndPoint, String subscribeTopic,
int intervalInMillis) {
@@ -62,6 +64,8 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
return dataPushServiceHandler;
}
+ //TODO:: Terminate logs with a period
+ //TODO: Need to print exceptions
@Override
public void connect() {
final AgentManager agentManager = AgentManager.getInstance();
@@ -70,21 +74,27 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
while (!isConnected()) {
try {
connectToQueue();
- subscribeToQueue();
agentManager.updateAgentStatus("Connected to MQTT Queue");
- publishDeviceData(agentManager.getPushInterval());
+ } catch (TransportHandlerException e) {
+ log.warn(AgentConstants.LOG_APPENDER + "Connection to MQTT Broker at: " + mqttBrokerEndPoint +
+ " failed.\n Will retry in " + timeoutInterval + " milli-seconds.");
+ }
+
+ try {
+ subscribeToQueue();
+ agentManager.updateAgentStatus("Subscribed to MQTT Queue");
+ publishDeviceData();
} catch (TransportHandlerException e) {
- log.warn(AgentConstants.LOG_APPENDER +
- "Connection/Subscription to MQTT Broker at: " +
+ log.warn(AgentConstants.LOG_APPENDER + "Subscription to MQTT Broker at: " +
mqttBrokerEndPoint + " failed");
+ agentManager.updateAgentStatus("Subscription to broker failed.");
+ }
- try {
- Thread.sleep(timeoutInterval);
- } catch (InterruptedException ex) {
- log.error(AgentConstants.LOG_APPENDER +
- "MQTT-Subscriber: Thread Sleep Interrupt Exception");
- }
+ try {
+ Thread.sleep(timeoutInterval);
+ } catch (InterruptedException ex) {
+ log.error(AgentConstants.LOG_APPENDER + "MQTT: Connect-Thread Sleep Interrupt Exception.");
}
}
}
@@ -95,121 +105,130 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
connectorThread.start();
}
+
@Override
public void processIncomingMessage(MqttMessage message, String... messageParams) {
final AgentManager agentManager = AgentManager.getInstance();
- log.info(AgentConstants.LOG_APPENDER + "Message " + message.toString() + " was received");
-
+ String serverName = agentManager.getAgentConfigs().getServerName();
String deviceOwner = agentManager.getAgentConfigs().getDeviceOwner();
String deviceID = agentManager.getAgentConfigs().getDeviceId();
+ String receivedMessage;
String replyMessage;
+ String securePayLoad;
- String[] controlSignal = message.toString().split(":");
-// log.info("########## Incoming Message : " + controlSignal[0]);
- // message- ":" format.(ex: "BULB:ON", "TEMPERATURE", "HUMIDITY")
-
-
- if (isJSONValid(message.toString())) {
- JsonObject jobj = new Gson().fromJson(message.toString(), JsonObject.class);
- String type = jobj.get("type").toString();
-
- if (type.equalsIgnoreCase("\"policy\"")) {
- String content = jobj.get("content").toString();
- updatePolicy(content);
- }
- } else {
- switch (controlSignal[0].toUpperCase()) {
- case AgentConstants.BULB_CONTROL:
- boolean stateToSwitch = controlSignal[1].equals(AgentConstants.CONTROL_ON);
-
- agentManager.changeAlarmStatus(stateToSwitch);
- log.info(AgentConstants.LOG_APPENDER + "Bulb was switched to state: '" + controlSignal[1] + "'");
- break;
-
- case AgentConstants.TEMPERATURE_CONTROL:
- int currentTemperature = agentManager.getTemperature();
-
- String replyTemperature = "Current temperature was read as: '" + currentTemperature + "C'";
- log.info(AgentConstants.LOG_APPENDER + replyTemperature);
-
- String tempPublishTopic = String.format(
- AgentConstants.MQTT_PUBLISH_TOPIC, deviceOwner, deviceID);
- replyMessage = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature;
-
- try {
- publishToQueue(tempPublishTopic, replyMessage);
- } catch (TransportHandlerException e) {
- log.error(AgentConstants.LOG_APPENDER +
- "MQTT - Publishing, reply message to the MQTT Queue at: " +
- agentManager.getAgentConfigs().getMqttBrokerEndpoint() + " failed");
- }
- break;
-
- case AgentConstants.HUMIDITY_CONTROL:
- int currentHumidity = agentManager.getHumidity();
+ try {
+ receivedMessage = AgentUtilOperations.extractMessageFromPayload(message.toString());
+ log.info(AgentConstants.LOG_APPENDER + "Message [" + receivedMessage + "] was received");
+ } catch (AgentCoreOperationException e) {
+ log.warn(AgentConstants.LOG_APPENDER + "Could not extract message from payload.", e);
+ return;
+ }
- String replyHumidity = "Current humidity was read as: '" + currentHumidity + "%'";
- log.info(AgentConstants.LOG_APPENDER + replyHumidity);
- String humidPublishTopic = String.format(
- AgentConstants.MQTT_PUBLISH_TOPIC, deviceOwner, deviceID);
- replyMessage = AgentConstants.HUMIDITY_CONTROL + ":" + currentHumidity;
+ String[] controlSignal = receivedMessage.split(":");
+ // message- ":" format.(ex: "BULB:ON", "TEMPERATURE", "HUMIDITY")
- try {
- publishToQueue(humidPublishTopic, replyMessage);
- } catch (TransportHandlerException e) {
- log.error(AgentConstants.LOG_APPENDER +
- "MQTT - Publishing, reply message to the MQTT Queue at: " +
- agentManager.getAgentConfigs().getMqttBrokerEndpoint() + " failed");
- }
- break;
+ try {
+ if (isJSONValid(receivedMessage)) {
+ JsonObject jobj = new Gson().fromJson(receivedMessage, JsonObject.class);
+ String type = jobj.get("type").toString();
- default:
- log.warn(AgentConstants.LOG_APPENDER + "'" + controlSignal[0] +
- "' is invalid and not-supported for this device-type");
- break;
+ if (type.equalsIgnoreCase("\"policy\"")) {
+ String content = jobj.get("content").toString();
+ updatePolicy(content);
+ }
+ } else {
+ switch (controlSignal[0].toUpperCase()) {
+ case AgentConstants.BULB_CONTROL:
+ boolean stateToSwitch = controlSignal[1].equals(AgentConstants.CONTROL_ON);
+ agentManager.changeAlarmStatus(stateToSwitch);
+ log.info(
+ AgentConstants.LOG_APPENDER + "Bulb was switched to state: '" + controlSignal[1] + "'");
+ break;
+
+ case AgentConstants.TEMPERATURE_CONTROL:
+ int currentTemperature = agentManager.getTemperature();
+
+ String replyTemperature = "Current temperature was read as: '" + currentTemperature + "C'";
+ log.info(AgentConstants.LOG_APPENDER + replyTemperature);
+
+ String tempPublishTopic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC,
+ serverName, deviceOwner, deviceID);
+
+ replyMessage = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature;
+ securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage);
+ publishToQueue(tempPublishTopic, securePayLoad);
+ break;
+
+ case AgentConstants.HUMIDITY_CONTROL:
+ int currentHumidity = agentManager.getHumidity();
+
+ String replyHumidity = "Current humidity was read as: '" + currentHumidity + "%'";
+ log.info(AgentConstants.LOG_APPENDER + replyHumidity);
+
+ String humidPublishTopic = String.format(
+ AgentConstants.MQTT_PUBLISH_TOPIC, serverName, deviceOwner, deviceID);
+
+ replyMessage = AgentConstants.HUMIDITY_CONTROL + ":" + currentHumidity;
+ securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage);
+ publishToQueue(humidPublishTopic, securePayLoad);
+ break;
+
+ default:
+ log.warn(AgentConstants.LOG_APPENDER + "'" + controlSignal[0] +
+ "' is invalid and not-supported for this device-type");
+ break;
+ }
}
+ } catch (AgentCoreOperationException e) {
+ log.warn(AgentConstants.LOG_APPENDER + "Preparing Secure payload failed", e);
+ } catch (TransportHandlerException e) {
+ log.error(AgentConstants.LOG_APPENDER +
+ "MQTT - Publishing, reply message to the MQTT Queue at: " +
+ agentManager.getAgentConfigs().getMqttBrokerEndpoint() + " failed");
}
- }
+ }
@Override
- public void publishDeviceData(int publishInterval) {
+ public void publishDeviceData() {
final AgentManager agentManager = AgentManager.getInstance();
+ int publishInterval = agentManager.getPushInterval();
Runnable pushDataRunnable = new Runnable() {
@Override
public void run() {
int currentTemperature = agentManager.getTemperature();
- String payLoad =
- "PUBLISHER:" + AgentConstants.TEMPERATURE_CONTROL + ":" +
- currentTemperature;
+ String message = "PUBLISHER:" + AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature;
- MqttMessage pushMessage = new MqttMessage();
- pushMessage.setPayload(payLoad.getBytes(StandardCharsets.UTF_8));
- pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);
- pushMessage.setRetained(true);
+ try {
+ String payLoad = AgentUtilOperations.prepareSecurePayLoad(message);
- String topic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC,
- agentManager.getAgentConfigs().getDeviceOwner(),
- agentManager.getAgentConfigs().getDeviceId());
+ MqttMessage pushMessage = new MqttMessage();
+ pushMessage.setPayload(payLoad.getBytes(StandardCharsets.UTF_8));
+ pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);
+ pushMessage.setRetained(false);
+
+ String topic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC,
+ agentManager.getAgentConfigs().getServerName(),
+ agentManager.getAgentConfigs().getDeviceOwner(),
+ agentManager.getAgentConfigs().getDeviceId());
- try {
publishToQueue(topic, pushMessage);
- log.info(AgentConstants.LOG_APPENDER + "Message: '" + pushMessage +
- "' published to MQTT Queue at [" +
- agentManager.getAgentConfigs().getMqttBrokerEndpoint() +
- "] under topic [" + topic + "]");
+ log.info(AgentConstants.LOG_APPENDER + "Message: '" + message + "' published to MQTT Queue at [" +
+ agentManager.getAgentConfigs().getMqttBrokerEndpoint() + "] under topic [" +
+ topic + "]");
} catch (TransportHandlerException e) {
log.warn(AgentConstants.LOG_APPENDER + "Data Publish attempt to topic - [" +
- AgentConstants.MQTT_PUBLISH_TOPIC + "] failed for payload [" +
- payLoad + "]");
+ AgentConstants.MQTT_PUBLISH_TOPIC + "] failed for payload [" + message + "]");
+ } catch (AgentCoreOperationException e) {
+ log.warn(AgentConstants.LOG_APPENDER + "Preparing Secure payload failed", e);
}
}
};
- dataPushServiceHandler = service.scheduleAtFixedRate(pushDataRunnable, publishInterval,
- publishInterval, TimeUnit.SECONDS);
+ dataPushServiceHandler = service.scheduleAtFixedRate(pushDataRunnable, publishInterval, publishInterval,
+ TimeUnit.SECONDS);
}
@@ -218,8 +237,12 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
Runnable stopConnection = new Runnable() {
public void run() {
while (isConnected()) {
- try {
+
+ if (dataPushServiceHandler != null) {
dataPushServiceHandler.cancel(true);
+ }
+
+ try {
closeConnection();
} catch (MqttException e) {
@@ -250,6 +273,10 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
}
+ @Override
+ public void publishDeviceData(String... publishData) {
+
+ }
private boolean isJSONValid(String JSON_STRING) {
try {
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/xmpp/FireAlarmXMPPCommunicator.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/xmpp/FireAlarmXMPPCommunicator.java
index 76a115072d..55c3cf1d08 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/xmpp/FireAlarmXMPPCommunicator.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/xmpp/FireAlarmXMPPCommunicator.java
@@ -21,10 +21,12 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.communica
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.packet.Message;
-import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.xmpp.XMPPTransportHandler;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core.AgentConstants;
-import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core.AgentManager;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core.AgentUtilOperations;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.exception.AgentCoreOperationException;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportHandlerException;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.xmpp.XMPPTransportHandler;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@@ -69,7 +71,7 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
resource = agentManager.getAgentConfigs().getDeviceOwner();
xmppDeviceJID = username + "@" + server;
- xmppAdminJID = AgentConstants.XMPP_ADMIN_ACCOUNT_UNAME + "@" + server;
+ xmppAdminJID = agentManager.getAgentConfigs().getServerName() + "_" + AgentConstants.DEVICE_TYPE + "@" + server;
Runnable connect = new Runnable() {
@@ -77,25 +79,24 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
if (!isConnected()) {
try {
connectToServer();
+ } catch (TransportHandlerException e) {
+ log.warn(AgentConstants.LOG_APPENDER + "Connection to XMPP server at: " + server + " failed");
+ }
+
+ try {
loginToServer(username, password, resource);
agentManager.updateAgentStatus("Connected to XMPP Server");
-
setMessageFilterAndListener(xmppAdminJID, xmppDeviceJID, true);
- publishDeviceData(agentManager.getPushInterval());
-
+ publishDeviceData();
} catch (TransportHandlerException e) {
- if (log.isDebugEnabled()) {
- log.warn(AgentConstants.LOG_APPENDER +
- "Connection/Login to XMPP server at: " + server +
- " failed");
- }
+ log.warn(AgentConstants.LOG_APPENDER + "Login to XMPP server at: " + server + " failed");
+ agentManager.updateAgentStatus("No XMPP Account for Device");
}
}
}
};
- connectorServiceHandler = service.scheduleAtFixedRate(connect, 0, timeoutInterval,
- TimeUnit.MILLISECONDS);
+ connectorServiceHandler = service.scheduleAtFixedRate(connect, 0, timeoutInterval, TimeUnit.MILLISECONDS);
}
/**
@@ -110,81 +111,102 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
final AgentManager agentManager = AgentManager.getInstance();
String from = xmppMessage.getFrom();
String message = xmppMessage.getBody();
- log.info(AgentConstants.LOG_APPENDER + "Received XMPP message [" + message + "] from " +
- from);
-
+ String receivedMessage;
String replyMessage;
- String[] controlSignal = message.split(":");
+ String securePayLoad;
+
+ try {
+ receivedMessage = AgentUtilOperations.extractMessageFromPayload(message);
+ log.info(AgentConstants.LOG_APPENDER + "Message [" + receivedMessage + "] was received");
+ } catch (AgentCoreOperationException e) {
+ log.warn(AgentConstants.LOG_APPENDER + "Could not extract message from payload.", e);
+ return;
+ }
+
+ String[] controlSignal = receivedMessage.split(":");
//message- ":" format. (ex: "BULB:ON", "TEMPERATURE", "HUMIDITY")
+ try {
+ switch (controlSignal[0].toUpperCase()) {
+ case AgentConstants.BULB_CONTROL:
+ if (controlSignal.length != 2) {
+ replyMessage = "BULB controls need to be in the form - 'BULB:{ON|OFF}'";
+ log.warn(replyMessage);
+ securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage);
+ sendXMPPMessage(xmppAdminJID, securePayLoad, "CONTROL-REPLY");
+ break;
+ }
- switch (controlSignal[0].toUpperCase()) {
- case AgentConstants.BULB_CONTROL:
- if (controlSignal.length != 2) {
- replyMessage = "BULB controls need to be in the form - 'BULB:{ON|OFF}'";
- log.warn(replyMessage);
- sendXMPPMessage(xmppAdminJID, replyMessage, "CONTROL-REPLY");
+ agentManager.changeAlarmStatus(controlSignal[1].equals(AgentConstants.CONTROL_ON));
+ log.info(AgentConstants.LOG_APPENDER + "Bulb was switched to state: '" + controlSignal[1] + "'");
break;
- }
- agentManager.changeAlarmStatus(controlSignal[1].equals(AgentConstants.CONTROL_ON));
- log.info(AgentConstants.LOG_APPENDER + "Bulb was switched to state: '" +
- controlSignal[1] + "'");
- break;
+ case AgentConstants.TEMPERATURE_CONTROL:
+ int currentTemperature = agentManager.getTemperature();
- case AgentConstants.TEMPERATURE_CONTROL:
- int currentTemperature = agentManager.getTemperature();
+ String replyTemperature =
+ "The current temperature was read to be: '" + currentTemperature +
+ "C'";
+ log.info(AgentConstants.LOG_APPENDER + replyTemperature);
- String replyTemperature =
- "The current temperature was read to be: '" + currentTemperature +
- "C'";
- log.info(AgentConstants.LOG_APPENDER + replyTemperature);
-
- replyMessage = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature;
- sendXMPPMessage(xmppAdminJID, replyMessage, "CONTROL-REPLY");
- break;
+ replyMessage = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature;
+ securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage);
+ sendXMPPMessage(xmppAdminJID, securePayLoad, "CONTROL-REPLY");
+ break;
- case AgentConstants.HUMIDITY_CONTROL:
- int currentHumidity = agentManager.getHumidity();
+ case AgentConstants.HUMIDITY_CONTROL:
+ int currentHumidity = agentManager.getHumidity();
- String replyHumidity =
- "The current humidity was read to be: '" + currentHumidity + "%'";
- log.info(AgentConstants.LOG_APPENDER + replyHumidity);
+ String replyHumidity = "The current humidity was read to be: '" + currentHumidity + "%'";
+ log.info(AgentConstants.LOG_APPENDER + replyHumidity);
- replyMessage = AgentConstants.HUMIDITY_CONTROL + ":" + currentHumidity;
- sendXMPPMessage(xmppAdminJID, replyMessage, "CONTROL-REPLY");
- break;
+ replyMessage = AgentConstants.HUMIDITY_CONTROL + ":" + currentHumidity;
+ securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage);
+ sendXMPPMessage(xmppAdminJID, securePayLoad, "CONTROL-REPLY");
+ break;
- default:
- replyMessage = "'" + controlSignal[0] +
- "' is invalid and not-supported for this device-type";
- log.warn(replyMessage);
- sendXMPPMessage(xmppAdminJID, replyMessage, "CONTROL-ERROR");
- break;
+ default:
+ replyMessage = "'" + controlSignal[0] + "' is invalid and not-supported for this device-type";
+ log.warn(replyMessage);
+ securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage);
+ sendXMPPMessage(xmppAdminJID, securePayLoad, "CONTROL-ERROR");
+ break;
+ }
+ } catch (AgentCoreOperationException e) {
+ log.warn(AgentConstants.LOG_APPENDER + "Preparing Secure payload failed", e);
}
}
+
@Override
- public void publishDeviceData(int publishInterval) {
+ public void publishDeviceData() {
final AgentManager agentManager = AgentManager.getInstance();
+ int publishInterval = agentManager.getPushInterval();
Runnable pushDataRunnable = new Runnable() {
@Override
public void run() {
- int currentTemperature = agentManager.getTemperature();
- String payLoad = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature;
-
Message xmppMessage = new Message();
- xmppMessage.setTo(xmppAdminJID);
- xmppMessage.setSubject("PUBLISHER");
- xmppMessage.setBody(payLoad);
- xmppMessage.setType(Message.Type.chat);
-
- sendXMPPMessage(xmppAdminJID, xmppMessage);
- log.info(AgentConstants.LOG_APPENDER + "Message: '" + xmppMessage.getBody() +
- "' sent to XMPP JID [" + xmppAdminJID + "] under subject [" +
- xmppMessage.getSubject() + "]");
+
+ try {
+ int currentTemperature = agentManager.getTemperature();
+
+ String message = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature;
+ String payLoad = AgentUtilOperations.prepareSecurePayLoad(message);
+
+ xmppMessage.setTo(xmppAdminJID);
+ xmppMessage.setSubject("PUBLISHER");
+ xmppMessage.setBody(payLoad);
+ xmppMessage.setType(Message.Type.chat);
+
+ sendXMPPMessage(xmppAdminJID, xmppMessage);
+ log.info(AgentConstants.LOG_APPENDER + "Message: '" + message + "' sent to XMPP JID - " +
+ "[" + xmppAdminJID + "] under subject [" + xmppMessage.getSubject() + "].");
+ } catch (AgentCoreOperationException e) {
+ log.warn(AgentConstants.LOG_APPENDER + "Preparing Secure payload failed for XMPP JID - " +
+ "[" + xmppAdminJID + "] with subject - [" + xmppMessage.getSubject() + "].");
+ }
}
};
@@ -197,22 +219,27 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
public void disconnect() {
Runnable stopConnection = new Runnable() {
public void run() {
- while (isConnected()) {
+
+ if (dataPushServiceHandler != null) {
dataPushServiceHandler.cancel(true);
+ }
+
+ if (connectorServiceHandler != null) {
connectorServiceHandler.cancel(true);
+ }
+
+ while (isConnected()) {
closeConnection();
if (log.isDebugEnabled()) {
log.warn(AgentConstants.LOG_APPENDER +
- "Unable to 'STOP' connection to XMPP server at: " +
- server);
+ "Unable to 'STOP' connection to XMPP server at: " + server);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
- log.error(AgentConstants.LOG_APPENDER +
- "XMPP-Terminator: Thread Sleep Interrupt Exception");
+ log.error(AgentConstants.LOG_APPENDER + "XMPP-Terminator: Thread Sleep Interrupt Exception");
}
}
@@ -224,8 +251,15 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
terminatorThread.start();
}
+
@Override
public void processIncomingMessage() {
}
+
+ @Override
+ public void publishDeviceData(String... publishData) {
+
+ }
+
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConfiguration.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConfiguration.java
index 9b4006aaf0..49e437cc16 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConfiguration.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConfiguration.java
@@ -24,6 +24,7 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core;
* downloading the device agent from the IoT-Server.
*/
public class AgentConfiguration {
+ private String serverName;
private String deviceOwner;
private String deviceId;
private String deviceName;
@@ -38,6 +39,14 @@ public class AgentConfiguration {
private String refreshToken;
private int dataPushInterval;
+ public String getServerName() {
+ return serverName;
+ }
+
+ public void setServerName(String serverName) {
+ this.serverName = serverName;
+ }
+
public String getDeviceOwner() {
return deviceOwner;
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java
index f8cce50785..b491b8e5db 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java
@@ -18,12 +18,6 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
public class AgentConstants {
public static final String DEVICE_TYPE = "virtual_firealarm";
public static final String LOG_APPENDER = "AGENT_LOG:: ";
@@ -33,6 +27,7 @@ public class AgentConstants {
IoT-Server specific information
--------------------------------------------------------------------------------------- */
public static final String DEVICE_CONTROLLER_API_EP = "/virtual_firealarm/controller";
+ public static final String DEVICE_ENROLLMENT_API_EP = "/scep";
public static final String DEVICE_REGISTER_API_EP = "/register";
public static final String DEVICE_PUSH_TEMPERATURE_API_EP = "/push_temperature";
public static final String PUSH_DATA_PAYLOAD =
@@ -41,10 +36,9 @@ public class AgentConstants {
public static final String PUSH_SIMULATION_DATA_PAYLOAD =
"{\"owner\":\"%s\",\"deviceId\":\"%s\",\"reply\":\"%s\",\"value\":\"%s\",\"isSimulated\":\"%s\",\"duration\":\"%s\",\"frequency\":\"%s\"}";
- public static final String AGENT_CONTROL_APP_EP = "/firealarm-webapp";
- public static final String DEVICE_DETAILS_PAGE_EP = "/store/pages/device/%s/%s";
- public static final String DEVICE_ANALYTICS_PAGE_URL =
- "/store/pages/analytics?deviceId=%s&deviceType=%s";
+ public static final String AGENT_CONTROL_APP_EP = "/devicemgt/device/%s?id=%s";
+ public static final String DEVICE_DETAILS_PAGE_EP = "/devicemgt/device/%s?id=%s";
+ public static final String DEVICE_ANALYTICS_PAGE_URL = "/devicemgt/analytics?deviceId=%s&deviceType=%s&deviceName=%s";
/* ---------------------------------------------------------------------------------------
HTTP Connection specific information for communicating with IoT-Server
--------------------------------------------------------------------------------------- */
@@ -62,8 +56,8 @@ public class AgentConstants {
--------------------------------------------------------------------------------------- */
public static final int DEFAULT_MQTT_RECONNECTION_INTERVAL = 2; // time in seconds
public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0;
- public static final String MQTT_SUBSCRIBE_TOPIC = "wso2/iot/%s/" + DEVICE_TYPE + "/%s";
- public static final String MQTT_PUBLISH_TOPIC = "wso2/iot/%s/" + DEVICE_TYPE + "/%s/publisher";
+ public static final String MQTT_SUBSCRIBE_TOPIC = "%s/%s/" + DEVICE_TYPE + "/%s";
+ public static final String MQTT_PUBLISH_TOPIC = "%s/%s/" + DEVICE_TYPE + "/%s/publisher";
/* ---------------------------------------------------------------------------------------
XMPP Connection specific information
--------------------------------------------------------------------------------------- */
@@ -72,6 +66,7 @@ public class AgentConstants {
Device/Agent specific properties to be read from the 'deviceConfig.properties' file
--------------------------------------------------------------------------------------- */
public static final String AGENT_PROPERTIES_FILE_NAME = "deviceConfig.properties";
+ public static final String SERVER_NAME_PROPERTY = "server-name";
public static final String DEVICE_OWNER_PROPERTY = "owner";
public static final String DEVICE_ID_PROPERTY = "deviceId";
public static final String DEVICE_NAME_PROPERTY = "device-name";
@@ -89,6 +84,7 @@ public class AgentConstants {
/* ---------------------------------------------------------------------------------------
Default values for the Device/Agent specific configurations listed above
--------------------------------------------------------------------------------------- */
+ public static final String DEFAULT_SERVER_NAME = "WSO2IoTServer";
public static final String DEFAULT_DEVICE_OWNER = "admin";
public static final String DEFAULT_DEVICE_ID = "1234567890";
public static final String DEFAULT_DEVICE_NAME = "admin_1234567890";
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java
index 8207439b93..24826b5b9c 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java
@@ -20,15 +20,15 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.communication.http.FireAlarmHTTPCommunicator;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.communication.mqtt.FireAlarmMQTTCommunicator;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.communication.xmpp.FireAlarmXMPPCommunicator;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.enrollment.EnrollmentManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.exception.AgentCoreOperationException;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.sidhdhi.SidhdhiQuery;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportHandler;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportUtils;
-import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.sidhdhi.SidhdhiQuery;
-import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.communication.http.FireAlarmHTTPCommunicator;
-import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.communication.mqtt.FireAlarmMQTTCommunicator;
-import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.communication.xmpp.FireAlarmXMPPCommunicator;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.virtual.VirtualHardwareManager;
import java.nio.charset.StandardCharsets;
@@ -97,11 +97,12 @@ public class AgentManager {
this.agentConfigs = AgentUtilOperations.readIoTServerConfigs();
// Initialise IoT-Server URL endpoints from the configuration read from file
- AgentUtilOperations.initializeHTTPEndPoints();
+ AgentUtilOperations.initializeServerEndPoints();
String analyticsPageContext = String.format(AgentConstants.DEVICE_ANALYTICS_PAGE_URL,
agentConfigs.getDeviceId(),
- AgentConstants.DEVICE_TYPE);
+ AgentConstants.DEVICE_TYPE,
+ agentConfigs.getDeviceName());
String controlPageContext = String.format(AgentConstants.DEVICE_DETAILS_PAGE_EP,
AgentConstants.DEVICE_TYPE,
@@ -121,28 +122,29 @@ public class AgentManager {
Map xmppIPPortMap;
try {
- xmppIPPortMap = TransportUtils.getHostAndPort(agentConfigs.getXmppServerEndpoint
- ());
-
+ xmppIPPortMap = TransportUtils.getHostAndPort(agentConfigs.getXmppServerEndpoint());
String xmppServer = xmppIPPortMap.get("Host");
int xmppPort = Integer.parseInt(xmppIPPortMap.get("Port"));
+
TransportHandler xmppCommunicator = new FireAlarmXMPPCommunicator(xmppServer, xmppPort);
agentCommunicator.put(AgentConstants.XMPP_PROTOCOL, xmppCommunicator);
} catch (TransportHandlerException e) {
log.error("XMPP Endpoint String - " + agentConfigs.getXmppServerEndpoint() +
- ", provided in the configuration file is invalid.");
+ ", provided in the configuration file is invalid.");
}
String mqttTopic = String.format(AgentConstants.MQTT_SUBSCRIBE_TOPIC,
+ agentConfigs.getServerName(),
agentConfigs.getDeviceOwner(),
agentConfigs.getDeviceId());
- TransportHandler httpCommunicator = new FireAlarmHTTPCommunicator();
- TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(
- agentConfigs.getDeviceOwner(), agentConfigs.getDeviceId(),
- agentConfigs.getMqttBrokerEndpoint(), mqttTopic);
+// TransportHandler httpCommunicator = new FireAlarmHTTPCommunicator();
+ TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(agentConfigs.getDeviceOwner(),
+ agentConfigs.getDeviceId(),
+ agentConfigs.getMqttBrokerEndpoint(),
+ mqttTopic);
- agentCommunicator.put(AgentConstants.HTTP_PROTOCOL, httpCommunicator);
+// agentCommunicator.put(AgentConstants.HTTP_PROTOCOL, httpCommunicator);
agentCommunicator.put(AgentConstants.MQTT_PROTOCOL, mqttCommunicator);
try {
@@ -169,9 +171,6 @@ public class AgentManager {
}
}
- //Start agent communication
- agentCommunicator.get(protocol).connect();
-
try {
EnrollmentManager.getInstance().beginEnrollmentFlow();
} catch (AgentCoreOperationException e) {
@@ -179,6 +178,9 @@ public class AgentManager {
e.printStackTrace();
System.exit(0);
}
+
+ //Start agent communication
+ agentCommunicator.get(protocol).connect();
}
private void switchCommunicator(String stopProtocol, String startProtocol) {
@@ -189,7 +191,7 @@ public class AgentManager {
Thread.sleep(250);
} catch (InterruptedException e) {
log.info(AgentConstants.LOG_APPENDER +
- "Sleep error in 'Switch-Communicator' Thread's shutdown wait.");
+ "Sleep error in 'Switch-Communicator' Thread's shutdown wait.");
}
}
@@ -242,7 +244,7 @@ public class AgentManager {
/*------------------------------------------------------------------------------------------*/
/* Getter and Setter Methods for the private variables */
- /*------------------------------------------------------------------------------------------*/
+ /*------------------------------------------------------------------------------------------*/
public void setRootPath(String rootPath) {
this.rootPath = rootPath;
@@ -336,7 +338,7 @@ public class AgentManager {
default:
log.warn("Unknown protocol " + protocol);
}
- transportHandler.publishDeviceData(pushInterval);
+ transportHandler.publishDeviceData();
if (log.isDebugEnabled()) {
log.debug("The Data Publish Interval was changed to: " + pushInterval);
@@ -353,6 +355,7 @@ public class AgentManager {
/**
* Get temperature reading from device
+ *
* @return Temperature
*/
public int getTemperature() {
@@ -361,9 +364,10 @@ public class AgentManager {
/**
* Get humidity reading from device
+ *
* @return Humidity
*/
- public int getHumidity(){
+ public int getHumidity() {
return VirtualHardwareManager.getInstance().getHumidity();
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java
index 92ce9265ba..d192b5c846 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java
@@ -20,13 +20,19 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.json.JSONObject;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.enrollment.EnrollmentManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.exception.AgentCoreOperationException;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.CommunicationUtils;
+import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.TransportHandlerException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
+import java.security.PrivateKey;
+import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Properties;
@@ -39,6 +45,8 @@ import java.util.Properties;
public class AgentUtilOperations {
private static final Log log = LogFactory.getLog(AgentUtilOperations.class);
+ private static final String JSON_MESSAGE_KEY = "Msg";
+ private static final String JSON_SIGNATURE_KEY = "Sig";
/**
* This method reads the agent specific configurations for the device from the
@@ -72,6 +80,8 @@ public class AgentUtilOperations {
//load a properties file from class path, inside static method
properties.load(propertiesInputStream);
+ iotServerConfigs.setServerName(properties.getProperty(
+ AgentConstants.SERVER_NAME_PROPERTY));
iotServerConfigs.setDeviceOwner(properties.getProperty(
AgentConstants.DEVICE_OWNER_PROPERTY));
iotServerConfigs.setDeviceId(properties.getProperty(
@@ -99,6 +109,8 @@ public class AgentUtilOperations {
iotServerConfigs.setDataPushInterval(Integer.parseInt(properties.getProperty(
AgentConstants.PUSH_INTERVAL_PROPERTY)));
+ log.info(AgentConstants.LOG_APPENDER + "Server name: " +
+ iotServerConfigs.getServerName());
log.info(AgentConstants.LOG_APPENDER + "Device Owner: " +
iotServerConfigs.getDeviceOwner());
log.info(AgentConstants.LOG_APPENDER + "Device ID: " + iotServerConfigs.getDeviceId());
@@ -142,9 +154,8 @@ public class AgentUtilOperations {
propertiesInputStream.close();
} catch (IOException e) {
log.error(AgentConstants.LOG_APPENDER +
- "Error occurred whilst trying to close InputStream " +
- "resource used to read the '" + propertiesFileName +
- "' file");
+ "Error occurred whilst trying to close InputStream resource used to read the '" +
+ propertiesFileName + "' file");
}
}
}
@@ -162,6 +173,7 @@ public class AgentUtilOperations {
AgentConfiguration iotServerConfigs = new AgentConfiguration();
+ iotServerConfigs.setDeviceOwner(AgentConstants.DEFAULT_SERVER_NAME);
iotServerConfigs.setDeviceOwner(AgentConstants.DEFAULT_DEVICE_OWNER);
iotServerConfigs.setDeviceId(AgentConstants.DEFAULT_DEVICE_ID);
iotServerConfigs.setDeviceName(AgentConstants.DEFAULT_DEVICE_NAME);
@@ -188,12 +200,17 @@ public class AgentUtilOperations {
* retrieve the deviceIP of the network-interface read
* from the configs file
*/
- public static void initializeHTTPEndPoints() {
+ public static void initializeServerEndPoints() {
AgentManager agentManager = AgentManager.getInstance();
- String apimEndpoint = agentManager.getAgentConfigs().getHTTP_ServerEndpoint();
+ String serverSecureEndpoint = agentManager.getAgentConfigs().getHTTPS_ServerEndpoint();
+ String serverUnSecureEndpoint = agentManager.getAgentConfigs().getHTTP_ServerEndpoint();
String backEndContext = agentManager.getAgentConfigs().getControllerContext();
- String deviceControllerAPIEndpoint = apimEndpoint + backEndContext;
+ String deviceControllerAPIEndpoint = serverSecureEndpoint + backEndContext;
+
+ String deviceEnrollmentEndpoint =
+ serverUnSecureEndpoint + backEndContext + AgentConstants.DEVICE_ENROLLMENT_API_EP;
+ agentManager.setEnrollmentEP(deviceEnrollmentEndpoint);
String registerEndpointURL =
deviceControllerAPIEndpoint + AgentConstants.DEVICE_REGISTER_API_EP;
@@ -205,12 +222,88 @@ public class AgentUtilOperations {
log.info(AgentConstants.LOG_APPENDER + "IoT Server's Device Controller API Endpoint: " +
deviceControllerAPIEndpoint);
+ log.info(AgentConstants.LOG_APPENDER + "Device Enrollment EndPoint: " +
+ registerEndpointURL);
log.info(AgentConstants.LOG_APPENDER + "DeviceIP Registration EndPoint: " +
registerEndpointURL);
log.info(AgentConstants.LOG_APPENDER + "Push-Data API EndPoint: " + pushDataEndPointURL);
}
+ public static String prepareSecurePayLoad(String message) throws AgentCoreOperationException {
+ PublicKey serverPublicKey = EnrollmentManager.getInstance().getServerPublicKey();
+ PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey();
+
+ String encryptedMsg;
+ try {
+ encryptedMsg = CommunicationUtils.encryptMessage(message, serverPublicKey);
+ } catch (TransportHandlerException e) {
+ String errorMsg = "Error occurred whilst trying to encryptMessage: [" + message + "]";
+ log.error(errorMsg);
+ throw new AgentCoreOperationException(errorMsg, e);
+ }
+
+ String signedPayload;
+ try {
+ signedPayload = CommunicationUtils.signMessage(encryptedMsg, devicePrivateKey);
+ } catch (TransportHandlerException e) {
+ String errorMsg = "Error occurred whilst trying to sign encrypted message of: [" + message + "]";
+ log.error(errorMsg);
+ throw new AgentCoreOperationException(errorMsg, e);
+ }
+
+ JSONObject jsonPayload = new JSONObject();
+ jsonPayload.put(JSON_MESSAGE_KEY, encryptedMsg);
+ jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload);
+
+ return jsonPayload.toString();
+ }
+
+
+ public static String extractMessageFromPayload(String message) throws AgentCoreOperationException {
+ String actualMessage;
+
+ PublicKey serverPublicKey = EnrollmentManager.getInstance().getServerPublicKey();
+ PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey();
+
+ JSONObject jsonPayload = new JSONObject(message);
+ Object encryptedMessage = jsonPayload.get(JSON_MESSAGE_KEY);
+ Object signedPayload = jsonPayload.get(JSON_SIGNATURE_KEY);
+ boolean verification;
+
+ if (encryptedMessage != null && signedPayload != null) {
+ try {
+ verification = CommunicationUtils.verifySignature(
+ encryptedMessage.toString(), signedPayload.toString(), serverPublicKey);
+ } catch (TransportHandlerException e) {
+ String errorMsg =
+ "Error occurred whilst trying to verify signature on received message: [" + message + "]";
+ log.error(errorMsg);
+ throw new AgentCoreOperationException(errorMsg, e);
+ }
+ } else {
+ String errorMsg = "The received message is in an INVALID format. " +
+ "Need to be JSON - {\"Msg\":\"\", \"Sig\":\"\"}.";
+ throw new AgentCoreOperationException(errorMsg);
+ }
+
+ try {
+ if (verification) {
+ actualMessage = CommunicationUtils.decryptMessage(encryptedMessage.toString(), devicePrivateKey);
+ } else {
+ String errorMsg = "Could not verify payload signature. The message was not signed by a valid client";
+ log.error(errorMsg);
+ throw new AgentCoreOperationException(errorMsg);
+ }
+ } catch (TransportHandlerException e) {
+ String errorMsg = "Error occurred whilst trying to decrypt received message: [" + encryptedMessage + "]";
+ log.error(errorMsg);
+ throw new AgentCoreOperationException(errorMsg, e);
+ }
+
+ return actualMessage;
+ }
+
public static String formatMessage(String message) {
StringBuilder formattedMsg = new StringBuilder(message);
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/enrollment/EnrollmentManager.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/enrollment/EnrollmentManager.java
index bbf4384d90..b6f26ad057 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/enrollment/EnrollmentManager.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/enrollment/EnrollmentManager.java
@@ -227,10 +227,11 @@ public class EnrollmentManager {
private PKCS10CertificationRequest generateCertSignRequest() throws AgentCoreOperationException {
// Build the CN for the cert that's being requested.
X500NameBuilder nameBld = new X500NameBuilder(BCStyle.INSTANCE);
- nameBld.addRDN(BCStyle.CN, AgentManager.getInstance().getAgentConfigs().getDeviceName());
+ nameBld.addRDN(BCStyle.CN, AgentManager.getInstance().getAgentConfigs().getServerName());
nameBld.addRDN(BCStyle.O, AgentManager.getInstance().getAgentConfigs().getDeviceOwner());
nameBld.addRDN(BCStyle.OU, AgentManager.getInstance().getAgentConfigs().getDeviceOwner());
nameBld.addRDN(BCStyle.UNIQUE_IDENTIFIER, AgentManager.getInstance().getAgentConfigs().getDeviceId());
+ nameBld.addRDN(BCStyle.SERIALNUMBER, AgentManager.getInstance().getAgentConfigs().getDeviceId());
X500Name principal = nameBld.build();
JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER);
@@ -403,6 +404,7 @@ public class EnrollmentManager {
/**
* Gets the Public-Key of the client.
+ *
* @return the public key of the client.
*/
public PublicKey getPublicKey() {
@@ -411,6 +413,7 @@ public class EnrollmentManager {
/**
* Gets the Private-Key of the client.
+ *
* @return the private key of the client.
*/
public PrivateKey getPrivateKey() {
@@ -419,6 +422,7 @@ public class EnrollmentManager {
/**
* Gets the SCEP-Certificate of the client.
+ *
* @return the SCEP Certificate of the client.
*/
public X509Certificate getSCEPCertificate() {
@@ -427,6 +431,7 @@ public class EnrollmentManager {
/**
* Gets the Public-Key of the Server.
+ *
* @return the pubic key of the server.
*/
public PublicKey getServerPublicKey() {
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/exception/AgentCoreOperationException.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/exception/AgentCoreOperationException.java
index 817a2ab40e..7aa1020427 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/exception/AgentCoreOperationException.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/exception/AgentCoreOperationException.java
@@ -19,39 +19,39 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.exception;
-public class AgentCoreOperationException extends Exception{
- private static final long serialVersionUID = 2736466230451105710L;
+public class AgentCoreOperationException extends Exception {
+ private static final long serialVersionUID = 2736466230451105710L;
- private String errorMessage;
+ private String errorMessage;
- public String getErrorMessage() {
- return errorMessage;
- }
+ public String getErrorMessage() {
+ return errorMessage;
+ }
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
- public AgentCoreOperationException(String msg, Exception nestedEx) {
- super(msg, nestedEx);
- setErrorMessage(msg);
- }
+ public AgentCoreOperationException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ setErrorMessage(msg);
+ }
- public AgentCoreOperationException(String message, Throwable cause) {
- super(message, cause);
- setErrorMessage(message);
- }
+ public AgentCoreOperationException(String message, Throwable cause) {
+ super(message, cause);
+ setErrorMessage(message);
+ }
- public AgentCoreOperationException(String msg) {
- super(msg);
- setErrorMessage(msg);
- }
+ public AgentCoreOperationException(String msg) {
+ super(msg);
+ setErrorMessage(msg);
+ }
- public AgentCoreOperationException() {
- super();
- }
+ public AgentCoreOperationException() {
+ super();
+ }
- public AgentCoreOperationException(Throwable cause) {
- super(cause);
- }
+ public AgentCoreOperationException(Throwable cause) {
+ super(cause);
+ }
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/sidhdhi/SidhdhiQuery.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/sidhdhi/SidhdhiQuery.java
index 1f18602802..4b2a3257be 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/sidhdhi/SidhdhiQuery.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/sidhdhi/SidhdhiQuery.java
@@ -49,37 +49,37 @@ import java.nio.file.Paths;
* care of re-initializing same.
*/
public class SidhdhiQuery implements Runnable {
- private static final Log log = LogFactory.getLog(SidhdhiQuery.class);
- final AgentConstants constants = new AgentConstants();
+ private static final Log log = LogFactory.getLog(SidhdhiQuery.class);
+ final AgentConstants constants = new AgentConstants();
- //Bam data push client
- private static SiddhiManager siddhiManager = new SiddhiManager();
+ //Bam data push client
+ private static SiddhiManager siddhiManager = new SiddhiManager();
- public static SiddhiManager getSiddhiManager() {
- return siddhiManager;
- }
+ public static SiddhiManager getSiddhiManager() {
+ return siddhiManager;
+ }
- public static void setSiddhiManager(SiddhiManager siddhiManager) {
- SidhdhiQuery.siddhiManager = siddhiManager;
- }
+ public static void setSiddhiManager(SiddhiManager siddhiManager) {
+ SidhdhiQuery.siddhiManager = siddhiManager;
+ }
- public void run() {
+ public void run() {
- //Start the execution plan with pre-defined or previously persisted Siddhi query
+ //Start the execution plan with pre-defined or previously persisted Siddhi query
- String sidhdhiQueryPath =
- AgentManager.getInstance().getRootPath() + AgentConstants.CEP_FILE_NAME;
+ String sidhdhiQueryPath =
+ AgentManager.getInstance().getRootPath() + AgentConstants.CEP_FILE_NAME;
- File f = new File(sidhdhiQueryPath);
- if (!f.exists()) {
- FileOutputStream out = null;
- try {
- out = new FileOutputStream(sidhdhiQueryPath);
- out.write(AgentConstants.CEP_QUERY.getBytes(StandardCharsets.UTF_8));
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (out != null){
+ File f = new File(sidhdhiQueryPath);
+ if (!f.exists()) {
+ FileOutputStream out = null;
+ try {
+ out = new FileOutputStream(sidhdhiQueryPath);
+ out.write(AgentConstants.CEP_QUERY.getBytes(StandardCharsets.UTF_8));
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ if (out != null) {
try {
out.close();
} catch (IOException e) {
@@ -89,135 +89,135 @@ public class SidhdhiQuery implements Runnable {
}
}
- StartExecutionPlan startExecutionPlan = new StartExecutionPlan().invoke();
-
- while (true) {
-
- //Check if there is new policy update available
- if (AgentManager.isUpdated()) {
- System.out.print("### Policy Update Detected!");
- //Restart execution plan with new query
- restartSiddhi();
- startExecutionPlan = new StartExecutionPlan().invoke();
- }
- InputHandler inputHandler = startExecutionPlan.getInputHandler();
-
- //Sending events to Siddhi
- try {
- int humidityReading = AgentManager.getInstance().getTemperature();
- inputHandler.send(new Object[]{"FIRE_1", humidityReading});
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- break;
- }
- }
- }
-
- /**
- * Re-Initialize SiddhiManager
- */
- private void restartSiddhi() {
- siddhiManager.shutdown();
- siddhiManager = new SiddhiManager();
- }
-
-
- /**
- * Read content from a given file and return as a string
- *
- * @param path
- * @param encoding
- * @return
- */
- public static String readFile(String path, Charset encoding) {
- byte[] encoded = new byte[0];
- try {
- encoded = Files.readAllBytes(Paths.get(path));
- } catch (IOException e) {
- log.error("Error reading Sidhdhi query from file.");
- }
- return new String(encoded, encoding);
- }
-
-
- /**
- * Read humidity data from API URL
- *
- * @param humidityAPIUrl
- * @return
- */
- private String readHumidityData(String humidityAPIUrl) {
- HttpClient client = new DefaultHttpClient();
- HttpGet request = new HttpGet(humidityAPIUrl);
- String responseStr = null;
- try {
- HttpResponse response = client.execute(request);
- log.debug("Response Code : " + response);
- InputStream input = response.getEntity().getContent();
- BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
- responseStr = String.valueOf(br.readLine());
- br.close();
-
- } catch (IOException e) {
- //log.error("Exception encountered while trying to make get request.");
- log.error("Error while reading humidity reading from file!");
- return responseStr;
- }
- return responseStr;
- }
-
- /**
- * Initialize SiddhiExecution plan
- */
- private static class StartExecutionPlan {
- private InputHandler inputHandler;
-
- public InputHandler getInputHandler() {
- return inputHandler;
- }
-
- public StartExecutionPlan invoke() {
- String executionPlan;
-
- String sidhdhiQueryPath =
- AgentManager.getInstance().getRootPath() + AgentConstants.CEP_FILE_NAME;
- executionPlan = readFile(sidhdhiQueryPath, StandardCharsets.UTF_8);
-
- //Generating runtime
- siddhiManager.addExecutionPlan(executionPlan);
-
- siddhiManager.addCallback("bulbOnStream", new StreamCallback() {
- @Override
- public void receive(Event[] events) {
- System.out.println("Bulb on Event Fired!");
- if (events.length > 0) {
- if (!AgentManager.getInstance().isAlarmOn()) {
- AgentManager.getInstance().changeAlarmStatus(true);
- System.out.println("#### Performed HTTP call! ON.");
- }
- }
- }
- });
-
- siddhiManager.addCallback("bulbOffStream", new StreamCallback() {
- @Override
- public void receive(Event[] inEvents) {
- System.out.println("Bulb off Event Fired");
- if (AgentManager.getInstance().isAlarmOn()) {
- AgentManager.getInstance().changeAlarmStatus(false);
- System.out.println("#### Performed HTTP call! OFF.");
- }
- }
-
- });
-
- //Retrieving InputHandler to push events into Siddhi
- inputHandler = siddhiManager.getInputHandler("fireAlarmEventStream");
-
- //Starting event processing
- System.out.println("Execution Plan Started!");
- return this;
- }
- }
+ StartExecutionPlan startExecutionPlan = new StartExecutionPlan().invoke();
+
+ while (true) {
+
+ //Check if there is new policy update available
+ if (AgentManager.isUpdated()) {
+ System.out.print("### Policy Update Detected!");
+ //Restart execution plan with new query
+ restartSiddhi();
+ startExecutionPlan = new StartExecutionPlan().invoke();
+ }
+ InputHandler inputHandler = startExecutionPlan.getInputHandler();
+
+ //Sending events to Siddhi
+ try {
+ int humidityReading = AgentManager.getInstance().getTemperature();
+ inputHandler.send(new Object[]{"FIRE_1", humidityReading});
+ Thread.sleep(3000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ break;
+ }
+ }
+ }
+
+ /**
+ * Re-Initialize SiddhiManager
+ */
+ private void restartSiddhi() {
+ siddhiManager.shutdown();
+ siddhiManager = new SiddhiManager();
+ }
+
+
+ /**
+ * Read content from a given file and return as a string
+ *
+ * @param path
+ * @param encoding
+ * @return
+ */
+ public static String readFile(String path, Charset encoding) {
+ byte[] encoded = new byte[0];
+ try {
+ encoded = Files.readAllBytes(Paths.get(path));
+ } catch (IOException e) {
+ log.error("Error reading Sidhdhi query from file.");
+ }
+ return new String(encoded, encoding);
+ }
+
+
+ /**
+ * Read humidity data from API URL
+ *
+ * @param humidityAPIUrl
+ * @return
+ */
+ private String readHumidityData(String humidityAPIUrl) {
+ HttpClient client = new DefaultHttpClient();
+ HttpGet request = new HttpGet(humidityAPIUrl);
+ String responseStr = null;
+ try {
+ HttpResponse response = client.execute(request);
+ log.debug("Response Code : " + response);
+ InputStream input = response.getEntity().getContent();
+ BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
+ responseStr = String.valueOf(br.readLine());
+ br.close();
+
+ } catch (IOException e) {
+ //log.error("Exception encountered while trying to make get request.");
+ log.error("Error while reading humidity reading from file!");
+ return responseStr;
+ }
+ return responseStr;
+ }
+
+ /**
+ * Initialize SiddhiExecution plan
+ */
+ private static class StartExecutionPlan {
+ private InputHandler inputHandler;
+
+ public InputHandler getInputHandler() {
+ return inputHandler;
+ }
+
+ public StartExecutionPlan invoke() {
+ String executionPlan;
+
+ String sidhdhiQueryPath =
+ AgentManager.getInstance().getRootPath() + AgentConstants.CEP_FILE_NAME;
+ executionPlan = readFile(sidhdhiQueryPath, StandardCharsets.UTF_8);
+
+ //Generating runtime
+ siddhiManager.addExecutionPlan(executionPlan);
+
+ siddhiManager.addCallback("bulbOnStream", new StreamCallback() {
+ @Override
+ public void receive(Event[] events) {
+ System.out.println("Bulb on Event Fired!");
+ if (events.length > 0) {
+ if (!AgentManager.getInstance().isAlarmOn()) {
+ AgentManager.getInstance().changeAlarmStatus(true);
+ System.out.println("#### Performed HTTP call! ON.");
+ }
+ }
+ }
+ });
+
+ siddhiManager.addCallback("bulbOffStream", new StreamCallback() {
+ @Override
+ public void receive(Event[] inEvents) {
+ System.out.println("Bulb off Event Fired");
+ if (AgentManager.getInstance().isAlarmOn()) {
+ AgentManager.getInstance().changeAlarmStatus(false);
+ System.out.println("#### Performed HTTP call! OFF.");
+ }
+ }
+
+ });
+
+ //Retrieving InputHandler to push events into Siddhi
+ inputHandler = siddhiManager.getInputHandler("fireAlarmEventStream");
+
+ //Starting event processing
+ System.out.println("Execution Plan Started!");
+ return this;
+ }
+ }
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/CommunicationUtils.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/CommunicationUtils.java
index 944c9e6154..e6e16ba52b 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/CommunicationUtils.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/CommunicationUtils.java
@@ -55,7 +55,7 @@ public class CommunicationUtils {
* @param encryptionKey the key to use for the encryption of the message.
* @return the encrypted message in String format.
* @throws TransportHandlerException if an error occurs with the encryption flow which can be due to Padding
- * issues, encryption key being invalid or the algorithm used is unrecognizable.
+ * issues, encryption key being invalid or the algorithm used is unrecognizable.
*/
public static String encryptMessage(String message, Key encryptionKey) throws TransportHandlerException {
Cipher encrypter;
@@ -92,6 +92,7 @@ public class CommunicationUtils {
}
///TODO:: Exception needs to change according to the common package
+
/**
* Signed a given message using the PrivateKey that's passes in.
*
@@ -99,7 +100,7 @@ public class CommunicationUtils {
* @param signatureKey the PrivateKey with which the message is to be signed.
* @return the Base64Encoded String of the signed payload.
* @throws TransportHandlerException if some error occurs with the signing process which may be related to the
- * signature algorithm used or the key used for signing.
+ * signature algorithm used or the key used for signing.
*/
public static String signMessage(String message, PrivateKey signatureKey) throws TransportHandlerException {
@@ -143,7 +144,7 @@ public class CommunicationUtils {
* the data to be signed by.
* @return true if the signed data verifies to be signed by the corresponding Private Key.
* @throws TransportHandlerException if some error occurs with the verification process which may be related to
- * the signature algorithm used or the key used for signing.
+ * the signature algorithm used or the key used for signing.
*/
public static boolean verifySignature(String data, String signedData, PublicKey verificationKey)
throws TransportHandlerException {
@@ -184,7 +185,7 @@ public class CommunicationUtils {
* @param decryptKey the key to use in the decryption process.
* @return the decrypted message in String format.
* @throws TransportHandlerException if an error occurs with the encryption flow which can be due to Padding
- * issues, encryption key being invalid or the algorithm used is unrecognizable.
+ * issues, encryption key being invalid or the algorithm used is unrecognizable.
*/
public static String decryptMessage(String encryptedMessage, Key decryptKey) throws TransportHandlerException {
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportHandler.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportHandler.java
index 7efed0049f..8034f66e27 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportHandler.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportHandler.java
@@ -39,7 +39,9 @@ public interface TransportHandler {
void processIncomingMessage();
- void publishDeviceData(int publishInterval);
+ void publishDeviceData(String... publishData);
+
+ void publishDeviceData();
void disconnect();
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportHandlerException.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportHandlerException.java
index 7671881886..aeccc0fbce 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportHandlerException.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportHandlerException.java
@@ -19,38 +19,38 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport;
public class TransportHandlerException extends Exception {
- private static final long serialVersionUID = 2736466230451105440L;
+ private static final long serialVersionUID = 2736466230451105440L;
- private String errorMessage;
+ private String errorMessage;
- public String getErrorMessage() {
- return errorMessage;
- }
+ public String getErrorMessage() {
+ return errorMessage;
+ }
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
- public TransportHandlerException(String msg, Exception nestedEx) {
- super(msg, nestedEx);
- setErrorMessage(msg);
- }
+ public TransportHandlerException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ setErrorMessage(msg);
+ }
- public TransportHandlerException(String message, Throwable cause) {
- super(message, cause);
- setErrorMessage(message);
- }
+ public TransportHandlerException(String message, Throwable cause) {
+ super(message, cause);
+ setErrorMessage(message);
+ }
- public TransportHandlerException(String msg) {
- super(msg);
- setErrorMessage(msg);
- }
+ public TransportHandlerException(String msg) {
+ super(msg);
+ setErrorMessage(msg);
+ }
- public TransportHandlerException() {
- super();
- }
+ public TransportHandlerException() {
+ super();
+ }
- public TransportHandlerException(Throwable cause) {
- super(cause);
- }
+ public TransportHandlerException(Throwable cause) {
+ super(cause);
+ }
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportUtils.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportUtils.java
index b12fdfab62..a9b6676a3c 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportUtils.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/TransportUtils.java
@@ -41,261 +41,262 @@ import java.util.Map;
import java.util.Random;
public class TransportUtils {
- private static final Log log = LogFactory.getLog(TransportUtils.class);
-
- public static final int MIN_PORT_NUMBER = 9000;
- public static final int MAX_PORT_NUMBER = 11000;
-
- /**
- * Given a server endpoint as a String, this method splits it into Protocol, Host and Port
- *
- * @param ipString a network endpoint in the format - '://:'
- * @return a map with keys "Protocol", "Host" & "Port" for the related values from the ipString
- * @throws TransportHandlerException
- */
- public static Map getHostAndPort(String ipString)
- throws TransportHandlerException {
- Map ipPortMap = new HashMap();
- String[] ipPortArray = ipString.split(":");
-
- if (ipPortArray.length != 3) {
- String errorMsg =
- "The IP String - '" + ipString +
- "' is invalid. It needs to be in format '://:'.";
- log.info(errorMsg);
- throw new TransportHandlerException(errorMsg);
- }
-
- ipPortMap.put("Protocol", ipPortArray[0]);
- ipPortMap.put("Host", ipPortArray[1].replace(File.separator, ""));
- ipPortMap.put("Port", ipPortArray[2]);
- return ipPortMap;
- }
-
- /**
- * This method validates whether a specific IP Address is of IPv4 type
- *
- * @param ipAddress the IP Address which needs to be validated
- * @return true if it is of IPv4 type and false otherwise
- */
- public static boolean validateIPv4(String ipAddress) {
- try {
- if (ipAddress == null || ipAddress.isEmpty()) {
- return false;
- }
-
- String[] parts = ipAddress.split("\\.");
- if (parts.length != 4) {
- return false;
- }
-
- for (String s : parts) {
- int i = Integer.parseInt(s);
- if ((i < 0) || (i > 255)) {
- return false;
- }
- }
- return !ipAddress.endsWith(".");
-
- } catch (NumberFormatException nfe) {
- log.warn("The IP Address: " + ipAddress + " could not " +
- "be validated against IPv4-style");
- return false;
- }
- }
-
-
- public static Map getInterfaceIPMap() throws TransportHandlerException {
-
- Map interfaceToIPMap = new HashMap();
- Enumeration networkInterfaces;
- String networkInterfaceName = "";
- String ipAddress;
-
- try {
- networkInterfaces = NetworkInterface.getNetworkInterfaces();
- } catch (SocketException exception) {
- String errorMsg =
- "Error encountered whilst trying to get the list of network-interfaces";
- log.error(errorMsg);
- throw new TransportHandlerException(errorMsg, exception);
- }
-
- try {
- for (; networkInterfaces.hasMoreElements(); ) {
- networkInterfaceName = networkInterfaces.nextElement().getName();
-
- if (log.isDebugEnabled()) {
- log.debug("Network Interface: " + networkInterfaceName);
- log.debug("------------------------------------------");
- }
-
- Enumeration interfaceIPAddresses = NetworkInterface.getByName(
- networkInterfaceName).getInetAddresses();
-
- for (; interfaceIPAddresses.hasMoreElements(); ) {
- ipAddress = interfaceIPAddresses.nextElement().getHostAddress();
-
- if (log.isDebugEnabled()) {
- log.debug("IP Address: " + ipAddress);
- }
-
- if (TransportUtils.validateIPv4(ipAddress)) {
- interfaceToIPMap.put(networkInterfaceName, ipAddress);
- }
- }
-
- if (log.isDebugEnabled()) {
- log.debug("------------------------------------------");
- }
- }
- } catch (SocketException exception) {
- String errorMsg =
- "Error encountered whilst trying to get the IP Addresses of the network " +
- "interface: " + networkInterfaceName;
- log.error(errorMsg);
- throw new TransportHandlerException(errorMsg, exception);
- }
-
- return interfaceToIPMap;
- }
-
-
- /**
- * Attempts to find a free port between the MIN_PORT_NUMBER(9000) and MAX_PORT_NUMBER(11000).
- * Tries 'RANDOMLY picked' port numbers between this range up-until "randomAttempts" number of
- * times. If still fails, then tries each port in descending order from the MAX_PORT_NUMBER
- * whilst skipping already attempted ones via random selection.
- *
- * @param randomAttempts no of times to TEST port numbers picked randomly over the given range
- * @return an available/free port
- */
- public static synchronized int getAvailablePort(int randomAttempts) {
- ArrayList failedPorts = new ArrayList(randomAttempts);
-
- Random randomNum = new Random();
- int randomPort = MAX_PORT_NUMBER;
-
- while (randomAttempts > 0) {
- randomPort = randomNum.nextInt(MAX_PORT_NUMBER - MIN_PORT_NUMBER) + MIN_PORT_NUMBER;
-
- if (checkIfPortAvailable(randomPort)) {
- return randomPort;
- }
- failedPorts.add(randomPort);
- randomAttempts--;
- }
-
- randomPort = MAX_PORT_NUMBER;
-
- while (true) {
- if (!failedPorts.contains(randomPort) && checkIfPortAvailable(randomPort)) {
- return randomPort;
- }
- randomPort--;
- }
- }
-
-
- private static boolean checkIfPortAvailable(int port) {
- ServerSocket tcpSocket = null;
- DatagramSocket udpSocket = null;
-
- try {
- tcpSocket = new ServerSocket(port);
- tcpSocket.setReuseAddress(true);
-
- udpSocket = new DatagramSocket(port);
- udpSocket.setReuseAddress(true);
- return true;
- } catch (IOException ex) {
- // denotes the port is in use
- } finally {
- if (tcpSocket != null) {
- try {
- tcpSocket.close();
- } catch (IOException e) {
- /* not to be thrown */
- }
- }
-
- if (udpSocket != null) {
- udpSocket.close();
- }
- }
-
- return false;
- }
-
-
- /**
- * This is a utility method that creates and returns a HTTP connection object.
- *
- * @param urlString the URL pattern to which the connection needs to be created
- * @return an HTTPConnection object which cn be used to send HTTP requests
- * @throws TransportHandlerException if errors occur when creating the HTTP connection with
- * the given URL string
- */
- public static HttpURLConnection getHttpConnection(String urlString) throws
- TransportHandlerException {
- URL connectionUrl;
- 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 TransportHandlerException(errorMsg, e);
- } catch (IOException exception) {
- String errorMsg = "Error occured whilst trying to open a connection to: " + urlString;
- log.error(errorMsg);
- throw new TransportHandlerException(errorMsg, exception);
- }
- return httpConnection;
- }
-
- /**
- * This is a utility method that reads and returns the response from a HTTP connection
- *
- * @param httpConnection the connection from which a response is expected
- * @return the response (as a string) from the given HTTP connection
- * @throws TransportHandlerException if any errors occur whilst reading the response from
- * the connection stream
- */
- public static String readResponseFromHttpRequest(HttpURLConnection httpConnection)
- throws TransportHandlerException {
- BufferedReader bufferedReader;
- try {
- bufferedReader = new BufferedReader(new InputStreamReader(
- httpConnection.getInputStream(), StandardCharsets.UTF_8));
- } catch (IOException exception) {
- String errorMsg = "There is an issue with connecting the reader to the input stream at: " +
- httpConnection.getURL();
- log.error(errorMsg);
- throw new TransportHandlerException(errorMsg, exception);
- }
-
- String responseLine;
- StringBuilder completeResponse = new StringBuilder();
-
- try {
- while ((responseLine = bufferedReader.readLine()) != null) {
- completeResponse.append(responseLine);
- }
- } catch (IOException exception) {
- String errorMsg = "Error occured whilst trying read from the connection stream at: " +
- httpConnection.getURL();
- log.error(errorMsg);
- throw new TransportHandlerException(errorMsg, exception);
- }
- try {
- bufferedReader.close();
- } catch (IOException exception) {
- log.error("Could not succesfully close the bufferedReader to the connection at: " + httpConnection.getURL());
- }
- return completeResponse.toString();
- }
+ private static final Log log = LogFactory.getLog(TransportUtils.class);
+
+ public static final int MIN_PORT_NUMBER = 9000;
+ public static final int MAX_PORT_NUMBER = 11000;
+
+ /**
+ * Given a server endpoint as a String, this method splits it into Protocol, Host and Port
+ *
+ * @param ipString a network endpoint in the format - '://:'
+ * @return a map with keys "Protocol", "Host" & "Port" for the related values from the ipString
+ * @throws TransportHandlerException
+ */
+ public static Map getHostAndPort(String ipString)
+ throws TransportHandlerException {
+ Map ipPortMap = new HashMap();
+ String[] ipPortArray = ipString.split(":");
+
+ if (ipPortArray.length != 3) {
+ String errorMsg =
+ "The IP String - '" + ipString +
+ "' is invalid. It needs to be in format '://:'.";
+ log.info(errorMsg);
+ throw new TransportHandlerException(errorMsg);
+ }
+
+ ipPortMap.put("Protocol", ipPortArray[0]);
+ ipPortMap.put("Host", ipPortArray[1].replace(File.separator, ""));
+ ipPortMap.put("Port", ipPortArray[2]);
+ return ipPortMap;
+ }
+
+ /**
+ * This method validates whether a specific IP Address is of IPv4 type
+ *
+ * @param ipAddress the IP Address which needs to be validated
+ * @return true if it is of IPv4 type and false otherwise
+ */
+ public static boolean validateIPv4(String ipAddress) {
+ try {
+ if (ipAddress == null || ipAddress.isEmpty()) {
+ return false;
+ }
+
+ String[] parts = ipAddress.split("\\.");
+ if (parts.length != 4) {
+ return false;
+ }
+
+ for (String s : parts) {
+ int i = Integer.parseInt(s);
+ if ((i < 0) || (i > 255)) {
+ return false;
+ }
+ }
+ return !ipAddress.endsWith(".");
+
+ } catch (NumberFormatException nfe) {
+ log.warn("The IP Address: " + ipAddress + " could not " +
+ "be validated against IPv4-style");
+ return false;
+ }
+ }
+
+
+ public static Map getInterfaceIPMap() throws TransportHandlerException {
+
+ Map interfaceToIPMap = new HashMap();
+ Enumeration networkInterfaces;
+ String networkInterfaceName = "";
+ String ipAddress;
+
+ try {
+ networkInterfaces = NetworkInterface.getNetworkInterfaces();
+ } catch (SocketException exception) {
+ String errorMsg =
+ "Error encountered whilst trying to get the list of network-interfaces";
+ log.error(errorMsg);
+ throw new TransportHandlerException(errorMsg, exception);
+ }
+
+ try {
+ for (; networkInterfaces.hasMoreElements(); ) {
+ networkInterfaceName = networkInterfaces.nextElement().getName();
+
+ if (log.isDebugEnabled()) {
+ log.debug("Network Interface: " + networkInterfaceName);
+ log.debug("------------------------------------------");
+ }
+
+ Enumeration interfaceIPAddresses = NetworkInterface.getByName(
+ networkInterfaceName).getInetAddresses();
+
+ for (; interfaceIPAddresses.hasMoreElements(); ) {
+ ipAddress = interfaceIPAddresses.nextElement().getHostAddress();
+
+ if (log.isDebugEnabled()) {
+ log.debug("IP Address: " + ipAddress);
+ }
+
+ if (TransportUtils.validateIPv4(ipAddress)) {
+ interfaceToIPMap.put(networkInterfaceName, ipAddress);
+ }
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug("------------------------------------------");
+ }
+ }
+ } catch (SocketException exception) {
+ String errorMsg =
+ "Error encountered whilst trying to get the IP Addresses of the network " +
+ "interface: " + networkInterfaceName;
+ log.error(errorMsg);
+ throw new TransportHandlerException(errorMsg, exception);
+ }
+
+ return interfaceToIPMap;
+ }
+
+
+ /**
+ * Attempts to find a free port between the MIN_PORT_NUMBER(9000) and MAX_PORT_NUMBER(11000).
+ * Tries 'RANDOMLY picked' port numbers between this range up-until "randomAttempts" number of
+ * times. If still fails, then tries each port in descending order from the MAX_PORT_NUMBER
+ * whilst skipping already attempted ones via random selection.
+ *
+ * @param randomAttempts no of times to TEST port numbers picked randomly over the given range
+ * @return an available/free port
+ */
+ public static synchronized int getAvailablePort(int randomAttempts) {
+ ArrayList failedPorts = new ArrayList(randomAttempts);
+
+ Random randomNum = new Random();
+ int randomPort = MAX_PORT_NUMBER;
+
+ while (randomAttempts > 0) {
+ randomPort = randomNum.nextInt(MAX_PORT_NUMBER - MIN_PORT_NUMBER) + MIN_PORT_NUMBER;
+
+ if (checkIfPortAvailable(randomPort)) {
+ return randomPort;
+ }
+ failedPorts.add(randomPort);
+ randomAttempts--;
+ }
+
+ randomPort = MAX_PORT_NUMBER;
+
+ while (true) {
+ if (!failedPorts.contains(randomPort) && checkIfPortAvailable(randomPort)) {
+ return randomPort;
+ }
+ randomPort--;
+ }
+ }
+
+
+ private static boolean checkIfPortAvailable(int port) {
+ ServerSocket tcpSocket = null;
+ DatagramSocket udpSocket = null;
+
+ try {
+ tcpSocket = new ServerSocket(port);
+ tcpSocket.setReuseAddress(true);
+
+ udpSocket = new DatagramSocket(port);
+ udpSocket.setReuseAddress(true);
+ return true;
+ } catch (IOException ex) {
+ // denotes the port is in use
+ } finally {
+ if (tcpSocket != null) {
+ try {
+ tcpSocket.close();
+ } catch (IOException e) {
+ /* not to be thrown */
+ }
+ }
+
+ if (udpSocket != null) {
+ udpSocket.close();
+ }
+ }
+
+ return false;
+ }
+
+
+ /**
+ * This is a utility method that creates and returns a HTTP connection object.
+ *
+ * @param urlString the URL pattern to which the connection needs to be created
+ * @return an HTTPConnection object which cn be used to send HTTP requests
+ * @throws TransportHandlerException if errors occur when creating the HTTP connection with
+ * the given URL string
+ */
+ public static HttpURLConnection getHttpConnection(String urlString) throws
+ TransportHandlerException {
+ URL connectionUrl;
+ 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 TransportHandlerException(errorMsg, e);
+ } catch (IOException exception) {
+ String errorMsg = "Error occured whilst trying to open a connection to: " + urlString;
+ log.error(errorMsg);
+ throw new TransportHandlerException(errorMsg, exception);
+ }
+ return httpConnection;
+ }
+
+ /**
+ * This is a utility method that reads and returns the response from a HTTP connection
+ *
+ * @param httpConnection the connection from which a response is expected
+ * @return the response (as a string) from the given HTTP connection
+ * @throws TransportHandlerException if any errors occur whilst reading the response from
+ * the connection stream
+ */
+ public static String readResponseFromHttpRequest(HttpURLConnection httpConnection)
+ throws TransportHandlerException {
+ BufferedReader bufferedReader;
+ try {
+ bufferedReader = new BufferedReader(new InputStreamReader(
+ httpConnection.getInputStream(), StandardCharsets.UTF_8));
+ } catch (IOException exception) {
+ String errorMsg = "There is an issue with connecting the reader to the input stream at: " +
+ httpConnection.getURL();
+ log.error(errorMsg);
+ throw new TransportHandlerException(errorMsg, exception);
+ }
+
+ String responseLine;
+ StringBuilder completeResponse = new StringBuilder();
+
+ try {
+ while ((responseLine = bufferedReader.readLine()) != null) {
+ completeResponse.append(responseLine);
+ }
+ } catch (IOException exception) {
+ String errorMsg = "Error occured whilst trying read from the connection stream at: " +
+ httpConnection.getURL();
+ log.error(errorMsg);
+ throw new TransportHandlerException(errorMsg, exception);
+ }
+ try {
+ bufferedReader.close();
+ } catch (IOException exception) {
+ log.error(
+ "Could not succesfully close the bufferedReader to the connection at: " + httpConnection.getURL());
+ }
+ return completeResponse.toString();
+ }
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/xmpp/XMPPTransportHandler.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/xmpp/XMPPTransportHandler.java
index 80b9090dfc..ba8320c7cf 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/xmpp/XMPPTransportHandler.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/transport/xmpp/XMPPTransportHandler.java
@@ -152,13 +152,10 @@ public abstract class XMPPTransportHandler implements TransportHandler
protected void connectToServer() throws TransportHandlerException {
try {
connection.connect();
- log.info(String.format(
- "Connection to XMPP Server at %1$s established successfully......", server));
+ log.info(String.format("Connection to XMPP Server at %1$s established successfully......", server));
} catch (XMPPException xmppExcepion) {
- String errorMsg =
- "Connection attempt to the XMPP Server at " + server + " via port " + port +
- " failed.";
+ String errorMsg = "Connection attempt to the XMPP Server at " + server + " via port " + port + " failed.";
log.info(errorMsg);
throw new TransportHandlerException(errorMsg, xmppExcepion);
}
@@ -180,28 +177,20 @@ public abstract class XMPPTransportHandler implements TransportHandler
try {
if (resource == null) {
connection.login(username, password);
- log.info(String.format("Logged into XMPP Server at %1$s as user %2$s......",
- server, username));
+ log.info(String.format("Logged into XMPP Server at %1$s as user %2$s......", server, username));
} else {
connection.login(username, password, resource);
- log.info(String.format(
- "Logged into XMPP Server at %1$s as user %2$s on resource %3$s......",
- server, username, resource));
+ log.info(String.format("Logged into XMPP Server at %1$s as user %2$s on resource %3$s......",
+ server, username, resource));
}
} catch (XMPPException xmppException) {
String errorMsg =
- "Login attempt to the XMPP Server at " + server + " with username - " +
- username + " failed.";
- log.info(errorMsg);
+ "Login attempt to the XMPP Server at " + server + " with username - " + username + " failed.";
+ log.error(errorMsg);
throw new TransportHandlerException(errorMsg, xmppException);
}
- } else {//TODO:: Log not required
- String errorMsg =
- "Not connected to XMPP-Server to attempt Login. Please 'connectToServer' " +
- "before Login";
- if (log.isDebugEnabled()) {
- log.debug(errorMsg);
- }
+ } else {
+ String errorMsg = "Not connected to XMPP-Server to attempt Login. Please 'connectToServer' before Login";
throw new TransportHandlerException(errorMsg);
}
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/resources/deviceConfig.properties b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/resources/deviceConfig.properties
index fb83c24d6f..930742a2aa 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/resources/deviceConfig.properties
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/resources/deviceConfig.properties
@@ -16,6 +16,7 @@
#
#[Device-Configurations]
+server-name=WSO2IoTServer
owner=shabirmean
deviceId=t4ctwq8qfl11
device-name=SMEAN_t4ctwq8qfl11
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java
index f9cde6b424..cb74b048b5 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java
@@ -59,6 +59,8 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
return dataPushServiceHandler;
}
+ //TODO:: Terminate logs with a period
+ //TODO: Need to print exceptions
@Override
public void connect() {
final AgentManager agentManager = AgentManager.getInstance();
@@ -67,23 +69,27 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
while (!isConnected()) {
try {
connectToQueue();
- subscribeToQueue();
- //TODO:: Terminate logs with a period
agentManager.updateAgentStatus("Connected to MQTT Queue");
+ } catch (TransportHandlerException e) {
+ log.warn(AgentConstants.LOG_APPENDER + "Connection to MQTT Broker at: " + mqttBrokerEndPoint +
+ " failed.\n Will retry in " + timeoutInterval + " milli-seconds.");
+ }
+
+ try{
+ subscribeToQueue();
+ agentManager.updateAgentStatus("Subscribed to MQTT Queue");
publishDeviceData();
} catch (TransportHandlerException e) {
- log.warn(AgentConstants.LOG_APPENDER +
- "Connection/Subscription to MQTT Broker at: " +
+ log.warn(AgentConstants.LOG_APPENDER + "Subscription to MQTT Broker at: " +
mqttBrokerEndPoint + " failed");
+ agentManager.updateAgentStatus("Subscription to broker failed.");
+ }
- try {
- Thread.sleep(timeoutInterval);
- } catch (InterruptedException ex) {
- //TODO: Need to print exception
- log.error(AgentConstants.LOG_APPENDER +
- "MQTT-Subscriber: Thread Sleep Interrupt Exception");
- }
+ try {
+ Thread.sleep(timeoutInterval);
+ } catch (InterruptedException ex) {
+ log.error(AgentConstants.LOG_APPENDER + "MQTT: Connect-Thread Sleep Interrupt Exception.");
}
}
}
@@ -215,8 +221,12 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
Runnable stopConnection = new Runnable() {
public void run() {
while (isConnected()) {
- try {
+
+ if (dataPushServiceHandler != null) {
dataPushServiceHandler.cancel(true);
+ }
+
+ try {
closeConnection();
} catch (MqttException e) {
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/xmpp/FireAlarmXMPPCommunicator.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/xmpp/FireAlarmXMPPCommunicator.java
index b05fe32b77..86c4a0f7bf 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/xmpp/FireAlarmXMPPCommunicator.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/xmpp/FireAlarmXMPPCommunicator.java
@@ -79,17 +79,18 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
if (!isConnected()) {
try {
connectToServer();
+ } catch (TransportHandlerException e) {
+ log.warn(AgentConstants.LOG_APPENDER + "Connection to XMPP server at: " + server + " failed");
+ }
+
+ try {
loginToServer(username, password, resource);
agentManager.updateAgentStatus("Connected to XMPP Server");
-
setMessageFilterAndListener(xmppAdminJID, xmppDeviceJID, true);
publishDeviceData();
-
} catch (TransportHandlerException e) {
- if (log.isDebugEnabled()) {
- log.warn(AgentConstants.LOG_APPENDER +
- "Connection/Login to XMPP server at: " + server + " failed");
- }
+ log.warn(AgentConstants.LOG_APPENDER + "Login to XMPP server at: " + server + " failed");
+ agentManager.updateAgentStatus("No XMPP Account for Device");
}
}
}
@@ -219,12 +220,15 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
Runnable stopConnection = new Runnable() {
public void run() {
- if ( dataPushServiceHandler != null) {
+ if (dataPushServiceHandler != null) {
dataPushServiceHandler.cancel(true);
}
- while (isConnected()) {
+ if (connectorServiceHandler != null) {
connectorServiceHandler.cancel(true);
+ }
+
+ while (isConnected()) {
closeConnection();
if (log.isDebugEnabled()) {
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java
index fbe9a4c355..22ee97bc9b 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java
@@ -36,10 +36,9 @@ public class AgentConstants {
public static final String PUSH_SIMULATION_DATA_PAYLOAD =
"{\"owner\":\"%s\",\"deviceId\":\"%s\",\"reply\":\"%s\",\"value\":\"%s\",\"isSimulated\":\"%s\",\"duration\":\"%s\",\"frequency\":\"%s\"}";
- public static final String AGENT_CONTROL_APP_EP = "/firealarm-webapp";
- public static final String DEVICE_DETAILS_PAGE_EP = "/store/pages/device/%s/%s";
- public static final String DEVICE_ANALYTICS_PAGE_URL =
- "/store/pages/analytics?deviceId=%s&deviceType=%s";
+ public static final String AGENT_CONTROL_APP_EP = "/devicemgt/device/%s?id=%s";
+ public static final String DEVICE_DETAILS_PAGE_EP = "/devicemgt/device/%s?id=%s";
+ public static final String DEVICE_ANALYTICS_PAGE_URL = "/devicemgt/analytics?deviceId=%s&deviceType=%s&deviceName=%s";
/* ---------------------------------------------------------------------------------------
HTTP Connection specific information for communicating with IoT-Server
--------------------------------------------------------------------------------------- */
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java
index a24332c60f..af814a2c67 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java
@@ -40,6 +40,7 @@ public class AgentManager {
private static final Log log = LogFactory.getLog(AgentManager.class);
private static AgentManager agentManager;
private String rootPath = "";
+
private boolean deviceReady = false;
private boolean isAlarmOn = false;
@@ -82,7 +83,8 @@ public class AgentManager {
String analyticsPageContext = String.format(AgentConstants.DEVICE_ANALYTICS_PAGE_URL,
agentConfigs.getDeviceId(),
- AgentConstants.DEVICE_TYPE);
+ AgentConstants.DEVICE_TYPE,
+ agentConfigs.getDeviceName());
String controlPageContext = String.format(AgentConstants.DEVICE_DETAILS_PAGE_EP,
AgentConstants.DEVICE_TYPE,
@@ -102,9 +104,7 @@ public class AgentManager {
Map xmppIPPortMap;
try {
- xmppIPPortMap = TransportUtils.getHostAndPort(agentConfigs.getXmppServerEndpoint
- ());
-
+ xmppIPPortMap = TransportUtils.getHostAndPort(agentConfigs.getXmppServerEndpoint());
String xmppServer = xmppIPPortMap.get("Host");
int xmppPort = Integer.parseInt(xmppIPPortMap.get("Port"));
@@ -120,12 +120,13 @@ public class AgentManager {
agentConfigs.getDeviceOwner(),
agentConfigs.getDeviceId());
- TransportHandler httpCommunicator = new FireAlarmHTTPCommunicator();
- TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(
- agentConfigs.getDeviceOwner(), agentConfigs.getDeviceId(),
- agentConfigs.getMqttBrokerEndpoint(), mqttTopic);
+// TransportHandler httpCommunicator = new FireAlarmHTTPCommunicator();
+ TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(agentConfigs.getDeviceOwner(),
+ agentConfigs.getDeviceId(),
+ agentConfigs.getMqttBrokerEndpoint(),
+ mqttTopic);
- agentCommunicator.put(AgentConstants.HTTP_PROTOCOL, httpCommunicator);
+// agentCommunicator.put(AgentConstants.HTTP_PROTOCOL, httpCommunicator);
agentCommunicator.put(AgentConstants.MQTT_PROTOCOL, mqttCommunicator);
try {
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/CommunicationUtils.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/CommunicationUtils.java
index afcd45ed1e..bb445a3d9d 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/CommunicationUtils.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/CommunicationUtils.java
@@ -18,9 +18,9 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport;
+import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.apache.commons.codec.binary.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/xmpp/XMPPTransportHandler.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/xmpp/XMPPTransportHandler.java
index e4fb161e43..4ac76f45b6 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/xmpp/XMPPTransportHandler.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/transport/xmpp/XMPPTransportHandler.java
@@ -152,13 +152,10 @@ public abstract class XMPPTransportHandler implements TransportHandler
protected void connectToServer() throws TransportHandlerException {
try {
connection.connect();
- log.info(String.format(
- "Connection to XMPP Server at %1$s established successfully......", server));
+ log.info(String.format("Connection to XMPP Server at %1$s established successfully......", server));
} catch (XMPPException xmppExcepion) {
- String errorMsg =
- "Connection attempt to the XMPP Server at " + server + " via port " + port +
- " failed.";
+ String errorMsg = "Connection attempt to the XMPP Server at " + server + " via port " + port + " failed.";
log.info(errorMsg);
throw new TransportHandlerException(errorMsg, xmppExcepion);
}
@@ -180,28 +177,20 @@ public abstract class XMPPTransportHandler implements TransportHandler
try {
if (resource == null) {
connection.login(username, password);
- log.info(String.format("Logged into XMPP Server at %1$s as user %2$s......",
- server, username));
+ log.info(String.format("Logged into XMPP Server at %1$s as user %2$s......", server, username));
} else {
connection.login(username, password, resource);
- log.info(String.format(
- "Logged into XMPP Server at %1$s as user %2$s on resource %3$s......",
- server, username, resource));
+ log.info(String.format("Logged into XMPP Server at %1$s as user %2$s on resource %3$s......",
+ server, username, resource));
}
} catch (XMPPException xmppException) {
String errorMsg =
- "Login attempt to the XMPP Server at " + server + " with username - " +
- username + " failed.";
- log.info(errorMsg);
+ "Login attempt to the XMPP Server at " + server + " with username - " + username + " failed.";
+ log.error(errorMsg);
throw new TransportHandlerException(errorMsg, xmppException);
}
- } else {//TODO:: Log not required
- String errorMsg =
- "Not connected to XMPP-Server to attempt Login. Please 'connectToServer' " +
- "before Login";
- if (log.isDebugEnabled()) {
- log.debug(errorMsg);
- }
+ } else {
+ String errorMsg = "Not connected to XMPP-Server to attempt Login. Please 'connectToServer' before Login";
throw new TransportHandlerException(errorMsg);
}
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/resources/deviceConfig.properties b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/resources/deviceConfig.properties
index fb83c24d6f..930742a2aa 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/resources/deviceConfig.properties
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/resources/deviceConfig.properties
@@ -16,6 +16,7 @@
#
#[Device-Configurations]
+server-name=WSO2IoTServer
owner=shabirmean
deviceId=t4ctwq8qfl11
device-name=SMEAN_t4ctwq8qfl11
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/VirtualFireAlarmService.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/VirtualFireAlarmService.java
index c505e1c36f..c9c0056548 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/VirtualFireAlarmService.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/VirtualFireAlarmService.java
@@ -121,8 +121,8 @@ public class VirtualFireAlarmService {
final VirtualFireAlarmXMPPConnector virtualFireAlarmXMPPConnector) {
this.virtualFireAlarmXMPPConnector = virtualFireAlarmXMPPConnector;
- if (MqttConfig.getInstance().isEnabled()) {
- Runnable mqttStarter = new Runnable() {
+ if (XmppConfig.getInstance().isEnabled()) {
+ Runnable xmppStarter = new Runnable() {
@Override
public void run() {
virtualFireAlarmXMPPConnector.initConnector();
@@ -130,9 +130,9 @@ public class VirtualFireAlarmService {
}
};
- Thread mqttStarterThread = new Thread(mqttStarter);
- mqttStarterThread.setDaemon(true);
- mqttStarterThread.start();
+ Thread xmppStarterThread = new Thread(xmppStarter);
+ xmppStarterThread.setDaemon(true);
+ xmppStarterThread.start();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, VirtualFireAlarmMQTTConnector not started.");
}
@@ -144,7 +144,7 @@ public class VirtualFireAlarmService {
public void setVirtualFireAlarmMQTTConnector(
final VirtualFireAlarmMQTTConnector virtualFireAlarmMQTTConnector) {
this.virtualFireAlarmMQTTConnector = virtualFireAlarmMQTTConnector;
- if (XmppConfig.getInstance().isEnabled()) {
+ if (MqttConfig.getInstance().isEnabled()) {
virtualFireAlarmMQTTConnector.connect();
} else {
log.warn("XMPP disabled in 'devicemgt-config.xml'. Hence, VirtualFireAlarmXMPPConnector not started.");
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/transport/VirtualFireAlarmXMPPConnector.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/transport/VirtualFireAlarmXMPPConnector.java
index b5ddf93dfd..ef74390d14 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/transport/VirtualFireAlarmXMPPConnector.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.controller.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/transport/VirtualFireAlarmXMPPConnector.java
@@ -71,42 +71,43 @@ public class VirtualFireAlarmXMPPConnector extends XMPPTransportHandler {
}
public void createXMPPAccountForDeviceType() {
- boolean accountExists = false;
+ boolean accountExists;
XmppServerClient xmppServerClient = new XmppServerClient();
xmppServerClient.initControlQueue();
try {
accountExists = xmppServerClient.doesXMPPUserAccountExist(xmppVFireAlarmAdminUsername);
- } catch (DeviceControllerException e) {
- String errorMsg = "An error was encountered whilst trying to check whether Server XMPP account exists " +
- "for device-type - " + VirtualFireAlarmConstants.DEVICE_TYPE;
- log.error(errorMsg, e);
- }
- if (!accountExists) {
- XmppAccount xmppAccount = new XmppAccount();
-
- xmppAccount.setAccountName(xmppVFireAlarmAdminUsername);
- xmppAccount.setUsername(xmppVFireAlarmAdminUsername);
- xmppAccount.setPassword(V_FIREALARM_XMPP_PASSWORD);
- xmppAccount.setEmail("");
-
- try {
- boolean xmppCreated = xmppServerClient.createXMPPAccount(xmppAccount);
- if (!xmppCreated) {
- log.warn("Server XMPP Account was not created for device-type - " +
- VirtualFireAlarmConstants.DEVICE_TYPE +
- ". Check whether XMPP is enabled in \"devicemgt-config.xml\" & restart.");
- } else {
- log.info("Server XMPP Account [" + xmppVFireAlarmAdminUsername +
- "] was not created for device-type - " + VirtualFireAlarmConstants.DEVICE_TYPE);
+ if (!accountExists) {
+ XmppAccount xmppAccount = new XmppAccount();
+
+ xmppAccount.setAccountName(xmppVFireAlarmAdminUsername);
+ xmppAccount.setUsername(xmppVFireAlarmAdminUsername);
+ xmppAccount.setPassword(V_FIREALARM_XMPP_PASSWORD);
+ xmppAccount.setEmail("");
+
+ try {
+ boolean xmppCreated = xmppServerClient.createXMPPAccount(xmppAccount);
+ if (!xmppCreated) {
+ log.warn("Server XMPP Account was not created for device-type - " +
+ VirtualFireAlarmConstants.DEVICE_TYPE +
+ ". Check whether XMPP is enabled in \"devicemgt-config.xml\" & restart.");
+ } else {
+ log.info("Server XMPP Account [" + xmppVFireAlarmAdminUsername +
+ "] was not created for device-type - " + VirtualFireAlarmConstants.DEVICE_TYPE);
+ }
+ } catch (DeviceControllerException e) {
+ String errorMsg =
+ "An error was encountered whilst trying to create Server XMPP account for device-type - "
+ + VirtualFireAlarmConstants.DEVICE_TYPE;
+ log.error(errorMsg, e);
}
- } catch (DeviceControllerException e) {
- String errorMsg =
- "An error was encountered whilst trying to create Server XMPP account for device-type - "
- + VirtualFireAlarmConstants.DEVICE_TYPE;
- log.error(errorMsg, e);
}
+
+ } catch (DeviceControllerException e) {
+ String errorMsg = "An error was encountered whilst trying to check whether Server XMPP account exists " +
+ "for device-type - " + VirtualFireAlarmConstants.DEVICE_TYPE + ".\n Check [devicemgt-config.xml]";
+ log.error(errorMsg, e);
}
}
diff --git a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/VirtualFireAlarmService.java b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/VirtualFireAlarmService.java
index 1f08a15dff..e340b63c5d 100644
--- a/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/VirtualFireAlarmService.java
+++ b/components/device-mgt-iot-virtualfirealarm/org.wso2.carbon.device.mgt.iot.virtualfirealarm.mgt.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/VirtualFireAlarmService.java
@@ -95,14 +95,9 @@ public class VirtualFireAlarmService {
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
- public static final String XMPP_PROTOCOL = "XMPP";
- public static final String HTTP_PROTOCOL = "HTTP";
- public static final String MQTT_PROTOCOL = "MQTT";
-
private VerificationManager verificationManager;
private VirtualFireAlarmMQTTConnector virtualFireAlarmMQTTConnector;
private VirtualFireAlarmXMPPConnector virtualFireAlarmXMPPConnector;
- private ConcurrentHashMap deviceToIpMap = new ConcurrentHashMap<>();
/**
* @param verificationManager
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 f4007e4b5a..bc51240cc5 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
@@ -47,6 +47,10 @@
org.wso2.carbon.device.mgt.iot.androidsense.api
war
+
+ com.h2database.wso2
+ h2-database-engine
+
@@ -134,6 +138,44 @@
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+
+
+
+ create-android-sense-plugin-mgt-schema
+ package
+
+ run
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
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
new file mode 100644
index 0000000000..b5fd6aa336
Binary files /dev/null and b/features/device-mgt-iot-androidsense-feature/org.wso2.carbon.device.mgt.iot.androidsense.feature/src/main/resources/database/AndroidSenseDM_DB.h2.db differ
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 363b9f6401..1fc9b1bf5f 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,4 +10,5 @@ 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.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/pom.xml b/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/pom.xml
index d8ff3a757f..9210d92e59 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
@@ -47,6 +47,10 @@
org.wso2.carbon.device.mgt.iot.arduino.service.impl
war
+
+ com.h2database.wso2
+ h2-database-engine
+
@@ -137,6 +141,45 @@
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+
+
+
+ create-arduino-plugin-mgt-schema
+ package
+
+ run
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
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
new file mode 100644
index 0000000000..83aac0e4f9
Binary files /dev/null and b/features/device-mgt-iot-arduino-feature/org.wso2.carbon.device.mgt.iot.arduino.feature/src/main/resources/database/ArduinoDM_DB.h2.db differ
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 b657148f81..81f3576d03 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,3 +10,4 @@ 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.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/pom.xml b/features/device-mgt-iot-digitaldisplay-feature/org.wso2.carbon.device.mgt.iot.digitaldisplay.feature/pom.xml
index e73df653a8..0ff03e31b5 100644
--- a/features/device-mgt-iot-digitaldisplay-feature/org.wso2.carbon.device.mgt.iot.digitaldisplay.feature/pom.xml
+++ b/features/device-mgt-iot-digitaldisplay-feature/org.wso2.carbon.device.mgt.iot.digitaldisplay.feature/pom.xml
@@ -32,7 +32,10 @@
1.9.2-SNAPSHOT
war
-
+
+ com.h2database.wso2
+ h2-database-engine
+
@@ -123,6 +126,44 @@
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+
+
+
+ create-digital-display-plugin-mgt-schema
+ package
+
+ run
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
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
new file mode 100644
index 0000000000..99cf289480
Binary files /dev/null and b/features/device-mgt-iot-digitaldisplay-feature/org.wso2.carbon.device.mgt.iot.digitaldisplay.feature/src/main/resources/database/DigitalDisplayDM_DB.h2.db differ
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 47f3460854..c2a5ee7649 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,3 +8,4 @@ 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.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/pom.xml b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/pom.xml
index 4ab113b21f..bab4aa84b5 100644
--- a/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/pom.xml
+++ b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/pom.xml
@@ -29,6 +29,10 @@
org.wso2.carbon.device.mgt.iot.droneanalyzer.api
war
+
+ com.h2database.wso2
+ h2-database-engine
+
@@ -118,6 +122,45 @@
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+
+
+
+ create-drone-analyzer-plugin-mgt-schema
+ package
+
+ run
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
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
new file mode 100644
index 0000000000..2bc2566bbb
Binary files /dev/null and b/features/device-mgt-iot-droneanalyzer-feature/org.wso2.carbon.device.mgt.iot.droneanalyzer.feature/src/main/resources/database/DroneAnalyzerDM_DB.h2.db differ
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 f45bf3b15e..76c663d420 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,3 +10,4 @@ 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.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/pom.xml b/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/pom.xml
index 4c346ed589..61c2a3b131 100644
--- a/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/pom.xml
+++ b/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/pom.xml
@@ -52,6 +52,10 @@
org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl
war
+
+ com.h2database.wso2
+ h2-database-engine
+
@@ -151,6 +155,45 @@
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+
+
+
+ create-raspberrypi-plugin-mgt-schema
+ package
+
+ run
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/database/RaspberryPiDM_DB.h2.db b/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/database/RaspberryPiDM_DB.h2.db
new file mode 100644
index 0000000000..0d095aa474
Binary files /dev/null and b/features/device-mgt-iot-raspberrypi-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.feature/src/main/resources/database/RaspberryPiDM_DB.h2.db differ
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 d8b9f08841..561502c417 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,3 +10,4 @@ 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.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/pom.xml b/features/device-mgt-iot-virtualfirealarm-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/pom.xml
index 6bded2bc55..75e9e78ae9 100644
--- a/features/device-mgt-iot-virtualfirealarm-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/pom.xml
+++ b/features/device-mgt-iot-virtualfirealarm-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/pom.xml
@@ -54,6 +54,10 @@
1.9.2-SNAPSHOT
war
+
+ com.h2database.wso2
+ h2-database-engine
+
@@ -194,6 +198,44 @@
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+
+
+
+ create-virtual-firealarm-plugin-mgt-schema
+ package
+
+ run
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/features/device-mgt-iot-virtualfirealarm-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/database/VirtualFireAlarmDM_DB.h2.db b/features/device-mgt-iot-virtualfirealarm-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/database/VirtualFireAlarmDM_DB.h2.db
new file mode 100644
index 0000000000..f4fea15744
Binary files /dev/null and b/features/device-mgt-iot-virtualfirealarm-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature/src/main/resources/database/VirtualFireAlarmDM_DB.h2.db differ
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 7232bbcbdf..97090f7c6e 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,3 +14,4 @@ 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.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/pom.xml b/features/device-mgt-mdm-android-feature/org.wso2.carbon.device.mgt.mobile.android.feature/pom.xml
index fb537f11c0..0df6f53c6a 100644
--- a/features/device-mgt-mdm-android-feature/org.wso2.carbon.device.mgt.mobile.android.feature/pom.xml
+++ b/features/device-mgt-mdm-android-feature/org.wso2.carbon.device.mgt.mobile.android.feature/pom.xml
@@ -43,6 +43,10 @@
org.wso2.carbon.devicemgt-plugins
org.wso2.carbon.device.mgt.mobile.android
+
+ com.h2database.wso2
+ h2-database-engine
+
@@ -138,6 +142,45 @@
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+
+
+
+ create-android-mobile-plugin-mgt-schema
+ package
+
+ run
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
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
new file mode 100644
index 0000000000..7eca951de4
Binary files /dev/null and b/features/device-mgt-mdm-android-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/database/WSO2MobileAndroid_DB.h2.db differ
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 17704328cb..a30fb7a137 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,3 +4,4 @@ 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.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/pom.xml b/features/device-mgt-mdm-windows-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/pom.xml
index b8fd970b33..a6f32d0b69 100644
--- a/features/device-mgt-mdm-windows-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/pom.xml
+++ b/features/device-mgt-mdm-windows-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/pom.xml
@@ -43,6 +43,10 @@
org.wso2.carbon.devicemgt-plugins
org.wso2.carbon.device.mgt.mobile.windows
+
+ com.h2database.wso2
+ h2-database-engine
+
@@ -138,6 +142,45 @@
+
+
+ org.apache.maven.plugins
+ maven-antrun-plugin
+
+
+
+ create-windows-mobile-plugin-mgt-schema
+ package
+
+ run
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
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
new file mode 100644
index 0000000000..ca0bd4ed55
Binary files /dev/null and b/features/device-mgt-mdm-windows-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/src/main/resources/database/WSO2MobileWindows_DB.h2.db differ
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 51c9fac4be..9b394f853c 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,3 +3,4 @@ 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.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.windows_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\