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

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

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

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

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

@ -33,6 +33,9 @@
} else if(action === 'getData'){
print(providerAPI.getData(id, type, timeFrom, timeTo));
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 tableName = "ORG_WSO2_GEO_FUSEDSPATIALEVENT";
var alertTable = "ORG_WSO2_GEO_ALERTSNOTIFICATION";
var typeMap = {
"bool": "string",
@ -130,9 +131,9 @@ var getConfig, validate, getMode, getSchema, getData, registerCallBackforPush;
"query": luceneQuery,
"start": 0,
"count": limit,
"sortBy" : [{
"field" : "timeStamp",
"sortType" : "ASC"
"sortBy": [{
"field": "timeStamp",
"sortType": "ASC"
}]
};
result = connector.search(loggedInUser, tableName, stringify(filter)).getMessage();
@ -151,4 +152,28 @@ var getConfig, validate, getMode, getSchema, getData, registerCallBackforPush;
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) {
$.getJSON("/portal/store/carbon.super/fs/gadget/geo-dashboard/controllers/get_alerts_history.jag?objectId=" + objectId, function (data) {
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":
$.ajax({
url: '/portal/store/carbon.super/fs/gadget/geo-dashboard/controllers/gadget-controller.jag?action=getAlerts&id=' + objectId,
method: "GET",
contentType: "application/json",
async: false,
success: function (data) {
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");
return;
case "WARNING":
$(alertDOMElement).addClass("list-group-item list-group-item-warning");
break;
case "ALERTED":
$(alertDOMElement).addClass("list-group-item list-group-item-danger");
break;
case "OFFLINE":
$(alertDOMElement).addClass("list-group-item list-group-item-success");
break;
}
$(alertDOMElement).html(val.INFORMATION);
$(alertDOMElement).css({marginTop: "5px"});
$(alertDOMElement).attr('onClick', 'showAlertInMap(this)');
// Set HTML5 data attributes for later use
$(alertDOMElement).attr('data-id', val.ID);
$(alertDOMElement).attr('data-latitude', val.LATITUDE);
$(alertDOMElement).attr('data-longitude', val.LONGITUDE);
$(alertDOMElement).attr('data-state', val.STATE);
$(alertDOMElement).attr('data-information', val.INFORMATION);
alertsContainer.append(alertDOMElement);
});
return;
case "WARNING":
$(alertDOMElement).addClass("list-group-item list-group-item-warning");
break;
case "ALERTED":
$(alertDOMElement).addClass("list-group-item list-group-item-danger");
break;
case "OFFLINE":
$(alertDOMElement).addClass("list-group-item list-group-item-success");
break;
}
$(alertDOMElement).html(val.INFORMATION);
$(alertDOMElement).css({marginTop: "5px"});
$(alertDOMElement).attr('onClick', 'showAlertInMap(this)');
// Set HTML5 data attributes for later use
$(alertDOMElement).attr('data-id', val.ID);
$(alertDOMElement).attr('data-latitude', val.LATITUDE);
$(alertDOMElement).attr('data-longitude', val.LONGITUDE);
$(alertDOMElement).attr('data-state', val.STATE);
$(alertDOMElement).attr('data-information', val.INFORMATION);
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.
-->
<artifact name="Geo-Publisher-RDBMS-GeoAlertNotifications" version="1.0.0" type="event/publisher" serverRole="GeoDashboard">
<file>Geo-Publisher-RDBMS-GeoAlertNotifications-1.0.0.xml</file>
<artifact name="Geo-Publisher-RDBMS-GeoAlertNotifications" version="1.0.0" type="analytics/eventstore" serverRole="GeoDashboard">
<file>Geo-Publisher-RDBMS-GeoAlertNotifications.xml</file>
</artifact>

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

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

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

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

@ -161,7 +161,6 @@
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_sense_streams" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="android_sms_chart_gadget" 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"/>
<dependency artifact="android_un_secured_devices_gadget" version="1.0.0" include="true"
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_accelerometer_streams" version="1.0.0" include="true"

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

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

@ -18,7 +18,7 @@
<div class="panel panel-default">
<div id="general-config-heading" class="panel-heading" role="tab">
<h2 class="sub-title panel-title">
Android Sense Endpoint Configuration
Android Sense Configuration
</h2>
</div>
<div id="android_sense-config-body" class="panel-collapse panel-body"
@ -27,22 +27,32 @@
class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span>
</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">
<button id="save-general-btn" class="wr-btn" onclick="addConfiguration();">
Save
<button id="save-general-btn" class="wr-btn" onclick="artifactUpload();">
Deploy Analytics Artifacts
</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>

@ -18,20 +18,7 @@
function onRequest(context){
var viewModel = {};
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
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.
}
);
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
viewModel["permissions"] = userModule.getUIPermissions();
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="{{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>
{{#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"
target="_blank">[ here ]</a> for latest instructions and
troubleshooting.</p>

@ -19,20 +19,9 @@
function onRequest(context){
var viewModel = {};
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/admin/devicetype/deploy/android_sense/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.
}
);
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var uiPermissions = userModule.getUIPermissions();
viewModel["permissions"] = uiPermissions;
viewModel["hostName"] = devicemgtProps["generalConfig"]["host"];
viewModel["enrollmentURL"] = viewModel["hostName"] + context.unit.publicUri + "/asset/androidsense.apk";
return viewModel;

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

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

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

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

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

@ -27,36 +27,35 @@
class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span>
</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">
<button id="save-general-btn" class="wr-btn" onclick="addConfiguration();">
Save
<button id="save-general-btn" class="wr-btn" onclick="artifactUpload();">
Deploy Analytics Artifacts
</button>
</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"}}
{{js "js/platform-configuration.js"}}
{{/zone}}

@ -18,20 +18,7 @@
function onRequest(context){
var viewModel = {};
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
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.
}
);
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/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) {
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var resp = tokenUtil.decode(encodedClientKeys).split(":");
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username, "default", {});
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;
if (user.domain == "carbon.super") {
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username , "default", {});
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;
} 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};
}

