Merge branch 'master' of https://github.com/wso2/carbon-device-mgt-plugins into devicetype-3.1.0

revert-dabc3590
ayyoob 8 years ago
commit 92ee01d597

@ -1,6 +1,8 @@
#carbon-device-mgt-plugins # carbon-device-mgt-plugins
<a href='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt-plugins/'><img src='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt-plugins/badge/icon'></a> <a href='https://opensource.org/licenses/Apache-2.0'><img src='https://img.shields.io/badge/License-Apache%202.0-blue.svg'></a><br/>
<a href='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt-plugins/'><img src='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt-plugins/badge/icon'></a> - Java7<br/>
<a href='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt-plugins__java8/'><img src='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt-plugins__java8/badge/icon'></a> - Java8
WSO2 MOBILE DEVICE MANAGER WSO2 MOBILE DEVICE MANAGER

@ -21,7 +21,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>iot-analytics</artifactId> <artifactId>iot-analytics</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>iot-analytics</artifactId> <artifactId>iot-analytics</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>iot-analytics</artifactId> <artifactId>iot-analytics</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>iot-analytics</artifactId> <artifactId>iot-analytics</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -33,6 +33,9 @@
} else if(action === 'getData'){ } else if(action === 'getData'){
print(providerAPI.getData(id, type, timeFrom, timeTo)); print(providerAPI.getData(id, type, timeFrom, timeTo));
return; return;
} else if(action === 'getAlerts'){
print(providerAPI.getAlerts(id));
return;
} }
}()); }());

@ -34,6 +34,7 @@ var getConfig, validate, getMode, getSchema, getData, registerCallBackforPush;
var JS_MIN_VALUE = "-9007199254740992"; var JS_MIN_VALUE = "-9007199254740992";
var tableName = "ORG_WSO2_GEO_FUSEDSPATIALEVENT"; var tableName = "ORG_WSO2_GEO_FUSEDSPATIALEVENT";
var alertTable = "ORG_WSO2_GEO_ALERTSNOTIFICATION";
var typeMap = { var typeMap = {
"bool": "string", "bool": "string",
@ -130,9 +131,9 @@ var getConfig, validate, getMode, getSchema, getData, registerCallBackforPush;
"query": luceneQuery, "query": luceneQuery,
"start": 0, "start": 0,
"count": limit, "count": limit,
"sortBy" : [{ "sortBy": [{
"field" : "timeStamp", "field": "timeStamp",
"sortType" : "ASC" "sortType": "ASC"
}] }]
}; };
result = connector.search(loggedInUser, tableName, stringify(filter)).getMessage(); result = connector.search(loggedInUser, tableName, stringify(filter)).getMessage();
@ -151,4 +152,28 @@ var getConfig, validate, getMode, getSchema, getData, registerCallBackforPush;
return data; return data;
}; };
getAlerts = function (deviceId) {
var limit = 50;
var result;
//if there's a filter present, we should perform a Lucene search instead of reading the table
var luceneQuery = 'id:"' + deviceId;
var filter = {
"query": luceneQuery,
"start": 0,
"count": limit,
"sortBy": [{
"field": "timeStamp",
"sortType": "ASC"
}]
};
result = connector.search(loggedInUser, tableName, stringify(filter)).getMessage();
result = JSON.parse(result);
var data = [];
for (var i = 0; i < result.length; i++) {
var values = result[i].values;
data.push(values);
}
return data;
};
}()); }());

@ -509,38 +509,43 @@ function removeGeoFence(geoFenceElement, id) {
} }
function getAlertsHistory(objectId) { function getAlertsHistory(objectId) {
$.getJSON("/portal/store/carbon.super/fs/gadget/geo-dashboard/controllers/get_alerts_history.jag?objectId=" + objectId, function (data) { $.ajax({
var alertsContainer = $('#showAlertsArea').empty(); url: '/portal/store/carbon.super/fs/gadget/geo-dashboard/controllers/gadget-controller.jag?action=getAlerts&id=' + objectId,
$.each(data, function (key, val) { method: "GET",
var alertDOMElement = document.createElement('a'); // Reason for using document.createElement (performance issue) http://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent contentType: "application/json",
async: false,
switch (val.STATE) { success: function (data) {
case "NORMAL": var alertsContainer = $('#showAlertsArea').empty();
$.each(data, function (key, val) {
var alertDOMElement = document.createElement('a'); // Reason for using document.createElement (performance issue) http://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent
switch (val.STATE) {
case "NORMAL":
// $(alertDOMElement).addClass("list-group-item list-group-item-info"); // $(alertDOMElement).addClass("list-group-item list-group-item-info");
return; return;
case "WARNING": case "WARNING":
$(alertDOMElement).addClass("list-group-item list-group-item-warning"); $(alertDOMElement).addClass("list-group-item list-group-item-warning");
break; break;
case "ALERTED": case "ALERTED":
$(alertDOMElement).addClass("list-group-item list-group-item-danger"); $(alertDOMElement).addClass("list-group-item list-group-item-danger");
break; break;
case "OFFLINE": case "OFFLINE":
$(alertDOMElement).addClass("list-group-item list-group-item-success"); $(alertDOMElement).addClass("list-group-item list-group-item-success");
break; break;
} }
$(alertDOMElement).html(val.INFORMATION); $(alertDOMElement).html(val.INFORMATION);
$(alertDOMElement).css({marginTop: "5px"}); $(alertDOMElement).css({marginTop: "5px"});
$(alertDOMElement).attr('onClick', 'showAlertInMap(this)'); $(alertDOMElement).attr('onClick', 'showAlertInMap(this)');
// Set HTML5 data attributes for later use // Set HTML5 data attributes for later use
$(alertDOMElement).attr('data-id', val.ID); $(alertDOMElement).attr('data-id', val.ID);
$(alertDOMElement).attr('data-latitude', val.LATITUDE); $(alertDOMElement).attr('data-latitude', val.LATITUDE);
$(alertDOMElement).attr('data-longitude', val.LONGITUDE); $(alertDOMElement).attr('data-longitude', val.LONGITUDE);
$(alertDOMElement).attr('data-state', val.STATE); $(alertDOMElement).attr('data-state', val.STATE);
$(alertDOMElement).attr('data-information', val.INFORMATION); $(alertDOMElement).attr('data-information', val.INFORMATION);
alertsContainer.append(alertDOMElement); alertsContainer.append(alertDOMElement);
}); });
}
}); });
} }

@ -1,37 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<eventPublisher name="Geo-Publisher-RDBMS-GeoAlertNotifications"
statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.geo.AlertsNotifications" version="1.0.0"/>
<mapping customMapping="enable" type="map">
<property>
<from name="id"/>
<to name="id"/>
</property>
<property>
<from name="state"/>
<to name="state"/>
</property>
<property>
<from name="information"/>
<to name="information"/>
</property>
<property>
<from name="timeStamp"/>
<to name="timeStamp"/>
</property>
<property>
<from name="longitude"/>
<to name="longitude"/>
</property>
<property>
<from name="latitude"/>
<to name="latitude"/>
</property>
</mapping>
<to eventAdapterType="rdbms">
<property name="datasource.name">WSO2_GEO_DB</property>
<property name="table.name">alerts_history</property>
<property name="execution.mode">insert</property>
<property name="update.keys"/>
</to>
</eventPublisher>

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<EventStoreConfiguration>
<TableSchema>
<ColumnDefinition>
<Name>id</Name>
<IsFacet>false</IsFacet>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>state</Name>
<IsFacet>false</IsFacet>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>information</Name>
<IsFacet>false</IsFacet>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>timeStamp</Name>
<IsFacet>false</IsFacet>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>latitude</Name>
<IsFacet>false</IsFacet>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>longitude</Name>
<IsFacet>false</IsFacet>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>type</Name>
<IsFacet>false</IsFacet>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
</TableSchema>
<Source>
<StreamId>Geo-Publisher-RDBMS-GeoAlertNotifications:1.0.0</StreamId>
</Source>
<MergeSchema>false</MergeSchema>
<RecordStoreName>EVENT_STORE</RecordStoreName>
</EventStoreConfiguration>

@ -16,6 +16,6 @@
~ under the License. ~ under the License.
--> -->
<artifact name="Geo-Publisher-RDBMS-GeoAlertNotifications" version="1.0.0" type="event/publisher" serverRole="GeoDashboard"> <artifact name="Geo-Publisher-RDBMS-GeoAlertNotifications" version="1.0.0" type="analytics/eventstore" serverRole="GeoDashboard">
<file>Geo-Publisher-RDBMS-GeoAlertNotifications-1.0.0.xml</file> <file>Geo-Publisher-RDBMS-GeoAlertNotifications.xml</file>
</artifact> </artifact>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>analytics</artifactId> <artifactId>analytics</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>carbon-device-mgt-plugins-parent</artifactId> <artifactId>carbon-device-mgt-plugins-parent</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -1,55 +1,55 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="center_horizontal" android:layout_height="match_parent" android:gravity="center_horizontal"
android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" tools:context="org.wso2.carbon.iot.android.sense.RegisterActivity" android:paddingTop="@dimen/activity_vertical_margin" tools:context="org.wso2.carbon.iot.android.sense.RegisterActivity"
android:weightSum="1"> android:weightSum="1">
<!-- Login progress --> <!-- Login progress -->
<ProgressBar android:id="@+id/login_progress" style="?android:attr/progressBarStyleLarge" <ProgressBar android:id="@+id/login_progress" style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="8dp" android:visibility="gone" /> android:layout_marginBottom="8dp" android:visibility="gone" />
<ScrollView android:id="@+id/login_form" android:layout_width="match_parent" <ScrollView android:id="@+id/login_form" android:layout_width="match_parent"
android:layout_height="153dp" android:layout_height="153dp"
android:fillViewport="false" android:fillViewport="false"
> >
<LinearLayout android:id="@+id/email_login_form" android:layout_width="match_parent" <LinearLayout android:id="@+id/email_login_form" android:layout_width="match_parent"
android:layout_height="wrap_content" android:orientation="vertical"> android:layout_height="wrap_content" android:orientation="vertical">
<EditText <EditText
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:hint="@string/prompt_username" android:layout_height="wrap_content" android:hint="@string/prompt_username"
android:id="@+id/username" android:id="@+id/username"
android:inputType="text" android:inputType="text"
android:maxLines="1" android:singleLine="true" android:maxLines="1" android:singleLine="true"
/> />
<EditText android:id="@+id/password" android:layout_width="match_parent" <EditText android:id="@+id/password" android:layout_width="match_parent"
android:layout_height="wrap_content" android:hint="@string/prompt_password" android:layout_height="wrap_content" android:hint="@string/prompt_password"
android:inputType="textPassword" android:inputType="textPassword"
android:maxLines="1" android:singleLine="true" android:maxLines="1" android:singleLine="true"
/> />
<EditText <EditText
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:hint="@string/hostname" android:layout_height="wrap_content" android:hint="@string/hostname"
android:id="@+id/hostname" android:id="@+id/hostname"
android:text="https://localhost:8243" android:text="https://localhost:8243"
android:inputType="text" android:inputType="text"
android:maxLines="1" android:singleLine="true"/> android:maxLines="1" android:singleLine="true"/>
</LinearLayout> </LinearLayout>
</ScrollView> </ScrollView>
<Button android:id="@+id/device_register_button" style="?android:textAppearanceSmall" <Button android:id="@+id/device_register_button" style="?android:textAppearanceSmall"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="16dp" android:text="@string/action_sign_in" android:layout_marginTop="16dp" android:text="@string/action_sign_in"
android:textStyle="bold" android:textStyle="bold"
android:layout_gravity="center_horizontal"/> android:layout_gravity="center_horizontal"/>
</LinearLayout> </LinearLayout>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>androidsense-plugin</artifactId> <artifactId>androidsense-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -161,7 +161,6 @@
serverRole="DataAnalyticsServer"/> serverRole="DataAnalyticsServer"/>
<dependency artifact="android_sense_dashboard" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/> <dependency artifact="android_sense_dashboard" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="android_headset_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/> <dependency artifact="android_headset_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="android_sense_streams" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="android_sms_chart_gadget" version="1.0.0" include="true" <dependency artifact="android_sms_chart_gadget" version="1.0.0" include="true"
serverRole="DataAnalyticsServer"/> serverRole="DataAnalyticsServer"/>
<dependency artifact="android_sms_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/> <dependency artifact="android_sms_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
@ -174,7 +173,6 @@
serverRole="DataAnalyticsServer"/> serverRole="DataAnalyticsServer"/>
<dependency artifact="android_un_secured_devices_gadget" version="1.0.0" include="true" <dependency artifact="android_un_secured_devices_gadget" version="1.0.0" include="true"
serverRole="DataAnalyticsServer"/> serverRole="DataAnalyticsServer"/>
<dependency artifact="android_sense_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="android_sense_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/> <dependency artifact="android_sense_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="android_accelerometer_streams" version="1.0.0" include="true" <dependency artifact="android_accelerometer_streams" version="1.0.0" include="true"

