restoring previous errornous jaggery app

application-manager-new
Rasika Perera 10 years ago
parent 77eb089e2a
commit c478db455f

@ -16,7 +16,6 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
var uri = request.getRequestURI(); var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri)); var uriMatcher = new URIMatcher(String(uri));
@ -33,27 +32,85 @@ var carbonHttpsServletTransport = carbon.server.address('https');
var result; var result;
if (uriMatcher.match("/{context}/api/device/sketch/download")) { if (uriMatcher.match("/{context}/api/device/sketch/download/{downloadId}")) {
sketchType = request.getParameter("sketchType"); downloadId = uriMatcher.elements().downloadId;
deviceType = request.getParameter("deviceType"); //Just download the already created zip archive
var CarbonUtils = Packages.org.wso2.carbon.utils.CarbonUtils;
var sketchFolder = "repository/resources/sketches";
var archivesPath = "file://"+CarbonUtils.getCarbonHome() + "/" + sketchFolder + "/archives/" + downloadId + ".zip";
var zipFile = new File(archivesPath);
response.addHeader('Content-type', "application/zip, application/octet-stream");
response.addHeader('Cache-Control', 'public,max-age=12960000');
response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadId + ".zip\"");
try {
zipFile.open('r');
var stream = zipFile.getStream();
print(stream);
}catch(err){
}finally{
if(zipFile!=null) {
zipFile.close();
}
}
} else if (uriMatcher.match("/{context}/api/device/sketch/download")) {
//Create a new zip archive and register user calling endpoint
/* This should match with $CARBON_HOME/repository/resources/sketches/{sketchType} */
sketchType = request.getParameter("sketchType");
/* This should be registered device type of the CDMF(Connected Device Management Framework) */
deviceType = request.getParameter("deviceType");
if (!sketchType) {
log.error("Sketch Type is empty!");
// http status code 400 refers to - Bad request.
result = 400;
} else {
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
response.sendRedirect(dcProps.appContext + "login?#login-required");
exit();
}
//URL: https://localhost:9443/{deviceType}/download?owner={username}
deviceManagerService = carbonHttpsServletTransport + "/" + deviceType + "/manager";
sketchDownloadEndPoint = deviceManagerService + "/device/" + sketchType + "/download";
response.sendRedirect(sketchDownloadEndPoint + "?owner=" + user.username);
exit();//stop execution
}
} else if (uriMatcher.match("/{context}/api/device/sketch/generate_link")) {
var contents = request.getContent();
sketchType = contents.sketchType;
deviceType = contents.deviceType;
generateLink = contents.generateLink;
if (!sketchType) { if (!sketchType) {
log.error("Sketch Type is empty"); log.error("Sketch Type is empty!");
} // http status code 400 refers to - Bad request.
result = 400;
var user = session.get(constants.USER_SESSION_KEY); } else {
if (!user) { var user = session.get(constants.USER_SESSION_KEY);
response.sendRedirect(dcProps.appContext + "login?#login-required");
exit(); if (!user) {
result = 403;
}else {
//URL: https://localhost:9443/{deviceType}/download?owner={username}
deviceManagerService = carbonHttpsServletTransport + "/" + deviceType + "/manager";
sketchGenerateLinkEndPoint = deviceManagerService + "/device/" + sketchType + "/generate_link";
var fileId = get(sketchGenerateLinkEndPoint + "?owner=" + user.username, null, "text");
result = carbonHttpsServletTransport + constants.WEB_APP_CONTEXT + "/api/device/sketch/download/" + fileId.data;
}
} }
//URL: https://localhost:9443/{deviceType}/download?owner={username}
deviceManagerService = carbonHttpsServletTransport + "/" + deviceType + "/manager";
sketchDownloadEndPoint = deviceManagerService + "/device/" + sketchType + "/download";
response.sendRedirect(sketchDownloadEndPoint + "?owner=" + user.username);
exit();//stop execution
} else if (uriMatcher.match("/{context}/api/devices/all")) { } else if (uriMatcher.match("/{context}/api/devices/all")) {
var user = session.get(constants.USER_SESSION_KEY); var user = session.get(constants.USER_SESSION_KEY);
if (!user) { if (!user) {
response.sendRedirect(dcProps.appContext + "login?#login-required"); response.sendRedirect(dcProps.appContext + "login?#login-required");
@ -66,7 +123,12 @@ if (uriMatcher.match("/{context}/api/device/sketch/download")) {
var data = {}; var data = {};
//XMLHTTPRequest's GET //XMLHTTPRequest's GET
result = get(listAllDevicesEndPoint, data, "json"); try {
result = get(listAllDevicesEndPoint, data, "json");
}catch(err){
log.error("Error occured while retrieveing all devices with username: "+user.username);
result=[];
}
} else if (uriMatcher.match("/{context}/api/devices/types")) { } else if (uriMatcher.match("/{context}/api/devices/types")) {

@ -0,0 +1,31 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/operation-api.jag");
var deviceModule = require("/modules/device.js").deviceModule;
if (uriMatcher.match("/{context}/api/operation")) {
payload = request.getContent();
result = deviceModule.performOperation(payload.devices, payload.operation);
}
%>

@ -0,0 +1,49 @@
<%
/*
* 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.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/policy-api.jag");
var constants = require("/modules/constants.js");
var dcProps = require('/config/dc-props.js').config();
var policyModule = require("/modules/policy.js").policyModule;
var result;
if (uriMatcher.match("/{context}/api/policies/update")) {
payload = request.getContent();
policyModule.updatePolicyPriorities(payload);
} else if (uriMatcher.match("/{context}/api/policies/{id}/delete")) {
elements = uriMatcher.elements();
policyId = elements.id;
try {
result = policyModule.deletePolicy(policyId);
} catch (e) {
log.error("Exception occurred while trying to delete policy for id:" + policyId, e);
// http status code 500 refers to - Internal Server Error.
result = 500;
}
}
// returning the result.
if (result) {
response.content = result;
}
%>

@ -31,118 +31,111 @@ var statsClient = new Packages.org.wso2.carbon.device.mgt.iot.common.analytics.s
if (uriMatcher.match("/{context}/api/stats")) { if (uriMatcher.match("/{context}/api/stats")) {
deviceId = request.getParameter("deviceId"); deviceId = request.getParameter("deviceId");
deviceType = request.getParameter("deviceType"); deviceType = request.getParameter("deviceType");
from = request.getParameter("from"); from = request.getParameter("from");
to = request.getParameter("to"); to = request.getParameter("to");
user = session.get(constants.USER_SESSION_KEY); user = session.get(constants.USER_SESSION_KEY);
if (!user) { if (!user) {
response.sendRedirect(dcProps.appContext + "login?#login-required"); response.sendRedirect(dcProps.appContext + "login?#login-required");
exit(); exit();
} }
log.info("deviceId : " + deviceId + " from : " + from + " to : " + to); log.info("deviceId : " + deviceId + " from : " + from + " to : " + to);
switch (deviceType){ switch (deviceType) {
case "firealarm": case "firealarm":
result = getFireAlarmData(user.username, deviceId, from, to); result = getFireAlarmData(user.username, deviceId, from, to);
break; break;
case "sensebot": case "sensebot":
result = getSensebotData(user.username, deviceId, from, to); result = getSensebotData(user.username, deviceId, from, to);
break; break;
case "arduino": case "arduino":
result = getArduinoData(user.username, deviceId, from, to); result = getArduinoData(user.username, deviceId, from, to);
break; break;
case "digital_display": case "digital_display":
result = getDigitalDisplayData(user.username, deviceId, from, to); result = getDigitalDisplayData(user.username, deviceId, from, to);
break; break;
case "android_sense": case "android_sense":
result = getAndroidSenseData(user.username, deviceId, from, to); result = getAndroidSenseData(user.username, deviceId, from, to);
break; break;
case "raspberrypi": case "raspberrypi":
result = getDigitalDisplayData(user.username, deviceId, from, to); result = getDigitalDisplayData(user.username, deviceId, from, to);
break; break;
default: default:
result = new Object(); result = new Object();
} }
} }
// returning the result. // returning the result.
if (result) { if (result) {
print(result); print(result);
} }
function getFireAlarmData(user, deviceId, from, to){ function getFireAlarmData(user, deviceId, from, to) {
result = new Object(); result = new Object();
result['temperatureData'] = getSensorData("DEVICE_TEMPERATURE_SUMMARY","TEMPERATURE",user, deviceId, from, to); result['cpuTemperatureData'] = getSensorData("DEVICE_CPU_TEMPERATURE_SUMMARY", "TEMPERATURE", user, deviceId, from, to);
result['fanData'] = getSensorData("DEVICE_FAN_USAGE_SUMMARY","status",user, deviceId, from, to); result['temperatureData'] = getSensorData("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, deviceId, from, to);
result['bulbData'] = getSensorData("DEVICE_BULB_USAGE_SUMMARY","status",user, deviceId, from, to); result['fanData'] = getSensorData("DEVICE_FAN_USAGE_SUMMARY", "status", user, deviceId, from, to);
return result; result['bulbData'] = getSensorData("DEVICE_BULB_USAGE_SUMMARY", "status", user, deviceId, from, to);
return result;
} }
function getSensebotData(user, deviceId, from, to){ function getSensebotData(user, deviceId, from, to) {
result = new Object(); result = new Object();
result['sonarData'] = getSensorData("SONAR_SENSOR_SUMMARY","sonar",user, deviceId, from, to); result['sonarData'] = getSensorData("SONAR_SENSOR_SUMMARY", "sonar", user, deviceId, from, to);
result['motionData'] = getSensorData("PIR_MOTION_SENSOR_SUMMARY","motion",user, deviceId, from, to); result['motionData'] = getSensorData("PIR_MOTION_SENSOR_SUMMARY", "motion", user, deviceId, from, to);
result['lightData'] = getSensorData("LDR_LIGHT_SENSOR_SUMMARY","light",user, deviceId, from, to); result['lightData'] = getSensorData("LDR_LIGHT_SENSOR_SUMMARY", "light", user, deviceId, from, to);
result['temperatureData'] = getSensorData("DEVICE_TEMPERATURE_SUMMARY","TEMPERATURE",user, deviceId, from, to); result['temperatureData'] = getSensorData("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, deviceId, from, to);
return result; return result;
} }
function getArduinoData(user, deviceId, from, to){ function getArduinoData(user, deviceId, from, to) {
result = new Object(); result = new Object();
result['temperatureData'] = getSensorData("DEVICE_TEMPERATURE_SUMMARY","TEMPERATURE",user, deviceId, from, to); result['temperatureData'] = getSensorData("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, deviceId, from, to);
return result; return result;
} }
function getDigitalDisplayData(user, deviceId, from, to){ function getAndroidSenseData(user, deviceId, from, to) {
result = new Object(); result = new Object();
result['ramData'] = getSensorData("RAM_USAGE_SUMMARY","motion",user, deviceId, from, to); result['ramData'] = getSensorData("RAM_USAGE_SUMMARY", "motion", user, deviceId, from, to);
result['cpuData'] = getSensorData("CPU_LOAD_SUMMARY","light",user, deviceId, from, to); result['cpuData'] = getSensorData("CPU_LOAD_SUMMARY", "light", user, deviceId, from, to);
result['temperatureData'] = getSensorData("DEVICE_TEMPERATURE_SUMMARY","TEMPERATURE",user, deviceId, from, to); result['temperatureData'] = getSensorData("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, deviceId, from, to);
return result; result['motionData'] = getSensorData("PIR_MOTION_SENSOR_SUMMARY", "motion", user, deviceId, from, to);
return result;
} }
function getAndroidSenseData(user, deviceId, from, to){ function getDigitalDisplayData(user, deviceId, from, to) {
result = new Object(); result = new Object();
result['ramData'] = getSensorData("RAM_USAGE_SUMMARY","motion",user, deviceId, from, to); result['ramData'] = getSensorData("RAM_USAGE_SUMMARY", "motion", user, deviceId, from, to);
result['cpuData'] = getSensorData("CPU_LOAD_SUMMARY","light",user, deviceId, from, to); result['cpuData'] = getSensorData("CPU_LOAD_SUMMARY", "light", user, deviceId, from, to);
result['temperatureData'] = getSensorData("DEVICE_TEMPERATURE_SUMMARY","TEMPERATURE",user, deviceId, from, to); result['cpuTemperatureData'] = getSensorData("DEVICE_CPU_TEMPERATURE_SUMMARY", "TEMPERATURE", user, deviceId, from, to);
result['motionData'] = getSensorData("PIR_MOTION_SENSOR_SUMMARY","motion",user, deviceId, from, to); return result;
return result;
}
function getDigitalDisplayData(user, deviceId, from, to){
result = new Object();
result['ramData'] = getSensorData("RAM_USAGE_SUMMARY","motion",user, deviceId, from, to);
result['cpuData'] = getSensorData("CPU_LOAD_SUMMARY","light",user, deviceId, from, to);
result['temperatureData'] = getSensorData("DEVICE_TEMPERATURE_SUMMARY","TEMPERATURE",user, deviceId, from, to);
return result;
} }
function getSensorData(table, column, user, deviceId, from, to) { function getSensorData(table, column, user, deviceId, from, to) {
var fetchedData = null; var fetchedData = null;
try { try {
fetchedData = statsClient.getDeviceStats(table, column, user, deviceId, from, to); fetchedData = statsClient.getDeviceStats(table, column, user, deviceId, from, to);
}catch(error){ } catch (error) {
log.info(error); log.error(error);
} }
var sensorData = []; var sensorData = [];
if(fetchedData==null) return []; if (fetchedData == null) return [];
for (var i = 0; i < fetchedData.size(); i++) { for (var i = 0; i < fetchedData.size(); i++) {
sensorData.push({ sensorData.push({
time: fetchedData.get(i).getTime(), time: fetchedData.get(i).getTime(),
value: fetchedData.get(i).getValue() value: fetchedData.get(i).getValue()
}); });
} }
return sensorData; return sensorData;
} }
%> %>

@ -25,7 +25,9 @@ var log = new Log("api/user-api.jag");
var constants = require("/modules/constants.js"); var constants = require("/modules/constants.js");
var dcProps = require('/config/dc-props.js').config(); var dcProps = require('/config/dc-props.js').config();
var userModule = require("/modules/user.js").userModule; var userModule = require("/modules/user.js").userModule;
var deviceModule = require("/modules/device.js").deviceModule;
var utility = require("/modules/utility.js").utility; var utility = require("/modules/utility.js").utility;
var deviceManagementService = utility.getDeviceManagementService();
var result; var result;
@ -40,7 +42,14 @@ if (uriMatcher.match("/{context}/api/user/login/")) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("User Logged In : " + user); log.debug("User Logged In : " + user);
} }
response.sendRedirect(constants.WEB_APP_CONTEXT); var hasDevcies = (deviceManagementService.getDevicesOfUser(username).size() >= 1);
if(hasDevcies){
response.sendRedirect(constants.WEB_APP_CONTEXT+"/devices");
}else{
response.sendRedirect(constants.WEB_APP_CONTEXT);
}
}, function () { }, function () {
response.sendRedirect(dcProps.appContext + "login?#auth-failed"); response.sendRedirect(dcProps.appContext + "login?#auth-failed");
}); });
@ -69,7 +78,7 @@ if (uriMatcher.match("/{context}/api/user/login/")) {
} else { } else {
userRoles = String(addUserFormData.userRoles).split(","); userRoles = String(addUserFormData.userRoles).split(",");
} }
userRoles="deviceRole, deviceUser";
try { try {
result = userModule.registerUser(username, firstname, lastname, emailAddress, password, result = userModule.registerUser(username, firstname, lastname, emailAddress, password,
userRoles); userRoles);

@ -3,17 +3,25 @@
"logLevel": "info", "logLevel": "info",
"initScripts": ["/config/init.js"], "initScripts": ["/config/init.js"],
"urlMappings": [ "urlMappings": [
{
"url" : "/testb/*",
"path" : "test.jag"
},
{ {
"url" : "/test/*", "url" : "/test/*",
"path" : "test/testExecutor.jag" "path" : "test/testExecutor.jag"
}, },
{ {
"url": "/api/device/*", "url": "/api/device/*",
"path": "/api/device-api.jag" "path": "/api/device-api.jag"
},
{
"url": "/api/devices/*",
"path": "/api/device-api.jag"
}, },
{ {
"url": "/api/devices/*", "url": "/api/operation/*",
"path": "/api/device-api.jag" "path": "/api/operation-api.jag"
}, },
{ {
"url": "/api/user/*", "url": "/api/user/*",
@ -27,6 +35,10 @@
"url": "/api/stats/*", "url": "/api/stats/*",
"path": "/api/stats-api.jag" "path": "/api/stats-api.jag"
}, },
{
"url": "/api/policies/*",
"path": "/api/policy-api.jag"
},
{ {
"url": "/sso/login", "url": "/sso/login",
"path": "/lib/login.jag" "path": "/lib/login.jag"

@ -0,0 +1,44 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ defineZone "title"}}</title>
{{ defineZone "topCss"}}
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-liquid">
<div class="navbar-header">
<a class="navbar-brand" href="#">{{defineZone "brand"}}</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="/login">Login</a></li>
{{ defineZone "upperRight"}}
</ul>
</div>
</div>
</div>
<div id="wrap">
<div class="container-fluid">
<div class="row">
{{ defineZone "content"}}
</div>
</div>
<!-- /container -->
</div>
<div class="footer">
<div class="container">
<div class="row">
<div class="col-md-12">
{{ defineZone "footer"}}
</div>
</div>
</div>
</div>
</body>
</html>

@ -1,14 +1,15 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="favicon.png" type="image/x-icon" />
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> {{defineZone "favicon"}}
<title>{{ defineZone "title"}}</title> <title>
{{ defineZone "topLibCss"}} {{ defineZone "title"}}
{{ defineZone "topCss"}} </title>
{{ defineZone "topJs"}} {{ defineZone "topLibCss"}}
{{ defineZone "topCss"}}
</head> </head>
<body> <body>
<div class="wr-modalpopup"> <div class="wr-modalpopup">
@ -32,6 +33,7 @@
{{ defineZone "body"}} {{ defineZone "body"}}
{{ defineZone "footer"}} {{ defineZone "footer"}}
</div> </div>
{{ defineZone "bottomjquery" }}
{{ defineZone "bottomLibJs" }} {{ defineZone "bottomLibJs" }}
{{ defineZone "bottomJs" }} {{ defineZone "bottomJs" }}
</body> </body>

@ -22,6 +22,8 @@ var sso = require('/modules/sso.js').sso;
var constants = require('/modules/constants.js'); var constants = require('/modules/constants.js');
var carbonModule = require("carbon"); var carbonModule = require("carbon");
var log = new Log(); var log = new Log();
var apiWrapperUtil = require("/modules/api-wrapper-util.js").apiWrapperUtil;
var userModule = require("/modules/user.js").userModule;
var keyStoreParams = { var keyStoreParams = {
keyStoreName: dataConfig.ssoConfiguration.keyStoreName, keyStoreName: dataConfig.ssoConfiguration.keyStoreName,
keyStorePassword: dataConfig.ssoConfiguration.keyStorePassword, keyStorePassword: dataConfig.ssoConfiguration.keyStorePassword,
@ -31,14 +33,18 @@ sso.configure(dataConfig.ssoConfiguration.issuer,
dataConfig.ssoConfiguration.appName, dataConfig.ssoConfiguration.appName,
keyStoreParams, dataConfig.ssoConfiguration.identityProviderURL); keyStoreParams, dataConfig.ssoConfiguration.identityProviderURL);
sso.acs( sso.acs(
function(loggedInUser) { function(loggedInUser, samlResponse) {
var carbonUser = carbonModule.server.tenantUser(loggedInUser); var carbonUser = carbonModule.server.tenantUser(loggedInUser);
session.put(constants.USER_SESSION_KEY, carbonUser); session.put(constants.USER_SESSION_KEY, carbonUser);
var username = carbonUser.username; var username = carbonUser.username;
if(log.isDebugEnabled()){ if(log.isDebugEnabled()){
log.debug("User logged in: "+username); log.debug("User logged in: "+username);
} }
response.sendRedirect(dataConfig.appContext); var permissions = userModule.getUIPermissions();
if (permissions.DASHBOARD_VIEW){
apiWrapperUtil.setupAccessTokenPair("saml", samlResponse);
response.sendRedirect(dataConfig.appContext + "/device-mgt");
}
}, function() { }, function() {
if(log.isDebugEnabled()){ if(log.isDebugEnabled()){
log.debug("User logged out"); log.debug("User logged out");

@ -82,41 +82,10 @@ var route;
}; };
var renderStatic = function (unit, path) { var renderStatic = function (unit, path) {
var unitModel = null; if (log.isDebugEnabled()) {
var unitName = ""; log.debug('[' + requestId + '] for unit "' + unit + '" a request received for a static file "' + path + '"');
var parts = (unit + path).split("/");
//'unitName' name can be "unitA" or "categoryA/unitA" or "categoryA/categoryAb/unitB"...etc
//incrementally trying to resolve a unit using url path parts.
for (var i = 0; i < parts.length; i++) {
if (unitName == "") {
unitName = parts[i];
} else {
unitName += "/" + parts[i];
}
try {
var model = fuse.getUnitDefinition(unitName);
if (model) {
unitModel = {
name: model.name,
path: parts.splice(i + 1).join("/")
};
break;
}
} catch (err) {
//unit not found, ignore error
}
} }
var staticFile = fuse.getFile(unit, 'public' + path);
if (unitModel == null) {
log.error("unit `"+unit+"` not found!");
return false;
}
var staticFile = fuse.getFile(unitModel.name, 'public' + "/" + unitModel.path);
if (staticFile.isExists() && !staticFile.isDirectory()) { if (staticFile.isExists() && !staticFile.isDirectory()) {
response.addHeader('Content-type', getMime(path)); response.addHeader('Content-type', getMime(path));
response.addHeader('Cache-Control', 'public,max-age=12960000'); response.addHeader('Cache-Control', 'public,max-age=12960000');
@ -139,7 +108,7 @@ var route;
if (jagFile.isExists()) { if (jagFile.isExists()) {
include(jagFile.getPath()); include(jagFile.getPath());
return true; return true;
} else { }else{
return false; return false;
} }
}; };
@ -178,20 +147,24 @@ var route;
var layout = fuseState.layout; var layout = fuseState.layout;
if (layout !== null) { if (layout !== null) {
log.debug( if (log.isDebugEnabled()) {
'[' + requestId + '] request for "' + path + '" will be rendered using layout "' + log.debug(
layout + '" (defined in "' + mainUnit + '") and zones ' + '[' + requestId + '] request for "' + path + '" will be rendered using layout "' +
stringify(zones) layout + '" (defined in "' + mainUnit + '") and zones ' +
); stringify(zones)
);
}
var output = handlebars.Handlebars.compileFile(fuse.getLayoutPath(layout))({}); var output = handlebars.Handlebars.compileFile(fuse.getLayoutPath(layout))({});
response.addHeader('Content-type', 'text/html'); response.addHeader('Content-type', 'text/html');
print(output); print(output);
return true; return true;
} else { } else {
log.debug( if (log.isDebugEnabled()) {
'[' + requestId + '] request for "' + path + '" will can\'t be rendered, since no layout is defined' + log.debug(
'in any of the units ' + stringify(zones)); '[' + requestId + '] request for "' + path + '" will can\'t be rendered, since no layout is defined' +
'in any of the units ' + stringify(zones));
}
return false; return false;
} }
}; };
@ -207,7 +180,9 @@ var route;
*/ */
function renderLess(unit, path) { function renderLess(unit, path) {
//TODO: fix - incorrect less files makes it respond the old less even if it is nocahce. //TODO: fix - incorrect less files makes it respond the old less even if it is nocahce.
log.debug('[' + requestId + '] for unit "' + unit + '" a request received for a less file "' + path + '"'); if (log.isDebugEnabled()) {
log.debug('[' + requestId + '] for unit "' + unit + '" a request received for a less file "' + path + '"');
}
var cacheKey = '/tmp/cached_' + unit + path.replace(/[^\w\.-]/g, '_'); var cacheKey = '/tmp/cached_' + unit + path.replace(/[^\w\.-]/g, '_');
fuseState.currentUnit = unit; fuseState.currentUnit = unit;
var cachedCss = new File(cacheKey); var cachedCss = new File(cacheKey);
@ -221,7 +196,9 @@ var route;
if (lessFile.isExists()) { if (lessFile.isExists()) {
var x = require('less-rhino-1.7.5.js'); var x = require('less-rhino-1.7.5.js');
x.compile([lessFile.getPath(), cacheKey]); x.compile([lessFile.getPath(), cacheKey]);
log.debug('[' + requestId + '] for unit "' + unit + '" request for "' + path + '" is cached as "' + cacheKey + '"'); if (log.isDebugEnabled()) {
log.debug('[' + requestId + '] for unit "' + unit + '" request for "' + path + '" is cached as "' + cacheKey + '"');
}
} }
} }

@ -1,5 +1,4 @@
<% <%
var getPath = File.prototype.getPath; var getPath = File.prototype.getPath;
File.prototype.getPath = function() { File.prototype.getPath = function() {
var path = getPath.call(this); var path = getPath.call(this);
@ -12,8 +11,7 @@ var fuseState = {
zones: {}, zones: {},
appName: '', appName: '',
currentZone: [], //TODO: rename to zone Stack currentZone: [], //TODO: rename to zone Stack
currentUnit: null, currentUnit: null
viewModelCache:{}
}; };
var requestId = function makeId() { var requestId = function makeId() {

@ -15,7 +15,6 @@ var getHbsFile, getFile, toRelativePath, cleanupAncestors,
for (var i = 0; i < definitions.length; i++) { for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i]; var definition = definitions[i];
lookUpTable[definition.name] = i; lookUpTable[definition.name] = i;
//log.info("initLookUp()"+definition.name+"<-"+i);
} }
} }
}; };
@ -46,7 +45,6 @@ var getHbsFile, getFile, toRelativePath, cleanupAncestors,
}; };
var getAncestorModels = function (unit) { var getAncestorModels = function (unit) {
//log.info('[' + requestId + '] getAncestorModels()'+unit);
var unitModel = getUnitDefinition(unit); var unitModel = getUnitDefinition(unit);
var ancestors = [unitModel]; var ancestors = [unitModel];
var parentName; var parentName;
@ -150,12 +148,11 @@ var getHbsFile, getFile, toRelativePath, cleanupAncestors,
}; };
getUnitDefinition = function (unit) { getUnitDefinition = function (unit) {
//log.info('[' + requestId + '] getUnitDefinition()'+unit);
var definitions = getUnitDefinitions(); var definitions = getUnitDefinitions();
initLookUp(definitions); initLookUp(definitions);
//log.info('[' + requestId + '] lookUpTable[unit]:'+unit);
var model = definitions[lookUpTable[unit]]; var model = definitions[lookUpTable[unit]];
if (!model) { if (!model) {
log.warn('[' + requestId + '] unit "' + unit + '" does not exits');
throw '[' + requestId + '] unit "' + unit + '" does not exits'; throw '[' + requestId + '] unit "' + unit + '" does not exits';
} }
return model; return model;
@ -208,7 +205,7 @@ var getHbsFile, getFile, toRelativePath, cleanupAncestors,
var unitDir = unitDirs[i]; var unitDir = unitDirs[i];
if (unitDir.isDirectory()) { if (unitDir.isDirectory()) {
var unitName = unitDir.getName(); var unitName = unitDir.getName();
//log.info("reading: "+unitName + " basePath:'" + basePath + "'"); //log.info("reading: "+unitName + " basePath:"+basePath);
var definitionFile = new File(fuse.getUnitPath(basePath+unitName) + '/' + unitName + '.json'); var definitionFile = new File(fuse.getUnitPath(basePath+unitName) + '/' + unitName + '.json');
if(definitionFile.isExists()) { if(definitionFile.isExists()) {
@ -221,7 +218,9 @@ var getHbsFile, getFile, toRelativePath, cleanupAncestors,
} }
var path = definitionFile.getPath(); var path = definitionFile.getPath();
log.debug('[' + requestId + '] reading file "' + path + '"'); if (log.isDebugEnabled()) {
log.debug('[' + requestId + '] reading file "' + path + '"');
}
unitModel.definition = require(path); unitModel.definition = require(path);
// add the information derived by parsing hbs file to the same model // add the information derived by parsing hbs file to the same model
@ -351,10 +350,12 @@ var getHbsFile, getFile, toRelativePath, cleanupAncestors,
} }
while (len--) { while (len--) {
if (toDelete[units[len]]) { if (toDelete[units[len]]) {
log.debug( if (log.isDebugEnabled()) {
'[' + requestId + '] unit "' + units[len] + log.debug(
'" is overridden by "' + toDelete[units[len]] + '"' '[' + requestId + '] unit "' + units[len] +
); '" is overridden by "' + toDelete[units[len]] + '"'
);
}
units.splice(len, 1); units.splice(len, 1);
} }
} }
@ -384,7 +385,6 @@ var getHbsFile, getFile, toRelativePath, cleanupAncestors,
* @returns {File} * @returns {File}
*/ */
getFile = function (unitName, path, opt_suffix) { getFile = function (unitName, path, opt_suffix) {
//log.info("getFile() unitName:"+unitName+", path:"+path+", opt_suffix:"+opt_suffix);
var slashPath = ((path[0] === '/') ? '' : '/') + path; var slashPath = ((path[0] === '/') ? '' : '/') + path;
var selfFileName = ''; var selfFileName = '';
var fileName = ''; var fileName = '';
@ -403,21 +403,21 @@ var getHbsFile, getFile, toRelativePath, cleanupAncestors,
var unitDef = getUnitDefinition(unitName); var unitDef = getUnitDefinition(unitName);
if (unitDef.path.indexOf('.hbs', unitDef.path.length - 4) !== -1) { if (unitDef.path.indexOf('.hbs', unitDef.path.length - 4) !== -1) {
if (opt_suffix.indexOf('.hbs', opt_suffix.length - 4) !== -1) { if (opt_suffix.indexOf('.hbs', opt_suffix.length - 4) !== -1) {
//log.info("1:"+unitDef.path);
return new File(unitDef.path); return new File(unitDef.path);
} else { } else {
//log.info("2:"+unitDef.path.replace(/.hbs$/, opt_suffix));
return new File(unitDef.path.replace(/.hbs$/, opt_suffix)); return new File(unitDef.path.replace(/.hbs$/, opt_suffix));
} }
} }
var selfFile = new File(getUnitPath(unitName) + slashPath + selfFileName); var selfFile = new File(getUnitPath(unitName) + slashPath + selfFileName);
if (selfFile.isExists()) { if (selfFile.isExists()) {
log.debug( if (log.isDebugEnabled()) {
'[' + requestId + '] for unit "' + unitName + '" file resolved : "' log.debug(
+ slashPath + selfFileName + '" -> "' + selfFile.getPath() + '"' '[' + requestId + '] for unit "' + unitName + '" file resolved : "'
); + slashPath + selfFileName + '" -> "' + selfFile.getPath() + '"'
//log.info("3:"+getUnitPath(unitName) + slashPath + selfFileName); );
}
return selfFile; return selfFile;
} }
@ -433,19 +433,21 @@ var getHbsFile, getFile, toRelativePath, cleanupAncestors,
} }
var file = new File(getUnitPath(ancestorName) + slashPath + fileName); var file = new File(getUnitPath(ancestorName) + slashPath + fileName);
if (file.isExists()) { if (file.isExists()) {
log.debug( if (log.isDebugEnabled()) {
'[' + requestId + '] for unit "' + unitName + '" file resolved : "' log.debug(
+ slashPath + selfFileName + '" -> "' + file.getPath() + '"' '[' + requestId + '] for unit "' + unitName + '" file resolved : "'
); + slashPath + selfFileName + '" -> "' + file.getPath() + '"'
//log.info("4:"+getUnitPath(ancestorName) + slashPath + fileName); );
}
return file; return file;
} }
} }
log.debug( if (log.isDebugEnabled()) {
'[' + requestId + '] for unit "' + unitName + '" (non-excising) file resolved : "' log.debug(
+ slashPath + selfFileName + '" -> "' + selfFile.getPath() + '"' '[' + requestId + '] for unit "' + unitName + '" (non-excising) file resolved : "'
); + slashPath + selfFileName + '" -> "' + selfFile.getPath() + '"'
//log.info("5:"+getUnitPath(unitName) + slashPath + selfFileName); );
}
return selfFile; return selfFile;
}; };

@ -11,35 +11,29 @@ var getScope = function (unit,configs) {
var viewModel = {}; var viewModel = {};
var cbResult; var cbResult;
if (jsFile.isExists()) { if (jsFile.isExists()) {
if(fuseState.viewModelCache[jsFile.getPath()]){ script = require(jsFile.getPath());
cbResult = fuseState.viewModelCache[jsFile.getPath()]; //Eagerly make the viewModel the template configs
}else{ viewModel = templateConfigs;
script = require(jsFile.getPath()); //Check if the unit author has specified an onRequest
//Eagerly make the viewModel the template configs //callback
viewModel = templateConfigs; if(script.hasOwnProperty('onRequest')){
//Check if the unit author has specified an onRequest script.app = {
//callback url: '/' + fuseState.appName,
if(script.hasOwnProperty('onRequest')){ publicURL: '/' + fuseState.appName + '/public/' + unit,
script.app = { "class": unit + '-unit'
url: '/' + fuseState.appName, };
publicURL: '/' + fuseState.appName + '/public/' + unit, onRequestCb = script.onRequest;
"class": unit + '-unit' cbResult = onRequestCb(templateConfigs);
}; log.debug("passing configs to unit "+unit+" configs: "+stringify(templateConfigs));
onRequestCb = script.onRequest; //If the execution does not yield an object we will print
cbResult = onRequestCb(templateConfigs); //a warning as the unit author may have forgotten to return a data object
log.debug("passing configs to unit "+unit+" configs: "+stringify(templateConfigs)); if(cbResult===undefined){
fuseState.viewModelCache[jsFile.getPath()] = cbResult; cbResult = {}; //Give an empty data object
log.warn('[' + requestId + '] unit "' + unit + '" has a onRequest method which does not return a value.This may lead to the '
+'unit not been rendered correctly.');
} }
viewModel = cbResult;
} }
//If the execution does not yield an object we will print
//a warning as the unit author may have forgotten to return a data object
if(cbResult===undefined){
cbResult = {}; //Give an empty data object
log.warn('[' + requestId + '] unit "' + unit + '" has a onRequest method which does not return a value.This may lead to the '
+'unit not been rendered correctly.');
}
viewModel = cbResult;
} }
else{ else{
//If there is no script then the view should get the configurations //If there is no script then the view should get the configurations
@ -62,7 +56,7 @@ Handlebars.innerZonesFromUnit = null;
Handlebars.registerHelper('defineZone', function (zoneName, zoneContent) { Handlebars.registerHelper('defineZone', function (zoneName, zoneContent) {
var result = ''; var result = '';
var zone = Handlebars.Utils.escapeExpression(zoneName); var zone = Handlebars.Utils.escapeExpression(zoneName);
fuseState.zoneStack.push(zone); fuseState.currentZone.push(zone);
var unitsToRender = fuseState.zones[zone] || []; var unitsToRender = fuseState.zones[zone] || [];
if (Handlebars.innerZones.length > 0) { if (Handlebars.innerZones.length > 0) {
@ -98,12 +92,12 @@ Handlebars.registerHelper('defineZone', function (zoneName, zoneContent) {
return result; return result;
} }
fuseState.zoneStack.pop(); fuseState.currentZone.pop();
return new Handlebars.SafeString(result); return new Handlebars.SafeString(result);
}); });
Handlebars.registerHelper('zone', function (zoneName, zoneContent) { Handlebars.registerHelper('zone', function (zoneName, zoneContent) {
var currentZone = fuseState.zoneStack[fuseState.zoneStack.length - 1]; var currentZone = fuseState.currentZone[fuseState.currentZone.length - 1];
if (currentZone == null) { if (currentZone == null) {
return 'zone_' + zoneName + ' '; return 'zone_' + zoneName + ' ';
} }
@ -119,7 +113,7 @@ Handlebars.registerHelper('zone', function (zoneName, zoneContent) {
}); });
Handlebars.registerHelper('layout', function (layoutName) { Handlebars.registerHelper('layout', function (layoutName) {
var currentZone = fuseState.zoneStack[fuseState.zoneStack.length - 1]; var currentZone = fuseState.currentZone[fuseState.currentZone.length - 1];
if (currentZone == null) { if (currentZone == null) {
return 'layout_' + layoutName; return 'layout_' + layoutName;
} else { } else {
@ -128,7 +122,7 @@ Handlebars.registerHelper('layout', function (layoutName) {
}); });
Handlebars.registerHelper('authorized', function () { Handlebars.registerHelper('authorized', function () {
var currentZone = fuseState.zoneStack[fuseState.zoneStack.length - 1]; var currentZone = fuseState.currentZone[fuseState.currentZone.length - 1];
if (currentZone == null) { if (currentZone == null) {
return ''; return '';
} else { } else {
@ -161,11 +155,11 @@ Handlebars.registerHelper('unit', function (unitName,options) {
log.error('unit does not have a main zone'); log.error('unit does not have a main zone');
} }
//TODO warn when unspecified decencies are included. //TODO warn when unspecified decencies are included.
fuseState.zoneStack.push('main'); fuseState.currentZone.push('main');
var template = fuse.getFile(baseUnit, '', '.hbs'); var template = fuse.getFile(baseUnit, '', '.hbs');
log.debug('[' + requestId + '] including "' + baseUnit + '"'+" with configs "+stringify(templateConfigs)); log.debug('[' + requestId + '] including "' + baseUnit + '"'+" with configs "+stringify(templateConfigs));
var result = new Handlebars.SafeString(Handlebars.compileFile(template)(getScope(baseUnit,templateConfigs))); var result = new Handlebars.SafeString(Handlebars.compileFile(template)(getScope(baseUnit,templateConfigs)));
fuseState.zoneStack.pop(); fuseState.currentZone.pop();
return result; return result;
}); });
@ -198,7 +192,6 @@ Handlebars.registerHelper('equal', function(lvalue, rvalue, options) {
return options.fn(this); return options.fn(this);
} }
}); });
Handlebars.registerHelper('unequal', function(lvalue, rvalue, options) { Handlebars.registerHelper('unequal', function(lvalue, rvalue, options) {
if (arguments.length < 3) if (arguments.length < 3)
throw new Error("Handlebars Helper equal needs 2 parameters"); throw new Error("Handlebars Helper equal needs 2 parameters");

@ -10190,7 +10190,7 @@ var compile = function (args) {
var parser = new less.Parser(options); var parser = new less.Parser(options);
parser.parse(input, function (e, root) { parser.parse(input, function (e, root) {
if (e) { if (e) {
log.info(e); log.error(e);
writeError(e, options); writeError(e, options);
quit(1); quit(1);
} else { } else {

@ -0,0 +1,41 @@
/*
* 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.
*/
var apiWrapperUtil = function () {
var module = {};
var tokenUtil = require("/modules/util.js").util;
module.refreshToken = function () {
var tokenPair = session.get("accessTokenPair");
tokenPair = tokenUtil.refreshToken(tokenPair);
session.put("accessTokenPair", tokenPair);
response.addCookie({'name': 'accessToken', 'value': tokenPair.accessToken});
};
module.setupAccessTokenPair = function (type, properties) {
var tokenPair;
var clientId = "pY0FbBUC_GI7mfHVS1FvhWAifEwa";
var clientSecret = "Tu5Za1R3fHtGc5yH4KK8TNiLVSca";
if (type == "password") {
//tokenPair = tokenUtil.getTokenWithPasswordGrantType(properties.username, properties.password, clientId, clientSecret);
} else if (type == "saml") {
}
//session.put("accessTokenPair", tokenPair);
//response.addCookie({'name': 'accessToken', 'value': tokenPair.accessToken});
};
return module;
}();

@ -20,7 +20,7 @@ var WEB_APP_TITLE = "WSO2 DC - Device Cloud";
var WEB_APP_CONTEXT = "/iotserver"; var WEB_APP_CONTEXT = "/iotserver";
var USER_SESSION_KEY = "USER"; var USER_SESSION_KEY = "USER";
var UNSPECIFIED = "Unspecified"; var UNSPECIFIED = "Unspecified";
var DEVICES_UNIT_PATH="/units/devices/"; var DEVICES_UNIT_PATH="/units/";
var DEVICE_IDENTIFIER = "deviceIdentifier"; var DEVICE_IDENTIFIER = "deviceIdentifier";
var DEVICE_NAME = "name"; var DEVICE_NAME = "name";
@ -38,7 +38,7 @@ var FEATURE_DESCRIPTION = "featureDescription";
var PLATFORM_ANDROID = "android"; var PLATFORM_ANDROID = "android";
var PLATFORM_IOS = "ios"; var PLATFORM_IOS = "ios";
var DEVICE_ENROLLMENT = "enrollment"; var DEVICE_ENROLLMENT = "dateOfEnrolment";
var VENDOR_APPLE = "Apple"; var VENDOR_APPLE = "Apple";
var ERRORS = { var ERRORS = {

@ -167,7 +167,7 @@ deviceModule = function () {
var data = {}; var data = {};
//XMLHTTPRequest's GET //XMLHTTPRequest's GET
log.info(removeDeviceEndpoint); //log.info(removeDeviceEndpoint);
return del(removeDeviceEndpoint, data, "text"); return del(removeDeviceEndpoint, data, "text");
}; };
@ -178,8 +178,8 @@ deviceModule = function () {
var data = {}; var data = {};
//XMLHTTPRequest's POST //XMLHTTPRequest's POST
log.info(updateDeviceEndpoint+ "?name="+device.name); //log.info(updateDeviceEndpoint+ "?name="+device.name);
return post(updateDeviceEndpoint+ "?name="+device.name, data, "text"); return post(updateDeviceEndpoint + "?name=" + encodeURIComponent(device.name), data, "text");
}; };
/* /*
@ -257,8 +257,8 @@ deviceModule = function () {
var deviceObject = {}; var deviceObject = {};
deviceObject[constants.DEVICE_IDENTIFIER] = device.getDeviceIdentifier(); deviceObject[constants.DEVICE_IDENTIFIER] = device.getDeviceIdentifier();
deviceObject[constants.DEVICE_NAME] = privateMethods.validateAndReturn(device.getName()); deviceObject[constants.DEVICE_NAME] = privateMethods.validateAndReturn(device.getName());
deviceObject[constants.DEVICE_OWNERSHIP] = privateMethods.validateAndReturn(device.getOwnership()); deviceObject[constants.DEVICE_OWNERSHIP] = privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
deviceObject[constants.DEVICE_OWNER] = device.getOwner(); deviceObject[constants.DEVICE_OWNER] = device.getEnrolmentInfo().getOwner();
deviceObject[constants.DEVICE_TYPE] = device.getType(); deviceObject[constants.DEVICE_TYPE] = device.getType();
if (device.getType() == constants.PLATFORM_IOS) { if (device.getType() == constants.PLATFORM_IOS) {
properties[constants.DEVICE_MODEL] = properties[constants.DEVICE_PRODUCT]; properties[constants.DEVICE_MODEL] = properties[constants.DEVICE_PRODUCT];
@ -266,7 +266,7 @@ deviceModule = function () {
properties[constants.DEVICE_VENDOR] = constants.VENDOR_APPLE; properties[constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
} }
deviceObject[constants.DEVICE_PROPERTIES] = properties; deviceObject[constants.DEVICE_PROPERTIES] = properties;
deviceObject[constants.DEVICE_ENROLLMENT] = device.getDateOfEnrolment(); deviceObject[constants.DEVICE_ENROLLMENT] = device.getEnrolmentInfo().getDateOfEnrolment();
return deviceObject; return deviceObject;
} }
}; };

@ -0,0 +1,85 @@
/*
* 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.
*/
var policyModule;
policyModule = function () {
var log = new Log("modules/policy.js");
var constants = require("/modules/constants.js");
var utility = require("/modules/utility.js").utility;
var userManagementService = utility.getUserManagementService();
var publicMethods = {};
var privateMethods = {};
publicMethods.getPolicies = function () {
//TODO-This method returns includes dummy policy data
var policies = [];
var policyObj = {
"id":1, // Identifier of the policy.
"priorityId":1, // Priority of the policies. This will be used only for simple evaluation.
"profile":{}, // Profile
"policyName":"Turn off light", // Name of the policy.
"generic":true, // If true, this should be applied to all related device.
"roles":{}, // Roles which this policy should be applied.
"ownershipType":{}, // Ownership type (COPE, BYOD, CPE)
"devices":{}, // Individual devices this policy should be applied
"users":{}, // Individual users this policy should be applied
"Compliance":{},
"policyCriterias":{},
"startTime":283468236, // Start time to apply the policy.
"endTime":283468236, // After this time policy will not be applied
"startDate":"", // Start date to apply the policy
"endDate":"", // After this date policy will not be applied.
"tenantId":-1234,
"profileId":1
};
policies.push(policyObj);
policyObj = {
"id":2, // Identifier of the policy.
"priorityId":1, // Priority of the policies. This will be used only for simple evaluation.
"profile":{}, // Profile
"policyName":"Turn on Buzzer", // Name of the policy.
"generic":false, // If true, this should be applied to all related device.
"roles":{}, // Roles which this policy should be applied.
"ownershipType":{}, // Ownership type (COPE, BYOD, CPE)
"devices":{}, // Individual devices this policy should be applied
"users":{}, // Individual users this policy should be applied
"Compliance":{},
"policyCriterias":{},
"startTime":283468236, // Start time to apply the policy.
"endTime":283468236, // After this time policy will not be applied
"startDate":"", // Start date to apply the policy
"endDate":"", // After this date policy will not be applied.
"tenantId":-1234,
"profileId":2
};
policies.push(policyObj);
return policies;
};
return publicMethods;
}();

@ -252,7 +252,9 @@ userModule = function () {
log.error("User object was not found in the session"); log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND; throw constants.ERRORS.USER_NOT_FOUND;
} }
var userList = userManagementService.getUsersForTenant(carbonUser.tenantId); var userList = userManagementService.getUsersForTenant(carbonUser.tenantId);
var i, userObject; var i, userObject;
for (i = 0; i < userList.size(); i++) { for (i = 0; i < userList.size(); i++) {
userObject = userList.get(i); userObject = userList.get(i);
@ -308,6 +310,34 @@ userModule = function () {
return permissions; return permissions;
}; };
/**
* Get User Roles from user store.
* If "Internal/Everyone" role is required - true param needs to be passed.
* @param enableInternalEveryone boolean value true/false to enable Internal/Everyone role
*/
publicMethods.getRoles = function (enableInternalEveryone) {
var carbonModule = require("carbon");
var carbonServer = application.get("carbonServer");
var carbonUser = session.get(constants.USER_SESSION_KEY);
if (!carbonUser) {
log.error("User object was not found in the session");
throw constants.ERRORS.USER_NOT_FOUND;
}
var userManager = new carbonModule.user.UserManager(carbonServer, carbonUser.tenantId);
var allRoles = userManager.allRoles();
var filteredRoles = [];
var i;
for (i = 0; i < allRoles.length; i++) {
if (enableInternalEveryone && allRoles[i] == "Internal/everyone") {
filteredRoles.push(allRoles[i]);
}
if (allRoles[i].indexOf("Internal/") != 0) {
filteredRoles.push(allRoles[i]);
}
}
return filteredRoles;
};
publicMethods.logout = function (successCallback) { publicMethods.logout = function (successCallback) {
session.invalidate(); session.invalidate();
successCallback(); successCallback();

@ -0,0 +1,89 @@
/*
* 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.
*/
var util = function () {
var module = {};
var Base64 = Packages.org.apache.commons.codec.binary.Base64;
var String = Packages.java.lang.String;
var log = new Log();
/**
* Encode the payload in Base64
* @param payload
* @returns {Packages.java.lang.String}
*/
function encode(payload){
return new String(Base64.encodeBase64(new String(payload).getBytes()));
}
/**
* Get an AccessToken pair based on username and password
* @param username
* @param password
* @param clientId
* @param clientSecret
* @param scope
* @returns {{accessToken: "", refreshToken: ""}}
*/
module.getTokenWithPasswordGrantType = function (username, password, clientId, clientSecret, scope) {
var xhr = new XMLHttpRequest();
var tokenEndpoint = "https://localhost:9443/oauth2/token";
var encodedClientKeys = encode(clientId + ":" + clientSecret);
xhr.open("POST", tokenEndpoint, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientKeys);
xhr.send("grant_type=password&username=" + username + "&password=" + password + "&scope=" + scope);
delete password, delete clientSecret, delete encodedClientKeys;
var tokenPair = {};
if (xhr.status == 200) {
var data = parse(xhr.responseText);
tokenPair.refreshToken = data.refresh_token;
tokenPair.accessToken = data.access_token;
} else if (xhr.status == 403) {
throw "Error in obtaining token with Password Grant Type";
} else {
throw "Error in obtaining token with Password Grant Type";
}
return tokenPair;
};
module.getTokenWithSAMLGrantType = function () {
};
module.refreshToken = function(tokenPair){
var xhr = new XMLHttpRequest();
var tokenEndpoint = "https://localhost:9443/oauth2/token";
var encodedClientKeys = encode(clientId + ":" + clientSecret);
xhr.open("POST", tokenEndpoint, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic " + encodedClientKeys);
xhr.send("grant_type=refresh_token&refresh_token=" + tokenPair.refreshToken + "&scope=" + scope);
delete password, delete clientSecret, delete encodedClientKeys;
var tokenPair = {};
if (xhr.status == 200) {
var data = parse(xhr.responseText);
tokenPair.refreshToken = data.refresh_token;
tokenPair.accessToken = data.access_token;
} else if (xhr.status == 403) {
throw "Error in obtaining token with Password Grant Type";
} else {
throw "Error in obtaining token with Password Grant Type";
}
return tokenPair;
};
return module;
}();

@ -41,22 +41,52 @@ utility = function () {
publicMethods.insertAppPermissions = function (userModule, type) { publicMethods.insertAppPermissions = function (userModule, type) {
userModule.addPermissions([{key: "device-mgt", name: "Device Management"}], "", type); userModule.addPermissions([{key: "device-mgt", name: "Device Management"}], "", type);
userModule.addPermissions([{key: "admin", name: "Device Management Admin"}], "device-mgt", type); userModule.addPermissions([{
userModule.addPermissions([{key: "user", name: "Device Management User"}], "device-mgt", type); key: "admin",
name: "Device Management Admin"
}], "device-mgt", type);
userModule.addPermissions([{
key: "user",
name: "Device Management User"
}], "device-mgt", type);
userModule.addPermissions([{key: "devices", name: "Devices"}], "device-mgt/admin", type); userModule.addPermissions([{key: "devices", name: "Devices"}], "device-mgt/admin", type);
userModule.addPermissions([{key: "devices/list", name: "List Devices"}], "device-mgt/admin", type); userModule.addPermissions([{
userModule.addPermissions([{key: "devices/operation", name: "Perform Operation"}], "device-mgt/admin", type); key: "devices/list",
name: "List Devices"
}], "device-mgt/admin", type);
userModule.addPermissions([{
key: "devices/operation",
name: "Perform Operation"
}], "device-mgt/admin", type);
userModule.addPermissions([{key: "users", name: "Users"}], "device-mgt/admin", type); userModule.addPermissions([{key: "users", name: "Users"}], "device-mgt/admin", type);
userModule.addPermissions([{key: "users/add", name: "Add New Users"}], "device-mgt/admin", type); userModule.addPermissions([{
userModule.addPermissions([{key: "users/invite", name: "Invite Users"}], "device-mgt/admin", type); key: "users/add",
userModule.addPermissions([{key: "users/list", name: "List Users"}], "device-mgt/admin", type); name: "Add New Users"
userModule.addPermissions([{key: "users/remove", name: "Remove Users"}], "device-mgt/admin", type); }], "device-mgt/admin", type);
userModule.addPermissions([{
key: "users/invite",
name: "Invite Users"
}], "device-mgt/admin", type);
userModule.addPermissions([{
key: "users/list",
name: "List Users"
}], "device-mgt/admin", type);
userModule.addPermissions([{
key: "users/remove",
name: "Remove Users"
}], "device-mgt/admin", type);
userModule.addPermissions([{key: "devices", name: "Devices"}], "device-mgt/user", type); userModule.addPermissions([{key: "devices", name: "Devices"}], "device-mgt/user", type);
userModule.addPermissions([{key: "devices/list", name: "List Devices"}], "device-mgt/user", type); userModule.addPermissions([{
userModule.addPermissions([{key: "devices/operation", name: "Perform Operation"}], "device-mgt/user", "init"); key: "devices/list",
name: "List Devices"
}], "device-mgt/user", type);
userModule.addPermissions([{
key: "devices/operation",
name: "Perform Operation"
}], "device-mgt/user", "init");
}; };
return publicMethods; return publicMethods;

@ -1,3 +1,4 @@
{{authorized}}
{{layout "fluid"}} {{layout "fluid"}}
{{#zone "title"}} {{#zone "title"}}
WSO2 DC | Device Cloud WSO2 DC | Device Cloud

@ -4,5 +4,5 @@
{{/zone}} {{/zone}}
{{#zone "body"}} {{#zone "body"}}
{{unit "appbar" link="store" title="STORE"}} {{unit "appbar" link="store" title="STORE"}}
{{unit "devices/android"}} {{unit "android"}}
{{/zone}} {{/zone}}

@ -4,5 +4,5 @@
{{/zone}} {{/zone}}
{{#zone "body"}} {{#zone "body"}}
{{unit "appbar" link="store" title="STORE"}} {{unit "appbar" link="store" title="STORE"}}
{{unit "devices/android_sense"}} {{unit "android_sense"}}
{{/zone}} {{/zone}}

@ -4,5 +4,5 @@
{{/zone}} {{/zone}}
{{#zone "body"}} {{#zone "body"}}
{{unit "appbar" link="store" title="STORE"}} {{unit "appbar" link="store" title="STORE"}}
{{unit "devices/arduino"}} {{unit "arduino"}}
{{/zone}} {{/zone}}

@ -4,5 +4,5 @@
{{/zone}} {{/zone}}
{{#zone "body"}} {{#zone "body"}}
{{unit "appbar" link="store" title="STORE"}} {{unit "appbar" link="store" title="STORE"}}
{{unit "devices/digital_display"}} {{unit "digital_display"}}
{{/zone}} {{/zone}}

@ -4,5 +4,5 @@
{{/zone}} {{/zone}}
{{#zone "body"}} {{#zone "body"}}
{{unit "appbar" link="store" title="STORE"}} {{unit "appbar" link="store" title="STORE"}}
{{unit "devices/firealarm"}} {{unit "firealarm"}}
{{/zone}} {{/zone}}

@ -4,7 +4,7 @@
Devices Devices
{{/zone}} {{/zone}}
{{#zone "body"}} {{#zone "body"}}
{{unit "appbar" link="device-mgt" title="Device Management"}} {{unit "appbar" link="device-mgt" title="My Devices"}}
{{unit "extended-search-box"}} {{unit "extended-search-box"}}
{{unit "operation-mod"}} {{unit "operation-mod"}}
<div class="wr-device-list row"> <div class="wr-device-list row">

@ -4,5 +4,5 @@
{{/zone}} {{/zone}}
{{#zone "body"}} {{#zone "body"}}
{{unit "appbar" link="store" title="STORE"}} {{unit "appbar" link="store" title="STORE"}}
{{unit "devices/raspberrypi"}} {{unit "raspberrypi"}}
{{/zone}} {{/zone}}

@ -4,5 +4,5 @@
{{/zone}} {{/zone}}
{{#zone "body"}} {{#zone "body"}}
{{unit "appbar" link="store" title="STORE"}} {{unit "appbar" link="store" title="STORE"}}
{{unit "devices/sensebot"}} {{unit "sensebot"}}
{{/zone}} {{/zone}}

@ -4,5 +4,5 @@
{{/zone}} {{/zone}}
{{#zone "body"}} {{#zone "body"}}
{{unit "appbar" link="store" title="STORE"}} {{unit "appbar" link="store" title="STORE"}}
{{unit "devices/windows"}} {{unit "windows"}}
{{/zone}} {{/zone}}

@ -0,0 +1,9 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
WSO2 DC | Add New Policy
{{/zone}}
{{#zone "body"}}
{{unit "appbar" link="policies" title="My Policies"}}
{{unit "policy-create"}}
{{/zone}}

@ -0,0 +1,21 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
Policies
{{/zone}}
{{#zone "body"}}
{{unit "appbar" link="policies" title="My Policies"}}
{{unit "extended-search-box"}}
<div class="wr-device-list row">
<div class="wr-hidden-operations wr-advance-operations">
</div>
<div class="col-md-12 wr-page-content">
<!-- content -->
<div>
{{unit "policy-listing"}}
</div>
<!-- /content -->
</div>
</div>
{{/zone}}

@ -0,0 +1,12 @@
<%
var userModule = require("/modules/user.js").userModule;
userModule.addPermissions([{key: "device-mgt/", name: "Device Management"}], "");
userModule.addPermissions([{key: "device-mgt/admin", name: "Device Management Admin"}], "");
userModule.addPermissions([{key: "device-mgt/user", name: "Device Management User"}], "");
userModule.addPermissions([{key: "devices", name: "Device"}], "device-mgt/admin");
userModule.addPermissions([{key: "devices", name: "Device"}], "device-mgt/user");
userModule.addPermissions([{key: "devices/list", name: "List all Devices"}], "device-mgt/admin");
userModule.addPermissions([{key: "devices/list", name: "List own Devices"}], "device-mgt/user");
new Log().info(userModule.isAuthorized("/permission/device-mgt/admin/devices/list"));
%>

@ -0,0 +1,100 @@
/*
* 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.
*/
describe('Device Module', function () {
var log = new Log();
var mobileDB;
var cdmDB;
var deviceModule = require("/modules/device.js").deviceModule;
function tearUp() {
mobileDB = new Database("MobileDM_DS");
cdmDB = new Database("DM_DS");
cdmDB.query("insert into dm_device(description, name, date_of_enrollment, date_of_last_update, " +
"ownership,status, device_type_id, device_identification, owner, tenant_id ) " +
"values ('Galaxy Tab','Admin Samsung', 1425467382, 1425467382, 'BYOD', 'ACTIVE'," +
" 1,'4892813d-0b18-4a02-b7b1-61775257488e', 'admin@wso2.com', '-1234');");
cdmDB.query("insert into dm_device(description, name, date_of_enrollment, date_of_last_update, " +
"ownership,status, device_type_id, device_identification, owner, tenant_id ) " +
"values ('Galaxy Tab','Admin Samsung', 1425467382, 1425467382, 'BYOD', 'ACTIVE'," +
" 1,'4892813d-0b18-4a02-b7b1-61775257488F', 'mdm@wso2.com', '-1234');");
mobileDB.query("insert into mbl_device (mobile_device_id, push_token, imei ,imsi, os_version, " +
"device_model , vendor ,latitude ,longitude , challenge ,token, unlock_token ,serial ) " +
"values ('4892813d-0b18-4a02-b7b1-61775257488e', 'sdfsdf', 'cxv', 'vbcb', '4.1', " +
"'Galaxy Tab', 'Samsung', '234234234', '4345345234234', 'dfjsdlfk', 'wuweir234', " +
"'ksdfjlskfjwer', '234234');");
mobileDB.query("insert into mbl_device (mobile_device_id, push_token, imei ,imsi, os_version, " +
"device_model , vendor ,latitude ,longitude , challenge ,token, unlock_token ,serial ) " +
"values ('4892813d-0b18-4a02-b7b1-61775257488F', 'sdfsdf', 'cxv', 'vbcb', '4.1', " +
"'Galaxy Tab', 'Samsung', '234234234', '4345345234234', 'dfjsdlfk', 'wuweir234', " +
"'ksdfjlskfjwer', '234234');");
}
function tearDown() {
deleteData();
mobileDB.close();
cdmDB.close();
}
function deleteData(){
cdmDB.query("delete from dm_device where device_identification='4892813d-0b18-4a02-b7b1-61775257488e'");
cdmDB.query("delete from dm_device where device_identification='4892813d-0b18-4a02-b7b1-61775257488F'");
mobileDB.query("delete from mbl_device where mobile_device_id='4892813d-0b18-4a02-b7b1-61775257488e'");
mobileDB.query("delete from mbl_device where mobile_device_id='4892813d-0b18-4a02-b7b1-61775257488F'");
}
it('List all Devices - Device Module', function () {
try {
tearUp();
var results = deviceModule.listDevices();
expect(results.length).not.toBe(0);
} catch (e) {
log.error(e);
throw e;
} finally {
tearDown();
}
});
it('List Devices for User - Device Module', function () {
try {
tearUp();
var results = deviceModule.listDevicesForUser("mdm@wso2.com");
expect(results.length).toBe(1);
} catch (e) {
log.error(e);
throw e;
} finally {
tearDown();
}
});
it('Perform operation on the device', function(){
try {
tearUp();
var devices = [{"id": "4892813d-0b18-4a02-b7b1-61775257488e", "type": "android"}];
var operation = {"featureName": "DEVICE_LOCK", "type": "COMMAND", "properties": {"enabled": true}}
var results = deviceModule.performOperation(devices, operation);
expect(results.length).toBe(1);
} catch (e) {
log.error(e);
throw e;
} finally {
tearDown();
}
});
});

@ -0,0 +1,88 @@
/*
* 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.
*/
describe('Device Module', function () {
var log = new Log();
var mobileDB;
var cdmDB;
var deviceModule = require("/modules/device.js").deviceModule;
var userModule = require("/modules/user.js").userModule;
var constants = require("/modules/constants.js");
function tearUp() {
mobileDB = new Database("MobileDM_DS");
cdmDB = new Database("DM_DS");
cdmDB.query("insert into dm_device(description, name, date_of_enrollment, date_of_last_update, " +
"ownership,status, device_type_id, device_identification, owner, tenant_id ) " +
"values ('Galaxy Tab','Admin Samsung', 1425467382, 1425467382, 'BYOD', 'ACTIVE'," +
" 1,'4892813d-0b18-4a02-b7b1-61775257488e', 'admin@wso2.com', '-1234');");
cdmDB.query("insert into dm_device(description, name, date_of_enrollment, date_of_last_update, " +
"ownership,status, device_type_id, device_identification, owner, tenant_id ) " +
"values ('Galaxy Tab','Admin Samsung', 1425467382, 1425467382, 'BYOD', 'ACTIVE'," +
" 1,'4892813d-0b18-4a02-b7b1-61775257488F', 'mdm@wso2.com', '-1234');");
mobileDB.query("insert into mbl_device (mobile_device_id, push_token, imei ,imsi, os_version, " +
"device_model , vendor ,latitude ,longitude , challenge ,token, unlock_token ,serial ) " +
"values ('4892813d-0b18-4a02-b7b1-61775257488e', 'sdfsdf', 'cxv', 'vbcb', '4.1', " +
"'Galaxy Tab', 'Samsung', '234234234', '4345345234234', 'dfjsdlfk', 'wuweir234', " +
"'ksdfjlskfjwer', '234234');");
mobileDB.query("insert into mbl_device (mobile_device_id, push_token, imei ,imsi, os_version, " +
"device_model , vendor ,latitude ,longitude , challenge ,token, unlock_token ,serial ) " +
"values ('4892813d-0b18-4a02-b7b1-61775257488F', 'sdfsdf', 'cxv', 'vbcb', '4.1', " +
"'Galaxy Tab', 'Samsung', '234234234', '4345345234234', 'dfjsdlfk', 'wuweir234', " +
"'ksdfjlskfjwer', '234234');");
session.put(constants.USER_SESSION_KEY, {"username" : "admin", "domain": "carbon.super", "tenantId": "-1234"});
}
function tearDown() {
deleteData();
mobileDB.close();
cdmDB.close();
session.put(constants.USER_SESSION_KEY, null);
}
function deleteData(){
cdmDB.query("delete from dm_device where device_identification='4892813d-0b18-4a02-b7b1-61775257488e'");
cdmDB.query("delete from dm_device where device_identification='4892813d-0b18-4a02-b7b1-61775257488F'");
mobileDB.query("delete from mbl_device where mobile_device_id='4892813d-0b18-4a02-b7b1-61775257488e'");
mobileDB.query("delete from mbl_device where mobile_device_id='4892813d-0b18-4a02-b7b1-61775257488F'");
}
it('List all users', function () {
try {
tearUp();
var results = userModule.getUsers();
expect(results.length).not.toBe(0);
} catch (e) {
log.error(e);
throw e;
} finally {
tearDown();
}
});
it('Check permission for user', function () {
try {
tearUp();
expect(userModule.isAuthorized("/permission/device-mgt/user/devices/list")).toBe(true);
} catch (e) {
log.error(e);
throw e;
} finally {
tearDown();
}
});
});

@ -0,0 +1,4 @@
<%
var apiWrapperUtil = require("/modules/api-wrapper-util.js").apiWrapperUtil;
apiWrapperUtil.refreshToken();
%>

@ -48,6 +48,8 @@
</div> </div>
<div id="div-bulbData"> <div id="div-bulbData">
</div> </div>
<div id="div-cpuTemperatureData">
</div>
<div id="div-CPUData"> <div id="div-CPUData">
</div> </div>
<div id="div-RAMData"> <div id="div-RAMData">
@ -70,4 +72,5 @@
<script src="{{self.publicURL}}/js/graphs/sonar_graph.js"></script> <script src="{{self.publicURL}}/js/graphs/sonar_graph.js"></script>
<script src="{{self.publicURL}}/js/graphs/cpu_graph.js"></script> <script src="{{self.publicURL}}/js/graphs/cpu_graph.js"></script>
<script src="{{self.publicURL}}/js/graphs/ram_graph.js"></script> <script src="{{self.publicURL}}/js/graphs/ram_graph.js"></script>
<script src="{{self.publicURL}}/js/graphs/cpu_temperature_graph.js"></script>
{{/zone}} {{/zone}}

@ -1,6 +1,10 @@
var fromDate; var fromDate;
var toDate; var toDate;
var currentDay = new Date();
var startDate = new Date(currentDay.getTime() - (60 * 60 * 24 * 100));
var endDate = new Date(currentDay.getTime());
// create a custom bar renderer that has no gaps // create a custom bar renderer that has no gaps
Rickshaw.Graph.Renderer.BarNoGap = Rickshaw.Class.create(Rickshaw.Graph.Renderer.Bar, { Rickshaw.Graph.Renderer.BarNoGap = Rickshaw.Class.create(Rickshaw.Graph.Renderer.Bar, {
name: 'bar_no_gap', name: 'bar_no_gap',
@ -11,10 +15,11 @@ Rickshaw.Graph.Renderer.BarNoGap = Rickshaw.Class.create(Rickshaw.Graph.Renderer
} }
}); });
function initDate(){
var currentDay = new Date(); currentDay = new Date();
var startDate = new Date(currentDay.getTime() - (60 * 60 * 24 * 100)); startDate = new Date(currentDay.getTime() - (60 * 60 * 24 * 100));
var endDate = new Date(currentDay.getTime()); endDate = new Date(currentDay.getTime());
}
var configObject = { var configObject = {
startOfWeek: 'monday', startOfWeek: 'monday',
@ -38,6 +43,7 @@ var configObject = {
var DateRange = convertDate(startDate) + " " + configObject.separator + " " + convertDate(endDate); var DateRange = convertDate(startDate) + " " + configObject.separator + " " + convertDate(endDate);
$(document).ready(function () { $(document).ready(function () {
initDate();
$('#date-range').dateRangePicker(configObject) $('#date-range').dateRangePicker(configObject)
.bind('datepicker-apply', function (event, dateRange) { .bind('datepicker-apply', function (event, dateRange) {
$(this).addClass('active'); $(this).addClass('active');
@ -61,21 +67,25 @@ $(document).ready(function () {
//day picker //day picker
$('#today-btn').on('click', function () { $('#today-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - 86400000, currentDay.getTime()); getDateTime(currentDay.getTime() - 86400000, currentDay.getTime());
}); });
//hour picker //hour picker
$('#hour-btn').on('click', function () { $('#hour-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - 3600000, currentDay.getTime()); getDateTime(currentDay.getTime() - 3600000, currentDay.getTime());
}) });
//week picker //week picker
$('#week-btn').on('click', function () { $('#week-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - 604800000, currentDay.getTime()); getDateTime(currentDay.getTime() - 604800000, currentDay.getTime());
}) });
//month picker //month picker
$('#month-btn').on('click', function () { $('#month-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - (604800000 * 4), currentDay.getTime()); getDateTime(currentDay.getTime() - (604800000 * 4), currentDay.getTime());
}); });
@ -148,69 +158,77 @@ function updateGraphs(stats) {
console.log(stats); console.log(stats);
var temperatureData = stats['temperatureData']; var temperatureData = stats['temperatureData'];
if (typeof temperatureData != 'undefined'){ if (typeof temperatureData != 'undefined') {
$('#div-temperatureData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Temperature</h2><hr><div id='canvas-wrapper1'></div></div><hr></div>"); $('#div-temperatureData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Temperature</h2><hr><div id='canvas-wrapper1'></div></div><hr></div>");
updateTemperatureGraph(convertStatsToGraphData(temperatureData)); updateTemperatureGraph(convertStatsToGraphData(temperatureData));
}else{ } else {
$('#div-temperatureData').html(""); $('#div-temperatureData').html("");
} }
var lightData = stats['lightData']; var lightData = stats['lightData'];
if (typeof lightData != 'undefined'){ if (typeof lightData != 'undefined') {
$('#div-lightData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Light</h2><hr><div id='canvas-wrapper2'></div></div><hr></div>"); $('#div-lightData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Light</h2><hr><div id='canvas-wrapper2'></div></div><hr></div>");
updateLightGraph(convertStatsToGraphData(lightData)); updateLightGraph(convertStatsToGraphData(lightData));
}else{ } else {
$('#div-lightData').html(""); $('#div-lightData').html("");
} }
var motionData = stats['motionData']; var motionData = stats['motionData'];
if (typeof motionData != 'undefined'){ if (typeof motionData != 'undefined') {
$('#div-motionData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Motion</h2><hr><div id='canvas-wrapper3'></div></div><hr></div>"); $('#div-motionData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Motion</h2><hr><div id='canvas-wrapper3'></div></div><hr></div>");
updateMotionGraph(convertStatsToGraphData(motionData)); updateMotionGraph(convertStatsToGraphData(motionData));
}else{ } else {
$('#div-motionData').html(""); $('#div-motionData').html("");
} }
var sonarData = stats['sonarData']; var sonarData = stats['sonarData'];
if (typeof sonarData != 'undefined'){ if (typeof sonarData != 'undefined') {
$('#div-sonarData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Sonar</h2><hr><div id='canvas-wrapper4'></div></div><hr></div>"); $('#div-sonarData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Sonar</h2><hr><div id='canvas-wrapper4'></div></div><hr></div>");
updateSonarGraph(convertStatsToGraphData(sonarData)); updateSonarGraph(convertStatsToGraphData(sonarData));
}else{ } else {
$('#div-sonarData').html(""); $('#div-sonarData').html("");
} }
var fanData = stats['fanData']; var fanData = stats['fanData'];
if (typeof fanData != 'undefined'){ if (typeof fanData != 'undefined') {
$('#div-fanData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Fan Status</h2><hr><div id='canvas-wrapper5'></div></div><hr></div>"); $('#div-fanData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Fan Status</h2><hr><div id='canvas-wrapper5'></div></div><hr></div>");
updateFanGraph(convertStateStatsToGraphData(fanData)); updateFanGraph(convertStateStatsToGraphData(fanData));
}else{ } else {
$('#div-fanData').html(""); $('#div-fanData').html("");
} }
var bulbData = stats['bulbData']; var bulbData = stats['bulbData'];
if (typeof bulbData != 'undefined'){ if (typeof bulbData != 'undefined') {
$('#div-bulbData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Bulb Status</h2><hr><div id='canvas-wrapper6'></div></div><hr></div>"); $('#div-bulbData').html("").html("<div class='row margin-double'><div><h2 class='grey'>Bulb Status</h2><hr><div id='canvas-wrapper6'></div></div><hr></div>");
updateBulbGraph(convertStateStatsToGraphData(bulbData)); updateBulbGraph(convertStateStatsToGraphData(bulbData));
}else{ } else {
$('#div-bulbData').html(""); $('#div-bulbData').html("");
} }
var cpuData = stats['cpuData']; var cpuData = stats['cpuData'];
if (typeof cpuData != 'undefined'){ if (typeof cpuData != 'undefined') {
$('#div-CPUData').html("").html("<div class='row margin-double'><div><h2 class='grey'>CPU Load</h2><hr><div id='canvas-wrapper7'></div></div><hr></div>"); $('#div-CPUData').html("").html("<div class='row margin-double'><div><h2 class='grey'>CPU Load</h2><hr><div id='canvas-wrapper7'></div></div><hr></div>");
updateCPUGraph(convertStateStatsToGraphData(cpuData)); updateCPUGraph(convertStateStatsToGraphData(cpuData));
}else{ } else {
$('#div-CPUData').html(""); $('#div-CPUData').html("");
} }
var ramData = stats['ramData']; var ramData = stats['ramData'];
if (typeof ramData != 'undefined'){ if (typeof ramData != 'undefined') {
$('#div-RAMData').html("").html("<div class='row margin-double'><div><h2 class='grey'>RAM Usage</h2><hr><div id='canvas-wrapper8'></div></div><hr></div>"); $('#div-RAMData').html("").html("<div class='row margin-double'><div><h2 class='grey'>RAM Usage</h2><hr><div id='canvas-wrapper8'></div></div><hr></div>");
updateRAMGraph(convertStateStatsToGraphData(ramData)); updateRAMGraph(convertStateStatsToGraphData(ramData));
}else{ } else {
$('#div-RAMData').html(""); $('#div-RAMData').html("");
} }
var cpuTemperatureData = stats['cpuTemperatureData'];
if (typeof cpuTemperatureData != 'undefined') {
$('#div-cpuTemperatureData').html("").html("<div class='row margin-double'><div><h2 class='grey'>CPU Temperature</h2><hr><div id='canvas-wrapper9'></div></div><hr></div>");
updateCPUTemperatureGraph(convertStatsToGraphData(cpuTemperatureData));
} else {
$('#div-cpuTemperatureData').html("");
}
scaleGraphs(); scaleGraphs();
} }
@ -219,8 +237,18 @@ function scaleGraphs() {
if (sliders.length == 0) { if (sliders.length == 0) {
return; return;
} }
var graphWidth = 0;
for (var i = 1; i < 10; i++){
if ($('#canvas-wrapper' + i).length){
graphWidth = $('#canvas-wrapper' + i).width() - 50;
break;
}
}
if (graphWidth <= 0){
return;
}
var graphWidth = $('#canvas-wrapper1').width() - 50;
//Scale graphs //Scale graphs
var sliderX = graphWidth * 60 * 60 / (toDate - fromDate); var sliderX = graphWidth * 60 * 60 / (toDate - fromDate);
if (sliderX < graphWidth) { if (sliderX < graphWidth) {
@ -283,9 +311,9 @@ function convertStateStatsToGraphData(stats) {
function convertDate(date) { function convertDate(date) {
var month = date.getMonth() + 1; var month = date.getMonth() + 1;
var day = date.getDate(); var day = date.getDate();
var hour=date.getHours(); var hour = date.getHours();
var minute=date.getMinutes(); var minute = date.getMinutes();
return date.getFullYear() + '-' + (('' + month).length < 2 ? '0' : '') return date.getFullYear() + '-' + (('' + month).length < 2 ? '0' : '')
+ month + '-' + (('' + day).length < 2 ? '0' : '') + day +" "+ (('' + hour).length < 2 ? '0' : '') + month + '-' + (('' + day).length < 2 ? '0' : '') + day + " " + (('' + hour).length < 2 ? '0' : '')
+ hour +":"+(('' + minute).length < 2 ? '0' : '')+ minute; + hour + ":" + (('' + minute).length < 2 ? '0' : '') + minute;
} }

@ -0,0 +1,70 @@
function updateCPUTemperatureGraph(temperatureData) {
console.log("cpuTemperatureData");
renderCPUTemperatureChart(temperatureData);
}
function renderCPUTemperatureChart(chartDataRaw) {
var chartWrapperElmId = "#canvas-wrapper9";
var graphWidth = $(chartWrapperElmId).width() - 50;
if (chartDataRaw.length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
}
var chartData = [];
for (var i = 0; i < chartDataRaw.length; i++) {
chartData.push({x: parseInt(chartDataRaw[i].x), y: parseInt(chartDataRaw[i].y)});
}
//var i = parseInt(fromDate);
//while (i < parseInt(toDate)){
// var rnd = Math.random() * (30 - 20) + 20;
// chartData.push({x:i * 1000, y:rnd});
// i += 60 * 5;
//}
var chartDiv = "chart9";
var sliderDiv = "slider9";
var x_axis = "x_axis9";
var y_axis = "y_axis9";
$(chartWrapperElmId).html("").html('<div id="' + y_axis + '" class="custom_y_axis"></div><div id="' + chartDiv + '" class="custom_rickshaw_graph"></div><div id="' + x_axis + '" class="custom_x_axis"></div><div id="' + sliderDiv + '" class="custom_slider"></div>');
var graph = new Rickshaw.Graph({
element: document.getElementById(chartDiv),
width: graphWidth,
height: 400,
strokeWidth: 1,
renderer: 'line',
xScale: d3.time.scale(),
padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0},
series: [
{color: '#FF4000', data: chartData}
]
});
graph.render();
var xAxis = new Rickshaw.Graph.Axis.X({
graph: graph,
orientation: 'bottom',
element: document.getElementById(x_axis),
tickFormat: graph.x.tickFormat()
});
xAxis.render();
var yAxis = new Rickshaw.Graph.Axis.Y({
graph: graph,
orientation: 'left',
element: document.getElementById(y_axis),
width: 40,
height: 410
});
yAxis.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: graph,
element: document.getElementById(sliderDiv)
});
}

@ -0,0 +1,4 @@
function onRequest(context){
context.sketchPath = "api/device/sketch/download";
return context;
}

@ -0,0 +1,4 @@
function onRequest(context){
context.sketchPath = "api/device/sketch/download";
return context;
}

@ -41,11 +41,11 @@
<!-- common navigation --> <!-- common navigation -->
<div id="hiddenNav" class="wr-hidden-nav"> <div id="hiddenNav" class="wr-hidden-nav">
<ul> <ul>
<li><a href="/iotserver/devices"><i class="fw fw-mobile"></i>Device Management</a></li> <li><a href="/iotserver/devices"><i class="fw fw-mobile"></i>My Devices</a></li>
{{#if permissions.ADD_USER}} {{#if permissions.ADD_USER}}
<li><a href="/iotserver/users"><i class="fw fw-user"></i>User Management</a></li> <li><a href="/iotserver/users"><i class="fw fw-user"></i>User Management</a></li>
{{/if}} {{/if}}
<li><a href="#"><i class="fw fw-policy"></i>Policy Management</a></li> <li><a href="/iotserver/policies"><i class="fw fw-policy"></i>Policy Management</a></li>
<li><a href="/iotserver/dashboard"><i class="fw fw-settings"></i>Dashboard</a></li> <li><a href="/iotserver/dashboard"><i class="fw fw-settings"></i>Dashboard</a></li>
</ul> </ul>
</div> </div>

@ -1,6 +1,6 @@
function onRequest(context) { function onRequest(context) {
var constants = require("/modules/constants.js"); var constants = require("/modules/constants.js");
var user = session.get(constants.USER_SESSION_KEY); var carbonUser = session.get(constants.USER_SESSION_KEY);
var links = { var links = {
"users": [], "users": [],
@ -18,7 +18,7 @@ function onRequest(context) {
}; };
var deviceMgtLink = { var deviceMgtLink = {
title: "Go back to Device Management", title: "Go back to My Devices",
icon: "fw-left-arrow", icon: "fw-left-arrow",
url: "/iotserver/devices" url: "/iotserver/devices"
}; };
@ -38,9 +38,12 @@ function onRequest(context) {
links.analytics.push(deviceMgtLink); links.analytics.push(deviceMgtLink);
links['device-mgt'].push(dashboardLink); links['device-mgt'].push(dashboardLink);
if (user) { if (!carbonUser) {
//user is not logged in
}else{
var userModule = require("/modules/user.js").userModule; var userModule = require("/modules/user.js").userModule;
var permissions = userModule.getUIPermissions(); var permissions = userModule.getUIPermissions();
context.permissions = permissions; context.permissions = permissions;
//if (permissions.ADD_USER) { //if (permissions.ADD_USER) {

@ -0,0 +1,4 @@
function onRequest(context){
context.sketchPath = "api/device/sketch/download";
return context;
}

@ -24,7 +24,46 @@ function formatDates(){
} }
(function () { (function () {
var deviceId = $(".device-id");
var deviceIdentifier = deviceId.data("deviceid");
var deviceType = deviceId.data("type");
var payload = [deviceIdentifier];
if (deviceType == "ios") {
var serviceUrl = "/ios/operation/deviceinfo";
} else if (deviceType == "android") {
var serviceUrl = "/mdm-android-agent/operation/device-info";
}
invokerUtil.post(serviceUrl, payload,
function(message){
console.log(message);
}, function (message) {
console.log(message);
});
$(document).ready(function(){ $(document).ready(function(){
loadOperationBar(deviceType);
loadMap();
formatDates(); formatDates();
}); });
function loadMap(){
var map;
function initialize() {
var mapOptions = {
zoom: 18
};
var lat = 6.9098591;
var long = 79.8523753;
map = new google.maps.Map(document.getElementById('device-location'),
mapOptions);
var pos = new google.maps.LatLng(lat,
long);
var marker = new google.maps.Marker({
position: pos,
map: map
});
map.setCenter(pos);
}
google.maps.event.addDomListener(window, 'load', initialize);
}
}()); }());

@ -93,7 +93,7 @@
<div class="col-lg-5 col-md-6 col-centered"> <div class="col-lg-5 col-md-6 col-centered">
<h3>Device was successfully updated.</h3> <h3>Device was successfully updated.</h3>
<div class="buttons"> <div class="buttons">
<a href="#" id="remove-device-200-link" class="btn-operations"> <a href="#" id="edit-device-200-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;&nbsp;
</a> </a>
</div> </div>

@ -168,7 +168,7 @@ function loadDevices(searchType, searchParam) {
addDeviceSelectedClass(this); addDeviceSelectedClass(this);
}); });
attachEvents(); attachEvents();
formatDates(); //formatDates();
} }
}; };
invokerUtil.get(serviceURL, invokerUtil.get(serviceURL,
@ -253,24 +253,25 @@ function attachEvents() {
$("a#remove-device-yes-link").click(function () { $("a#remove-device-yes-link").click(function () {
invokerUtil.get( invokerUtil.get(
removeDeviceAPI, removeDeviceAPI,
function (data) { function (data,txtStatus,jqxhr) {
if (data == 200) { var status = jqxhr.status;
$("#" + username).addClass("hide"); if (status == 200) {
$(modalPopupContent).html($('#remove-device-200-content').html()); $(modalPopupContent).html($('#remove-device-200-content').html());
$("a#remove-device-200-link").click(function () { $('div[data-deviceid="' + deviceId + '"]').remove();
$("a#remove-device-200-link").click(function () {
hidePopup(); hidePopup();
}); });
} else if (data == 400) { } else if (status == 400) {
$(modalPopupContent).html($('#remove-device-400-content').html()); $(modalPopupContent).html($('#remove-device-400-content').html());
$("a#remove-device-400-link").click(function () { $("a#remove-device-400-link").click(function () {
hidePopup(); hidePopup();
}); });
} else if (data == 403) { } else if (status == 403) {
$(modalPopupContent).html($('#remove-device-403-content').html()); $(modalPopupContent).html($('#remove-device-403-content').html());
$("a#remove-device-403-link").click(function () { $("a#remove-device-403-link").click(function () {
hidePopup(); hidePopup();
}); });
} else if (data == 409) { } else if (status == 409) {
$(modalPopupContent).html($('#remove-device-409-content').html()); $(modalPopupContent).html($('#remove-device-409-content').html());
$("a#remove-device-409-link").click(function () { $("a#remove-device-409-link").click(function () {
hidePopup(); hidePopup();
@ -308,28 +309,30 @@ function attachEvents() {
showPopup(); showPopup();
$("a#edit-device-yes-link").click(function () { $("a#edit-device-yes-link").click(function () {
var device={"device":{"name" : $('#edit-device-name').val()}}; var newDeviceName = $('#edit-device-name').val();
var device={"device":{"name" : newDeviceName}};
invokerUtil.post( invokerUtil.post(
editDeviceAPI, editDeviceAPI,
device, device,
function (data) { function (data,txtStatus,jqxhr) {
if (data == 200) { var status = jqxhr.status;
$("#" + username).addClass("hide"); if (status == 200) {
$(modalPopupContent).html($('#edit-device-200-content').html()); $(modalPopupContent).html($('#edit-device-200-content').html());
$("div[data-deviceid='"+deviceId+"'] .ast-name").html(newDeviceName);
$("a#edit-device-200-link").click(function () { $("a#edit-device-200-link").click(function () {
hidePopup(); hidePopup();
}); });
} else if (data == 400) { } else if (status == 400) {
$(modalPopupContent).html($('#edit-device-400-content').html()); $(modalPopupContent).html($('#edit-device-400-content').html());
$("a#edit-device-400-link").click(function () { $("a#edit-device-400-link").click(function () {
hidePopup(); hidePopup();
}); });
} else if (data == 403) { } else if (status == 403) {
$(modalPopupContent).html($('#edit-device-403-content').html()); $(modalPopupContent).html($('#edit-device-403-content').html());
$("a#edit-device-403-link").click(function () { $("a#edit-device-403-link").click(function () {
hidePopup(); hidePopup();
}); });
} else if (data == 409) { } else if (status == 409) {
$(modalPopupContent).html($('#edit-device-409-content').html()); $(modalPopupContent).html($('#edit-device-409-content').html());
$("a#edit-device-409-link").click(function () { $("a#edit-device-409-link").click(function () {
hidePopup(); hidePopup();

@ -1,6 +1,6 @@
{{#each devices}} {{#each devices}}
{{deviceMap this}} {{deviceMap this}}
<div class="ctrl-wr-asset" data-deviceid="{{id}}" data-type="{{type}}"> <div class="ctrl-wr-asset" data-deviceid="{{deviceIdentifier}}" data-type="{{type}}">
<div class="itm-select"> <div class="itm-select">
<label class="wr-input-control checkbox"> <label class="wr-input-control checkbox">
<input type="checkbox"/> <input type="checkbox"/>
@ -12,7 +12,7 @@
<div class="ast-img"><img src="{{../imageLocation}}{{type}}.png"/></div> <div class="ast-img"><img src="{{../imageLocation}}{{type}}.png"/></div>
<div class="ast-desc"> <div class="ast-desc">
<div class="ast-title"> <div class="ast-title">
<h3 class="ast-name">Device {{name}}</h3> <h3 class="ast-name">{{name}}</h3>
<span class="ast-auth">Device Type: {{type}}</span> <span class="ast-auth">Device Type: {{type}}</span>
<span class="ast-auth">Date of Enrollment: <span class="formatDate">{{dateOfEnrolment}}</span></span> <span class="ast-auth">Date of Enrollment: <span class="formatDate">{{dateOfEnrolment}}</span></span>
</div> </div>

@ -1,4 +0,0 @@
function onRequest(context){
context.sketchPath = "../api/device/sketch/download";
return context;
}

@ -1,4 +0,0 @@
function onRequest(context){
context.sketchPath = "../api/device/sketch/download";
return context;
}

@ -1,4 +0,0 @@
function onRequest(context){
context.sketchPath = "../api/device/sketch/download";
return context;
}

@ -1,90 +0,0 @@
{{#zone "main"}}
<div class="container container-bg white-bg">
<div class=" margin-top-double">
<div class="row row padding-top-double padding-bottom-double margin-bottom-double">
<div class="col-lg-12 margin-top-double">
<h1 class="grey ">Fire Alarm</h1>
<hr>
<p class="margin-bottom-double light-grey ">Connect your Fire Alarm device
to the WSO2 device cloud. </p>
</div>
</div>
<div class="row margin-bottom-double">
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4 padding-top">
<img src="{{self.publicURL}}/images/firealarm.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-6 col-md-8 col-lg-8 padding-top">
<h2 class="uppercase">Ingredients</h2>
<hr>
<p class="grey margin-top">Hardware Requirements </p>
<br><br>
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"> </i>
<i class="fw fw-right-arrow-2 fw-stack-1x"></i>
</span>Arduino Uno<br><br>
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"> </i>
<i class="fw fw-right-arrow-2 fw-stack-1x"></i>
</span>Arduino Ethernet / WiFi Shield
<br /><br />
<form method="POST" class="float-left margin-right"
action="{{sketchPath}}">
<input type="hidden" name="deviceType" value="firealarm" />
<input type="hidden" name="sketchType" value="firealarm_wifi" />
<button class="wr-btn" type="submit">Create Sketch for
Wifi
</button>
</form>
<form method="POST" class="form-login-box float-left"
action="{{sketchPath}}">
<input type="hidden" name="deviceType" value="firealarm" />
<input type="hidden" name="sketchType" value="firealarm" />
<button class="wr-btn margin-right" type="submit">Create
Sketch
for Ethernet</button>
</form>
<br/>
</div>
<div class ="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double grey-bg ">
<h2 class="uppercase">Prepare</h2><hr>
<p class="grey margin-top">Get your device ready </p>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">01 </span> <span class="padding-left"> Mount the Ethernet / Wifi shield on the Arduino Uno device.</span>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom">
<span class="circle">02 </span> <span class="padding-left"> Mount the Ethernet / Wifi shield on the Arduino Uno device.</span>
</div>
<div class="margin-doubles padding-top-double margin-bottom-double light-grey margin-left-double margin-bottom">
<span class="circle">03 </span> <span class="padding-left"> Mount the Ethernet / Wifi shield on the Arduino Uno device.</span>
</div>
</div>
</div>
<div class="row row padding-top-double padding-bottom-double margin-bottom-double ">
<div class="col-lg-12 margin-top-double">
<h2 class="uppercase ">Connect (Quickstart)</h2>
<hr>
<p class="margin-bottom-double light-grey ">Internet of Things Foundation Quickstart connection </p>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">01 </span> <span class="padding-left">Use the following command to download the installer from GitHub:</span><br>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">02 </span> <span class="padding-left">Download the Sketch installer from the Arduino website http://arduino.cc/en/Main/Software</span><br>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">03 </span> <span class="padding-left"> Install the Sketch program</span><br>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">04 </span> <span class="padding-left">Use the Sketch program to open the samples code samples/quickstart/quickstart.ino</span><br>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">05 </span> <span class="padding-left">View the lower part of the Sketch pad window to check that the COM connection is shown as active</span><br>
</div>
</div>
</div>
</div>
{{/zone}}
{{#zone "topCss"}}
<link href="{{self.publicURL}}/css/fontwso2.css" rel="stylesheet">
<link href="{{self.publicURL}}/css/fontwso2-extend.css" rel="stylesheet">
{{/zone}}

@ -0,0 +1,215 @@
{{#zone "main"}}
<div class="container container-bg white-bg">
<div class=" margin-top-double">
<div class="row row padding-top-double padding-bottom-double margin-bottom-double">
<div class="col-lg-12 margin-top-double">
<h1 class="grey ">Fire Alarm</h1>
<hr>
<p class="margin-bottom-double light-grey ">Connect your Fire Alarm device
to the WSO2 device cloud. </p>
</div>
</div>
<div class="row margin-bottom-double">
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4 padding-top">
<img src="{{self.publicURL}}/images/firealarm.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-6 col-md-8 col-lg-8 padding-top">
<h2 class="uppercase">Ingredients</h2>
<hr>
<p class="grey margin-top">Hardware Requirements </p>
<br>
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"> </i>
<i class="fw fw-right-arrow-2 fw-stack-1x"></i>
</span>Raspberry Pi (Internet Enabled)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"> </i>
<i class="fw fw-right-arrow-2 fw-stack-1x"></i>
</span>DHT11 Temperature Sensor<br/><br/>
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"> </i>
<i class="fw fw-right-arrow-2 fw-stack-1x"></i>
</span>LED
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"> </i>
<i class="fw fw-right-arrow-2 fw-stack-1x"></i>
</span>Buzzer(3v)<br><br>
<a href="#" class="download-link btn-operations" data-devicetype="firealarm" data-sketchtype="firealarm">Download</a>
<!--form method="POST" class="form-login-box float-left"
action="{{sketchPath}}">
<input type="hidden" name="deviceType" value="firealarm" />
<input type="hidden" name="sketchType" value="firealarm" />
<button class="wr-btn margin-right" type="submit">Create
Sketch
for Ethernet</button>
</form-->
<br/>
</div>
<div class ="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double grey-bg ">
<h2 class="uppercase">Prepare</h2><hr>
<p class="grey margin-top"><b>Get your device ready</b></p>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">01 </span> <span class="padding-left"><b>Set up your RaspberryPi device as shown in the schematic below and get the FireAlarm setup.</b></span>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom">
<span class="circle">02 </span> <span class="padding-left"><b>Connect a monitor to your RaspberryPi via the HDMI cable to get a UI view of the device.</b></span>
</div>
<div class="margin-doubles padding-top-double margin-bottom-double light-grey margin-left-double margin-bottom">
<span class="circle">03 </span> <span class="padding-left"><b>Get the RaspberryPi to connect to the internet (via Ethernet or Wifi) and note its IP_ADDRESS</b></span>
</div>
</div>
<div class ="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double grey-bg ">
<h2 class="uppercase">Schematic Diagram</h2><hr>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{self.publicURL}}/images/schematicsGuide.png" target="_blank">
<img src="{{self.publicURL}}/images/schematicsGuide.png" class="img-responsive" style="max-width: 500px; max-height: 500px" />
</a>
</center>
</div>
</div>
<div class="row row padding-top-double padding-bottom-double margin-bottom-double ">
<div class="col-lg-12 margin-top-double">
<h2 class="uppercase ">Connect (Quickstart)</h2>
<hr>
<p class="margin-bottom-double light-grey ">Internet of Things Foundation Quickstart connection </p>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">01 </span> <span class="padding-left"><b>Click on the <i>"Create DEB"</i> button above to get the download link for the FireAlarm setup files</b></span><br>
</div>
<br>
<div>
<span class="padding-left"><i>(The following commands can be issued by directly typing into the terminal of the device or by an <b>"ssh"</b> login from a remote PC)</i></span>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">02 </span> <span class="padding-left"><b>Download the FireAlarm setup files using the following command: "curl -k &#60;url_link_received_from_the_above_step&#62; > Agent.zip"</b></span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <i> This will download a zip file named &#34;Agent.zip&#34;</i>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">03 </span> <span class="padding-left"><b>Run the following commands to successfuly install the package and get the service running:</b></span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>&nbsp;&nbsp;cd &#60PATH_WHERE_THE_DOWNLOADED_&#34;Agent.zip&#34;_FILE_IS&#62 </b> <br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <b>unzip Agent.zip -d Agent</b> <br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <b>cd Agent</b> <br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <b>sudo chmod 755 startservice.sh</b> <br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <b>sudo ./startservice.sh</b> <br>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">04 </span> <span class="padding-left">Follow the installation instructions and complete installation. Upon completion the Agent would have started automatically</span><br>
</div>
</div>
</div>
</div>
<div id="download-device-modal-content" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Please download the file from following link.</h3>
<br/>
<div class="buttons">
<form method="POST" action="{{sketchPath}}">
<input type="hidden" name="deviceType" value="firealarm" />
<input type="hidden" name="sketchType" value="firealarm" />
<button class="btn-operations" type="submit" style="font-size: 13px;border:none; padding: 10px 10px; display: inline-block; margin-right: 2px; text-decoration: none;">Download Now</button>
&nbsp;&nbsp;
<a href="#" id="download-device-download-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Copy Link&nbsp;&nbsp;&nbsp;&nbsp;
</a>
&nbsp;&nbsp;
</form>
</div>
</div>
</div>
</div>
</div>
<div id="download-device-modal-content-links" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Please download the file from following link(Press CTRL+C).</h3>
<br/>
<div>
<input id="download-device-url" style="color:#3f3f3f;padding:5px" type="text" value="" placeholder="Type here" size="60">
</div>
</div>
</div>
</div>
</div>
<div id="device-400-content" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Exception at backend. Try Later.</h3>
<div class="buttons">
<a href="#" id="device-400-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-403-content" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Action not permitted.</h3>
<div class="buttons">
<a href="#" id="device-403-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-409-content" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Device Sketch does not exist.</h3>
<div class="buttons">
<a href="#" id="device-409-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-unexpected-error-content" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Unexpected error.</h3>
<div class="buttons">
<a href="#" id="device-unexpected-error-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
{{/zone}}
{{#zone "topCss"}}
<link href="{{self.publicURL}}/css/fontwso2.css" rel="stylesheet">
<link href="{{self.publicURL}}/css/fontwso2-extend.css" rel="stylesheet">
{{/zone}}
{{#zone "bottomJs"}}
<script src="{{self.publicURL}}/js/firealarm.js"></script>
{{/zone}}

@ -0,0 +1,213 @@
{{#zone "main"}}
<div class="container container-bg white-bg">
<div class=" margin-top-double">
<div class="row row padding-top-double padding-bottom-double margin-bottom-double">
<div class="col-lg-12 margin-top-double">
<h1 class="grey ">Fire Alarm</h1>
<hr>
<p class="margin-bottom-double light-grey ">Connect your Fire Alarm device
to the WSO2 device cloud. </p>
</div>
</div>
<div class="row margin-bottom-double">
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4 padding-top">
<img src="{{self.publicURL}}/images/firealarm.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-6 col-md-8 col-lg-8 padding-top">
<h2 class="uppercase">Ingredients</h2>
<hr>
<p class="grey margin-top">Hardware Requirements </p>
<br>
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"> </i>
<i class="fw fw-right-arrow-2 fw-stack-1x"></i>
</span>Raspberry Pi (Internet Enabled)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"> </i>
<i class="fw fw-right-arrow-2 fw-stack-1x"></i>
</span>DHT11 Temperature Sensor<br/><br/>
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"> </i>
<i class="fw fw-right-arrow-2 fw-stack-1x"></i>
</span>LED
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"> </i>
<i class="fw fw-right-arrow-2 fw-stack-1x"></i>
</span>Buzzer(3v)<br><br>
<a href="#" class="download-link btn-operations" data-devicetype="firealarm" data-sketchtype="firealarm">Download</a>
<!--form method="POST" class="form-login-box float-left"
action="{{sketchPath}}">
<input type="hidden" name="deviceType" value="firealarm" />
<input type="hidden" name="sketchType" value="firealarm" />
<button class="wr-btn margin-right" type="submit">Create
Sketch
for Ethernet</button>
</form-->
<br/>
</div>
<div class ="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double grey-bg ">
<h2 class="uppercase">Prepare</h2><hr>
<p class="grey margin-top"><b>Get your device ready</b></p>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">01 </span> <span class="padding-left"><b>Set up your RaspberryPi device as shown in the schematic below and get the FireAlarm setup.</b></span>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom">
<span class="circle">02 </span> <span class="padding-left"><b>Connect a monitor to your RaspberryPi via the HDMI cable to get a UI view of the device.</b></span>
</div>
<div class="margin-doubles padding-top-double margin-bottom-double light-grey margin-left-double margin-bottom">
<span class="circle">03 </span> <span class="padding-left"><b>Get the RaspberryPi to connect to the internet (via Ethernet or Wifi) and note its IP_ADDRESS</b></span>
</div>
</div>
<div class ="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double grey-bg ">
<h2 class="uppercase">Schematic Diagram</h2><hr>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{self.publicURL}}/images/schematicsGuide.png" target="_blank">
<img src="{{self.publicURL}}/images/schematicsGuide.png" class="img-responsive" style="max-width: 500px; max-height: 500px" />
</a>
</center>
</div>
</div>
<div class="row row padding-top-double padding-bottom-double margin-bottom-double ">
<div class="col-lg-12 margin-top-double">
<h2 class="uppercase ">Connect (Quickstart)</h2>
<hr>
<p class="margin-bottom-double light-grey ">Internet of Things Foundation Quickstart connection </p>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">01 </span> <span class="padding-left"><b>Click on the <i>"Create DEB"</i> button above to get the download link for the FireAlarm setup files</b></span><br>
</div>
<br>
<div>
<span class="padding-left"><i>(The following commands can be issued by directly typing into the terminal of the device or by an <b>"ssh"</b> login from a remote PC)</i></span>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">02 </span> <span class="padding-left"><b>Download the FireAlarm setup files using the following command: "wget &#60;url_link_received_from_the_above_step&#62;"</b></span><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <i> This will download a zip file named &#34;FireAlarmAgent.zip&#34;</i>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">03 </span> <span class="padding-left"><b>Run the following commands to successfuly install the package and get the service running:</b></span><br>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">04 </span> <span class="padding-left">Use the Sketch program to open the samples code samples/quickstart/quickstart.ino</span><br>
</div>
<div class="margin-doubles padding-top-double light-grey margin-left-double margin-bottom ">
<span class="circle">05 </span> <span class="padding-left">View the lower part of the Sketch pad window to check that the COM connection is shown as active</span><br>
</div>
</div>
</div>
</div>
<div id="download-device-modal-content" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Please download the file from following link.</h3>
<br/>
<div class="buttons">
<form method="POST" action="{{sketchPath}}">
<input type="hidden" name="deviceType" value="firealarm" />
<input type="hidden" name="sketchType" value="firealarm" />
<button class="btn-operations" type="submit" style="font-size: 13px;border:none; padding: 10px 10px; display: inline-block; margin-right: 2px; text-decoration: none;">Download Now</button>
&nbsp;&nbsp;
<a href="#" id="download-device-download-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Copy Link&nbsp;&nbsp;&nbsp;&nbsp;
</a>
&nbsp;&nbsp;
</form>
</div>
</div>
</div>
</div>
</div>
<div id="download-device-modal-content-links" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Please download the file from following link(Press CTRL+C).</h3>
<br/>
<div>
<input id="download-device-url" style="color:#3f3f3f;padding:5px" type="text" value="" placeholder="Type here" size="60">
</div>
</div>
</div>
</div>
</div>
<div id="device-400-content" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Exception at backend. Try Later.</h3>
<div class="buttons">
<a href="#" id="device-400-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-403-content" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Action not permitted.</h3>
<div class="buttons">
<a href="#" id="device-403-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-409-content" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Device Sketch does not exist.</h3>
<div class="buttons">
<a href="#" id="device-409-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-unexpected-error-content" class="hide">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>Unexpected error.</h3>
<div class="buttons">
<a href="#" id="device-unexpected-error-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Ok&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
{{/zone}}
{{#zone "topCss"}}
<link href="{{self.publicURL}}/css/fontwso2.css" rel="stylesheet">
<link href="{{self.publicURL}}/css/fontwso2-extend.css" rel="stylesheet">
{{/zone}}
{{#zone "bottomJs"}}
<script src="{{self.publicURL}}/js/firealarm.js"></script>
{{/zone}}

@ -0,0 +1,104 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var modalPopup = ".wr-modalpopup";
var modalPopupContainer = modalPopup + " .modalpopup-container";
var modalPopupContent = modalPopup + " .modalpopup-content";
var body = "body";
/*
* set popup maximum height function.
*/
function setPopupMaxHeight() {
$(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30)));
$(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2)));
}
/*
* show popup function.
*/
function showPopup() {
$(modalPopup).show();
setPopupMaxHeight();
}
/*
* hide popup function.
*/
function hidePopup() {
$(modalPopupContent).html('');
$(modalPopup).hide();
}
/*
* DOM ready functions.
*/
$(document).ready(function () {
attachEvents();
});
function attachEvents() {
/**
* Following click function would execute
* when a user clicks on "Download" link
* on Device Management page in WSO2 DC Console.
*/
$("a.download-link").click(function () {
var sketchType = $(this).data("sketchtype");
var deviceType = $(this).data("devicetype");
var downloadDeviceAPI = "/iotserver/api/device/sketch/generate_link";
var payload = {"sketchType":sketchType, "deviceType":deviceType};
console.log(payload);
$(modalPopupContent).html($('#download-device-modal-content').html());
showPopup();
$("a#download-device-download-link").click(function () {
invokerUtil.post(
downloadDeviceAPI,
payload,
function (data, textStatus, jqxhr) {
if(jqxhr.status == 200) {
$(modalPopupContent).html($('#download-device-modal-content-links').html());
$("#download-device-url").val(data);
$("#download-device-url").focus(function () {
$(this).select();
});
showPopup();
}else{
$(modalPopupContent).html($('#device-403-content').html());
$("#device-403-link").click(function () {
window.location.reload();
});
showPopup();
}
},
function () {
$(modalPopupContent).html($('#device-unexpected-error-content').html());
$("a#device-unexpected-error-link").click(function () {
hidePopup();
});
}
);
});
$("a#download-device-cancel-link").click(function () {
hidePopup();
});
});
}

@ -1,5 +1,5 @@
{{#zone "brand"}} {{#zone "brand"}}
<img src="{{self.publicURL}}/img/logo.png" /><h2 class="app-title"><span>IOT Device Manager</span></h2> <img src="{{self.publicURL}}/img/logo.png" /><h2 class="app-title" style="text-transform:none !important"><span>IoT Device Manager</span></h2>
{{/zone}} {{/zone}}
{{#zone "favicon"}} {{#zone "favicon"}}
<link rel="icon" href="{{self.publicURL}}/img/favicon.png" type="image/x-icon" /> <link rel="icon" href="{{self.publicURL}}/img/favicon.png" type="image/x-icon" />

@ -0,0 +1,243 @@
{{#zone "main"}}
<div class="row">
<div class="col-md-12">
<div class="hidden wr-steps">
<div class="col-md-3 col-xs-3">
<div class="itm-wiz itm-wiz-current" data-step="policy-platform"><div class="wiz-no">1</div><div class="wiz-lbl hidden-xs"><span>Select Platform</span></div></div>
<br class="c-both" />
</div>
<div class="col-md-3 col-xs-3">
<div class="itm-wiz" data-step="policy-profile"><div class="wiz-no">2</div><div class="wiz-lbl hidden-xs"><span>Configure Profile</span></div></div>
<br class="c-both" />
</div>
<div class="col-md-3 col-xs-3">
<div class="itm-wiz" data-step="policy-criteria"><div class="wiz-no">3</div><div class="wiz-lbl hidden-xs"><span>Assign to a group</span></div></div>
<br class="c-both" />
</div>
<div class="col-md-3 col-xs-3">
<div class="itm-wiz" data-step="policy-content"><div class="wiz-no">4</div><div class="wiz-lbl hidden-xs"><span>Publish</span></div></div>
<br class="c-both" />
</div>
</div>
<div class="container col-centered wr-content policy-message hidden">
<div class="wr-form">
<h1 class="wr-title">Policy creation is successful</h1>
Please click <b>"Finish"</b> to complete the process and go back to the policy list
<hr />
<button class="wr-btn wizard-stepper" data-current="policy-message" data-direct="/mdm/policies/" onclick="window.location.href=''">
&nbsp;&nbsp;&nbsp;&nbsp;Finish&nbsp;&nbsp;&nbsp;&nbsp;
</button>
</div>
</div>
<div class="container col-centered wr-content policy-content hidden">
<div class="wr-form">
<h1 class="page-sub-title">Add Policy</h1>
<div class="row wr-wizard"></div>
<div class="row">
<div class="col-lg-12">
<div>
<label class="wr-input-label" title="">
Set a Name to Your Policy
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</label>
<div class="wr-input-control">
<div class="cus-col-50">
<input id="policy-name-input" type="text" value="" placeholder="input text"/>
</div>
<br class="c-both" />
</div>
<label class="wr-input-label" title="">
Set Description
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</label>
<div class="wr-input-control">
<div class="cus-col-50">
<textarea id="policy-description-input" placeholder="description"></textarea>
</div>
<br class="c-both" />
</div>
</div>
<div class="wr-input-control wr-btn-grp">
<a href="#" class="wr-btn wizard-stepper" data-current="policy-content" data-back="true" data-next="policy-criteria">Back</a>
<a href="#" class="wr-btn wizard-stepper" data-current="policy-content" data-next="policy-message">Save</a>
</div>
</div>
</div>
</div>
</div>
<div class="container col-centered wr-content policy-criteria hidden">
<div class="wr-form">
<h1 class="page-sub-title">Add Policy</h1>
<div class="row wr-wizard"></div>
<div class="row">
<div class="col-lg-12">
<div>
<label class="wr-input-label" title="">
Set Device Ownership Type
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</label>
<div class="wr-input-control">
<div class="cus-col-50">
<select id="ownership-input" class="form-control">
<option>COPE</option>
<option>BYOD</option>
</select>
</div>
<br class="c-both" />
</div>
<div class="wr-input-control">
<label class="wr-input-control radio light" rel="assetfilter">
<input id="userRadio" type="radio" name="user-select" value="userSelectField" class="user-select-radio" />
<span class="helper">User</span>
</label>
<label class="wr-input-control radio light">
<input id="userRoleRadio" type="radio" name="user-select" value="userRoleSelectField" class="user-select-radio" />
<span class="helper">User Role</span>
</label>
</div>
<div id="userSelectField" class="user-select">
<label class="wr-input-label" title="">
Set User(s)
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</label>
<div class="wr-input-control">
<div class="cus-col-50">
<select id="users-input" class="form-control select2" multiple="multiple">
{{#each users}}
<option>{{username}}</option>
{{/each}}
</select>
</div>
<br class="c-both" />
</div>
</div>
<div id="userRoleSelectField" class="user-select" style="display:none">
<label class="wr-input-label" title="">
Set User Role(s)
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</label>
<div class="wr-input-control">
<div class="cus-col-50">
<select id="user-roles-input" class="form-control select2" multiple="multiple">
{{#each roles}}
<option>{{this}}</option>
{{/each}}
</select>
</div>
<br class="c-both" />
</div>
</div>
<label class="wr-input-label" title="">
Set Action upon Non-compliance
<span class="wr-help-tip glyphicon glyphicon-question-sign"></span>
</label>
<div class="wr-input-control">
<div class="cus-col-50">
<select id="action-input" class="form-control">
<option data-action="enforce">Enforce</option>
<option data-action="warn">Warn</option>
<option data-action="monitor">Monitor</option>
</select>
</div>
<br class="c-both" />
</div>
</div>
<div class="wr-input-control wr-btn-grp">
<a href="#" class="wr-btn wizard-stepper" data-current="policy-criteria" data-back="true" data-next="policy-profile">Back</a>
<a href="#" class="wr-btn wizard-stepper" data-current="policy-criteria" data-next="policy-content">Continue</a>
</div>
</div>
</div>
</div>
</div>
<div class="container col-centered wr-content policy-profile hidden">
<div class="wr-form">
<h1 class="page-sub-title">Add Policy</h1>
<div class="row wr-wizard"></div>
<div class="row">
<div class="col-lg-12">
<div class="wr-advance-operations">
<label class="wr-input-label col-sm-4" for="maxFailedAttempts">Policy</label>
<div class="wr-input-control">
<input type="text" class="form-control" id="policyDefinition" data-key="policyDefinition" placeholder="Enter the policy">
</div>
</div>
<div class="wr-input-control wr-btn-grp">
<a href="#" class="wr-btn wizard-stepper" data-current="policy-profile" data-back="true" data-next="policy-platform">Back</a>
<a href="#" class="wr-btn wizard-stepper" data-current="policy-profile" data-next="policy-criteria">Continue</a>
</div>
</div>
</div>
</div>
</div>
<div class="container col-centered wr-content policy-platform">
<div class="wr-form">
<h1 class="page-sub-title">Add Policy</h1>
<div class="row wr-wizard">
<div class="col-md-3 col-xs-3">
<div class="itm-wiz itm-wiz-current" data-step="policy-platform"><div class="wiz-no">1</div><div class="wiz-lbl hidden-xs"><span>Select Platform</span></div></div>
<br class="c-both" />
</div>
<div class="col-md-3 col-xs-3">
<div class="itm-wiz" data-step="policy-profile"><div class="wiz-no">2</div><div class="wiz-lbl hidden-xs"><span>Configure Profile</span></div></div>
<br class="c-both" />
</div>
<div class="col-md-3 col-xs-3">
<div class="itm-wiz" data-step="policy-criteria"><div class="wiz-no">3</div><div class="wiz-lbl hidden-xs"><span>Assign to a group</span></div></div>
<br class="c-both" />
</div>
<div class="col-md-3 col-xs-3">
<div class="itm-wiz" data-step="policy-content"><div class="wiz-no">4</div><div class="wiz-lbl hidden-xs"><span>Publish</span></div></div>
<br class="c-both" />
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="row wr-tile-buttons-list">
<div class="wr-input-control">
<ul class="tile-buttons row">
<li class="col-lg-4"><a href="#" class="wizard-stepper" data-current="policy-platform" data-next="policy-profile" data-platform="android" data-platform-id="1"><i class="fw fw-android"></i>Android</a></li>
<li class="col-lg-4"><a href="#" class="wizard-stepper" data-current="policy-platform" data-next="policy-profile" data-platform="ios" data-platform-id="2"><i class="fw fw-apple"></i>iOS</a></li>
<li class="col-lg-4"><a href="#" class="wizard-stepper" data-current="policy-platform" data-next="policy-profile" data-platform="windows" data-platform-id="3"><i class="fw fw-windows"></i>Windows</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- content -->
</div>
</div>
{{/zone}}
{{#zone "bottomJs"}}
<script id="hidden-operations-bar-ios" src="{{self.publicURL}}/templates/hidden-operations-ios.hbs" type="text/x-handlebars-template" ></script>
<script id="hidden-operations-bar-android" src="{{self.publicURL}}/templates/hidden-operations-android.hbs" type="text/x-handlebars-template" ></script>
<script src="{{self.publicURL}}/js/policy-create.js"></script>
{{/zone}}

@ -0,0 +1,10 @@
function onRequest(context){
var userModule = require("/modules/user.js").userModule;
var roles = userModule.getRoles(true);
var users = userModule.getUsers();
var actions = ["Enforce"];
context.roles = roles;
context.users = users;
context.actions = actions;
return context;
}

@ -0,0 +1,156 @@
$('select.select2').select2({
placeholder: 'Select..'
});
$('select.select2[multiple=multiple]').select2({
placeholder: 'Select..',
tags: true
});
var stepperRegistry = {},
hiddenOperation = '.wr-hidden-operations-content > div',
advanceOperation = '.wr-advance-operations';
function initStepper(selector){
$(selector).click(function(){
var nextStep = $(this).data("next");
var currentStep = $(this).data("current");
var isBack = $(this).data("back");
if (!isBack){
var action = stepperRegistry[currentStep];
if (action){
action(this);
}
}
if (!nextStep) {
var direct = $(this).data("direct");
window.location.href = direct;
}
$(".itm-wiz").each(function(){
var step = $(this).data("step");
if (step == nextStep){
$(this).addClass("itm-wiz-current");
}else{
$(this).removeClass("itm-wiz-current");
}
});
$(".wr-wizard").html($(".wr-steps").html());
$("." + nextStep).removeClass("hidden");
$("." + currentStep).addClass("hidden");
});
}
function showAdvanceOperation(operation, button){
$(button).addClass('selected');
$(button).siblings().removeClass('selected');
$(hiddenOperation + '[data-operation="' + operation + '"]').show();
$(hiddenOperation + '[data-operation="' + operation + '"]').siblings().hide();
}
var policy = {};
var configuredProfiles = [];
function savePolicy(){
var profilePayloads = [];
for (var key in policy.profile) {
if (policy.profile.hasOwnProperty(key)) {
profilePayloads.push({
featureCode: key,
deviceTypeId: policy.platformId,
content: policy.profile[key]
});
}
}
var payload = {
policyName: policy.policyName,
compliance: policy.selectedAction,
ownershipType: policy.selectedOwnership,
profile: {
profileName: policy.policyName,
deviceType: {
id: policy.platformId
},
profileFeaturesList: profilePayloads
}
};
payload.users = [];
payload.roles = [];
if (policy.selectedUsers){
payload.users = policy.selectedUsers;
}else if (policy.selectedUserRoles){
payload.roles = policy.selectedUserRoles;
}
invokerUtil.post("/mdm-admin/policies", payload, function(){
$(".policy-message").removeClass("hidden");
$(".add-policy").addClass("hidden");
}, function(){
});
}
$(document).ready(function(){
alert("hiiiii");
initStepper(".wizard-stepper");
$( "input[type='radio'].user-select-radio" ).change(function() {
$('.user-select').hide();
$('#'+$(this).val()).show();
});
//Adds an event listener to swithc
$(advanceOperation).on("click", ".wr-input-control.switch", function(evt){
var operation = $(this).parents(".operation-data").data("operation");
//prevents event bubbling by figuring out what element it's being called from
if (evt.target.tagName == "INPUT") {
if(!$(this).hasClass('collapsed')){
configuredProfiles.push(operation);
}else {
//splicing the array if operation is present
var index = jQuery.inArray( operation, configuredProfiles );
if (index!= -1){
configuredProfiles.splice( index, 1 );
}
}
console.log(configuredProfiles);
}
});
stepperRegistry['policy-content'] = function (actionButton){
policy.policyName = $("#policy-name-input").val();
policy.policyDescription = $("#policy-description-input").val();
//All data is collected. Policy can now be created.
savePolicy();
};
stepperRegistry['policy-criteria'] = function (actionButton){
$( "input[type='radio'].user-select-radio").each(function(){
if ( $(this).is(':radio')){
if ($(this).is(":checked")){
if($(this).val() == "userSelectField"){
policy.selectedUsers = $("#users-input").val();
}else if($(this).val() == "userRoleSelectField"){
policy.selectedUserRoles = $("#user-roles-input").val();
}
}
}
});
policy.selectedAction = $("#action-input").find(":selected").data("action");
policy.selectedOwnership = $("#ownership-input").val();
};
stepperRegistry['policy-profile'] = function (actionButton){
var deviceType = policy.platform;
var generatedProfile = operationModule.generateProfile(deviceType, configuredProfiles);
policy.profile = generatedProfile;
};
stepperRegistry['policy-platform'] = function (actionButton){
policy.platform = $(actionButton).data("platform");
policy.platformId = $(actionButton).data("platform-id");
};
$(".uu").click(function(){
var policyName = $("#policy-name-input").val();
var selectedProfiles = $("#profile-input").find(":selected");
var selectedProfileId = selectedProfiles.data("id");
var selectedUserRoles = $("#user-roles-input").val();
var selectedUsers = $("#users-input").val();
var selectedAction = $("#action-input").val();
});
});

@ -0,0 +1,201 @@
{{#zone "main"}}
<div class="row wr-device-board">
<div class="col-lg-12 wr-secondary-bar">
<label class="device-id device-select" data-deviceid="{{device.deviceIdentifier}}" data-type="{{device.type}}">
Device {{device.name}}
<span class="lbl-device">
{{#if device.viewModel.vendor}}
({{device.viewModel.vendor}} {{device.viewModel.model}})
{{/if}}
</span>
</label>
</div>
</div>
<div class="wr-device-list row">
<div class="wr-hidden-operations wr-advance-operations">
</div>
<div class="col-md-12 wr-page-content">
{{unit "operation-bar" deviceType=device.type}}
<div class="row">
<div class="col-md-12 wr-stats-board">
<!-- content -->
<div class="col-lg-2 ast-desc-image">
<div class="row">
<div class="col-lg-12 col-sm-4">
<img src="{{self.publicURL}}/img/device_icons/{{device.type}}.png" style="width:200px" />
</div>
<div class="col-lg-12 col-sm-4 ast-desc">
<div class="ast-device-desc"><b>Owner:</b> {{device.owner}}</div>
<div class="ast-device-desc"><b>Date of Enrollment:</b><br/> <span class="formatDate">{{device.enrollment}}</span></div>
<!--<div class="ast-device-desc"><b>Device:</b> {{device.viewModel.vendor}} {{device.properties.model}}</div>-->
<!--<div class="ast-device-desc"><b>Model:</b> {{device.viewModel.model}}</div>-->
<!--<div class="ast-device-desc"><b>IMEI:</b> {{device.viewModel.imei}}</div>-->
<!--{{#if device.viewModel.udid}}<div class="ast-device-desc"><b>UDID:</b> {{device.viewModel.udid}}</div>{{/if}}-->
<!--{{#if device.viewModel.phoneNumber}}<div class="ast-device-desc"><b>Phone Number:</b> {{device.viewModel.phoneNumber}}</div>{{/if}}-->
</div>
</div>
</div>
<div class="col-lg-10 tiles">
<!-- device summary -->
<div class="row">
<div class="col-lg-6 col-md-6">
{{#if device.viewModel.BatteryLevel}}
<div class="col-lg-4">
<div class="wr-stats-board-tile">
<div class="tile-name">BATTERY</div>
<div>
<div class="tile-icon"><i class="fw fw-battery"></i></div>
<div class="tile-stats">{{device.viewModel.BatteryLevel}}%</div>
</div>
</div>
</div>
{{/if}}
{{#if device.viewModel.DeviceCapacity}}
<div class="col-lg-4">
<div class="wr-stats-board-tile">
<div class="tile-name">STORAGE</div>
<div>
<div class="tile-icon"><i class="fw fw-hdd"></i></div>
<div class="tile-stats">{{device.viewModel.DeviceCapacityPercentage}}%<span class="tile-stats-free">{{device.viewModel.DeviceCapacityUsed}} GB Free</span></div>
</div>
</div>
</div>
{{/if}}
{{#if device.viewModel.internal_memory.FreeCapacity}}
<div class="col-lg-4">
<div class="wr-stats-board-tile">
<div class="tile-name">LOCAL STORAGE</div>
<div>
<div class="tile-icon"><i class="fw fw-hdd"></i></div>
<div class="tile-stats">{{device.viewModel.internal_memory.DeviceCapacityPercentage}}%<span class="tile-stats-free">{{device.viewModel.internal_memory.FreeCapacity}} GB Free</span></div>
</div>
</div>
</div>
{{/if}}
{{#if device.viewModel.external_memory.FreeCapacity}}
<div class="col-lg-4">
<div class="wr-stats-board-tile">
<div class="tile-name">EXTERNAL STORAGE</div>
<div>
<div class="tile-icon"><i class="fw fw-hdd"></i></div>
<div class="tile-stats">{{device.viewModel.external_memory.DeviceCapacityPercentage}}%<span class="tile-stats-free">{{device.viewModel.external_memory.FreeCapacity}} GB Free</span></div>
</div>
</div>
</div>
{{/if}}
</div>
</div>
<!-- /device summary -->
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<!-- statistics -->
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingFour">
<h2 class="sub-title panel-title">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseFour" aria-expanded="false" aria-controls="collapseFour">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-arrow fw-down-arrow fw-stack-1x"></i>
</span>
Device Statistics
</a>
</h2>
</div>
<div id="collapseFour" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingFour">
<div class="panel-body">
<a href="../../devices/analytics?deviceId={{deviceId}}&deviceType={{deviceType}}" ><i class="fw fw-charts"></i> Show Statistics</a>
</div>
</div>
</div>
<!-- /statistics -->
<!-- device location -->
<!--<div class="panel panel-default">-->
<!--<div class="panel-heading" role="tab" id="headingOne">-->
<!--<h2 class="sub-title panel-title">-->
<!--<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">-->
<!--<span class="fw-stack">-->
<!--<i class="fw fw-ring fw-stack-2x"></i>-->
<!--<i class="fw fw-arrow fw-down-arrow fw-stack-1x"></i>-->
<!--</span>-->
<!--Device Location-->
<!--</a>-->
<!--</h2>-->
<!--</div>-->
<!--<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">-->
<!--<div id="device-location" style="height:400px" class="panel-body">-->
<!--</div>-->
<!--</div>-->
<!--</div>-->
<!-- /device location -->
<!-- policies -->
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingTwo">
<h2 class="sub-title panel-title">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-arrow fw-down-arrow fw-stack-1x"></i>
</span>
Policies
</a>
</h2>
</div>
<div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
<div class="panel-body">
Not available yet
</div>
</div>
</div>
<!-- /policies -->
<!-- installed applications -->
<!--<div class="panel panel-default">-->
<!--<div class="panel-heading" role="tab" id="headingThree">-->
<!--<h2 class="sub-title panel-title">-->
<!--<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree">-->
<!--<span class="fw-stack">-->
<!--<i class="fw fw-ring fw-stack-2x"></i>-->
<!--<i class="fw fw-arrow fw-down-arrow fw-stack-1x"></i>-->
<!--</span>-->
<!--Installed Applications-->
<!--</a>-->
<!--</h2>-->
<!--</div>-->
<!--<div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">-->
<!--<div class="panel-body">-->
<!--Not available yet-->
<!--</div>-->
<!--</div>-->
<!--</div>-->
<!-- /installed applications -->
</div>
</div>
<!-- /content -->
</div>
</div>
</div>
</div>
{{/zone}}
{{#zone "bottomJs"}}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script src="{{self.publicURL}}/js/device-detail.js"></script>
{{/zone}}

@ -0,0 +1,58 @@
function onRequest(context) {
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var isMatched = uriMatcher.match("/{context}/device/{deviceType}/{+deviceId}");
if (isMatched) {
var matchedElements = uriMatcher.elements();
var deviceType = matchedElements.deviceType;
var deviceId = matchedElements.deviceId;
context.deviceType = deviceType;
context.deviceId = deviceId;
var deviceModule = require("/modules/device.js").deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId);
if (device){
var viewModel = {};
var deviceInfo = device.properties.DEVICE_INFO;
if (deviceInfo != undefined && String(deviceInfo.toString()).length > 0){
deviceInfo = JSON.parse(deviceInfo);
if (device.type == "ios"){
viewModel.imei = device.properties.IMEI;
viewModel.phoneNumber = deviceInfo.PhoneNumber;
viewModel.udid = deviceInfo.UDID;
viewModel.BatteryLevel = Math.round(deviceInfo.BatteryLevel * 100);
viewModel.DeviceCapacity = Math.round(deviceInfo.DeviceCapacity * 100) / 100;
viewModel.AvailableDeviceCapacity = Math.round(deviceInfo.AvailableDeviceCapacity * 100) / 100;
viewModel.DeviceCapacityUsed = Math.round((viewModel.DeviceCapacity
- viewModel.AvailableDeviceCapacity) * 100) / 100;
viewModel.DeviceCapacityPercentage = Math.round(viewModel.DeviceCapacityUsed
/ viewModel.DeviceCapacity * 10000) /100;
}else if(device.type == "android"){
viewModel.imei = device.properties.IMEI;
viewModel.model = device.properties.DEVICE_MODEL;
viewModel.vendor = device.properties.VENDOR;
viewModel.internal_memory = {};
viewModel.external_memory = {};
viewModel.location = {
latitude: device.properties.LATITUDE,
longitude: device.properties.LONGITUDE
};
viewModel.BatteryLevel = deviceInfo.BATTERY_LEVEL;
viewModel.internal_memory.FreeCapacity = Math.round((deviceInfo.INTERNAL_TOTAL_MEMORY -
deviceInfo.INTERNAL_AVAILABLE_MEMORY) * 100) / 100;
viewModel.internal_memory.DeviceCapacityPercentage = Math.round(deviceInfo.INTERNAL_AVAILABLE_MEMORY
/ deviceInfo.INTERNAL_TOTAL_MEMORY * 10000) / 100;
viewModel.external_memory.FreeCapacity = Math.round((deviceInfo.EXTERNAL_TOTAL_MEMORY -
deviceInfo.EXTERNAL_AVAILABLE_MEMORY) * 100) / 100;
viewModel.external_memory.DeviceCapacityPercentage = Math.round(deviceInfo.EXTERNAL_AVAILABLE_MEMORY
/deviceInfo.EXTERNAL_TOTAL_MEMORY * 10000) /100;
}
viewModel.enrollment = device.enrollment;
device.viewModel = viewModel;
}
}
context.device = device;
} else {
response.sendError(404);
}
return context;
}

@ -24,7 +24,46 @@ function formatDates(){
} }
(function () { (function () {
var deviceId = $(".device-id");
var deviceIdentifier = deviceId.data("deviceid");
var deviceType = deviceId.data("type");
var payload = [deviceIdentifier];
if (deviceType == "ios") {
var serviceUrl = "/ios/operation/deviceinfo";
} else if (deviceType == "android") {
var serviceUrl = "/mdm-android-agent/operation/device-info";
}
invokerUtil.post(serviceUrl, payload,
function(message){
console.log(message);
}, function (message) {
console.log(message);
});
$(document).ready(function(){ $(document).ready(function(){
loadOperationBar(deviceType);
loadMap();
formatDates(); formatDates();
}); });
function loadMap(){
var map;
function initialize() {
var mapOptions = {
zoom: 18
};
var lat = 6.9098591;
var long = 79.8523753;
map = new google.maps.Map(document.getElementById('device-location'),
mapOptions);
var pos = new google.maps.LatLng(lat,
long);
var marker = new google.maps.Marker({
position: pos,
map: map
});
map.setCenter(pos);
}
google.maps.event.addDomListener(window, 'load', initialize);
}
}()); }());

@ -0,0 +1,80 @@
{{#zone "main"}}
<div class="row">
<div class="col-md-12">
<!-- content -->
<div class="wr-content">
<p class="page-sub-title">Policies</p>
<p>{{listPolicyStatus}}</p>
<div class="wr-list-group wr-sortable">
{{#if policies}}
{{#each policies}}
<span id="{{id}}" class="list-group-item">
<i class="wr-sortable-icon fw fw-sort hide"></i>
<i class="wr-list-icon fw fw-user"></i>
<div class="wr-list-desc">
<h3 class="wr-list-name">{{policyName}}</h3>
<span class="wr-list-username">{{policyName}}</span>
</div>
<span class="list-group-item-actions">
<!--a href="#" class="invite-user-link cu-btn-inner" data-policyname="{{policyName}}">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-invitation fw-stack-1x"></i>
</span>
Invite
</a-->
<a href="#" class="remove-user-link cu-btn-inner" data-policyname="{{policyName}}">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-delete fw-stack-1x"></i>
</span>
Remove
</a>
</span>
<div class="clearfix"></div>
</span>
{{/each}}
{{else}}
<!-- no policies found -->
<div class="container-fluid wr-content-alt">
<div class="ctrl-info-panel col-md-6 col-centered">
<h2>You don't have any Policies added at the moment.</h2>
<p>
</a><a href="/iotserver/policies/add-policy" class="cu-btn">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i>
</span>
Add New Policy
</a>
</p>
</div>
</div>
<!-- /no policies found -->
{{/if}}
</div>
</div>
<!-- /content -->
</div>
</div>
{{/zone}}
{{#zone "common-navigation"}}
<!--Later add the navigation menu from here-->
{{/zone}}
{{#zone "action-bar"}}
{{#if permissions.ADD_POLICY}}
<a href="/iotserver/policies/add-policy" class="cu-btn">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-add-user fw-stack-1x"></i>
</span>
Add Policy
</a>
{{/if}}
{{/zone}}
{{#zone "bottomJs"}}
<script src="{{self.publicURL}}/js/policy-listing.js"></script>
{{/zone}}

@ -0,0 +1,18 @@
function onRequest(context) {
// var log = new Log("policy-listing");
var policyModule = require("/modules/policy.js").policyModule;
var allPolicies = policyModule.getPolicies();
if (!allPolicies || allPolicies.length == 0) {
context.policies = [];
context.listPolicyStatus = "Oops, Sorry, No other Policies found.";
} else {
var i, filteredPoliciesList = [];
for (i = 0; i < allPolicies.length; i++) {
filteredPoliciesList.push(allPolicies[i]);
}
context.policies = filteredPoliciesList;
context.listPolicyStatus = "Total number of Policies found : " + filteredPoliciesList.length;
}
//context.permissions = policyModule.getUIPermissions();
return context;
}

@ -0,0 +1,131 @@
/**
* Sorting function of users
* listed on User Management page in WSO2 MDM Console.
*/
$(function () {
var sortableElem = '.wr-sortable';
$(sortableElem).sortable({
beforeStop : function () {
var sortedIDs = $(this).sortable('toArray');
console.log(sortedIDs);
}
});
$(sortableElem).disableSelection();
});
var modalPopup = ".wr-modalpopup";
var modalPopupContainer = modalPopup + " .modalpopup-container";
var modalPopupContent = modalPopup + " .modalpopup-content";
var body = "body";
/*
* set popup maximum height function.
*/
function setPopupMaxHeight() {
$(modalPopupContent).css('max-height', ($(body).height() - ($(body).height()/100 * 30)));
$(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height()/2)));
}
/*
* show popup function.
*/
function showPopup() {
$(modalPopup).show();
setPopupMaxHeight();
}
/*
* hide popup function.
*/
function hidePopup() {
$(modalPopupContent).html('');
$(modalPopup).hide();
}
/**
* Following click function would execute
* when a user clicks on "Invite" link
* on User Management page in WSO2 MDM Console.
*/
$("a.invite-user-link").click(function () {
var username = $(this).data("username");
var inviteUserAPI = "/iotserver/api/users/" + username + "/invite";
$(modalPopupContent).html($('#invite-user-modal-content').html());
showPopup();
$("a#invite-user-yes-link").click(function () {
invokerUtil.get(
inviteUserAPI,
function () {
$(modalPopupContent).html($('#invite-user-success-content').html());
$("a#invite-user-success-link").click(function () {
hidePopup();
});
},
function () {
$(modalPopupContent).html($('#invite-user-error-content').html());
$("a#invite-user-error-link").click(function () {
hidePopup();
});
}
);
});
$("a#invite-user-cancel-link").click(function () {
hidePopup();
});
});
/**
* Following click function would execute
* when a user clicks on "Remove" link
* on User Management page in WSO2 MDM Console.
*/
$("a.remove-user-link").click(function () {
var username = $(this).data("username");
var removeUserAPI = "/iotserver/api/users/" + username + "/remove";
$(modalPopupContent).html($('#remove-user-modal-content').html());
showPopup();
$("a#remove-user-yes-link").click(function () {
invokerUtil.get(
removeUserAPI,
function (data) {
if (data == 200) {
$("#" + username).addClass("hide");
$(modalPopupContent).html($('#remove-user-200-content').html());
$("a#remove-user-200-link").click(function () {
hidePopup();
});
} else if (data == 400) {
$(modalPopupContent).html($('#remove-user-400-content').html());
$("a#remove-user-400-link").click(function () {
hidePopup();
});
} else if (data == 403) {
$(modalPopupContent).html($('#remove-user-403-content').html());
$("a#remove-user-403-link").click(function () {
hidePopup();
});
} else if (data == 409) {
$(modalPopupContent).html($('#remove-user-409-content').html());
$("a#remove-user-409-link").click(function () {
hidePopup();
});
}
},
function () {
$(modalPopupContent).html($('#remove-user-unexpected-error-content').html());
$("a#remove-user-unexpected-error-link").click(function () {
hidePopup();
});
}
);
});
$("a#remove-user-cancel-link").click(function () {
hidePopup();
});
});

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

Loading…
Cancel
Save