@ -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">
<i class="fw fw-download add-margin-1x"></i>Download Sketch
</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"
target="_blank">here</a> for latest instructions and
troubleshooting.</p>

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

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

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

@ -19,8 +19,6 @@
<artifacts>
<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"/>
</artifact>
</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>
<artifactId>raspberrypi-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version>
<version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

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

@ -27,43 +27,32 @@
class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span>
</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">
<button id="save-general-btn" class="wr-btn" onclick="addConfiguration();">
Save
<button id="save-general-btn" class="wr-btn" onclick="artifactUpload();">
Deploy Analytics Artifacts
</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>

@ -16,22 +16,9 @@
* under the License.
*/
function onRequest(context) {
function onRequest(context){
var viewModel = {};
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
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.
}
);
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
viewModel["permissions"] = userModule.getUIPermissions();
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 encodedClientKeys = session.get(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]);
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) {
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var resp = tokenUtil.decode(encodedClientKeys).split(":");
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username,"default", {});
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;
if (user.domain == "carbon.super") {
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username , "default", {});
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;
} 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};
}

@ -182,31 +182,4 @@ function doAction(data) {
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">
<i class="fw fw-download add-margin-1x"></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/Raspberry+Pi"
target="_blank">here</a> for latest instructions and

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

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

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

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

@ -19,8 +19,6 @@
<artifacts>
<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"/>
</artifact>
</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>
<artifactId>virtual-fire-alarm-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>3.0.25-SNAPSHOT</version>
<version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

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

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

@ -19,7 +19,7 @@
<div class="panel panel-default">
<div id="general-config-heading" class="panel-heading" role="tab">
<h2 class="sub-title panel-title">
Virtual Firealarm Endpoint Configuration
Virtual Firealarm Configuration
</h2>
</div>
<div id="virtual-alarm-config-body" class="panel-collapse panel-body"
@ -28,43 +28,32 @@
class="alert alert-danger hidden" role="alert">
<i class="icon fw fw-error"></i><span></span>
</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">
<button id="save-general-btn-virtualfirealarm" class="wr-btn" onclick="addConfiguration();">
Save
<button id="save-general-btn" class="wr-btn" onclick="artifactUpload();">
Deploy Analytics Artifacts
</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>

@ -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 encodedClientKeys = session.get(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]);
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) {
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var resp = tokenUtil.decode(encodedClientKeys).split(":");
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username,"default", {});
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;
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var resp = tokenUtil.decode(encodedClientKeys).split(":");
if (user.domain == "carbon.super") {
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username , "default", {});
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;
} 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};
}