@ -3,7 +3,7 @@
<parent> <parent>
<artifactId>androidsense-plugin</artifactId> <artifactId>androidsense-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>androidsense-plugin</artifactId> <artifactId>androidsense-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -18,7 +18,7 @@
<div class="panel panel-default"> <div class="panel panel-default">
<div id="general-config-heading" class="panel-heading" role="tab"> <div id="general-config-heading" class="panel-heading" role="tab">
<h2 class="sub-title panel-title"> <h2 class="sub-title panel-title">
Android Sense Endpoint Configuration Android Sense Configuration
</h2> </h2>
</div> </div>
<div id="android_sense-config-body" class="panel-collapse panel-body" <div id="android_sense-config-body" class="panel-collapse panel-body"
@ -27,22 +27,32 @@
class="alert alert-danger hidden" role="alert"> class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span> <i class="icon fw fw-error"></i><span></span>
</div> </div>
<div class="wr-input-control">
<label class="wr-input-label" for="email-config-host">
Mqtt Endpoint
<span class="helper" title="SMTP Server Host">
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</span>
<br>
</label>
<input id="mqtt-endpoint" type="text" class="form-control"
placeholder="[ Required Field ]">
<br>
</div>
<div class="wr-input-control wr-btn-grp"> <div class="wr-input-control wr-btn-grp">
<button id="save-general-btn" class="wr-btn" onclick="addConfiguration();"> <button id="save-general-btn" class="wr-btn" onclick="artifactUpload();">
Save Deploy Analytics Artifacts
</button> </button>
</div>
</div>
</div>
<div id="androidsense-statistic-response-template" style="display: none">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i id="status-icon" class="fw fw-error fw-stack-1x"></i>
</span>
<br>
</h3>
<h4>
<span id="title"></span>
<br>
</h4>
<span id="description"></span>
</div>
</div> </div>
</div> </div>
</div> </div>

@ -18,20 +18,7 @@
function onRequest(context){ function onRequest(context){
var viewModel = {}; var viewModel = {};
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; viewModel["permissions"] = userModule.getUIPermissions();
var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/admin/devicetype/deploy/raspberrypi/status";
serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
var responseContent = responsePayload.status;
new Log().error(responseContent);
if ("204" == responsePayload.status) {
viewModel["displayStatus"] = "Display";
}
},
function (responsePayload) {
//do nothing.
}
);
return viewModel; return viewModel;
} }

@ -95,3 +95,30 @@ var addConfiguration = function () {
} }
); );
}; };
var artifactUpload = function () {
var contentType = "application/json";
var backendEndBasePath = "/api/device-mgt/v1.0";
var urix = backendEndBasePath + "/admin/devicetype/deploy/android_sense";
var defaultStatusClasses = "fw fw-stack-1x";
var content = $("#androidsense-statistic-response-template").find(".content");
var title = content.find("#title");
var statusIcon = content.find("#status-icon");
var data = {}
invokerUtil.post(urix, data, function (data) {
title.html("Deploying statistic artifacts. Please wait...");
statusIcon.attr("class", defaultStatusClasses + " fw-check");
$(modalPopupContent).html(content.html());
showPopup();
setTimeout(function () {
hidePopup();
location.reload(true);
}, 5000);
}, function (jqXHR) {
title.html("Failed to deploy artifacts, Please contact administrator.");
statusIcon.attr("class", defaultStatusClasses + " fw-error");
$(modalPopupContent).html(content.html());
showPopup();
}, contentType);
};

@ -73,30 +73,3 @@ function attachEvents() {
} }
} }
function artifactUpload() {
var contentType = "application/json";
var urix = backendEndBasePath + "/admin/devicetype/deploy/android_sense";
var defaultStatusClasses = "fw fw-stack-1x";
var content = $("#androidsense-statistic-response-template").find(".content");
var title = content.find("#title");
var statusIcon = content.find("#status-icon");
var data = {}
invokerUtil.post(urix, data, function (data) {
title.html("Deploying statistic artifacts. Please wait...");
statusIcon.attr("class", defaultStatusClasses + " fw-check");
$(modalPopupContent).html(content.html());
showPopup();
setTimeout(function () {
hidePopup();
location.reload(true);
}, 5000);
}, function (jqXHR) {
title.html("Failed to deploy artifacts, Please contact administrator.");
statusIcon.attr("class", defaultStatusClasses + " fw-error");
$(modalPopupContent).html(content.html());
showPopup();
}, contentType);
}

@ -41,9 +41,6 @@
<a href="#" class="download-link btn-operations"><i class="fw fw-mobile fw-inverse fw-lg add-margin-1x"></i> Enroll Device</a> <a href="#" class="download-link btn-operations"><i class="fw fw-mobile fw-inverse fw-lg add-margin-1x"></i> Enroll Device</a>
<a href="{{hostName}}{{@unit.publicUri}}/asset/androidsense.apk" class="btn-operations"><i class="fw fw-download fw-inverse fw-lg add-margin-1x"></i> Download APK</a> <a href="{{hostName}}{{@unit.publicUri}}/asset/androidsense.apk" class="btn-operations"><i class="fw fw-download fw-inverse fw-lg add-margin-1x"></i> Download APK</a>
<a href="javascript:toggleEmailInvite()" class="btn-operations"><i class="fw fw-mail fw-inverse fw-lg add-margin-1x"></i> Invite by Email</a> <a href="javascript:toggleEmailInvite()" class="btn-operations"><i class="fw fw-mail fw-inverse fw-lg add-margin-1x"></i> Invite by Email</a>
{{#if displayStatus}}
<a href="javascript:artifactUpload()" class="btn-operations"><i class="fw fw-upload fw-inverse fw-lg add-margin-1x"></i> Deploy Analytics Artifacts</a>
{{/if}}
<p class="doc-link">Click <a href="https://docs.wso2.com/display/IoTS300/Android+Sense" <p class="doc-link">Click <a href="https://docs.wso2.com/display/IoTS300/Android+Sense"
target="_blank">[ here ]</a> for latest instructions and target="_blank">[ here ]</a> for latest instructions and
troubleshooting.</p> troubleshooting.</p>

@ -19,20 +19,9 @@
function onRequest(context){ function onRequest(context){
var viewModel = {}; var viewModel = {};
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/admin/devicetype/deploy/android_sense/status"; var uiPermissions = userModule.getUIPermissions();
serviceInvokers.XMLHttp.get( viewModel["permissions"] = uiPermissions;
url, function (responsePayload) {
var responseContent = responsePayload.status;
new Log().error(responseContent);
if ("204" == responsePayload.status) {
viewModel["displayStatus"] = "Display";
}
},
function (responsePayload) {
//do nothing.
}
);
viewModel["hostName"] = devicemgtProps["generalConfig"]["host"]; viewModel["hostName"] = devicemgtProps["generalConfig"]["host"];
viewModel["enrollmentURL"] = viewModel["hostName"] + context.unit.publicUri + "/asset/androidsense.apk"; viewModel["enrollmentURL"] = viewModel["hostName"] + context.unit.publicUri + "/asset/androidsense.apk";
return viewModel; return viewModel;

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device-types</artifactId> <artifactId>device-types</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>arduino-plugin</artifactId> <artifactId>arduino-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>arduino-plugin</artifactId> <artifactId>arduino-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -20,7 +20,10 @@
<param-name>doAuthentication</param-name> <param-name>doAuthentication</param-name>
<param-value>true</param-value> <param-value>true</param-value>
</context-param> </context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim--> <!--publish to apim-->
<context-param> <context-param>
<param-name>managed-api-enabled</param-name> <param-name>managed-api-enabled</param-name>

@ -23,7 +23,7 @@
<parent> <parent>
<artifactId>arduino-plugin</artifactId> <artifactId>arduino-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -27,36 +27,35 @@
class="alert alert-danger hidden" role="alert"> class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span> <i class="icon fw fw-error"></i><span></span>
</div> </div>
<div class="wr-input-control">
<label class="wr-input-label" for="email-config-host">
Http Server IP
<span class="helper" title="SMTP Server Host">
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</span>
<br>
</label>
<input id="http-endpoint" type="text" class="form-control"
placeholder="[ Required Field ]">
<br>
<label class="wr-input-label" for="email-config-host">
Http Server Port
<span class="helper" title="SMTP Server Host">
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</span>
<br>
</label>
<input id="https-endpoint" type="text" class="form-control"
placeholder="[ Required Field ]">
<br>
</div>
<div class="wr-input-control wr-btn-grp"> <div class="wr-input-control wr-btn-grp">
<button id="save-general-btn" class="wr-btn" onclick="addConfiguration();"> <button id="save-general-btn" class="wr-btn" onclick="artifactUpload();">
Save Deploy Analytics Artifacts
</button> </button>
</div> </div>
</div> </div>
</div> </div>
<div id="arduino-statistic-response-template" style="display: none">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i id="status-icon" class="fw fw-error fw-stack-1x"></i>
</span>
<br>
</h3>
<h4>
<span id="title"></span>
<br>
</h4>
<span id="description"></span>
</div>
</div>
</div>
</div>
{{#zone "bottomJs"}} {{#zone "bottomJs"}}
{{js "js/platform-configuration.js"}} {{js "js/platform-configuration.js"}}
{{/zone}} {{/zone}}

@ -18,20 +18,7 @@
function onRequest(context){ function onRequest(context){
var viewModel = {}; var viewModel = {};
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; viewModel["permissions"] = userModule.getUIPermissions();
var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/admin/devicetype/deploy/virtual_firealarm/status";
serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
var responseContent = responsePayload.status;
new Log().error(responseContent);
if ("204" == responsePayload.status) {
viewModel["displayStatus"] = "Display";
}
},
function (responsePayload) {
//do nothing.
}
);
return viewModel; return viewModel;
} }

@ -103,3 +103,30 @@ var addConfiguration = function () {
} }
); );
}; };
var artifactUpload = function () {
var contentType = "application/json";
var backendEndBasePath = "/api/device-mgt/v1.0";
var urix = backendEndBasePath + "/admin/devicetype/deploy/arduino";
var defaultStatusClasses = "fw fw-stack-1x";
var content = $("#arduino-statistic-response-template").find(".content");
var title = content.find("#title");
var statusIcon = content.find("#status-icon");
var data = {}
invokerUtil.post(urix, data, function (data) {
title.html("Deploying statistic artifacts. Please wait...");
statusIcon.attr("class", defaultStatusClasses + " fw-check");
$(modalPopupContent).html(content.html());
showPopup();
setTimeout(function () {
hidePopup();
location.reload(true);
}, 5000);
}, function (jqXHR) {
title.html("Failed to deploy artifacts, Please contact administrator.");
statusIcon.attr("class", defaultStatusClasses + " fw-error");
$(modalPopupContent).html(content.html());
showPopup();
}, contentType);
};

@ -31,12 +31,23 @@ function onRequest(context) {
if (encodedClientKeys) { if (encodedClientKeys) {
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"]; var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var resp = tokenUtil.decode(encodedClientKeys).split(":"); var resp = tokenUtil.decode(encodedClientKeys).split(":");
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username, "default", {});
if (tokenPair) { if (user.domain == "carbon.super") {
token = tokenPair.accessToken; var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username , "default", {});
} if (tokenPair) {
websocketEndpoint = websocketEndpoint + "/secured-websocket/org.wso2.iot.devices.temperature/1.0.0?" token = tokenPair.accessToken;
+ "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token; }
websocketEndpoint = websocketEndpoint + "/secured-websocket/org.wso2.iot.devices.temperature/1.0.0?"
+ "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token;
} else {
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username + "@" + user.domain
, "default", {});
if (tokenPair) {
token = tokenPair.accessToken;
}
websocketEndpoint = websocketEndpoint + "/secured-websocket/t/" + user.domain + "/org.wso2.iot.devices.temperature/1.0.0?"
+ "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token;
}
} }
return {"device": device, "websocketEndpoint": websocketEndpoint}; return {"device": device, "websocketEndpoint": websocketEndpoint};
} }

@ -184,30 +184,3 @@ function doAction(data) {
}); });
} }
} }
function artifactUpload() {
var contentType = "application/json";
var urix = backendEndBasePath + "/admin/devicetype/deploy/arduino";
var defaultStatusClasses = "fw fw-stack-1x";
var content = $("#arduino-statistic-response-template").find(".content");
var title = content.find("#title");
var statusIcon = content.find("#status-icon");
var data = {}
invokerUtil.post(urix, data, function (data) {
title.html("Deploying statistic artifacts. Please wait...");
statusIcon.attr("class", defaultStatusClasses + " fw-check");
$(modalPopupContent).html(content.html());
showPopup();
setTimeout(function () {
hidePopup();
location.reload(true);
}, 5000);
}, function (jqXHR) {
title.html("Failed to deploy artifacts, Please contact administrator.");
statusIcon.attr("class", defaultStatusClasses + " fw-error");
$(modalPopupContent).html(content.html());
showPopup();
}, contentType);
}

@ -66,11 +66,6 @@
<a href="#" class="download-link btn-operations"> <a href="#" class="download-link btn-operations">
<i class="fw fw-download add-margin-1x"></i>Download Sketch <i class="fw fw-download add-margin-1x"></i>Download Sketch
</a> </a>
{{#if displayStatus}}
<a href="javascript:artifactUpload()" class="btn-operations"><i
class="fw fw-upload fw-inverse fw-lg add-margin-1x"></i> Deploy Analytics Artifacts</a>
{{/if}}
<p class="doc-link">Click <a href="https://docs.wso2.com/display/IoTS300/Arduino" <p class="doc-link">Click <a href="https://docs.wso2.com/display/IoTS300/Arduino"
target="_blank">here</a> for latest instructions and target="_blank">here</a> for latest instructions and
troubleshooting.</p> troubleshooting.</p>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device-types</artifactId> <artifactId>device-types</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>carbon-device-mgt-plugins-parent</artifactId> <artifactId>carbon-device-mgt-plugins-parent</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>raspberrypi-plugin</artifactId> <artifactId>raspberrypi-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -19,8 +19,6 @@
<artifacts> <artifacts>
<artifact name="raspberrypi" version="1.0.0" type="carbon/application"> <artifact name="raspberrypi" version="1.0.0" type="carbon/application">
<dependency artifact="raspberrypi_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="raspberrypi_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="raspberrypi_execution" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/> <dependency artifact="raspberrypi_execution" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact> </artifact>
</artifacts> </artifacts>

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="raspberrypi_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>raspberrypi_receiver.xml</file>
</artifact>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>raspberrypi-plugin</artifactId> <artifactId>raspberrypi-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -23,7 +23,7 @@
<parent> <parent>
<artifactId>raspberrypi-plugin</artifactId> <artifactId>raspberrypi-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -27,43 +27,32 @@
class="alert alert-danger hidden" role="alert"> class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span> <i class="icon fw fw-error"></i><span></span>
</div> </div>
<div class="wr-input-control">
<label class="wr-input-label" for="email-config-host">
Http Endpoint
<span class="helper" title="SMTP Server Host">
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</span>
<br>
</label>
<input id="http-endpoint" type="text" class="form-control"
placeholder="[ Required Field ]">
<br>
<label class="wr-input-label" for="email-config-host">
Https Endpoint
<span class="helper" title="SMTP Server Host">
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</span>
<br>
</label>
<input id="https-endpoint" type="text" class="form-control"
placeholder="[ Required Field ]">
<br>
<label class="wr-input-label" for="email-config-host">
Mqtt Endpoint
<span class="helper" title="SMTP Server Host">
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</span>
<br>
</label>
<input id="mqtt-endpoint" type="text" class="form-control"
placeholder="[ Required Field ]">
<br>
</div>
<div class="wr-input-control wr-btn-grp"> <div class="wr-input-control wr-btn-grp">
<button id="save-general-btn" class="wr-btn" onclick="addConfiguration();"> <button id="save-general-btn" class="wr-btn" onclick="artifactUpload();">
Save Deploy Analytics Artifacts
</button> </button>
</div>
</div>
</div>
<div id="raspberrypi-statistic-response-template" style="display: none">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i id="status-icon" class="fw fw-error fw-stack-1x"></i>
</span>
<br>
</h3>
<h4>
<span id="title"></span>
<br>
</h4>
<span id="description"></span>
</div>
</div> </div>
</div> </div>
</div> </div>

@ -16,22 +16,9 @@
* under the License. * under the License.
*/ */
function onRequest(context) { function onRequest(context){
var viewModel = {}; var viewModel = {};
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; viewModel["permissions"] = userModule.getUIPermissions();
var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/admin/devicetype/deploy/arduino/status";
serviceInvokers.XMLHttp.get(
url, function (responsePayload) {
var responseContent = responsePayload.status;
new Log().error(responseContent);
if ("204" == responsePayload.status) {
viewModel["displayStatus"] = "Display";
}
},
function (responsePayload) {
//do nothing.
}
);
return viewModel; return viewModel;
} }

@ -113,3 +113,30 @@ var addConfiguration = function () {
} }
); );
}; };
var artifactUpload = function () {
var contentType = "application/json";
var backendEndBasePath = "/api/device-mgt/v1.0";
var urix = backendEndBasePath + "/admin/devicetype/deploy/raspberrypi";
var defaultStatusClasses = "fw fw-stack-1x";
var content = $("#raspberrypi-statistic-response-template").find(".content");
var title = content.find("#title");
var statusIcon = content.find("#status-icon");
var data = {}
invokerUtil.post(urix, data, function (data) {
title.html("Deploying statistic artifacts. Please wait...");
statusIcon.attr("class", defaultStatusClasses + " fw-check");
$(modalPopupContent).html(content.html());
showPopup();
setTimeout(function () {
hidePopup();
location.reload(true);
}, 5000);
}, function (jqXHR) {
title.html("Failed to deploy artifacts, Please contact administrator.");
statusIcon.attr("class", defaultStatusClasses + " fw-error");
$(modalPopupContent).html(content.html());
showPopup();
}, contentType);
};

@ -28,15 +28,32 @@ function onRequest(context) {
var jwtClient = jwtService.getJWTClient(); var jwtClient = jwtService.getJWTClient();
var encodedClientKeys = session.get(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]); var encodedClientKeys = session.get(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]);
var token = ""; var token = "";
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
if (encodedClientKeys) { if (encodedClientKeys) {
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"]; var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var resp = tokenUtil.decode(encodedClientKeys).split(":"); var resp = tokenUtil.decode(encodedClientKeys).split(":");
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username,"default", {});
if (tokenPair) { if (user.domain == "carbon.super") {
token = tokenPair.accessToken; var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username , "default", {});
} if (tokenPair) {
websocketEndpoint = websocketEndpoint + "/secured-websocket/org.wso2.iot.devices.temperature/1.0.0?" token = tokenPair.accessToken;
+ "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token; }
websocketEndpoint = websocketEndpoint + "/secured-websocket/org.wso2.iot.devices.temperature/1.0.0?"
+ "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token;
} else {
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username + "@" + user.domain
, "default", {});
if (tokenPair) {
token = tokenPair.accessToken;
}
websocketEndpoint = websocketEndpoint + "/secured-websocket/t/" + user.domain + "/org.wso2.iot.devices.temperature/1.0.0?"
+ "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token;
}
} }
return {"device": device, "websocketEndpoint": websocketEndpoint}; return {"device": device, "websocketEndpoint": websocketEndpoint};
} }

@ -182,31 +182,4 @@ function doAction(data) {
hidePopup(); hidePopup();
}); });
} }
}
function artifactUpload() {
var contentType = "application/json";
var urix = backendEndBasePath + "/admin/devicetype/deploy/raspberrypi";
var defaultStatusClasses = "fw fw-stack-1x";
var content = $("#raspberrypi-statistic-response-template").find(".content");
var title = content.find("#title");
var statusIcon = content.find("#status-icon");
var data = {}
invokerUtil.post(urix, data, function (data) {
title.html("Deploying statistic artifacts. Please wait...");
statusIcon.attr("class", defaultStatusClasses + " fw-check");
$(modalPopupContent).html(content.html());
showPopup();
setTimeout(function () {
hidePopup();
location.reload(true);
}, 5000);
}, function (jqXHR) {
title.html("Failed to deploy artifacts, Please contact administrator.");
statusIcon.attr("class", defaultStatusClasses + " fw-error");
$(modalPopupContent).html(content.html());
showPopup();
}, contentType);
} }