@ -134,31 +134,4 @@ function doAction(data) {
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 href="#" class="download-link btn-operations">
<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"
target="_blank">[ here ]</a> for latest instructions and

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

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

@ -20,6 +20,7 @@ import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
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.MobileAppTypes;
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.mdm.App;
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.device.mgt.common.DeviceIdentifier;
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.operation.mgt.Activity;
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.List;
@ -47,6 +58,9 @@ import java.util.Properties;
public class ApplicationOperationsImpl implements ApplicationOperations {
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.
@ -56,7 +70,7 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
throws MobileApplicationException {
if (log.isDebugEnabled()) {
log.debug(applicationOperationAction.getAction() + " action is triggered for " +
applicationOperationAction.getType() +".");
applicationOperationAction.getType() +".");
}
Operation operation = null;
@ -73,19 +87,19 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
getDevicesOfUser(userName);
for (org.wso2.carbon.device.mgt.common.Device device : deviceList) {
if(MDMAppConstants.WEBAPP.equals(applicationOperationAction.getApp().getPlatform()) ||
applicationOperationAction.getApp().getPlatform().equalsIgnoreCase(device.getType())){
if (MDMAppConstants.ACTIVE.equalsIgnoreCase(device.getEnrolmentInfo().
getStatus().toString())) {
if (MDMAppConstants.WEBAPP.equals(applicationOperationAction.getApp().getPlatform()) ||
applicationOperationAction.getApp().getPlatform().equalsIgnoreCase(device.getType())) {
if (MDMAppConstants.ACTIVE.equalsIgnoreCase(device.getEnrolmentInfo().
getStatus().toString())) {
deviceIdentifiers.add(getDeviceIdentifierByDevice(device));
}
}
}
}
} catch (DeviceManagementException devEx) {
String errorMsg = "Error occurred fetch device for user " + userName +
" at app installation";
logError(errorMsg, devEx);
String errorMsg = "Error occurred fetch device for user " + userName +
" at app installation";
logError(errorMsg, devEx);
throw new MobileApplicationException(errorMsg, devEx);
}
} else if (MDMAppConstants.ROLE.equals(applicationOperationAction.getType())) {
@ -105,9 +119,9 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
}
}
} catch (DeviceManagementException devMgtEx) {
String errorMsg = "Error occurred fetch device for user role " + userRole +
" at app installation";
logError(errorMsg, devMgtEx);
String errorMsg = "Error occurred fetch device for user role " + userRole +
" at app installation";
logError(errorMsg, devMgtEx);
throw new MobileApplicationException(errorMsg, devMgtEx);
}
@ -189,8 +203,8 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
}
}
}
activity = MDMServiceAPIUtils.getAppManagementService(applicationOperationAction.getTenantId())
.installApplicationForDevices(operation, deviceIdentifiers);
activity = MDMServiceAPIUtils.getAppManagementService(applicationOperationAction.getTenantId())
.installApplicationForDevices(operation, deviceIdentifiers);
}
@ -236,20 +250,18 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
List<Device> devices;
List<org.wso2.carbon.device.mgt.common.Device> deviceList = null;
try {
if(MDMAppConstants.WEBAPP.equals
(applicationOperationDevice.getPlatform())) {
deviceList = MDMServiceAPIUtils
.getDeviceManagementService(applicationOperationDevice.getTenantId()).
getDevicesOfUser(
applicationOperationDevice.getCurrentUser().getUsername());
} else {
if (MDMAppConstants.WEBAPP.equals
(applicationOperationDevice.getPlatform())) {
deviceList = MDMServiceAPIUtils
.getDeviceManagementService(applicationOperationDevice.getTenantId()).
getDevicesOfUser(applicationOperationDevice.getCurrentUser().getUsername());
} else {
deviceList = MDMServiceAPIUtils
.getDeviceManagementService(applicationOperationDevice.getTenantId()).
getDevicesOfUser(
applicationOperationDevice.getCurrentUser().getUsername(),
getDevicesOfUser(applicationOperationDevice.getCurrentUser().getUsername(),
applicationOperationDevice.getPlatform());
}
devices = new ArrayList<>(deviceList.size());
devices = new ArrayList<>(deviceList.size());
if(log.isDebugEnabled()){
log.debug("device list got from mdm "+ deviceList.toString());
}
@ -268,18 +280,18 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
device.setType(MDMAppConstants.MOBILE_DEVICE);
String imgUrl;
if (MDMAppConstants.ANDROID.equalsIgnoreCase(commonDevice.getType())) {
imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.NEXUS);
} else if (MDMAppConstants.IOS.equalsIgnoreCase(commonDevice.getType())) {
imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.IPHONE);
} else {
imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.NONE);
}
imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.NEXUS);
} else if (MDMAppConstants.IOS.equalsIgnoreCase(commonDevice.getType())) {
imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.IPHONE);
} else {
imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.NONE);
}
device.setImage(imgUrl);
device.setPlatform(commonDevice.getType());
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>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>appm-connector</artifactId>
<version>3.0.25-SNAPSHOT</version>
<version>3.0.35-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

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

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

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

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

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

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

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