@ -61,9 +61,6 @@
<a href="#" class="download-link btn-operations"> <a href="#" class="download-link btn-operations">
<i class="fw fw-download add-margin-1x"></i>Download Agent <i class="fw fw-download add-margin-1x"></i>Download Agent
</a> </a>
{{#if displayStatus}}
<a href="javascript:artifactUpload()" class="btn-operations"><i class="fw fw-upload fw-inverse fw-lg add-margin-1x"></i> Deploy Analytics Artifacts</a>
{{/if}}
<p class="doc-link">Click <a href="https://docs.wso2.com/display/IoTS300/Raspberry+Pi" <p class="doc-link">Click <a href="https://docs.wso2.com/display/IoTS300/Raspberry+Pi"
target="_blank">here</a> for latest instructions and target="_blank">here</a> for latest instructions and

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device-types</artifactId> <artifactId>device-types</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -23,7 +23,7 @@
<parent> <parent>
<artifactId>virtual-fire-alarm-plugin</artifactId> <artifactId>virtual-fire-alarm-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -23,7 +23,7 @@
<parent> <parent>
<artifactId>virtual-fire-alarm-plugin</artifactId> <artifactId>virtual-fire-alarm-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>virtual-fire-alarm-plugin</artifactId> <artifactId>virtual-fire-alarm-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -19,8 +19,6 @@
<artifacts> <artifacts>
<artifact name="virtualfirealarm" version="1.0.0" type="carbon/application"> <artifact name="virtualfirealarm" version="1.0.0" type="carbon/application">
<dependency artifact="virtualfirealarm_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="virtualfirealarm_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="virtualfirealarm_execution" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/> <dependency artifact="virtualfirealarm_execution" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact> </artifact>
</artifacts> </artifacts>

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="virtualfirealarm_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>virtualfirealarm_receiver.xml</file>
</artifact>

@ -1,23 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name= "virtualfirealarm_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.virtualfirealarm_1.0.0.json</file>
</artifact>

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>virtual-fire-alarm-plugin</artifactId> <artifactId>virtual-fire-alarm-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -20,6 +20,10 @@
<param-name>doAuthentication</param-name> <param-name>doAuthentication</param-name>
<param-value>true</param-value> <param-value>true</param-value>
</context-param> </context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim--> <!--publish to apim-->
<context-param> <context-param>

@ -23,7 +23,7 @@
<parent> <parent>
<artifactId>virtual-fire-alarm-plugin</artifactId> <artifactId>virtual-fire-alarm-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -19,7 +19,7 @@
<div class="panel panel-default"> <div class="panel panel-default">
<div id="general-config-heading" class="panel-heading" role="tab"> <div id="general-config-heading" class="panel-heading" role="tab">
<h2 class="sub-title panel-title"> <h2 class="sub-title panel-title">
Virtual Firealarm Endpoint Configuration Virtual Firealarm Configuration
</h2> </h2>
</div> </div>
<div id="virtual-alarm-config-body" class="panel-collapse panel-body" <div id="virtual-alarm-config-body" class="panel-collapse panel-body"
@ -28,43 +28,32 @@
class="alert alert-danger hidden" role="alert"> class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span> <i class="icon fw fw-error"></i><span></span>
</div> </div>
<div class="wr-input-control">
<label class="wr-input-label" for="email-config-host">
Http Endpoint
<span class="helper" title="SMTP Server Host">
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</span>
<br>
</label>
<input id="http-endpoint" type="text" class="form-control"
placeholder="[ Required Field ]">
<br>
<label class="wr-input-label" for="email-config-host">
Https Endpoint
<span class="helper" title="SMTP Server Host">
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</span>
<br>
</label>
<input id="https-endpoint" type="text" class="form-control"
placeholder="[ Required Field ]">
<br>
<label class="wr-input-label" for="email-config-host">
Mqtt Endpoint
<span class="helper" title="SMTP Server Host">
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</span>
<br>
</label>
<input id="mqtt-endpoint" type="text" class="form-control"
placeholder="[ Required Field ]">
<br>
</div>
<div class="wr-input-control wr-btn-grp"> <div class="wr-input-control wr-btn-grp">
<button id="save-general-btn-virtualfirealarm" class="wr-btn" onclick="addConfiguration();"> <button id="save-general-btn" class="wr-btn" onclick="artifactUpload();">
Save Deploy Analytics Artifacts
</button> </button>
</div>
</div>
</div>
<div id="virtual-firealarm-statistic-response-template" style="display: none">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>
<span class="fw-stack">
<i class="fw fw-circle-outline fw-stack-2x"></i>
<i id="status-icon" class="fw fw-error fw-stack-1x"></i>
</span>
<br>
</h3>
<h4>
<span id="title"></span>
<br>
</h4>
<span id="description"></span>
</div>
</div> </div>
</div> </div>
</div> </div>

@ -0,0 +1,24 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function onRequest(context){
var viewModel = {};
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
viewModel["permissions"] = userModule.getUIPermissions();
return viewModel;
}

@ -103,3 +103,30 @@ var addConfiguration = function () {
} }
); );
}; };
var artifactUpload = function () {
var contentType = "application/json";
var backendEndBasePath = "/api/device-mgt/v1.0";
var urix = backendEndBasePath + "/admin/devicetype/deploy/virtual_firealarm";
var defaultStatusClasses = "fw fw-stack-1x";
var content = $("#virtual-firealarm-statistic-response-template").find(".content");
var title = content.find("#title");
var statusIcon = content.find("#status-icon");
var data = {}
invokerUtil.post(urix, data, function (data) {
title.html("Deploying statistic artifacts. Please wait...");
statusIcon.attr("class", defaultStatusClasses + " fw-check");
$(modalPopupContent).html(content.html());
showPopup();
setTimeout(function () {
hidePopup();
location.reload(true);
}, 5000);
}, function (jqXHR) {
title.html("Failed to deploy artifacts, Please contact administrator.");
statusIcon.attr("class", defaultStatusClasses + " fw-error");
$(modalPopupContent).html(content.html());
showPopup();
}, contentType);
};

@ -28,15 +28,31 @@ function onRequest(context) {
var jwtClient = jwtService.getJWTClient(); var jwtClient = jwtService.getJWTClient();
var encodedClientKeys = session.get(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]); var encodedClientKeys = session.get(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]);
var token = ""; var token = "";
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
if (encodedClientKeys) { if (encodedClientKeys) {
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"]; var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var resp = tokenUtil.decode(encodedClientKeys).split(":"); var resp = tokenUtil.decode(encodedClientKeys).split(":");
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username,"default", {}); if (user.domain == "carbon.super") {
if (tokenPair) { var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username , "default", {});
token = tokenPair.accessToken; if (tokenPair) {
} token = tokenPair.accessToken;
websocketEndpoint = websocketEndpoint + "/secured-websocket/org.wso2.iot.devices.temperature/1.0.0?" }
+ "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token; websocketEndpoint = websocketEndpoint + "/secured-websocket/org.wso2.iot.devices.temperature/1.0.0?"
+ "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token;
} else {
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username + "@" + user.domain
, "default", {});
if (tokenPair) {
token = tokenPair.accessToken;
}
websocketEndpoint = websocketEndpoint + "/secured-websocket/t/" + user.domain + "/org.wso2.iot.devices.temperature/1.0.0?"
+ "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token;
}
} }
return {"device": device, "websocketEndpoint": websocketEndpoint}; return {"device": device, "websocketEndpoint": websocketEndpoint};
} }

@ -134,31 +134,4 @@ function doAction(data) {
hideAgentDownloadPopup(); hideAgentDownloadPopup();
}); });
} }
}
function artifactUpload() {
var contentType = "application/json";
var urix = backendEndBasePath + "/admin/devicetype/deploy/virtual_firealarm";
var defaultStatusClasses = "fw fw-stack-1x";
var content = $("#virtualfirealarm-statistic-response-template").find(".content");
var title = content.find("#title");
var statusIcon = content.find("#status-icon");
var data = {}
invokerUtil.post(urix, data, function (data) {
title.html("Deploying statistic artifacts. Please wait...");
statusIcon.attr("class", defaultStatusClasses + " fw-check");
$(modalPopupContent).html(content.html());
showPopup();
setTimeout(function () {
hidePopup();
location.reload(true);
}, 5000);
}, function (jqXHR) {
title.html("Failed to deploy artifacts, Please contact administrator.");
statusIcon.attr("class", defaultStatusClasses + " fw-error");
$(modalPopupContent).html(content.html());
showPopup();
}, contentType);
} }

@ -54,9 +54,6 @@
</a> </a>
<a href="#" class="download-link btn-operations"> <a href="#" class="download-link btn-operations">
<i class="fw fw-download"></i>Download Agent</a> <i class="fw fw-download"></i>Download Agent</a>
{{#if displayStatus}}
<a href="javascript:artifactUpload()" class="btn-operations"><i class="fw fw-upload fw-inverse fw-lg add-margin-1x"></i> Deploy Analytics Artifacts</a>
{{/if}}
<p class="doc-link">Click <a href="https://docs.wso2.com/display/IoTS300/Virtual+Firealarm" <p class="doc-link">Click <a href="https://docs.wso2.com/display/IoTS300/Virtual+Firealarm"
target="_blank">[ here ]</a> for latest instructions and target="_blank">[ here ]</a> for latest instructions and

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device-types</artifactId> <artifactId>device-types</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -18,7 +18,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>appm-connector</artifactId> <artifactId>appm-connector</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -20,6 +20,7 @@ import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import org.wso2.carbon.appmgt.impl.service.ServiceReferenceHolder;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.MobileApp; import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.MobileApp;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.MobileAppTypes; import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.MobileAppTypes;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException; import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException;
@ -32,6 +33,7 @@ import org.wso2.carbon.appmgt.mobile.beans.ApplicationOperationDevice;
import org.wso2.carbon.appmgt.mobile.interfaces.ApplicationOperations; import org.wso2.carbon.appmgt.mobile.interfaces.ApplicationOperations;
import org.wso2.carbon.appmgt.mobile.mdm.App; import org.wso2.carbon.appmgt.mobile.mdm.App;
import org.wso2.carbon.appmgt.mobile.mdm.Device; import org.wso2.carbon.appmgt.mobile.mdm.Device;
import org.wso2.carbon.appmgt.mobile.store.Generic;
import org.wso2.carbon.appmgt.mobile.utils.MobileApplicationException; import org.wso2.carbon.appmgt.mobile.utils.MobileApplicationException;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
@ -39,6 +41,15 @@ import org.wso2.carbon.device.mgt.common.Platform;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.appmgt.mobile.utils.User;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -47,6 +58,9 @@ import java.util.Properties;
public class ApplicationOperationsImpl implements ApplicationOperations { public class ApplicationOperationsImpl implements ApplicationOperations {
private static final Log log = LogFactory.getLog(ApplicationOperationsImpl.class); private static final Log log = LogFactory.getLog(ApplicationOperationsImpl.class);
public static final String MEDIA_TYPE_XML = "application/xml";
public static final String INSTALL = "install";
public static final String UNINSTALL = "uninstall";
/** /**
* @param applicationOperationAction holds the information needs to perform an action on mdm. * @param applicationOperationAction holds the information needs to perform an action on mdm.
@ -56,7 +70,7 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
throws MobileApplicationException { throws MobileApplicationException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug(applicationOperationAction.getAction() + " action is triggered for " + log.debug(applicationOperationAction.getAction() + " action is triggered for " +
applicationOperationAction.getType() +"."); applicationOperationAction.getType() +".");
} }
Operation operation = null; Operation operation = null;
@ -73,19 +87,19 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
getDevicesOfUser(userName); getDevicesOfUser(userName);
for (org.wso2.carbon.device.mgt.common.Device device : deviceList) { for (org.wso2.carbon.device.mgt.common.Device device : deviceList) {
if(MDMAppConstants.WEBAPP.equals(applicationOperationAction.getApp().getPlatform()) || if (MDMAppConstants.WEBAPP.equals(applicationOperationAction.getApp().getPlatform()) ||
applicationOperationAction.getApp().getPlatform().equalsIgnoreCase(device.getType())){ applicationOperationAction.getApp().getPlatform().equalsIgnoreCase(device.getType())) {
if (MDMAppConstants.ACTIVE.equalsIgnoreCase(device.getEnrolmentInfo(). if (MDMAppConstants.ACTIVE.equalsIgnoreCase(device.getEnrolmentInfo().
getStatus().toString())) { getStatus().toString())) {
deviceIdentifiers.add(getDeviceIdentifierByDevice(device)); deviceIdentifiers.add(getDeviceIdentifierByDevice(device));
} }
} }
} }
} }
} catch (DeviceManagementException devEx) { } catch (DeviceManagementException devEx) {
String errorMsg = "Error occurred fetch device for user " + userName + String errorMsg = "Error occurred fetch device for user " + userName +
" at app installation"; " at app installation";
logError(errorMsg, devEx); logError(errorMsg, devEx);
throw new MobileApplicationException(errorMsg, devEx); throw new MobileApplicationException(errorMsg, devEx);
} }
} else if (MDMAppConstants.ROLE.equals(applicationOperationAction.getType())) { } else if (MDMAppConstants.ROLE.equals(applicationOperationAction.getType())) {
@ -105,9 +119,9 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
} }
} }
} catch (DeviceManagementException devMgtEx) { } catch (DeviceManagementException devMgtEx) {
String errorMsg = "Error occurred fetch device for user role " + userRole + String errorMsg = "Error occurred fetch device for user role " + userRole +
" at app installation"; " at app installation";
logError(errorMsg, devMgtEx); logError(errorMsg, devMgtEx);
throw new MobileApplicationException(errorMsg, devMgtEx); throw new MobileApplicationException(errorMsg, devMgtEx);
} }
@ -189,8 +203,8 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
} }
} }
} }
activity = MDMServiceAPIUtils.getAppManagementService(applicationOperationAction.getTenantId()) activity = MDMServiceAPIUtils.getAppManagementService(applicationOperationAction.getTenantId())
.installApplicationForDevices(operation, deviceIdentifiers); .installApplicationForDevices(operation, deviceIdentifiers);
} }
@ -236,20 +250,18 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
List<Device> devices; List<Device> devices;
List<org.wso2.carbon.device.mgt.common.Device> deviceList = null; List<org.wso2.carbon.device.mgt.common.Device> deviceList = null;
try { try {
if(MDMAppConstants.WEBAPP.equals if (MDMAppConstants.WEBAPP.equals
(applicationOperationDevice.getPlatform())) { (applicationOperationDevice.getPlatform())) {
deviceList = MDMServiceAPIUtils deviceList = MDMServiceAPIUtils
.getDeviceManagementService(applicationOperationDevice.getTenantId()). .getDeviceManagementService(applicationOperationDevice.getTenantId()).
getDevicesOfUser( getDevicesOfUser(applicationOperationDevice.getCurrentUser().getUsername());
applicationOperationDevice.getCurrentUser().getUsername()); } else {
} else {
deviceList = MDMServiceAPIUtils deviceList = MDMServiceAPIUtils
.getDeviceManagementService(applicationOperationDevice.getTenantId()). .getDeviceManagementService(applicationOperationDevice.getTenantId()).
getDevicesOfUser( getDevicesOfUser(applicationOperationDevice.getCurrentUser().getUsername(),
applicationOperationDevice.getCurrentUser().getUsername(),
applicationOperationDevice.getPlatform()); applicationOperationDevice.getPlatform());
} }
devices = new ArrayList<>(deviceList.size()); devices = new ArrayList<>(deviceList.size());
if(log.isDebugEnabled()){ if(log.isDebugEnabled()){
log.debug("device list got from mdm "+ deviceList.toString()); log.debug("device list got from mdm "+ deviceList.toString());
} }
@ -268,18 +280,18 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
device.setType(MDMAppConstants.MOBILE_DEVICE); device.setType(MDMAppConstants.MOBILE_DEVICE);
String imgUrl; String imgUrl;
if (MDMAppConstants.ANDROID.equalsIgnoreCase(commonDevice.getType())) { if (MDMAppConstants.ANDROID.equalsIgnoreCase(commonDevice.getType())) {
imgUrl = String.format(applicationOperationDevice.getConfigParams() imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL), .get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.NEXUS); MDMAppConstants.NEXUS);
} else if (MDMAppConstants.IOS.equalsIgnoreCase(commonDevice.getType())) { } else if (MDMAppConstants.IOS.equalsIgnoreCase(commonDevice.getType())) {
imgUrl = String.format(applicationOperationDevice.getConfigParams() imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL), .get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.IPHONE); MDMAppConstants.IPHONE);
} else { } else {
imgUrl = String.format(applicationOperationDevice.getConfigParams() imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL), .get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.NONE); MDMAppConstants.NONE);
} }
device.setImage(imgUrl); device.setImage(imgUrl);
device.setPlatform(commonDevice.getType()); device.setPlatform(commonDevice.getType());
devices.add(device); devices.add(device);
@ -311,5 +323,138 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
} }
} }
public static UserStoreManager getUserStoreManager() throws UserStoreException {
RealmService realmService;
UserStoreManager userStoreManager;
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
if (realmService == null) {
String msg = "Realm service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
int tenantId = ctx.getTenantId();
userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
return userStoreManager;
}
class ApplicationSubscription extends Thread {
User currentUser;
String action;
App app;
int tenantId;
String type;
String[] params;
UserStoreManager userStoreManager;
UserRegistry userRegistry;
public ApplicationSubscription(User currentUser, String action, App app, int tenantId, final String type,
final String[] params) {
this.currentUser = currentUser;
this.action = action;
this.app = app;
this.tenantId = tenantId;
this.type = type;
this.params = params;
}
@Override
public void run() {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
privilegedCarbonContext.setTenantId(tenantId);
RealmService realmService = (RealmService) privilegedCarbonContext.getOSGiService(RealmService.class, null);
if (realmService == null) {
String msg = "RealmService is not initialized";
log.error(msg);
throw new IllegalStateException(msg);
}
String tenantDomain;
try {
tenantDomain = realmService.getTenantManager().getDomain(tenantId);
privilegedCarbonContext.setTenantDomain(tenantDomain);
privilegedCarbonContext.setUsername(currentUser.getUsername());
userStoreManager = getUserStoreManager();
userRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
.getGovernanceUserRegistry(currentUser.getUsername(), tenantId);
} catch (UserStoreException e) {
log.error("Error occured while fetching user store", e);
} catch (RegistryException e) {
log.error("Error occured while fetching registry instance", e);
}
String basePath = "/users/";
String subscriptionPath = "/subscriptions/mobileapp/";
String path;
if (type != null && type.equals("role")) {
for (String param : params) {
String[] users;
if (log.isDebugEnabled()) {
log.debug("role being added:" + param);
}
try {
users = userStoreManager.getUserListOfRole(param);
for (String user : users) {
path = basePath + user + subscriptionPath + app.getId();
updateSubscription(action, path, user, userRegistry);
}
} catch (UserStoreException e) {
log.error("Error occured while getting user list of role " + param, e);
}
}
} else if (type != null && type.equals("user")) {
for (String user : params) {
if (log.isDebugEnabled()) {
log.debug("user:" + user);
}
path = basePath + user + subscriptionPath + app.getId();
updateSubscription(action, path, user, userRegistry);
}
} else if (type != null && type.equals("device")) {
log.debug("device user:" + currentUser.getUsername());
path = basePath + currentUser.getUsername() + subscriptionPath + app.getId();
updateSubscription(action, path, currentUser.getUsername(), userRegistry);
}
log.info("registry subscription complete.");
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
private void updateSubscription(String action, String path, String username, UserRegistry userRegistry) {
if (log.isDebugEnabled()) {
log.debug("update subscribe user:" + username + " , action:" + action + " ,path:" + path);
}
if (action != null && action.equals(INSTALL)) {
try {
if (!userRegistry.resourceExists(path)) {
Resource resource = userRegistry.newResource();
resource.setMediaType(MEDIA_TYPE_XML);
userRegistry.put(path, resource);
Generic generic = new Generic();
generic.showAppVisibilityToUser(path, username, "ALLOW");
}
} catch (RegistryException e) {
log.error("Error occured while accessing registry.", e);
}
} else if (action != null && action.equals(UNINSTALL)) {
try {
if (userRegistry.resourceExists(path)) {
userRegistry.delete(path);
Generic generic = new Generic();
generic.showAppVisibilityToUser(path, username, "DENY");
}
} catch (RegistryException e) {
log.error("Error occured while accessing registry.", e);
}
}
}
} }

@ -18,7 +18,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>appm-connector</artifactId> <artifactId>appm-connector</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>extensions</artifactId> <artifactId>extensions</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -20,7 +20,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>cdmf-transport-adapters</artifactId> <artifactId>cdmf-transport-adapters</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

@ -40,7 +40,7 @@ public class MQTTContentValidator implements ContentValidator {
@Override @Override
public String getType() { public String getType() {
return null; return CDMF_MQTT_CONTENT_VALIDATOR;
} }
@Override @Override

@ -20,7 +20,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>cdmf-transport-adapters</artifactId> <artifactId>cdmf-transport-adapters</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -69,9 +69,14 @@ public class HTTPMessageServlet extends HttpServlet {
this.tenantId = tenantId; this.tenantId = tenantId;
this.exposedTransports = eventAdapterConfiguration.getProperties().get( this.exposedTransports = eventAdapterConfiguration.getProperties().get(
HTTPEventAdapterConstants.EXPOSED_TRANSPORTS); HTTPEventAdapterConstants.EXPOSED_TRANSPORTS);
String globalContentValidator = globalProperties.get(HTTPEventAdapterConstants.
ADAPTER_CONF_CONTENT_VALIDATOR_TYPE);
String contentValidatorType = eventAdapterConfiguration.getProperties().get( String contentValidatorType = eventAdapterConfiguration.getProperties().get(
HTTPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_TYPE); HTTPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_TYPE);
if (globalContentValidator != null && !globalContentValidator.isEmpty() ) {
contentValidatorType = globalContentValidator;
}
if (contentValidatorType == null || HTTPEventAdapterConstants.DEFAULT.equals(contentValidatorType)) { if (contentValidatorType == null || HTTPEventAdapterConstants.DEFAULT.equals(contentValidatorType)) {
contentValidator = InputAdapterServiceDataHolder.getInputAdapterExtensionService() contentValidator = InputAdapterServiceDataHolder.getInputAdapterExtensionService()
.getDefaultContentValidator(); .getDefaultContentValidator();

@ -20,7 +20,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>cdmf-transport-adapters</artifactId> <artifactId>cdmf-transport-adapters</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
@ -32,10 +32,10 @@
<url>http://wso2.org</url> <url>http://wso2.org</url>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>commons-codec.wso2</groupId> <groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId> <artifactId>commons-codec</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.analytics-common</groupId> <groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.input.adapter.core</artifactId> <artifactId>org.wso2.carbon.event.input.adapter.core</artifactId>
@ -76,10 +76,10 @@
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.input.adapter.extension</artifactId> <artifactId>org.wso2.carbon.device.mgt.input.adapter.extension</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId> <artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
@ -133,18 +133,22 @@
org.apache.http.impl.client;version="${httpclient.version.range}", org.apache.http.impl.client;version="${httpclient.version.range}",
org.json.simple.*, org.json.simple.*,
com.jayway.jsonpath.*, com.jayway.jsonpath.*,
org.wso2.carbon.identity.jwt.client.extension.*, org.wso2.carbon.identity.jwt.client.extension.*,
javax.net.ssl, javax.net.ssl,
org.apache.commons.codec.binary, org.apache.commons.codec.binary,
org.apache.commons.logging, org.apache.commons.logging,
org.apache.http.entity, org.apache.http.entity,
org.osgi.framework, org.osgi.framework,
org.osgi.service.component, org.osgi.service.component,
org.osgi.service.http, org.osgi.service.http,
org.wso2.carbon.context, org.wso2.carbon.context,
org.wso2.carbon.core, org.wso2.carbon.core,
org.wso2.carbon.device.mgt.input.adapter.extension, org.wso2.carbon.device.mgt.input.adapter.extension,
org.wso2.carbon.user.api org.wso2.carbon.user.api,
org.wso2.carbon.utils.multitenancy,
org.apache.axis2.context,
org.wso2.carbon.core.multitenancy.utils,
org.wso2.carbon.utils
</Import-Package> </Import-Package>
</instructions> </instructions>
</configuration> </configuration>

@ -19,13 +19,14 @@ package org.wso2.carbon.device.mgt.input.adapter.mqtt;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.input.adapter.mqtt.util.MQTTAdapterListener; import org.wso2.carbon.device.mgt.input.adapter.mqtt.util.MQTTAdapterListener;
import org.wso2.carbon.device.mgt.input.adapter.mqtt.util.MQTTEventAdapterConstants;
import org.wso2.carbon.device.mgt.input.adapter.mqtt.util.MQTTBrokerConnectionConfiguration; import org.wso2.carbon.device.mgt.input.adapter.mqtt.util.MQTTBrokerConnectionConfiguration;
import org.wso2.carbon.device.mgt.input.adapter.mqtt.util.MQTTEventAdapterConstants;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapter; import org.wso2.carbon.event.input.adapter.core.InputEventAdapter;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration; import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterListener; import org.wso2.carbon.event.input.adapter.core.InputEventAdapterListener;
import org.wso2.carbon.event.input.adapter.core.exception.InputEventAdapterException; import org.wso2.carbon.event.input.adapter.core.exception.InputEventAdapterException;
import org.wso2.carbon.event.input.adapter.core.exception.TestConnectionNotSupportedException; import org.wso2.carbon.event.input.adapter.core.exception.TestConnectionNotSupportedException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -54,10 +55,11 @@ public class MQTTEventAdapter implements InputEventAdapter {
try { try {
mqttBrokerConnectionConfiguration = new MQTTBrokerConnectionConfiguration(eventAdapterConfiguration mqttBrokerConnectionConfiguration = new MQTTBrokerConnectionConfiguration(eventAdapterConfiguration
,globalProperties); ,globalProperties);
String topic = eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_MESSAGE_TOPIC);
mqttAdapterListener = new MQTTAdapterListener(mqttBrokerConnectionConfiguration mqttAdapterListener = new MQTTAdapterListener(mqttBrokerConnectionConfiguration
,eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_MESSAGE_TOPIC) ,topic
,eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID) ,eventAdapterConfiguration
,eventAdapterListener, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); ,eventAdapterListener);
} catch (Throwable t) { } catch (Throwable t) {
throw new InputEventAdapterException(t.getMessage(), t); throw new InputEventAdapterException(t.getMessage(), t);
} }
@ -77,6 +79,10 @@ public class MQTTEventAdapter implements InputEventAdapter {
@Override @Override
public void connect() { public void connect() {
if (!PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()
.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
return;
}
if (!mqttAdapterListener.isConnectionInitialized()) { if (!mqttAdapterListener.isConnectionInitialized()) {
mqttAdapterListener.createConnection(); mqttAdapterListener.createConnection();
} }
@ -87,6 +93,10 @@ public class MQTTEventAdapter implements InputEventAdapter {
public void disconnect() { public void disconnect() {
//when mqtt and this feature both together then this method becomes a blocking method, Therefore //when mqtt and this feature both together then this method becomes a blocking method, Therefore
// have used a thread to skip it. // have used a thread to skip it.
if (!PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()
.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
return;
}
try { try {
Thread thread = new Thread(new Runnable() { Thread thread = new Thread(new Runnable() {
public void run() { public void run() {

@ -120,7 +120,7 @@ public class MQTTEventAdapterFactory extends InputEventAdapterFactory {
// set clientId // set clientId
Property clientId = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID); Property clientId = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID);
clientId.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID)); clientId.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID));
clientId.setRequired(false); clientId.setRequired(true);
clientId.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID_HINT)); clientId.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID_HINT));
propertyList.add(clientId); propertyList.add(clientId);

@ -17,6 +17,7 @@
*/ */
package org.wso2.carbon.device.mgt.input.adapter.mqtt.internal; package org.wso2.carbon.device.mgt.input.adapter.mqtt.internal;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
@ -24,7 +25,9 @@ import org.osgi.service.http.HttpService;
import org.wso2.carbon.device.mgt.input.adapter.extension.InputAdapterExtensionService; import org.wso2.carbon.device.mgt.input.adapter.extension.InputAdapterExtensionService;
import org.wso2.carbon.device.mgt.input.adapter.mqtt.MQTTEventAdapterFactory; import org.wso2.carbon.device.mgt.input.adapter.mqtt.MQTTEventAdapterFactory;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterFactory; import org.wso2.carbon.event.input.adapter.core.InputEventAdapterFactory;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterService;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.utils.ConfigurationContextService;
/** /**
* @scr.component name="input.iot.mqtt.AdapterService.component" immediate="true" * @scr.component name="input.iot.mqtt.AdapterService.component" immediate="true"
@ -38,6 +41,15 @@ import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerSer
* policy="dynamic" * policy="dynamic"
* bind="setJWTClientManagerService" * bind="setJWTClientManagerService"
* unbind="unsetJWTClientManagerService" * unbind="unsetJWTClientManagerService"
* @scr.reference name="input.adapter.service" interface="org.wso2.carbon.event.input.adapter.core.InputEventAdapterService"
* cardinality="1..1"
* policy="dynamic"
* bind="setInputEventAdapterService"
* unbind="unsetInputEventAdapterService"
* @scr.reference name="config.context.service"
* interface="org.wso2.carbon.utils.ConfigurationContextService"
* cardinality="1..1" policy="dynamic" bind="setConfigurationContextService"
* unbind="unsetConfigurationContextService"
*/ */
public class InputAdapterServiceComponent { public class InputAdapterServiceComponent {
@ -80,4 +92,21 @@ public class InputAdapterServiceComponent {
InputAdapterServiceDataHolder.setJwtClientManagerService(null); InputAdapterServiceDataHolder.setJwtClientManagerService(null);
} }
protected void setInputEventAdapterService(InputEventAdapterService inputEventAdapterService) {
InputAdapterServiceDataHolder.setInputEventAdapterService(inputEventAdapterService);
}
protected void unsetInputEventAdapterService(InputEventAdapterService inputEventAdapterService) {
InputAdapterServiceDataHolder.setInputEventAdapterService(null);
}
protected void setConfigurationContextService(ConfigurationContextService contextService) {
ConfigurationContext serverConfigContext = contextService.getServerConfigContext();
InputAdapterServiceDataHolder.setMainServerConfigContext(serverConfigContext);
}
protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
InputAdapterServiceDataHolder.setMainServerConfigContext(null);
}
} }

@ -14,9 +14,11 @@
*/ */
package org.wso2.carbon.device.mgt.input.adapter.mqtt.internal; package org.wso2.carbon.device.mgt.input.adapter.mqtt.internal;
import org.apache.axis2.context.ConfigurationContext;
import org.osgi.service.http.HttpService; import org.osgi.service.http.HttpService;
import org.wso2.carbon.device.mgt.input.adapter.extension.InputAdapterExtensionService; import org.wso2.carbon.device.mgt.input.adapter.extension.InputAdapterExtensionService;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterService;
/** /**
* common place to hold some OSGI service references. * common place to hold some OSGI service references.
@ -26,6 +28,8 @@ public final class InputAdapterServiceDataHolder {
private static HttpService httpService; private static HttpService httpService;
private static InputAdapterExtensionService inputAdapterExtensionService; private static InputAdapterExtensionService inputAdapterExtensionService;
private static JWTClientManagerService jwtClientManagerService; private static JWTClientManagerService jwtClientManagerService;
private static InputEventAdapterService inputEventAdapterService;
private static ConfigurationContext mainServerConfigContext;
private InputAdapterServiceDataHolder() { private InputAdapterServiceDataHolder() {
} }
@ -55,4 +59,20 @@ public final class InputAdapterServiceDataHolder {
JWTClientManagerService jwtClientManagerService) { JWTClientManagerService jwtClientManagerService) {
InputAdapterServiceDataHolder.jwtClientManagerService = jwtClientManagerService; InputAdapterServiceDataHolder.jwtClientManagerService = jwtClientManagerService;
} }
public static InputEventAdapterService getInputEventAdapterService() {
return inputEventAdapterService;
}
public static void setInputEventAdapterService(InputEventAdapterService inputEventAdapterService) {
InputAdapterServiceDataHolder.inputEventAdapterService = inputEventAdapterService;
}
public static ConfigurationContext getMainServerConfigContext() {
return mainServerConfigContext;
}
public static void setMainServerConfigContext(ConfigurationContext mainServerConfigContext) {
InputAdapterServiceDataHolder.mainServerConfigContext = mainServerConfigContext;
}
} }

@ -17,12 +17,14 @@
*/ */
package org.wso2.carbon.device.mgt.input.adapter.mqtt.util; package org.wso2.carbon.device.mgt.input.adapter.mqtt.util;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
@ -33,16 +35,19 @@ import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.ServerStatus; import org.wso2.carbon.core.ServerStatus;
import org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils;
import org.wso2.carbon.device.mgt.input.adapter.extension.ContentInfo; import org.wso2.carbon.device.mgt.input.adapter.extension.ContentInfo;
import org.wso2.carbon.device.mgt.input.adapter.extension.ContentTransformer; import org.wso2.carbon.device.mgt.input.adapter.extension.ContentTransformer;
import org.wso2.carbon.device.mgt.input.adapter.extension.ContentValidator; import org.wso2.carbon.device.mgt.input.adapter.extension.ContentValidator;
import org.wso2.carbon.device.mgt.input.adapter.mqtt.internal.InputAdapterServiceDataHolder; import org.wso2.carbon.device.mgt.input.adapter.mqtt.internal.InputAdapterServiceDataHolder;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterListener; import org.wso2.carbon.event.input.adapter.core.InputEventAdapterListener;
import org.wso2.carbon.event.input.adapter.core.exception.InputEventAdapterRuntimeException; import org.wso2.carbon.event.input.adapter.core.exception.InputEventAdapterRuntimeException;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.io.IOException; import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@ -63,26 +68,29 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
private MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration; private MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration;
private String topic; private String topic;
private int tenantId; private String tenantDomain;
private boolean connectionSucceeded = false; private boolean connectionSucceeded = false;
ContentValidator contentValidator; private ContentValidator contentValidator;
ContentTransformer contentTransformer; private ContentTransformer contentTransformer;
private InputEventAdapterConfiguration inputEventAdapterConfiguration;
private InputEventAdapterListener eventAdapterListener = null; private InputEventAdapterListener eventAdapterListener = null;
public MQTTAdapterListener(MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration, public MQTTAdapterListener(MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration,
String topic, String mqttClientId, String topic, InputEventAdapterConfiguration inputEventAdapterConfiguration,
InputEventAdapterListener inputEventAdapterListener, int tenantId) { InputEventAdapterListener inputEventAdapterListener) {
String mqttClientId = inputEventAdapterConfiguration.getProperties()
if(mqttClientId == null || mqttClientId.trim().isEmpty()){ .get(MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID);
if (mqttClientId == null || mqttClientId.trim().isEmpty()) {
mqttClientId = MqttClient.generateClientId(); mqttClientId = MqttClient.generateClientId();
} }
this.inputEventAdapterConfiguration = inputEventAdapterConfiguration;
this.mqttBrokerConnectionConfiguration = mqttBrokerConnectionConfiguration; this.mqttBrokerConnectionConfiguration = mqttBrokerConnectionConfiguration;
this.cleanSession = mqttBrokerConnectionConfiguration.isCleanSession(); this.cleanSession = mqttBrokerConnectionConfiguration.isCleanSession();
int keepAlive = mqttBrokerConnectionConfiguration.getKeepAlive(); int keepAlive = mqttBrokerConnectionConfiguration.getKeepAlive();
this.topic = PropertyUtils.replaceTenantDomainProperty(topic); this.topic = PropertyUtils.replaceTenantDomainProperty(topic);
this.eventAdapterListener = inputEventAdapterListener; this.eventAdapterListener = inputEventAdapterListener;
this.tenantId = tenantId; this.tenantDomain = this.topic.split("/")[0];
//SORTING messages until the server fetches them //SORTING messages until the server fetches them
String temp_directory = System.getProperty("java.io.tmpdir"); String temp_directory = System.getProperty("java.io.tmpdir");
@ -104,7 +112,7 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
if (contentValidatorType == null || contentValidatorType.equals(MQTTEventAdapterConstants.DEFAULT)) { if (contentValidatorType == null || contentValidatorType.equals(MQTTEventAdapterConstants.DEFAULT)) {
contentValidator = InputAdapterServiceDataHolder.getInputAdapterExtensionService() contentValidator = InputAdapterServiceDataHolder.getInputAdapterExtensionService()
.getDefaultContentValidator(); .getDefaultContentValidator();
} else { } else {
contentValidator = InputAdapterServiceDataHolder.getInputAdapterExtensionService() contentValidator = InputAdapterServiceDataHolder.getInputAdapterExtensionService()
.getContentValidator(contentValidatorType); .getContentValidator(contentValidatorType);
} }
@ -124,7 +132,7 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
} }
} }
public void startListener() throws MqttException { public boolean startListener() throws MqttException {
if (this.mqttBrokerConnectionConfiguration.getUsername() != null && if (this.mqttBrokerConnectionConfiguration.getUsername() != null &&
this.mqttBrokerConnectionConfiguration.getDcrUrl() != null) { this.mqttBrokerConnectionConfiguration.getDcrUrl() != null) {
String username = this.mqttBrokerConnectionConfiguration.getUsername(); String username = this.mqttBrokerConnectionConfiguration.getUsername();
@ -145,7 +153,7 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
if (!mqttBrokerConnectionConfiguration.isGlobalCredentailSet()) { if (!mqttBrokerConnectionConfiguration.isGlobalCredentailSet()) {
registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX
+ mqttBrokerConnectionConfiguration.getAdapterName() + + mqttBrokerConnectionConfiguration.getAdapterName() +
"_" + tenantId); "_" + tenantDomain);
registrationProfile.setIsSaasApp(false); registrationProfile.setIsSaasApp(false);
} else { } else {
registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX
@ -175,17 +183,35 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
log.error(msg, e); log.error(msg, e);
} }
} }
} catch (HttpHostConnectException e) {
log.error("Keymanager is unreachable, Waiting....");
return false;
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
log.error("Invalid dcrUrl : " + dcrUrlString); log.error("Invalid dcrUrl : " + dcrUrlString);
} catch (JWTClientException | UserStoreException e) { return false;
} catch (JWTClientException | UserStoreException e) {
log.error("Failed to create an oauth token with jwt grant type.", e); log.error("Failed to create an oauth token with jwt grant type.", e);
} catch (NoSuchAlgorithmException |KeyManagementException |KeyStoreException | IOException e) { return false;
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | IOException e) {
log.error("Failed to create a http connection.", e); log.error("Failed to create a http connection.", e);
return false;
} }
} }
} }
mqttClient.connect(connectionOptions); try {
mqttClient.subscribe(topic); mqttClient.connect(connectionOptions);
} catch (MqttException e) {
log.warn("Broker is unreachable, Waiting.....");
return false;
}
try {
mqttClient.subscribe(topic);
} catch (MqttException e) {
log.error("Failed to subscribe to topic: " + topic + ", Retrying.....");
return false;
}
return true;
} }
public void stopListener(String adapterName) { public void stopListener(String adapterName) {
@ -197,7 +223,7 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
mqttClient.disconnect(3000); mqttClient.disconnect(3000);
} catch (MqttException e) { } catch (MqttException e) {
log.error("Can not unsubscribe from the destination " + topic + log.error("Can not unsubscribe from the destination " + topic +
" with the event adapter " + adapterName, e); " with the event adapter " + adapterName, e);
} }
} }
connectionSucceeded = true; connectionSucceeded = true;
@ -218,7 +244,14 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
log.debug(msgText); log.debug(msgText);
} }
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
if (!tenantDomain.equalsIgnoreCase(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
TenantAxisUtils.getTenantConfigurationContext(tenantDomain, InputAdapterServiceDataHolder.getMainServerConfigContext());
}
InputEventAdapterListener inputEventAdapterListener = InputAdapterServiceDataHolder
.getInputEventAdapterService().getInputAdapterRuntime(PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getTenantId(), inputEventAdapterConfiguration.getName());
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Event received in MQTT Event Adapter - " + msgText); log.debug("Event received in MQTT Event Adapter - " + msgText);
@ -231,10 +264,10 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
msgText = (String) contentTransformer.transform(msgText, dynamicProperties); msgText = (String) contentTransformer.transform(msgText, dynamicProperties);
contentInfo = contentValidator.validate(msgText, dynamicProperties); contentInfo = contentValidator.validate(msgText, dynamicProperties);
if (contentInfo != null && contentInfo.isValidContent()) { if (contentInfo != null && contentInfo.isValidContent()) {
eventAdapterListener.onEvent(contentInfo.getMessage()); inputEventAdapterListener.onEvent(contentInfo.getMessage());
} }
} else { } else {
eventAdapterListener.onEvent(msgText); inputEventAdapterListener.onEvent(msgText);
} }
} finally { } finally {
PrivilegedCarbonContext.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
@ -252,10 +285,14 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
while (!connectionSucceeded) { while (!connectionSucceeded) {
try { try {
connectionDuration = connectionDuration * MQTTEventAdapterConstants.RECONNECTION_PROGRESS_FACTOR; connectionDuration = connectionDuration * MQTTEventAdapterConstants.RECONNECTION_PROGRESS_FACTOR;
if (connectionDuration > MQTTEventAdapterConstants.MAXIMUM_RECONNECTION_DURATION) {
connectionDuration = MQTTEventAdapterConstants.MAXIMUM_RECONNECTION_DURATION;
}
Thread.sleep(connectionDuration); Thread.sleep(connectionDuration);
startListener(); if (startListener()) {
connectionSucceeded = true; connectionSucceeded = true;
log.info("MQTT Connection successful"); log.info("MQTT Connection successful");
}
} catch (InterruptedException e) { } catch (InterruptedException e) {
log.error("Interruption occurred while waiting for reconnection", e); log.error("Interruption occurred while waiting for reconnection", e);
} catch (MqttException e) { } catch (MqttException e) {
@ -276,7 +313,7 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
private String getToken(String clientId, String clientSecret) private String getToken(String clientId, String clientSecret)
throws UserStoreException, JWTClientException { throws UserStoreException, JWTClientException {
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
try { try {
String scopes = mqttBrokerConnectionConfiguration.getBrokerScopes(); String scopes = mqttBrokerConnectionConfiguration.getBrokerScopes();
String username = mqttBrokerConnectionConfiguration.getUsername(); String username = mqttBrokerConnectionConfiguration.getUsername();

@ -105,10 +105,18 @@ public class MQTTBrokerConnectionConfiguration {
this.brokerUrl = PropertyUtils.replaceMqttProperty(url); this.brokerUrl = PropertyUtils.replaceMqttProperty(url);
this.dcrUrl = PropertyUtils this.dcrUrl = PropertyUtils
.replaceMqttProperty(globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL)); .replaceMqttProperty(globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL));
this.contentValidatorType = eventAdapterConfiguration.getProperties() this.contentValidatorType = globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_TYPE);
.get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_TYPE); if (contentValidatorType == null || contentValidatorType.isEmpty()) {
this.cleanSession = Boolean.parseBoolean(eventAdapterConfiguration.getProperties() this.contentValidatorType = eventAdapterConfiguration.getProperties()
.get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION)); .get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_TYPE);
}
String cleanSession = globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION);
if (cleanSession == null || cleanSession.isEmpty()) {
this.cleanSession = Boolean.parseBoolean(eventAdapterConfiguration.getProperties()
.get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION));
} else {
this.cleanSession = Boolean.parseBoolean(cleanSession);
}
//If global properties are available those will be assigned else constant values will be assigned //If global properties are available those will be assigned else constant values will be assigned
if (globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE) != null) { if (globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE) != null) {
keepAlive = Integer.parseInt((globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE))); keepAlive = Integer.parseInt((globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE)));