@ -120,7 +120,7 @@ public class MQTTEventAdapterFactory extends InputEventAdapterFactory {
// set clientId
Property clientId = new Property(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));
propertyList.add(clientId);

@ -17,6 +17,7 @@
*/
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.LogFactory;
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.mqtt.MQTTEventAdapterFactory;
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.utils.ConfigurationContextService;
/**
* @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"
* bind="setJWTClientManagerService"
* 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 {
@ -80,4 +92,21 @@ public class InputAdapterServiceComponent {
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;
import org.apache.axis2.context.ConfigurationContext;
import org.osgi.service.http.HttpService;
import org.wso2.carbon.device.mgt.input.adapter.extension.InputAdapterExtensionService;
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.
@ -26,6 +28,8 @@ public final class InputAdapterServiceDataHolder {
private static HttpService httpService;
private static InputAdapterExtensionService inputAdapterExtensionService;
private static JWTClientManagerService jwtClientManagerService;
private static InputEventAdapterService inputEventAdapterService;
private static ConfigurationContext mainServerConfigContext;
private InputAdapterServiceDataHolder() {
}
@ -55,4 +59,20 @@ public final class 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;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
@ -33,16 +35,19 @@ import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
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.ContentTransformer;
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.event.input.adapter.core.InputEventAdapterConfiguration;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterListener;
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.exception.JWTClientException;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.io.IOException;
import java.net.MalformedURLException;
@ -63,26 +68,29 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
private MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration;
private String topic;
private int tenantId;
private String tenantDomain;
private boolean connectionSucceeded = false;
ContentValidator contentValidator;
ContentTransformer contentTransformer;
private ContentValidator contentValidator;
private ContentTransformer contentTransformer;
private InputEventAdapterConfiguration inputEventAdapterConfiguration;
private InputEventAdapterListener eventAdapterListener = null;
public MQTTAdapterListener(MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration,
String topic, String mqttClientId,
InputEventAdapterListener inputEventAdapterListener, int tenantId) {
if(mqttClientId == null || mqttClientId.trim().isEmpty()){
String topic, InputEventAdapterConfiguration inputEventAdapterConfiguration,
InputEventAdapterListener inputEventAdapterListener) {
String mqttClientId = inputEventAdapterConfiguration.getProperties()
.get(MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID);
if (mqttClientId == null || mqttClientId.trim().isEmpty()) {
mqttClientId = MqttClient.generateClientId();
}
this.inputEventAdapterConfiguration = inputEventAdapterConfiguration;
this.mqttBrokerConnectionConfiguration = mqttBrokerConnectionConfiguration;
this.cleanSession = mqttBrokerConnectionConfiguration.isCleanSession();
int keepAlive = mqttBrokerConnectionConfiguration.getKeepAlive();
this.topic = PropertyUtils.replaceTenantDomainProperty(topic);
this.eventAdapterListener = inputEventAdapterListener;
this.tenantId = tenantId;
this.tenantDomain = this.topic.split("/")[0];
//SORTING messages until the server fetches them
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)) {
contentValidator = InputAdapterServiceDataHolder.getInputAdapterExtensionService()
.getDefaultContentValidator();
} else {
} else {
contentValidator = InputAdapterServiceDataHolder.getInputAdapterExtensionService()
.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 &&
this.mqttBrokerConnectionConfiguration.getDcrUrl() != null) {
String username = this.mqttBrokerConnectionConfiguration.getUsername();
@ -145,7 +153,7 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
if (!mqttBrokerConnectionConfiguration.isGlobalCredentailSet()) {
registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX
+ mqttBrokerConnectionConfiguration.getAdapterName() +
"_" + tenantId);
"_" + tenantDomain);
registrationProfile.setIsSaasApp(false);
} else {
registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX
@ -175,17 +183,35 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
log.error(msg, e);
}
}
} catch (HttpHostConnectException e) {
log.error("Keymanager is unreachable, Waiting....");
return false;
} catch (MalformedURLException e) {
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);
} catch (NoSuchAlgorithmException |KeyManagementException |KeyStoreException | IOException e) {
return false;
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | IOException e) {
log.error("Failed to create a http connection.", e);
return false;
}
}
}
mqttClient.connect(connectionOptions);
mqttClient.subscribe(topic);
try {
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) {
@ -197,7 +223,7 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
mqttClient.disconnect(3000);
} catch (MqttException e) {
log.error("Can not unsubscribe from the destination " + topic +
" with the event adapter " + adapterName, e);
" with the event adapter " + adapterName, e);
}
}
connectionSucceeded = true;
@ -218,7 +244,14 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
log.debug(msgText);
}
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()) {
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);
contentInfo = contentValidator.validate(msgText, dynamicProperties);
if (contentInfo != null && contentInfo.isValidContent()) {
eventAdapterListener.onEvent(contentInfo.getMessage());
inputEventAdapterListener.onEvent(contentInfo.getMessage());
}
} else {
eventAdapterListener.onEvent(msgText);
inputEventAdapterListener.onEvent(msgText);
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
@ -252,10 +285,14 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
while (!connectionSucceeded) {
try {
connectionDuration = connectionDuration * MQTTEventAdapterConstants.RECONNECTION_PROGRESS_FACTOR;
if (connectionDuration > MQTTEventAdapterConstants.MAXIMUM_RECONNECTION_DURATION) {
connectionDuration = MQTTEventAdapterConstants.MAXIMUM_RECONNECTION_DURATION;
}
Thread.sleep(connectionDuration);
startListener();
connectionSucceeded = true;
log.info("MQTT Connection successful");
if (startListener()) {
connectionSucceeded = true;
log.info("MQTT Connection successful");
}
} catch (InterruptedException e) {
log.error("Interruption occurred while waiting for reconnection", e);
} catch (MqttException e) {
@ -276,7 +313,7 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
private String getToken(String clientId, String clientSecret)
throws UserStoreException, JWTClientException {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
try {
String scopes = mqttBrokerConnectionConfiguration.getBrokerScopes();
String username = mqttBrokerConnectionConfiguration.getUsername();

@ -105,10 +105,18 @@ public class MQTTBrokerConnectionConfiguration {
this.brokerUrl = PropertyUtils.replaceMqttProperty(url);
this.dcrUrl = PropertyUtils
.replaceMqttProperty(globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL));
this.contentValidatorType = eventAdapterConfiguration.getProperties()
.get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_TYPE);
this.cleanSession = Boolean.parseBoolean(eventAdapterConfiguration.getProperties()
.get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION));
this.contentValidatorType = globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_TYPE);
if (contentValidatorType == null || contentValidatorType.isEmpty()) {
this.contentValidatorType = eventAdapterConfiguration.getProperties()
.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 (globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE) != null) {
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 RECONNECTION_PROGRESS_FACTOR = 2;
public static final int MAXIMUM_RECONNECTION_DURATION = 60000;
public static final String EMPTY_STRING = "";
public static final String GRANT_TYPE_PARAM_NAME = "grant_type";

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

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

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

@ -90,9 +90,9 @@ public class MQTTEventAdapterFactory extends OutputEventAdapterFactory {
// set Quality of Service
Property qos = new Property(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.setDefaultValue("1");
qos.setDefaultValue("2");
staticPropertyList.add(brokerUrl);
staticPropertyList.add(userName);

@ -34,6 +34,7 @@ public class MQTTBrokerConnectionConfiguration {
private boolean cleanSession = true;
private int keepAlive;
private boolean globalCredentailSet;
private int qos;
public String getTokenUrl() {
return tokenUrl;
@ -75,6 +76,9 @@ public class MQTTBrokerConnectionConfiguration {
return globalCredentailSet;
}
public int getQos() {
return qos;
}
public MQTTBrokerConnectionConfiguration(OutputEventAdapterConfiguration eventAdapterConfiguration,
Map<String, String> globalProperties) {
adapterName = eventAdapterConfiguration.getName();
@ -98,14 +102,28 @@ public class MQTTBrokerConnectionConfiguration {
if (scopes == null) {
this.scopes = MQTTEventAdapterConstants.EMPTY_STRING;
}
this.cleanSession = Boolean.parseBoolean(eventAdapterConfiguration.getStaticProperties()
.get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION));
String cleanSession = globalProperties.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 (globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE) != null) {
keepAlive = Integer.parseInt((globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE)));
} else {
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>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>cdmf-transport-adapters</artifactId>
<version>3.0.25-SNAPSHOT</version>
<version>3.0.35-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>

@ -21,4 +21,39 @@
<web-app>
<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>

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

@ -63,23 +63,14 @@ public class DeviceAuthorizer implements Authorizer {
private static DeviceAccessAuthorizationAdminService deviceAccessAuthorizationAdminService;
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 STAT_PERMISSION = "statsPermission";
private static final String DEVICE_ID = "deviceId";
private static final String DEVICE_TYPE = "deviceType";
private static Log log = LogFactory.getLog(DeviceAuthorizer.class);
private static List<String> statPermissions;
public DeviceAuthorizer() {
}
@Override
public void init(Map<String, String> globalProperties) {
statPermissions = getPermissions(globalProperties);
if (statPermissions != null && !statPermissions.isEmpty()) {
for (String permission : statPermissions) {
PermissionUtil.putPermission(permission);
}
}
try {
deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger())
.logLevel(Logger.Level.FULL).requestInterceptor(new OAuthRequestInterceptor(globalProperties))
@ -102,9 +93,6 @@ public class DeviceAuthorizer implements Authorizer {
AuthorizationRequest authorizationRequest = new AuthorizationRequest();
authorizationRequest.setTenantDomain(authenticationInfo.getTenantDomain());
if (statPermissions != null && !statPermissions.isEmpty()) {
authorizationRequest.setPermissions(statPermissions);
}
authorizationRequest.setUsername(authenticationInfo.getUsername());
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
@ -137,14 +125,6 @@ public class DeviceAuthorizer implements Authorizer {
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() {
return new Client.Default(getTrustedSSLSocketFactory(), new HostnameVerifier() {
@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)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/admin/authorization")
@Path("/admin/authorization/stat")
/**
* This interface provided the definition of the device - user access verification service.
*/

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

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

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

@ -77,12 +77,14 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
private static final String CACHE_MANAGER_NAME = "mqttAuthorizationCacheManager";
private static final String CACHE_NAME = "mqttAuthorizationCache";
private static DeviceAccessAuthorizationAdminService deviceAccessAuthorizationAdminService;
private static OAuthRequestInterceptor oAuthRequestInterceptor;
private static final String GATEWAY_ERROR_CODE = "<am:code>404</am:code>";
public DeviceAccessBasedMQTTAuthorizer() {
oAuthRequestInterceptor = new OAuthRequestInterceptor();
this.MQTTAuthorizationConfiguration = AuthorizationConfigurationManager.getInstance();
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())
.target(DeviceAccessAuthorizationAdminService.class,
MQTTAuthorizationConfiguration.getDeviceMgtServerUrl() + CDMF_SERVER_BASE_CONTEXT);
@ -121,7 +123,12 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
}
return false;
} 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;
}
}
@ -164,6 +171,12 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
}
}
} 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);
}
} finally {

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

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

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

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

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

Loading…
Cancel
Save