@ -50,6 +50,7 @@ public class MQTTEventAdapterConstants {
public static final int INITIAL_RECONNECTION_DURATION = 4000; public static final int INITIAL_RECONNECTION_DURATION = 4000;
public static final int RECONNECTION_PROGRESS_FACTOR = 2; public static final int RECONNECTION_PROGRESS_FACTOR = 2;
public static final int MAXIMUM_RECONNECTION_DURATION = 60000;
public static final String EMPTY_STRING = ""; public static final String EMPTY_STRING = "";
public static final String GRANT_TYPE_PARAM_NAME = "grant_type"; public static final String GRANT_TYPE_PARAM_NAME = "grant_type";

@ -20,7 +20,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>cdmf-transport-adapters</artifactId> <artifactId>cdmf-transport-adapters</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

@ -20,7 +20,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>cdmf-transport-adapters</artifactId> <artifactId>cdmf-transport-adapters</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

@ -44,10 +44,10 @@ public class MQTTEventAdapter implements OutputEventAdapter {
private Map<String, String> globalProperties; private Map<String, String> globalProperties;
private MQTTAdapterPublisher mqttAdapterPublisher; private MQTTAdapterPublisher mqttAdapterPublisher;
private int connectionKeepAliveInterval; private int connectionKeepAliveInterval;
private String qos;
private static ThreadPoolExecutor threadPoolExecutor; private static ThreadPoolExecutor threadPoolExecutor;
private static final Log log = LogFactory.getLog(MQTTEventAdapter.class); private static final Log log = LogFactory.getLog(MQTTEventAdapter.class);
private int tenantId; private int tenantId;
private MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration;
public MQTTEventAdapter(OutputEventAdapterConfiguration eventAdapterConfiguration, public MQTTEventAdapter(OutputEventAdapterConfiguration eventAdapterConfiguration,
Map<String, String> globalProperties) { Map<String, String> globalProperties) {
@ -117,11 +117,11 @@ public class MQTTEventAdapter implements OutputEventAdapter {
@Override @Override
public void connect() { public void connect() {
MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration = mqttBrokerConnectionConfiguration =
new MQTTBrokerConnectionConfiguration(eventAdapterConfiguration, globalProperties); new MQTTBrokerConnectionConfiguration(eventAdapterConfiguration, globalProperties);
String clientId = eventAdapterConfiguration.getStaticProperties().get( String clientId = eventAdapterConfiguration.getStaticProperties().get(
MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID); MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID);
qos = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_MESSAGE_QOS);
mqttAdapterPublisher = new MQTTAdapterPublisher(mqttBrokerConnectionConfiguration, clientId, tenantId); mqttAdapterPublisher = new MQTTAdapterPublisher(mqttBrokerConnectionConfiguration, clientId, tenantId);
} }
@ -179,11 +179,7 @@ public class MQTTEventAdapter implements OutputEventAdapter {
} }
} }
} }
if (qos == null || qos.trim().isEmpty()) { mqttAdapterPublisher.publish(mqttBrokerConnectionConfiguration.getQos(), message.toString(), topic);
mqttAdapterPublisher.publish(message.toString(), topic);
} else {
mqttAdapterPublisher.publish(Integer.parseInt(qos), message.toString(), topic);
}
} catch (Throwable t) { } catch (Throwable t) {
EventAdapterUtil.logAndDrop(eventAdapterConfiguration.getName(), message, null, t, log, tenantId); EventAdapterUtil.logAndDrop(eventAdapterConfiguration.getName(), message, null, t, log, tenantId);
} }

@ -90,9 +90,9 @@ public class MQTTEventAdapterFactory extends OutputEventAdapterFactory {
// set Quality of Service // set Quality of Service
Property qos = new Property(MQTTEventAdapterConstants.ADAPTER_MESSAGE_QOS); Property qos = new Property(MQTTEventAdapterConstants.ADAPTER_MESSAGE_QOS);
qos.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_MESSAGE_QOS)); qos.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_MESSAGE_QOS));
qos.setRequired(true); qos.setRequired(false);
qos.setOptions(new String[]{"0", "1", "2"}); qos.setOptions(new String[]{"0", "1", "2"});
qos.setDefaultValue("1"); qos.setDefaultValue("2");
staticPropertyList.add(brokerUrl); staticPropertyList.add(brokerUrl);
staticPropertyList.add(userName); staticPropertyList.add(userName);

@ -34,6 +34,7 @@ public class MQTTBrokerConnectionConfiguration {
private boolean cleanSession = true; private boolean cleanSession = true;
private int keepAlive; private int keepAlive;
private boolean globalCredentailSet; private boolean globalCredentailSet;
private int qos;
public String getTokenUrl() { public String getTokenUrl() {
return tokenUrl; return tokenUrl;
@ -75,6 +76,9 @@ public class MQTTBrokerConnectionConfiguration {
return globalCredentailSet; return globalCredentailSet;
} }
public int getQos() {
return qos;
}
public MQTTBrokerConnectionConfiguration(OutputEventAdapterConfiguration eventAdapterConfiguration, public MQTTBrokerConnectionConfiguration(OutputEventAdapterConfiguration eventAdapterConfiguration,
Map<String, String> globalProperties) { Map<String, String> globalProperties) {
adapterName = eventAdapterConfiguration.getName(); adapterName = eventAdapterConfiguration.getName();
@ -98,14 +102,28 @@ public class MQTTBrokerConnectionConfiguration {
if (scopes == null) { if (scopes == null) {
this.scopes = MQTTEventAdapterConstants.EMPTY_STRING; this.scopes = MQTTEventAdapterConstants.EMPTY_STRING;
} }
this.cleanSession = Boolean.parseBoolean(eventAdapterConfiguration.getStaticProperties() String cleanSession = globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION);
.get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION)); if (cleanSession == null || cleanSession.isEmpty()) {
this.cleanSession = Boolean.parseBoolean(eventAdapterConfiguration.getStaticProperties()
.get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION));
} else {
this.cleanSession = Boolean.parseBoolean(cleanSession);
}
//If global properties are available those will be assigned else constant values will be assigned //If global properties are available those will be assigned else constant values will be assigned
if (globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE) != null) { if (globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE) != null) {
keepAlive = Integer.parseInt((globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE))); keepAlive = Integer.parseInt((globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE)));
} else { } else {
keepAlive = MQTTEventAdapterConstants.ADAPTER_CONF_DEFAULT_KEEP_ALIVE; keepAlive = MQTTEventAdapterConstants.ADAPTER_CONF_DEFAULT_KEEP_ALIVE;
} }
String qosVal = globalProperties.get(MQTTEventAdapterConstants.ADAPTER_MESSAGE_QOS);
if (qosVal != null && !qosVal.isEmpty()) {
this.qos = Integer.parseInt(qosVal);
} else {
qosVal = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_MESSAGE_QOS);
this.qos = Integer.parseInt(qosVal);
}
} }
} }

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>cdmf-transport-adapters</artifactId> <artifactId>cdmf-transport-adapters</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -21,4 +21,39 @@
<web-app> <web-app>
<display-name>Output WebSocket</display-name> <display-name>Output WebSocket</display-name>
<filter>
<filter-name>HttpHeaderSecurityFilter</filter-name>
<filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<init-param>
<param-name>hstsEnabled</param-name>
<param-value>false</param-value>
</init-param>
</filter>
<filter>
<filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
<filter-class>org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter</filter-class>
<init-param>
<param-name>patterns</param-name>
<param-value>text/html" ,application/json" ,text/plain</param-value>
</init-param>
<init-param>
<param-name>filterAction</param-name>
<param-value>enforce</param-value>
</init-param>
<init-param>
<param-name>httpHeaders</param-name>
<param-value>Cache-Control: no-store, no-cache, must-revalidate, private</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>HttpHeaderSecurityFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app> </web-app>

@ -21,7 +21,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>cdmf-transport-adapters</artifactId> <artifactId>cdmf-transport-adapters</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -63,23 +63,14 @@ public class DeviceAuthorizer implements Authorizer {
private static DeviceAccessAuthorizationAdminService deviceAccessAuthorizationAdminService; private static DeviceAccessAuthorizationAdminService deviceAccessAuthorizationAdminService;
private static final String CDMF_SERVER_BASE_CONTEXT = "/api/device-mgt/v1.0"; private static final String CDMF_SERVER_BASE_CONTEXT = "/api/device-mgt/v1.0";
private static final String DEVICE_MGT_SERVER_URL = "deviceMgtServerUrl"; private static final String DEVICE_MGT_SERVER_URL = "deviceMgtServerUrl";
private static final String STAT_PERMISSION = "statsPermission";
private static final String DEVICE_ID = "deviceId"; private static final String DEVICE_ID = "deviceId";
private static final String DEVICE_TYPE = "deviceType"; private static final String DEVICE_TYPE = "deviceType";
private static Log log = LogFactory.getLog(DeviceAuthorizer.class); private static Log log = LogFactory.getLog(DeviceAuthorizer.class);
private static List<String> statPermissions;
public DeviceAuthorizer() { public DeviceAuthorizer() {
} }
@Override @Override
public void init(Map<String, String> globalProperties) { public void init(Map<String, String> globalProperties) {
statPermissions = getPermissions(globalProperties);
if (statPermissions != null && !statPermissions.isEmpty()) {
for (String permission : statPermissions) {
PermissionUtil.putPermission(permission);
}
}
try { try {
deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()) deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger())
.logLevel(Logger.Level.FULL).requestInterceptor(new OAuthRequestInterceptor(globalProperties)) .logLevel(Logger.Level.FULL).requestInterceptor(new OAuthRequestInterceptor(globalProperties))
@ -102,9 +93,6 @@ public class DeviceAuthorizer implements Authorizer {
AuthorizationRequest authorizationRequest = new AuthorizationRequest(); AuthorizationRequest authorizationRequest = new AuthorizationRequest();
authorizationRequest.setTenantDomain(authenticationInfo.getTenantDomain()); authorizationRequest.setTenantDomain(authenticationInfo.getTenantDomain());
if (statPermissions != null && !statPermissions.isEmpty()) {
authorizationRequest.setPermissions(statPermissions);
}
authorizationRequest.setUsername(authenticationInfo.getUsername()); authorizationRequest.setUsername(authenticationInfo.getUsername());
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
@ -137,14 +125,6 @@ public class DeviceAuthorizer implements Authorizer {
return deviceMgtServerUrl; return deviceMgtServerUrl;
} }
private List<String> getPermissions(Map<String, String> properties) {
String stats = properties.get(STAT_PERMISSION);
if (stats != null && !stats.isEmpty()) {
return Arrays.asList(stats.replace("\n", "").split(" "));
}
return null;
}
private static Client getSSLClient() { private static Client getSSLClient() {
return new Client.Default(getTrustedSSLSocketFactory(), new HostnameVerifier() { return new Client.Default(getTrustedSSLSocketFactory(), new HostnameVerifier() {
@Override @Override

@ -1,76 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.output.adapter.websocket.authorization;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.device.mgt.output.adapter.websocket.internal.WebsocketEventAdaptorServiceDataHolder;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import java.util.StringTokenizer;
/**
* Utility class which holds necessary utility methods required for persisting permissions in
* registry.
*/
public class PermissionUtil {
public static final String PERMISSION_PROPERTY_NAME = "name";
private static Log log = LogFactory.getLog(DeviceAuthorizer.class);
public static void putPermission(String permission) {
try {
StringTokenizer tokenizer = new StringTokenizer(permission, "/");
String lastToken = "", currentToken, tempPath;
while (tokenizer.hasMoreTokens()) {
currentToken = tokenizer.nextToken();
tempPath = lastToken + "/" + currentToken;
if (!checkResourceExists(tempPath)) {
createRegistryCollection(tempPath, currentToken);
}
lastToken = tempPath;
}
} catch (org.wso2.carbon.registry.api.RegistryException e) {
log.error("Failed to creation permission in registry" + permission, e);
}
}
public static void createRegistryCollection(String path, String resourceName)
throws org.wso2.carbon.registry.api.RegistryException {
Resource resource = getGovernanceRegistry().newCollection();
resource.addProperty(PERMISSION_PROPERTY_NAME, resourceName);
getGovernanceRegistry().beginTransaction();
getGovernanceRegistry().put(path, resource);
getGovernanceRegistry().commitTransaction();
}
public static boolean checkResourceExists(String path)
throws RegistryException {
return getGovernanceRegistry().resourceExists(path);
}
public static Registry getGovernanceRegistry() throws RegistryException {
return WebsocketEventAdaptorServiceDataHolder.getRegistryService()
.getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
}
}

@ -28,7 +28,7 @@ import javax.ws.rs.core.MediaType;
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Path("/admin/authorization") @Path("/admin/authorization/stat")
/** /**
* This interface provided the definition of the device - user access verification service. * This interface provided the definition of the device - user access verification service.
*/ */

@ -20,7 +20,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>cdmf-transport-adapters</artifactId> <artifactId>cdmf-transport-adapters</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>extensions</artifactId> <artifactId>extensions</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>mb-extensions</artifactId> <artifactId>mb-extensions</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -77,12 +77,14 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
private static final String CACHE_MANAGER_NAME = "mqttAuthorizationCacheManager"; private static final String CACHE_MANAGER_NAME = "mqttAuthorizationCacheManager";
private static final String CACHE_NAME = "mqttAuthorizationCache"; private static final String CACHE_NAME = "mqttAuthorizationCache";
private static DeviceAccessAuthorizationAdminService deviceAccessAuthorizationAdminService; private static DeviceAccessAuthorizationAdminService deviceAccessAuthorizationAdminService;
private static OAuthRequestInterceptor oAuthRequestInterceptor;
private static final String GATEWAY_ERROR_CODE = "<am:code>404</am:code>";
public DeviceAccessBasedMQTTAuthorizer() { public DeviceAccessBasedMQTTAuthorizer() {
oAuthRequestInterceptor = new OAuthRequestInterceptor();
this.MQTTAuthorizationConfiguration = AuthorizationConfigurationManager.getInstance(); this.MQTTAuthorizationConfiguration = AuthorizationConfigurationManager.getInstance();
deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()) deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger())
.logLevel(Logger.Level.FULL).requestInterceptor(new OAuthRequestInterceptor()) .logLevel(Logger.Level.FULL).requestInterceptor(oAuthRequestInterceptor)
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(DeviceAccessAuthorizationAdminService.class, .target(DeviceAccessAuthorizationAdminService.class,
MQTTAuthorizationConfiguration.getDeviceMgtServerUrl() + CDMF_SERVER_BASE_CONTEXT); MQTTAuthorizationConfiguration.getDeviceMgtServerUrl() + CDMF_SERVER_BASE_CONTEXT);
@ -121,7 +123,12 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
} }
return false; return false;
} catch (FeignException e) { } catch (FeignException e) {
log.error(e.getMessage(), e); oAuthRequestInterceptor.resetApiApplicationKey();
if (e.getMessage().contains(GATEWAY_ERROR_CODE)) {
log.error("Failed to connect to the device authorization service.");
} else {
log.error(e.getMessage(), e);
}
return false; return false;
} }
} }
@ -164,6 +171,12 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
} }
} }
} catch (FeignException e) { } catch (FeignException e) {
oAuthRequestInterceptor.resetApiApplicationKey();
if (e.getMessage().contains(GATEWAY_ERROR_CODE)) {
log.error("Failed to connect to the device authorization service.");
} else {
log.error(e.getMessage(), e);
}
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
} finally { } finally {

@ -123,6 +123,10 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
template.header("Authorization", headerValue); template.header("Authorization", headerValue);
} }
public void resetApiApplicationKey() {
apiApplicationKey = null;
}
private static Client getSSLClient() { private static Client getSSLClient() {
return new Client.Default(getTrustedSSLSocketFactory(), new HostnameVerifier() { return new Client.Default(getTrustedSSLSocketFactory(), new HostnameVerifier() {
@Override @Override

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>extensions</artifactId> <artifactId>extensions</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>carbon-device-mgt-plugins-parent</artifactId> <artifactId>carbon-device-mgt-plugins-parent</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

@ -20,7 +20,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>siddhi-extensions</artifactId> <artifactId>siddhi-extensions</artifactId>
<version>3.0.25-SNAPSHOT</version> <version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -77,7 +77,7 @@
org.wso2.extension.siddhi.execution.json.* org.wso2.extension.siddhi.execution.json.*
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
org.json, org.json;version="${orbit.version.json.range}",
org.wso2.siddhi.core.*, org.wso2.siddhi.core.*,
org.wso2.siddhi.query.api.*, org.wso2.siddhi.query.api.*,
</Import-Package> </Import-Package>

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save