merged with upstream

application-manager-new
ayyoob 9 years ago
commit e6d9cb82af

@ -249,11 +249,6 @@
<mkdir dir="target/wso2carbon-core-${carbon.kernel.version}/repository/components/lib"/>
<copy todir="target/wso2carbon-core-${carbon.kernel.version}/repository/deployment/server/jaggeryapps"
overwrite="true">
<fileset dir="src/repository/jaggeryapps"/>
</copy>
<!--Copy samples to distribution-->
<copy todir="target/wso2carbon-core-${carbon.kernel.version}/samples"
overwrite="true">
@ -307,76 +302,76 @@
</execution>
<!--Install default samples-->
<!--<execution>-->
<!--<id>install_samples</id>-->
<!--<phase>package</phase>-->
<!--<configuration>-->
<!--<tasks>-->
<!--<mkdir dir="target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/iot"/>-->
<!--<copy todir="target/wso2carbon-core-${carbon.kernel.version}/repository/conf/iot"-->
<!--overwrite="true">-->
<!--<fileset-->
<!--file="../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/iot-config.xml"/>-->
<!--</copy>-->
<!--<subant target="deploy">-->
<!--<fileset-->
<!--dir="target/wso2carbon-core-${carbon.kernel.version}/samples/arduino"-->
<!--includes="build.xml"/>-->
<!--</subant>-->
<!--<subant target="deploy">-->
<!--<fileset-->
<!--dir="target/wso2carbon-core-${carbon.kernel.version}/samples/raspberrypi"-->
<!--includes="build.xml"/>-->
<!--</subant>-->
<!--<copy todir="../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/"-->
<!--overwrite="true">-->
<!--<fileset-->
<!--file="target/wso2carbon-core-${carbon.kernel.version}/repository/conf/iot/iot-config.xml"/>-->
<!--</copy>-->
<!--<move file="target/wso2carbon-core-${carbon.kernel.version}/samples/arduino/build.xml"-->
<!--toFile="target/wso2carbon-core-${carbon.kernel.version}/samples/arduino/build.xml.disable"/>-->
<!--<move file="target/wso2carbon-core-${carbon.kernel.version}/samples/raspberrypi/build.xml"-->
<!--toFile="target/wso2carbon-core-${carbon.kernel.version}/samples/raspberrypi/build.xml.disable"/>-->
<!--<move file="target/wso2carbon-core-${carbon.kernel.version}/samples/sample_pom.xml"-->
<!--toFile="target/wso2carbon-core-${carbon.kernel.version}/samples/pom.xml"-->
<!--overwrite="true"/>-->
<!--</tasks>-->
<!--</configuration>-->
<!--<goals>-->
<!--<goal>run</goal>-->
<!--</goals>-->
<!--</execution>-->
<execution>
<id>install_samples</id>
<phase>package</phase>
<configuration>
<tasks>
<mkdir dir="target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/iot"/>
<copy todir="target/wso2carbon-core-${carbon.kernel.version}/repository/conf/iot"
overwrite="true">
<fileset
file="../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/iot-config.xml"/>
</copy>
<subant target="deploy">
<fileset
dir="target/wso2carbon-core-${carbon.kernel.version}/samples/arduino"
includes="build.xml"/>
</subant>
<subant target="deploy">
<fileset
dir="target/wso2carbon-core-${carbon.kernel.version}/samples/raspberrypi"
includes="build.xml"/>
</subant>
<copy todir="../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/"
overwrite="true">
<fileset
file="target/wso2carbon-core-${carbon.kernel.version}/repository/conf/iot/iot-config.xml"/>
</copy>
<move file="target/wso2carbon-core-${carbon.kernel.version}/samples/arduino/build.xml"
toFile="target/wso2carbon-core-${carbon.kernel.version}/samples/arduino/build.xml.disable"/>
<move file="target/wso2carbon-core-${carbon.kernel.version}/samples/raspberrypi/build.xml"
toFile="target/wso2carbon-core-${carbon.kernel.version}/samples/raspberrypi/build.xml.disable"/>
<move file="target/wso2carbon-core-${carbon.kernel.version}/samples/sample_pom.xml"
toFile="target/wso2carbon-core-${carbon.kernel.version}/samples/pom.xml"
overwrite="true"/>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
<execution>
<id>clean_target</id>
<phase>install</phase>
<configuration>
<!--<tasks>-->
<!--<delete dir="target/jars"/>-->
<!--<delete dir="target/*.xml"/>-->
<!--<delete dir="target/archive-tmp"/>-->
<!--<delete dir="target/dependency-maven-plugin-markers"/>-->
<!--<delete dir="target/maven-archiver"/>-->
<!--<delete dir="target/wso2carbon-core-${carbon.kernel.version}"/>-->
<!--<delete file="target/wso2iot-${project.version}.jar"/>-->
<!--<delete dir="target/sources"/>-->
<!--<delete dir="target/site"/>-->
<!--<delete dir="target/antrun"/>-->
<!--<delete dir="src/site"/>-->
<!--&lt;!&ndash;<delete dir="target/shindig" />&ndash;&gt;-->
<!--<delete dir="target/jaxwebapps"/>-->
<!--</tasks>-->
<tasks>
<delete dir="target/jars"/>
<delete dir="target/*.xml"/>
<delete dir="target/archive-tmp"/>
<delete dir="target/dependency-maven-plugin-markers"/>
<delete dir="target/maven-archiver"/>
<delete dir="target/wso2carbon-core-${carbon.platform.version}"/>
<delete dir="target/wso2carbon-core-${carbon.kernel.version}"/>
<delete file="target/wso2iot-${project.version}.jar"/>
<delete dir="target/sources"/>
<delete dir="target/site"/>
<delete dir="target/antrun"/>
<delete dir="src/site"/>
&lt;!&ndash;<delete dir="target/shindig" />&ndash;&gt;
<delete dir="target/jaxwebapps"/>
</tasks>
<!-- <tasks>-->
<!-- <delete dir="target/archive-tmp"/>-->
<!-- <delete dir="target/dependency-maven-plugin-markers"/>-->
<!-- <delete dir="target/maven-archiver"/>-->
<!-- <delete dir="target/wso2carbon-core-${carbon.platform.version}"/>-->
<!-- <delete dir="target/sources"/>-->
<!-- <delete dir="target/site"/>-->
<!-- <delete dir="src/site"/>-->
<!-- </tasks>-->
</configuration>
<goals>
<goal>run</goal>

@ -330,9 +330,6 @@
</directory>
<outputDirectory>${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/
</outputDirectory>
<excludes>
<exclude>store/extensions/app/store-device/*</exclude>
</excludes>
</fileSet>
<!--============ Added with ES Features ===============-->
@ -786,6 +783,7 @@
</file>
<!--Webapp Authenticator Config file-->
<file>
<source>

@ -19,7 +19,7 @@
"enabled": false
}
},
"assets":["gadget","site", "device"],
"assets":["gadget","site", "deviceType"],
"disabledAssets":[],
"userRoles": ["Internal/publisher"],
"permissions": {
@ -30,7 +30,7 @@
"userSpace": "/_system/governance/users",
"accessible": [{
"context": "/_system/governance",
"collections": ["gadgets", "sites", "ebooks", "devices"],
"collections": ["gadgets", "sites", "ebooks", "deviceTypes"],
"actions": ["http://www.wso2.org/projects/registry/actions/get", "http://www.wso2.org/projects/registry/actions/add", "http://www.wso2.org/projects/registry/actions/delete", "authorize"]
}],
"app": {
@ -59,7 +59,7 @@
}, {
"type": "sites"
}, {
"type": "devices"
"type": "deviceTypes"
}]
},
"router": {

@ -1,238 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/device-api.jag");
var constants = require("/modules/constants.js");
var dcProps = require('/config/dc-props.js').config();
var deviceModule = require("/modules/device.js").deviceModule;
var carbon = require('carbon');
var carbonHttpServletTransport = carbon.server.address('http');
var carbonHttpsServletTransport = carbon.server.address('https');
var result;
if (uriMatcher.match("/{context}/api/device/sketch/download/{downloadId}")) {
downloadId = uriMatcher.elements().downloadId;
//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) {
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) {
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 = "curl -k " + carbonHttpsServletTransport + constants.WEB_APP_CONTEXT + "/api/device/sketch/download/" + fileId.data;
}
}
} else if (uriMatcher.match("/{context}/api/devices/all")) {
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
response.sendRedirect(dcProps.appContext + "login?#login-required");
exit();//stop execution
}
//URL: https://localhost:9443/devicecloud/manager/devices/username/{username}
deviceCloudService = carbonHttpsServletTransport + "/common/device_manager";
listAllDevicesEndPoint = deviceCloudService + "/devices/username/" + user.username;
result = get(listAllDevicesEndPoint, {}, "json");
var ownDevices = result.data;
var allDevices = [];
deviceCloudService = carbonHttpsServletTransport + "/common/group_manager";
var endPoint = deviceCloudService + "/group/user/" + user.username + "/all";
var data = {"username": user.username};
var groups = get(endPoint, data, "json").data;
for (var g in groups) {
endPoint = deviceCloudService + "/group/id/" + groups[g].id + "/device/all";
data = {"username": user.username};
var deviceInGroup = get(endPoint, data, "json").data;
groups[g].devices = deviceInGroup;
allDevices.push(groups[g]);
for (var od in ownDevices) {
for (var gd in deviceInGroup) {
if (deviceInGroup[gd].deviceIdentifier == ownDevices[od].deviceIdentifier) {
ownDevices[od].deviceIdentifier = -1;
}
}
}
}
var unsharedDevices = [];
for (var od in ownDevices) {
if (ownDevices[od].deviceIdentifier != -1){
unsharedDevices.push(ownDevices[od]);
}
}
allDevices.push({id: 0, devices: unsharedDevices});
result.data = allDevices;
} else if (uriMatcher.match("/{context}/api/devices/count")) {
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
response.sendRedirect(dcProps.appContext + "login?#login-required");
exit();//stop execution
}
//URL: https://localhost:9443/devicecloud/manager/devices/username/{username}
deviceCloudService = carbonHttpsServletTransport + "/common/device_manager";
listAllDevicesEndPoint = deviceCloudService + "/devices/username/" + user.username;
result = get(listAllDevicesEndPoint, {}, "json");
var ownDevices = result.data;
var allDevices = [];
deviceCloudService = carbonHttpsServletTransport + "/common/group_manager";
var endPoint = deviceCloudService + "/group/user/" + user.username + "/all";
var data = {"username": user.username};
var groups = get(endPoint, data, "json").data;
var count = 0;
for (var g in groups) {
endPoint = deviceCloudService + "/group/id/" + groups[g].id + "/device/all";
data = {"username": user.username};
var deviceInGroup = get(endPoint, data, "json").data;
groups[g].devices = deviceInGroup;
allDevices.push(groups[g]);
for (var od in ownDevices) {
for (var gd in deviceInGroup) {
if (deviceInGroup[gd].deviceIdentifier == ownDevices[od].deviceIdentifier) {
ownDevices[od].deviceIdentifier = -1;
}
}
}
count += deviceInGroup.length;
}
for (var od in ownDevices) {
if (ownDevices[od].deviceIdentifier != -1){
count++;
}
}
result = count.toString();
} else if (uriMatcher.match("/{context}/api/devices/types")) {
result = deviceModule.listDeviceTypes();
} else if (uriMatcher.match("/{context}/api/device/{deviceType}/{deviceId}/remove")) {
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
response.sendRedirect(dcProps.appContext + "login?#login-required");
exit();//stop execution
}
var elements = uriMatcher.elements();
var deviceId = elements.deviceId;
var deviceType = elements.deviceType;
result = deviceModule.removeDevice(deviceType, deviceId);
} else if (uriMatcher.match("/{context}/api/device/{deviceType}/{deviceId}/update")) {
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
response.sendRedirect(dcProps.appContext + "login?#login-required");
exit();//stop execution
}
var elements = uriMatcher.elements();
var deviceId = elements.deviceId;
var deviceType = elements.deviceType;
var cont = request.getContent();
if (!cont.device) {
// http status code 400 refers to - Bad request.
result = 400;
} else {
result = deviceModule.updateDevice(deviceType, deviceId, cont.device);
}
}
// returning the result.
if (result) {
print(result);
}
%>

@ -1,45 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/event-api.jag");
var constants = require("/modules/constants.js");
var dcProps = require('/config/dc-props.js').config();
var eventModule = require("/modules/event.js").eventModule;
var result;
if (uriMatcher.match("/{context}/api/event/list")) {
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
response.sendRedirect(dcProps.appContext + "login?#login-required");
exit();//stop execution
}
result = eventModule.getEventsData(user.username, 10);
}
// returning the result.
if (result) {
print(result);
}
%>

@ -1,256 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/group-api.jag");
var constants = require("/modules/constants.js");
var dcProps = require('/config/dc-props.js').config();
var carbon = require('carbon');
var carbonHttpsServletTransport = carbon.server.address('https');
var deviceCloudService = carbonHttpsServletTransport + "/common/group_manager";
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
response.sendRedirect(dcProps.appContext + "login?#login-required");
exit();//stop execution
}
var result;
var endPoint;
var data;
var groupId;
if (uriMatcher.match("/{context}/api/group/add")) {
var group = request.getContent();
var name = group["name"];
var description = group["description"];
//URL: POST https://localhost:9443/devicecloud/group_manager/group
endPoint = deviceCloudService + "/group";
data = {"name": name, "username": user.username, "description": description};
result = post(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/update")) {
groupId = uriMatcher.elements().groupId;
group = request.getContent();
name = group["name"];
description = group["description"];
//URL: PUT https://localhost:9443/devicecloud/group_manager/group/id/{groupId}
endPoint = deviceCloudService + "/group/id/" + groupId;
data = {"name": name, "username": user.username, "description": description};
result = put(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/remove")) {
groupId = uriMatcher.elements().groupId;
//URL: DELETE https://localhost:9443/devicecloud/group_manager/group/id/{groupId}
endPoint = deviceCloudService + "/group/id/" + groupId + "?username=" + user.username;
result = del(endPoint, {}, "json");
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}")) {
groupId = uriMatcher.elements().groupId;
//URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}
endPoint = deviceCloudService + "/group/id/" + groupId;
data = {"username": user.username};
result = get(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/name/{groupName}")) {
//URL: GET https://localhost:9443/devicecloud/group_manager/group/name/{name}
endPoint = deviceCloudService + "/group/name/" + uriMatcher.elements().groupName;
data = {"username": user.username};
result = get(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/all")) {
//URL: GET https://localhost:9443/devicecloud/group_manager/group/all
endPoint = deviceCloudService + "/group/user/" + user.username + "/all";
data = {"username": user.username};
result = get(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/all/count")) {
//URL: GET https://localhost:9443/devicecloud/group_manager/group/all/count
endPoint = deviceCloudService + "/group/user/" + user.username + "/all/count";
data = {"username": user.username};
result = get(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/share")) {
groupId = uriMatcher.elements().groupId;
var shareUser = request.getContent()["shareUser"];
role = request.getContent()["role"];
//URL: PUT https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/share
endPoint = deviceCloudService + "/group/id/" + groupId + "/share";
data = {"username": user.username, "shareUser": shareUser, "role": role};
result = post(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/unshare")) {
groupId = uriMatcher.elements().groupId;
var unShareUser = request.getContent()["unShareUser"];
role = request.getContent()["role"];
//URL: DELETE https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/unshare
endPoint = deviceCloudService + "/group/id/" + groupId + "/unshare";
data = {"username": user.username, "unShareUser": unShareUser, "role": role};
result = post(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/role/add")) {
groupId = uriMatcher.elements().groupId;
var permissions = request.getContent()["permissions"];
role = request.getContent()["role"];
//URL: POST https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/role
endPoint = deviceCloudService + "/group/id/" + groupId + "/role";
data = {"username": user.username, "permissions": permissions, "role": role};
result = post(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/role/delete")) {
groupId = uriMatcher.elements().groupId;
role = request.getContent()["role"];
//URL: DELETE https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/role
endPoint = deviceCloudService + "/group/id/" + groupId + "/role/" + role;
result = del(endPoint, {}, "json");
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/role/all")) {
groupId = uriMatcher.elements().groupId;
//URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/role/all
endPoint = deviceCloudService + "/group/id/" + groupId + "/role/all";
data = {"username": user.username};
result = get(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/{userId}/role/all")) {
groupId = uriMatcher.elements().groupId;
var userId = uriMatcher.elements().userId;
//URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/{user}/role/all
endPoint = deviceCloudService + "/group/id/" + groupId + "/" + userId + "/role/all";
data = {"username": user.username};
result = get(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/{userId}/rolemapping")) {
groupId = uriMatcher.elements().groupId;
userId = uriMatcher.elements().userId;
data = {"username": user.username};
//URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/role/all
endPoint = deviceCloudService + "/group/id/" + groupId + "/role/all";
var allRoles = get(endPoint, data, "json").data;
//URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/{user}/role/all
endPoint = deviceCloudService + "/group/id/" + groupId + "/" + userId + "/role/all";
var userRolesObj = get(endPoint, data, "json");
var userRoles = userRolesObj.data;
var roleMap = [];
for (var role in allRoles) {
var objRole = {"role": allRoles[role], "assigned": false};
for (var usrRole in userRoles) {
if (allRoles[role] == userRoles[usrRole]) {
objRole.assigned = true;
break;
}
}
roleMap.push(objRole);
}
result = {};
result.data = roleMap;
result.xhr = userRolesObj.xhr;
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/{userId}/roleupdate")) {
groupId = uriMatcher.elements().groupId;
userId = uriMatcher.elements().userId;
roleMap = request.getContent();
for (role in roleMap) {
if (roleMap[role].assigned == true) {
//URL: POST https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/share
endPoint = deviceCloudService + "/group/id/" + groupId + "/share";
data = {"username": user.username, "shareUser": userId, "role": roleMap[role].role};
result = post(endPoint, data, "json");
} else {
//URL: DELETE https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/unshare
endPoint = deviceCloudService + "/group/id/" + groupId + "/unshare";
data = {"username": user.username, "unShareUser": userId, "role": roleMap[role].role};
result = post(endPoint, data, "json");
}
}
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/user/all")) {
groupId = uriMatcher.elements().groupId;
//URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/user/all
endPoint = deviceCloudService + "/group/id/" + groupId + "/user/all";
data = {"username": user.username};
result = get(endPoint, data, "json");
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/device/all")) {
groupId = uriMatcher.elements().groupId;
//URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}
endPoint = deviceCloudService + "/group/id/" + groupId;
data = {"username": user.username};
var group = get(endPoint, data, "json").data;
//URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/device/all
endPoint = deviceCloudService + "/group/id/" + groupId + "/device/all";
data = {"username": user.username};
result = get(endPoint, data, "json");
group.devices = result.data;
result.data = {group: group}
} else if (uriMatcher.match("/{context}/api/group/id/{groupId}/assign")) {
groupId = uriMatcher.elements().groupId;
var deviceId = request.getContent()["deviceId"];
var deviceType = request.getContent()["deviceType"];
//URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/device/assign
endPoint = deviceCloudService + "/group/id/" + groupId + "/device/assign";
data = {"username": user.username, "deviceId": deviceId, "deviceType": deviceType};
result = put(endPoint, data, "json");
}
// returning the result.
if (result) {
response.status = result.xhr.status;
print(result.data);
}
%>

@ -1,31 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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);
}
%>

@ -1,69 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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/add")) {
var content = request.getContent();
var policyName = content.policyName;
var policyDefinition = content.profile.policyDefinition;
var policyDescription = content.profile.policyDescription;
var deviceType = content.profile.deviceType.name;
log.info("@@@@@ Policy Declaration : " + stringify(content));
try {
result = policyModule.addPolicy(policyName, deviceType, policyDefinition, policyDescription);
} catch (e) {
log.error("Exception occurred while trying to add new policy under name:" + id, e);
// http status code 500 refers to - Internal Server Error.
result = 500;
}
} else if (uriMatcher.match("/{context}/api/policies/{deviceType}/{policyName}/remove")) {
elements = uriMatcher.elements();
var id = elements.policyName;
var deviceType = elements.deviceType;
try {
result = policyModule.removePolicy(id, deviceType);
} catch (e) {
log.error("Exception occurred while trying to remove policy under name:" + id, e);
// http status code 500 refers to - Internal Server Error.
result = 500;
}
} else if (uriMatcher.match("/{context}/api/policies/count")) {
result = policyModule.getPolicies().length.toString();
}
// returning the result.
if (result) {
response.content = result;
}
%>

@ -1,245 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/stats-api.jag");
var constants = require("/modules/constants.js");
var dcProps = require('/config/dc-props.js').config();
var utility = require("/modules/utility.js").utility;
var deviceModule = require("/modules/device.js").deviceModule;
var from = request.getParameter("from");
var to = request.getParameter("to");
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
response.sendRedirect(dcProps.appContext + "login?#login-required");
exit();
}
var carbon = require('carbon');
var carbonHttpsServletTransport = carbon.server.address('https');
var deviceCloudService = carbonHttpsServletTransport + "/common/group_manager";
var statsClient = new Packages.org.wso2.carbon.device.mgt.iot.common.analytics.statistics.IoTUsageStatisticsClient;
var stats = {};
var deviceId;
var deviceType;
if (uriMatcher.match("/{context}/api/stats")) {
deviceId = request.getParameter("deviceId");
deviceType = request.getParameter("deviceType");
getDeviceData(deviceType, deviceId);
}else if (uriMatcher.match("/{context}/api/stats/group")){
var groupId = request.getParameter("groupId");
//URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/device/all
var endPoint = deviceCloudService + "/group/id/" + groupId + "/device/all";
var data = {"username": user.username};
var devices = get(endPoint, data, "json");
for (var device in devices.data){
deviceId = devices.data[device].deviceIdentifier;
deviceType = devices.data[device].type;
getDeviceData(deviceType, deviceId);
}
}
// returning the result.
if (stats) {
print(stats);
}
function getDeviceData(deviceType, deviceId){
var device = deviceModule.getDevice(deviceType, deviceId);
var uname = device.enrolmentInfo.owner;
if (!device){
return;
}
switch (deviceType) {
case "firealarm":
getFireAlarmData(uname, device, from, to);
break;
case "sensebot":
getSensebotData(uname, device, from, to);
break;
case "arduino":
getArduinoData(uname, device, from, to);
break;
case "digital_display":
getDigitalDisplayData(uname, device, from, to);
break;
case "android_sense":
getAndroidSenseData(uname, device, from, to);
break;
case "raspberrypi":
getDigitalDisplayData(uname, device, from, to);
break;
}
}
function getFireAlarmData(user, device, from, to) {
if (stats['temperatureData'] == null){
stats['temperatureData'] = [];
}
if (stats['sonarData'] == null){
stats['sonarData'] = [];
}
if (stats['motionData'] == null){
stats['motionData'] = [];
}
if (stats['lightData'] == null){
stats['lightData'] = [];
}
stats['temperatureData'].push({"device": device.name, "stats" : getSensorData("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, device.deviceIdentifier, from, to)});
stats['sonarData'].push({"device": device.name, "stats" : getSensorData("SONAR_SENSOR_SUMMARY", "sonar", user, device.deviceIdentifier, from, to)});
stats['motionData'].push({"device": device.name, "stats" : getSensorData("PIR_MOTION_SENSOR_SUMMARY", "motion", user, device.deviceIdentifier, from, to)});
stats['lightData'].push({"device": device.name, "stats" : getSensorData("LDR_LIGHT_SENSOR_SUMMARY", "light", user, device.deviceIdentifier, from, to)});
}
function getSensebotData(user, device, from, to) {
if (stats['sonarData'] == null){
stats['sonarData'] = [];
}
if (stats['motionData'] == null){
stats['motionData'] = [];
}
if (stats['lightData'] == null){
stats['lightData'] = [];
}
if (stats['temperatureData'] == null){
stats['temperatureData'] = [];
}
//Uncomment below section to emulate data
/*
var timeInterval = 30;
var i, rnd, chartData;
chartData = [];
var i = parseInt(from);
while (i < parseInt(to)) {
rnd = rnd = Math.random() * 50;
chartData.push({time: i, value: rnd});
i += timeInterval;
}
stats['sonarData'].push({"device": device.name, "stats" : chartData});
chartData = [];
var i = parseInt(from);
while (i < parseInt(to)) {
rnd = Math.round(Math.random());
chartData.push({time: i, value: rnd});
i += timeInterval;
}
stats['motionData'].push({"device": device.name, "stats" : chartData});
chartData = [];
var i = parseInt(from);
while (i < parseInt(to)) {
rnd = Math.round(Math.random());
chartData.push({time: i, value: rnd});
i += timeInterval;
}
stats['lightData'].push({"device": device.name, "stats" : chartData});
chartData = [];
var i = parseInt(from);
while (i < parseInt(to)) {
rnd = Math.random() * (27 - 24) + 24;
chartData.push({time: i, value: rnd});
i += timeInterval;
}
stats['temperatureData'].push({"device": device.name, "stats" : chartData});
*/
//Comment below section to emulate data
stats['sonarData'].push({"device": device.name, "stats" : getSensorData("SONAR_SENSOR_SUMMARY", "sonar", user, device.deviceIdentifier, from, to)});
stats['motionData'].push({"device": device.name, "stats" : getSensorData("PIR_MOTION_SENSOR_SUMMARY", "motion", user, device.deviceIdentifier, from, to)});
stats['lightData'].push({"device": device.name, "stats" : getSensorData("LDR_LIGHT_SENSOR_SUMMARY", "light", user, device.deviceIdentifier, from, to)});
stats['temperatureData'].push({"device": device.name, "stats" : getSensorData("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, device.deviceIdentifier, from, to)});
}
function getArduinoData(user, device, from, to) {
if (stats['temperatureData'] == null){
stats['temperatureData'] = [];
}
stats['temperatureData'].push({"device": device.name, "stats" : getSensorData("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, device.deviceIdentifier, from, to)});
}
function getAndroidSenseData(user, device, from, to) {
if (stats['ramData'] == null){
stats['ramData'] = [];
}
if (stats['cpuData'] == null){
stats['cpuData'] = [];
}
if (stats['temperatureData'] == null){
stats['temperatureData'] = [];
}
if (stats['motionData'] == null){
stats['motionData'] = [];
}
stats['ramData'].push({"device": device.name, "stats" : getSensorData("RAM_USAGE_SUMMARY", "motion", user, device.deviceIdentifier, from, to)});
stats['cpuData'].push({"device": device.name, "stats" : getSensorData("CPU_LOAD_SUMMARY", "light", user, device.deviceIdentifier, from, to)});
stats['temperatureData'].push({"device": device.name, "stats" : getSensorData("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, device.deviceIdentifier, from, to)});
stats['motionData'].push({"device": device.name, "stats" : getSensorData("PIR_MOTION_SENSOR_SUMMARY", "motion", user, device.deviceIdentifier, from, to)});
}
function getDigitalDisplayData(user, device, from, to) {
if (stats['ramData'] == null){
stats['ramData'] = [];
}
if (stats['cpuData'] == null){
stats['cpuData'] = [];
}
if (stats['cpuTemperatureData'] == null){
stats['cpuTemperatureData'] = [];
}
stats['ramData'].push({"device": device.name, "stats" : getSensorData("RAM_USAGE_SUMMARY", "motion", user, device.deviceIdentifier, from, to)});
stats['cpuData'].push({"device": device.name, "stats" : getSensorData("CPU_LOAD_SUMMARY", "light", user, device.deviceIdentifier, from, to)});
stats['cpuTemperatureData'].push({"device": device.name, "stats" : getSensorData("DEVICE_CPU_TEMPERATURE_SUMMARY", "TEMPERATURE", user, device.deviceIdentifier, from, to)});
}
function getSensorData(table, column, user, deviceIdentifier, from, to) {
var fetchedData = null;
try {
fetchedData = statsClient.getDeviceStats(table, column, user, deviceIdentifier, from, to);
} catch (error) {
log.error(error);
}
var sensorData = [];
if (fetchedData == null) return [];
for (var i = 0; i < fetchedData.size(); i++) {
sensorData.push({
time: fetchedData.get(i).getTime(),
value: fetchedData.get(i).getValue()
});
}
return sensorData;
}
%>

@ -1,145 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/user-api.jag");
var constants = require("/modules/constants.js");
var dcProps = require('/config/dc-props.js').config();
var userModule = require("/modules/user.js").userModule;
var deviceModule = require("/modules/device.js").deviceModule;
var utility = require("/modules/utility.js").utility;
var deviceManagementService = utility.getDeviceManagementService();
var result;
if (uriMatcher.match("/{context}/api/user/login/")) {
var username = request.getParameter("username");
var password = request.getParameter("password");
try {
userModule.login(username, password, function (user) {
utility.insertAppPermissions(userModule, "login");
if (log.isDebugEnabled()) {
log.debug("User Logged In : " + user);
}
response.sendRedirect(constants.WEB_APP_CONTEXT+"/dashboard");
}, function () {
response.sendRedirect(dcProps.appContext + "login?#auth-failed");
});
} catch (e) {
log.error("Exception occurred while a user tried to login to DC", e);
response.sendRedirect(dcProps.appContext + "login?#error");
}
} else if (uriMatcher.match("/{context}/api/user/logout/")) {
userModule.logout(function () {
response.sendRedirect(dcProps.appContext + "login");
});
} else if (uriMatcher.match("/{context}/api/users/register")) {
addUserFormData = request.getContent();
username = addUserFormData.username;
firstname = addUserFormData.firstname;
lastname = addUserFormData.lastname;
emailAddress = addUserFormData.emailAddress;
password = addUserFormData.password;
if (!addUserFormData.userRoles) {
userRoles = null;
} else {
userRoles = String(addUserFormData.userRoles).split(",");
}
userRoles="deviceRole,deviceUser".split(",");
try {
result = userModule.registerUser(username, firstname, lastname, emailAddress, password,
userRoles);
} catch (e) {
log.error("Exception occurred while trying to registering a new user to DC User Store", e);
// http status code 400 refers to - Bad request.
result = 400;
}
} else if (uriMatcher.match("/{context}/api/users/add")) {
if (userModule.isAuthorized("/permission/device-mgt/admin/users/add")) {
addUserFormData = request.getContent();
username = addUserFormData.username;
firstname = addUserFormData.firstname;
lastname = addUserFormData.lastname;
emailAddress = addUserFormData.emailAddress;
if (!addUserFormData.userRoles) {
userRoles = null;
} else {
userRoles = String(addUserFormData.userRoles).split(",");
}
try {
result = userModule.addUser(username, firstname, lastname, emailAddress, userRoles);
} catch (e) {
log.error("Exception occurred while trying to add a user to DC User Store", e);
// http status code 400 refers to - Bad request.
result = 400;
}
} else {
// http status code 403 refers to - forbidden.
result = 403;
}
} else if (uriMatcher.match("/{context}/api/users/{username}/remove")) {
if (userModule.isAuthorized("/permission/device-mgt/admin/users/remove")) {
elements = uriMatcher.elements();
username = elements.username;
try {
result = userModule.removeUser(username);
} catch (e) {
log.error("Exception occurred while trying to remove a user from DC User Store", e);
// http status code 400 refers to - Bad request.
result = 400;
}
} else {
// http status code 403 refers to - forbidden.
result = 403;
}
} else if (uriMatcher.match("/{context}/api/users")) {
result = userModule.getUsers();
} else if (uriMatcher.match("/{context}/api/users/count")) {
result = userModule.getUsers().length;
}
// returning the result.
if (result) {
print(result);
}
%>

@ -1,16 +0,0 @@
{
"appContext" : "/iotserver/",
"apiContext" : "api",
"httpsURL": "%https.ip%",
"httpURL": "%http.ip%",
"ssoConfiguration": {
"enabled": false,
"issuer": "iot",
"appName": "iot",
"identityProviderURL": "%https.ip%/sso/samlsso.jag",
"responseSigningEnabled": "true",
"keyStorePassword": "wso2carbon",
"identityAlias": "wso2carbon",
"keyStoreName": "/repository/resources/security/wso2carbon.jks"
}
}

@ -1,37 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var config = function () {
var conf = application.get("PINCH_CONFIG");
if (!conf) {//if not in cache
var pinch = require('/modules/pinch.min.js').pinch;
var server = require('carbon').server;
var config = require('/config/config.json');
pinch(config, /^/, function (path, key, value) {
if ((typeof value === 'string') && value.indexOf('%https.ip%') > -1) {
return value.replace('%https.ip%', server.address("https"));
} else if ((typeof value === 'string') && value.indexOf('%http.ip%') > -1) {
return value.replace('%http.ip%', server.address("http"));
}
return value;
});
application.put("PINCH_CONFIG", config);//caching
conf = config;
}
return conf;
};

@ -1,28 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var carbonModule = require("carbon");
var dcProps = require('/config/dc-props.js').config();
var carbonServer = new carbonModule.server.Server({
tenanted: true,
url: dcProps.httpsURL + '/admin'
});
application.put("carbonServer", carbonServer);
var userModule = require("/modules/user.js").userModule;
var utility = require("/modules/utility.js").utility;
utility.insertAppPermissions(userModule, "init");

@ -1,67 +0,0 @@
{
"displayName": "Fuse Sample",
"logLevel": "info",
"initScripts": ["/config/init.js"],
"urlMappings": [
{
"url" : "/testb/*",
"path" : "test.jag"
},
{
"url" : "/test/*",
"path" : "test/testExecutor.jag"
},
{
"url": "/api/device/*",
"path": "/api/device-api.jag"
},
{
"url": "/api/devices/*",
"path": "/api/device-api.jag"
},
{
"url": "/api/group/*",
"path": "/api/group-api.jag"
},
{
"url": "/api/event/*",
"path": "/api/event-api.jag"
},
{
"url": "/api/operation/*",
"path": "/api/operation-api.jag"
},
{
"url": "/api/user/*",
"path": "/api/user-api.jag"
},
{
"url": "/api/users/*",
"path": "/api/user-api.jag"
},
{
"url": "/api/stats/*",
"path": "/api/stats-api.jag"
},
{
"url": "/api/policies/*",
"path": "/api/policy-api.jag"
},
{
"url": "/sso/login",
"path": "/lib/login.jag"
},
{
"url": "/sso/logout",
"path": "/lib/logout.jag"
},
{
"url": "/sso/acs",
"path": "/lib/acs.jag"
},
{
"url": "/*",
"path": "/lib/fuse.jag"
}
]
}

@ -1,30 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
{{ defineZone "title"}}
</title>
{{ defineZone "topLibCss"}}
{{ defineZone "topCss"}}
</head>
<body>
<div class="container col-lg-12 col-md-12 col-sm-12">
<!-- header -->
<header>
<div class="row wr-global-header">
<div class="col-sm-8 app-logo">
{{ defineZone "brand"}}
</div>
</div>
</header>
<!-- /header -->
{{ defineZone "body"}}
{{ defineZone "footer"}}
</div>
{{ defineZone "bottomjquery" }}
{{ defineZone "bottomLibJs" }}
{{ defineZone "bottomJs" }}
</body>
</html>

@ -1,44 +0,0 @@
<!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,40 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="favicon.png" type="image/x-icon" />
{{defineZone "favicon"}}
<title>
{{ defineZone "title"}}
</title>
{{ defineZone "topLibCss"}}
{{ defineZone "topCss"}}
</head>
<body>
<div class="wr-modalpopup">
<div class="modalpopup-container">
<div class="modalpopup-close-btn" onclick="hidePopup();">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-left-arrow fw-stack-1x"></i>
</span>
GO BACK
</div>
<div class="modalpopup-content"><!-- dynamic content --></div>
</div>
<div class="modalpopup-bg"></div>
</div>
{{ defineZone "notification"}}
<div class="container col-lg-12 col-md-12 col-sm-12">
<!-- header -->
{{ defineZone "header"}}
<!-- /header -->
{{ defineZone "body"}}
{{ defineZone "footer"}}
</div>
{{ defineZone "bottomjquery" }}
{{ defineZone "bottomLibJs" }}
{{ defineZone "bottomJs" }}
</body>
</html>

@ -1,50 +0,0 @@
<!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">
<div class="col-sm-2">
{{ defineZone "left"}}
</div>
<div class="col-sm-10">
{{ defineZone "content"}}
</div>
</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,55 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var dataConfig = require('/config/dc-props.js').config();
var sso = require('/modules/sso.js').sso;
var constants = require('/modules/constants.js');
var carbonModule = require("carbon");
var log = new Log();
var apiWrapperUtil = require("/modules/api-wrapper-util.js").apiWrapperUtil;
var userModule = require("/modules/user.js").userModule;
var keyStoreParams = {
keyStoreName: dataConfig.ssoConfiguration.keyStoreName,
keyStorePassword: dataConfig.ssoConfiguration.keyStorePassword,
identityAlias: dataConfig.ssoConfiguration.identityAlias
};
sso.configure(dataConfig.ssoConfiguration.issuer,
dataConfig.ssoConfiguration.appName,
keyStoreParams, dataConfig.ssoConfiguration.identityProviderURL);
sso.acs(
function(loggedInUser, samlResponse) {
var carbonUser = carbonModule.server.tenantUser(loggedInUser);
session.put(constants.USER_SESSION_KEY, carbonUser);
var username = carbonUser.username;
if(log.isDebugEnabled()){
log.debug("User logged in: "+username);
}
var permissions = userModule.getUIPermissions();
if (permissions.DASHBOARD_VIEW){
apiWrapperUtil.setupAccessTokenPair("saml", samlResponse);
response.sendRedirect(dataConfig.appContext + "/device-mgt");
}
}, function() {
if(log.isDebugEnabled()){
log.debug("User logged out");
}
response.sendRedirect(dataConfig.appContext);
}
);
%>

@ -1,220 +0,0 @@
//public function declarations
var route;
(function () {
//public
/**
* front controller entity point. acts as the main function for every request.
*/
route = function () {
//lets assume URL looks like https://my.domain.com/app/{one}/{two}/{three}/{four}
var uri = request.getRequestURI(); // = app/{one}/{two}/{three}/{four}
var parts = splitFirst(uri);
fuseState.appName = parts.head;
var path = parts.tail; // = /{one}/{two}/{three}/{four}
var handled = false;
parts = splitFirst(path);
if (parts.head == 'public') { // {one} == 'public'
parts = splitFirst(parts.tail);
if (splitFirst(parts.tail).head == 'less') { // {three} == 'less'
handled = renderLess(parts.head, parts.tail); // renderLess({two},{three}/{four})
} else {
handled = renderStatic(parts.head, parts.tail);
}
} else {
handled = renderPage(path);
if (!handled) {
handled = renderUnit(path);
}
}
if (!handled) {
response.sendError(404, 'Requested resource not found');
}
};
//private
var log = new Log('fuse.router');
var getMime = function (path) {
var index = path.lastIndexOf('.') + 1;
var knowMime = {
'js': 'application/javascript',
'html': 'text/html',
'htm': 'text/html',
'woff': 'application/x-font-woff',
"png": "image/png",
"css": "text/css",
"hbs": "text/x-handlebars-template",
"apk": "application/vnd.android.package-archive",
"ipa": "application/octet-stream"
};
var mime;
if (index >= 0) {
mime = knowMime[path.substr(index)];
}
return mime || 'text/plain';
};
/**
* '/a/b/c/d' -> {'a','b/c/d'}
* @param path URI part, should start with '/'
* @returns {{head: string, tail: string}}
*/
var splitFirst = function (path) {
var firstSlashPos = path.indexOf('/', 1);
var head = path.substring(1, firstSlashPos);
var tail = path.substring(firstSlashPos);
return {head: head, tail: tail};
};
/**
* @param str
* @param prefix
* @returns {boolean} true iif str starts with prefix
*/
var startsWith = function (str, prefix) {
return (str.lastIndexOf(prefix, 0) === 0);
};
var renderStatic = function (unit, path) {
if (log.isDebugEnabled()) {
//log.debug('[' + requestId + '] for unit "' + unit + '" a request received for a static file "' + path + '"');
}
var staticFile = fuse.getFile(unit, 'public' + path);
if (staticFile.isExists() && !staticFile.isDirectory()) {
response.addHeader('Content-type', getMime(path));
response.addHeader('Cache-Control', 'public,max-age=12960000');
staticFile.open('r');
var stream = staticFile.getStream();
print(stream);
staticFile.close();
return true;
}
return false;
};
var renderPage = function (path) {
var jagFile;
if (path.indexOf('/', path.length - 1) !== -1) {
jagFile = new File('/pages' + path + 'index.jag');
} else {
jagFile = new File('/pages' + path + '.jag');
}
if (jagFile.isExists()) {
include(jagFile.getPath());
return true;
}else{
return false;
}
};
var renderUnit = function (path) {
var mainUnit = null;
var matchedUnits = fuse.getMatchedUnitDefinitions();
fuse.addDependencies(matchedUnits);
var zones = fuseState.zones;
// A map of maps. this is used to ensure same zone is not render twice in to same definition.
// zonesAdded = { titleZone : { zoneFromA : true, zoneFromB : true } }
var zonesAdded = {};
for (var i = 0; i < matchedUnits.length; i++) {
var definition = matchedUnits[i];
for (var j = 0; j < definition.zones.length; j++) {
var zone = definition.zones[j];
if (!zones[zone.name]) {
zones[zone.name] = [];
zonesAdded[zone.name] = {};
}
var zoneKey = zone.origin + ':' + zone.name; // temp unique key to identify zone form a given unit.
if (!zonesAdded[zone.name][zoneKey]) {
var zoneInfo = {unitName: definition.name};
if (zone.origin != definition.name) {
zoneInfo.originUnitName = zone.origin;
}
zones[zone.name].push(zoneInfo);
zonesAdded[zone.name][zoneKey] = true;
}
}
}
var layout = fuseState.layout;
if (layout !== null) {
if (log.isDebugEnabled()) {
log.debug(
//'[' + requestId + '] request for "' + path + '" will be rendered using layout "' +
//layout + '" (defined in "' + mainUnit + '") and zones ' +
//stringify(zones)
);
}
var output = handlebars.Handlebars.compileFile(fuse.getLayoutPath(layout))({});
response.addHeader('Content-type', 'text/html');
print(output);
return true;
} else {
if (log.isDebugEnabled()) {
//log.debug(
// '[' + requestId + '] request for "' + path + '" will can\'t be rendered, since no layout is defined' +
// 'in any of the units ' + stringify(zones));
}
return false;
}
};
function fileToString(path) {
}
/**
* convert less file to css and print to output. add '?nocache=true' to force regenerate.
* @param unit name of the unit
* @param path the path to the less file relative to unit root (should start with slash)
* @returns {boolean} is successfully rendered.
*/
function renderLess(unit, path) {
//TODO: fix - incorrect less files makes it respond the old less even if it is nocahce.
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, '_');
fuseState.currentUnit = unit;
var cachedCss = new File(cacheKey);
//TODO: move this check to caller function ??
if (fuseDebug || request.getParameter('nocache') == 'true' || !cachedCss.isExists()) {
var parts = splitFirst(path);
var lessPath = '/public/less' + parts.tail.replace(/\.css$/, '') + '.less';
var lessFile = fuse.getFile(unit, lessPath);
if (lessFile.isExists()) {
var x = require('less-rhino-1.7.5.js');
x.compile([lessFile.getPath(), cacheKey]);
if (log.isDebugEnabled()) {
//log.debug('[' + requestId + '] for unit "' + unit + '" request for "' + path + '" is cached as "' + cacheKey + '"');
}
}
}
if (cachedCss.isExists()) {
response.addHeader('Content-type', 'text/css');
response.addHeader('Cache-Control', 'public,max-age=12960000');
cachedCss.open('r');
var stream = cachedCss.getStream();
print(stream);
cachedCss.close();
return true;
}
return false;
}
})();

@ -1,35 +0,0 @@
<%
<!--var getPath = File.prototype.getPath;-->
<!--File.prototype.getPath = function() {-->
<!--var path = getPath.call(this);-->
<!--path = path.replace(/\\/g, '/');-->
<!--return path;-->
<!--};-->
//global object to pass request stat among fuse framework files.
var fuseState = {
zones: {},
appName: '',
currentZone: [], //TODO: rename to zone Stack
currentUnit: null
};
<!--var requestId = function makeId() {-->
<!--var text = "";-->
<!--var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";-->
<!--for (var i = 0; i < 5; i++)-->
<!--text += possible.charAt(Math.floor(Math.random() * possible.length));-->
<!--return text;-->
<!--}();-->
var fuseDebug = false;
//var fuseDebug = true;
var handlebars = require('handlebars-helpers.js');
var fuseRouter = require('fuse-router.js');
var fuse = require('fuse.js');
fuseRouter.route();
%>

@ -1,454 +0,0 @@
//public function declarations
var getHbsFile, getFile, toRelativePath, cleanupAncestors,
getUnitPath, getMatchedUnitDefinitions, getZoneDefinition, getUnitDefinition,
getUnitDefinitions, getLayoutPath, readUnitDefinitions;
(function () {
//private
var log = new Log('fuse.core');
var lookUpTable = null;
var definitions = null;
var initLookUp = function (definitions) {
if (lookUpTable === null) {
lookUpTable = {};
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
lookUpTable[definition.name] = i;
}
}
};
var isMatched = function (definition, layout) {
var urlMatch = function (pattern) {
var uriMatcher = new URIMatcher(request.getRequestURI());
return Boolean(uriMatcher.match('/{appName}' + pattern));
};
var permission = function (permissionStr) {
var carbonModule = require("carbon");
var carbonServer = application.get("carbonServer");
var carbonUser = session.get("USER");
if (carbonUser) {
var userManager = new carbonModule.user.UserManager(carbonServer, carbonUser.tenantId);
var user = new carbonModule.user.User(userManager, carbonUser.username);
return user.isAuthorized(permissionStr, "ui.execute");
}
return false;
};
var config = {'theme': 'default'};
var predicateStr = definition.definition.predicate;
if (predicateStr) {
var js = 'function(config,urlMatch,permission,layout){ return ' + predicateStr + ';}';
return Boolean(eval(js)(config, urlMatch,permission, layout ? layout : NaN));
}
return false;
};
var getAncestorModels = function (unit) {
var unitModel = getUnitDefinition(unit);
var ancestors = [unitModel];
var parentName;
while ((parentName = unitModel.definition.extends) != null) {
unitModel = getUnitDefinition(parentName);
ancestors.push(unitModel);
}
return ancestors;
};
addDependencies = function (unitModels) {
var resolved = {};
for (var i = 0; i < unitModels.length; i++) {
resolved[unitModels[i].name] = true;
}
for (i = 0; i < unitModels.length; i++) {
var unitModel = unitModels[i];
var dependencies = unitModel.definition.dependencies;
if (dependencies) {
for (var j = 0; j < dependencies.length; j++) {
var dependencyName = dependencies[j];
unitModels.push(getUnitDefinition(dependencyName));
resolved[dependencyName] = true;
}
}
}
};
//public
getMatchedUnitDefinitions = function () {
//TODO: return map not list
var unitDefinitions = getUnitDefinitions();
var matched = [];
var unMatched = [];
var layout = null;
var mainUnit = null;
var addToMatched = function (model) {
matched.push(model);
if (model.layout) {
if (layout == null) {
layout = model.layout;
mainUnit = model.name;
} else {
//log.warn(
// '[' + requestId + '] multiple layouts ' + mainUnit + ':' +
// layout + ' vs ' + model.name + ':' + model.layout
//);
}
}
};
// first pass
for (var i = 0; i < unitDefinitions.length; i++) {
var unitDefinition = unitDefinitions[i];
if (isMatched(unitDefinition)) {
addToMatched(unitDefinition);
} else {
unMatched.push(unitDefinition);
}
}
fuseState.layout = layout;
// second pass : we have to do this two passes since we don't know the layout
// first time around
if (layout) {
for (i = 0; i < unMatched.length; i++) {
unitDefinition = unMatched[i];
if (isMatched(unitDefinition, layout)) {
addToMatched(unitDefinition)
}
}
}
var toDelete = [];
for (i = 0; i < matched.length; i++) {
var ancestors = getAncestorModels(matched[i].name);
for (var j = 1; j < ancestors.length; j++) {
var ancestor = ancestors[j];
toDelete.push(ancestor.name);
}
}
for (i = matched.length - 1; i >= 0; i--) {
//log.info(matched[i].name);
if (toDelete.indexOf(matched[i].name) >= 0) {
matched.splice(i, 1);
}
}
return matched;
};
getUnitDefinition = function (unit) {
var definitions = getUnitDefinitions();
initLookUp(definitions);
var model = definitions[lookUpTable[unit]];
if (!model) {
//log.warn('[' + requestId + '] unit "' + unit + '" does not exits');
//throw '[' + requestId + '] unit "' + unit + '" does not exits';
}
return model;
};
var flattenAllInheritance = function (unitModels) {
var hasFlattend = {};
for (var i = 0; i < unitModels.length; i++) {
var model = unitModels[i];
if (!hasFlattend[model]) {
var ancestors = getAncestorModels(model.name);
for (var j = ancestors.length - 1; j >= 1; j--) {
flattenInheritance(ancestors[j], ancestors[j - 1]);
}
}
}
};
var flattenInheritance = function (parent, child) {
var parentZones = parent.zones;
for (var i = 0; i < parentZones.length; i++) {
var parentZone = parentZones[i];
child.zones.push(parentZone);
}
};
getUnitDefinitions = function () {
if (definitions !== null) {
return definitions;
} else {
definitions = [];
}
var unitDirs = new File('/units').listFiles();
definitions = readUnitDefinitions("",unitDirs,definitions);
//log.info(definitions);
addPageUnitDefinitions(definitions);
initLookUp(definitions);
flattenAllInheritance(definitions);
return definitions;
};
readUnitDefinitions = function(basePath, unitDirs, definitions){
for (var i = 0; i < unitDirs.length; i++) {
var unitDir = unitDirs[i];
if (unitDir.isDirectory()) {
var unitName = unitDir.getName();
//log.info("reading: "+unitName + " basePath:"+basePath);
var definitionFile = new File(fuse.getUnitPath(basePath+unitName) + '/' + unitName + '.json');
if(definitionFile.isExists()) {
var unitModel = {
name: unitName,
path: unitDir.getPath()
};
if(basePath!=""){
unitModel.name = basePath + unitName;
}
var path = definitionFile.getPath();
if (log.isDebugEnabled()) {
//log.debug('[' + requestId + '] reading file "' + path + '"');
}
unitModel.definition = require(path);
// add the information derived by parsing hbs file to the same model
var hbsMetadata = getHbsMetadata(unitModel);
unitModel.zones = hbsMetadata.zones;
if (hbsMetadata.layout) {
unitModel.layout = hbsMetadata.layout;
}
definitions.push(unitModel);
}else{
var unitSubDirs = new File(fuse.getUnitPath(basePath+"/"+unitName)).listFiles();
readUnitDefinitions(basePath+unitName+"/",unitSubDirs,definitions);
}
}
}
return definitions;
};
addPageUnitDefinitions = function (unitModels, dir) {
var pageFiles = new File(dir || '/pages').listFiles();
for (var i = 0; i < pageFiles.length; i++) {
var pageFile = pageFiles[i];
var fileName = pageFile.getName();
if (pageFile.isDirectory()) {
addPageUnitDefinitions(unitModels, pageFile.getPath())
} else if (fileName.indexOf('.hbs', fileName.length - 4) !== -1) { // File name ends with '.hbs'
var isLeaf = true;
//path relative to app root
var relativePath = pageFile.getPath()
.substring(6 + pageFile.getPath().indexOf('/pages/'), pageFile.getPath().length - 4);
if (relativePath.match(/\/index$/)) {
relativePath = relativePath.replace(/\/index$/, '');
var parentFile = new File(pageFile.getPath().substr(0, pageFile.getPath().lastIndexOf('/')));
var hasSiblings = parentFile.listFiles().length != 1;
if (hasSiblings) {
isLeaf = false;
}
}
//this will be used as a name for the virtual unit, useful for debugging purposes.
var unitName = (relativePath == '' ? 'index' : relativePath.substr(1).replace(/\//, '-') ) + '-page';
var predicate = "urlMatch('" + relativePath + "')";
// leaf is page that can handle multiple URLs. in this case it should have a wildcard at end.
// but since our current matcher doesn't support {/wildcard*} patten, "OR" ( || ) is used
if (isLeaf) {
predicate += " || urlMatch('" + relativePath + "/{+wildcard}')";
}
var unitModel = {
name: unitName,
path: pageFile.getPath(),
definition: {predicate: predicate}
};
var hbsMetadata = getHbsMetadata(unitModel);
unitModel.zones = hbsMetadata.zones;
if (hbsMetadata.layout) {
unitModel.layout = hbsMetadata.layout;
}
unitModels.push(unitModel);
}
}
};
getLayoutPath = function (layout) {
return '/layouts/' + layout + '.hbs';
};
getHbsFile = function (unit) {
// we determining if it's page unit or a proper unit
// by checking if path ends with '.hbs'
// TODO: improve getFile to do include this logic
if (unit.path.indexOf('.hbs', unit.path.length - 4) !== -1) {
return new File(unit.path);
} else {
if(unit.name.indexOf('/') !== -1){//a subcategory unit
var rawParts = unit.name.split("/");
return new File(unit.path + '/' + rawParts[rawParts.length-1] + '.hbs');
}else {
return new File(unit.path + '/' + unit.name + '.hbs');
}
}
};
var getHbsMetadata = function (unit) {
var zoneDef = {'zones': []};
var hbsFile = getHbsFile(unit);
if (!hbsFile.isExists()) {
log.error("Couldn't find .hbs file at: `" + unit.path + "`");
return zoneDef;
}
var output = handlebars.Handlebars.compileFile(hbsFile)({});
var zonesAndLayouts = output.trim().split(/\s+/gm);
for (var i = 0; i < zonesAndLayouts.length; i++) {
var name = zonesAndLayouts[i];
if (name.lastIndexOf('zone_', 0) === 0) {
zoneDef.zones.push({name: name.substr(5), origin: unit.name});
} else if (name.lastIndexOf('layout_', 0) === 0) {
zoneDef.layout = name.substr(7);
}
}
return zoneDef;
};
getUnitPath = function (unit) {
return '/units/' + unit;
};
cleanupAncestors = function (units) {
var toDelete = {};
var len = units.length;
for (var i = 0; i < len; i++) {
var unit = units[i];
if (!toDelete[unit]) {
var ancestors = getAncestorModels(unit.name);
for (var j = 1; j < ancestors.length; j++) {
toDelete[ancestors[j].name] = unit;
}
}
}
while (len--) {
if (toDelete[units[len]]) {
if (log.isDebugEnabled()) {
//log.debug(
// '[' + requestId + '] unit "' + units[len] +
// '" is overridden by "' + toDelete[units[len]] + '"'
//);
}
units.splice(len, 1);
}
}
};
toRelativePath = function (path) {
var start = 0;
if (path.lastIndexOf('/units/', 0) == 0) {
start = 7; // len('/units/')
}
var slashPos = path.indexOf('/', 7);
return {
unit: path.substring(start, slashPos),
path: path.substr(slashPos)
}
};
/**
* Get a file inside a unit by relative path. if the file is not available in the given unit,
* the closest ancestor's file will be returned. if an optional suffix is used the relative path is
* calculated as ( path + < unit name > + opt_suffix ). if no such a file exists a returned file object will
* point to provided unit's non-existing file location (not to any ancestors).
*
* @param unitName name of the unit
* @param path path relative to unit root.
* @param opt_suffix
* @returns {File}
*/
getFile = function (unitName, path, opt_suffix) {
var slashPath = ((path[0] === '/') ? '' : '/') + path;
var selfFileName = '';
var fileName = '';
if (opt_suffix) {
if(unitName.indexOf('/') !== -1) {//a subcategory unit
var rawParts = unitName.split("/");
selfFileName = rawParts[rawParts.length - 1];
}else {
selfFileName = unitName;
}
selfFileName = selfFileName + opt_suffix;
slashPath = slashPath + ((slashPath[slashPath.length - 1] === '/') ? '' : '/');
}
//TODO: remove this hack that makes in page-unit, any file is same
var unitDef = getUnitDefinition(unitName);
if (unitDef.path.indexOf('.hbs', unitDef.path.length - 4) !== -1) {
if (opt_suffix.indexOf('.hbs', opt_suffix.length - 4) !== -1) {
return new File(unitDef.path);
} else {
return new File(unitDef.path.replace(/.hbs$/, opt_suffix));
}
}
var selfFile = new File(getUnitPath(unitName) + slashPath + selfFileName);
if (selfFile.isExists()) {
if (log.isDebugEnabled()) {
//log.debug(
// '[' + requestId + '] for unit "' + unitName + '" file resolved : "'
// + slashPath + selfFileName + '" -> "' + selfFile.getPath() + '"'
//);
}
return selfFile;
}
var ancestors = getAncestorModels(unitName);
for (var i = 1; i < ancestors.length; i++) {
var ancestorName = ancestors[i].name;
if(ancestorName.indexOf('/') !== -1) {//a subcategory unit
var rawParts = ancestorName.split("/");
ancestorName = rawParts[rawParts.length - 1];
}
if (opt_suffix) {
fileName = ancestorName + opt_suffix;
}
var file = new File(getUnitPath(ancestorName) + slashPath + fileName);
if (file.isExists()) {
if (log.isDebugEnabled()) {
//log.debug(
// '[' + requestId + '] for unit "' + unitName + '" file resolved : "'
// + slashPath + selfFileName + '" -> "' + file.getPath() + '"'
//);
}
return file;
}
}
if (log.isDebugEnabled()) {
//log.debug(
// '[' + requestId + '] for unit "' + unitName + '" (non-excising) file resolved : "'
// + slashPath + selfFileName + '" -> "' + selfFile.getPath() + '"'
//);
}
return selfFile;
};
})();

@ -1,203 +0,0 @@
var log = new Log('fuse.handlebars');
//TODO: create a different set of helpers for init parsing
var Handlebars = require('handlebars-v2.0.0.js').Handlebars;
var USER_SESSION_KEY = "USER";
var getScope = function (unit,configs) {
var jsFile = fuse.getFile(unit, '', '.js');
var templateConfigs = configs || {};
var script;
var onRequestCb = function(){}; //Assume that onRequest function will not be defined by the user
var viewModel = {};
var cbResult;
if (jsFile.isExists()) {
script = require(jsFile.getPath());
//Eagerly make the viewModel the template org.wso2.carbon.device.mgt.iot.common.config.server.configs
viewModel = templateConfigs;
//Check if the unit author has specified an onRequest
//callback
if(script.hasOwnProperty('onRequest')){
script.app = {
url: '/' + fuseState.appName,
publicURL: '/' + fuseState.appName + '/public/' + unit,
"class": unit + '-unit'
};
onRequestCb = script.onRequest;
cbResult = onRequestCb(templateConfigs);
log.debug("passing org.wso2.carbon.device.mgt.iot.common.config.server.configs to unit "+unit+" org.wso2.carbon.device.mgt.iot.common.config.server.configs: "+stringify(templateConfigs));
//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{
//If there is no script then the view should get the configurations
//passed in the unit call
viewModel = templateConfigs;
}
viewModel.app = {
url: '/' + fuseState.appName
};
viewModel.self = {
publicURL: '/' + fuseState.appName + '/public/' + unit,
"class": unit + '-unit'
};
return viewModel;
};
Handlebars.innerZones = [];
Handlebars.innerZonesFromUnit = null;
Handlebars.registerHelper('defineZone', function (zoneName, zoneContent) {
var result = '';
var zone = Handlebars.Utils.escapeExpression(zoneName);
fuseState.currentZone.push(zone);
var unitsToRender = fuseState.zones[zone] || [];
if (Handlebars.innerZones.length > 0) {
unitsToRender = fuseState.zones[Handlebars.innerZones[0]] || [];
}
// if there is no one overriding, then display inline zone
if (zoneContent['fn'] && unitsToRender.length == 0) {
return zoneContent.fn(this).trim();
}
for (var i = 0; i < unitsToRender.length; i++) {
var unit = unitsToRender[i];
if (Handlebars.innerZonesFromUnit == null || Handlebars.innerZonesFromUnit.unitName == unit.unitName) {
var template = fuse.getFile(unit.originUnitName || unit.unitName, '', '.hbs');
//log.debug('[' + requestId + '] for zone "' + zone + '" including template :"' + template.getPath() + '"');
result += Handlebars.compileFile(template)(getScope(unit.unitName, zoneContent.data.root));
}
}
// we go to inner zones if result is empty, what we should really do it
// if matched zone is fully made of sub-zones. this is a hack to
// make it easy to implement.
if (result.trim().length == 0 && zoneContent['fn']) {
Handlebars.innerZones.push(zoneName);
for (i = 0; i < unitsToRender.length; i++) {
unit = unitsToRender[i];
Handlebars.innerZonesFromUnit = unit;
result += zoneContent.fn(this).trim();
Handlebars.innerZonesFromUnit = null;
}
Handlebars.innerZones.pop();
return result;
}
fuseState.currentZone.pop();
return new Handlebars.SafeString(result);
});
Handlebars.registerHelper('zone', function (zoneName, zoneContent) {
var currentZone = fuseState.currentZone[fuseState.currentZone.length - 1];
if (currentZone == null) {
return 'zone_' + zoneName + ' ';
}
// if it's exact zone match or if any in inner zone matches we render zone.
// this second condition is a hack. what we should really do is to keep another stack,
// and only match with the peek of that stack and always fill it with next in innerZone stack.
if (zoneName == currentZone || Handlebars.innerZones.indexOf(zoneName) >= 0) {
return zoneContent.fn(this).trim();
} else {
return '';
}
});
Handlebars.registerHelper('layout', function (layoutName) {
var currentZone = fuseState.currentZone[fuseState.currentZone.length - 1];
if (currentZone == null) {
return 'layout_' + layoutName;
} else {
return '';
}
});
Handlebars.registerHelper('authorized', function () {
var currentZone = fuseState.currentZone[fuseState.currentZone.length - 1];
if (currentZone == null) {
return '';
} else {
var loggedUser = session.get(USER_SESSION_KEY);
if(loggedUser == null){
response.sendRedirect("/"+ fuseState.appName + "/login");
exit();
}
}
});
Handlebars.registerHelper('unit', function (unitName,options) {
var unitDef = fuse.getUnitDefinition(unitName);
var baseUnit = null;
var templateConfigs = options.hash || {};
for (var i = 0; i < unitDef.zones.length; i++) {
var zone = unitDef.zones[i];
if (zone.name == 'main') {
baseUnit = zone.origin;
} else {
var golbalZone = fuseState.zones[zone.name];
if (!golbalZone) {
fuseState.zones[zone.name] = [{"unitName": unitName}];
} else {
fuseState.zones[zone.name].push({"unitName": unitName});
}
}
}
if (baseUnit == null) {
log.error('unit does not have a main zone');
}
//TODO warn when unspecified decencies are included.
fuseState.currentZone.push('main');
var template = fuse.getFile(baseUnit, '', '.hbs');
//log.debug('[' + requestId + '] including "' + baseUnit + '"'+" with org.wso2.carbon.device.mgt.iot.common.config.server.configs "+stringify(templateConfigs));
var result = new Handlebars.SafeString(Handlebars.compileFile(template)(getScope(baseUnit,templateConfigs)));
fuseState.currentZone.pop();
return result;
});
Handlebars.compileFile = function (file) {
//TODO: remove this overloaded argument
var f = (typeof file === 'string') ? new File(file) : file;
if (!Handlebars.cache) {
Handlebars.cache = {};
}
if (Handlebars.cache[f.getPath()] != null) {
return Handlebars.cache[f.getPath()];
}
f.open('r');
//log.debug('[' + requestId + '] reading file "' + f.getPath() + '"');
var content = f.readAll().trim();
f.close();
var compiled = Handlebars.compile(content);
Handlebars.cache[f.getPath()] = compiled;
return compiled;
};
Handlebars.registerHelper('equal', function(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlebars Helper equal needs 2 parameters");
if( lvalue!=rvalue ) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
Handlebars.registerHelper('unequal', function(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlebars Helper equal needs 2 parameters");
if( lvalue == rvalue ) {
return options.inverse(this);
} else {
return options.fn(this);
}
});

File diff suppressed because one or more lines are too long

@ -1,36 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
(function(){
var constants = require('/modules/constants.js');
if (!session.get(constants.USER_SESSION_KEY)) {
var dataConfig = require('/config/dc-props.js').config();
var sso = require('/modules/sso.js').sso;
var keyStoreParams = {
keyStoreName : dataConfig.ssoConfiguration.keyStoreName,
keyStorePassword : dataConfig.ssoConfiguration.keyStorePassword,
identityAlias : dataConfig.ssoConfiguration.identityAlias
}
sso.configure(dataConfig.ssoConfiguration.issuer, dataConfig.ssoConfiguration.appName, keyStoreParams,
dataConfig.ssoConfiguration.identityProviderURL);
sso.login();
}else{
response.sendRedirect(dataConfig.appContext);
}
}());
%>

@ -1,37 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var constants = require('/modules/constants.js');
var user = session.get(constants.USER_SESSION_KEY);
var dataConfig = require('/config/dc-props.js').config();
var log = new Log();
if (user === null) {
log.debug("Cannot perform logout. No user session found.");
response.sendRedirect(dataConfig.appContext+'dashboard');
} else {
var sso = require('/modules/sso.js').sso;
var keyStoreParams = {
keyStoreName: dataConfig.ssoConfiguration.keyStoreName,
keyStorePassword: dataConfig.ssoConfiguration.keyStorePassword,
identityAlias: dataConfig.ssoConfiguration.identityAlias
}
sso.configure(dataConfig.ssoConfiguration.issuer, dataConfig.ssoConfiguration.appName, keyStoreParams,
dataConfig.ssoConfiguration.identityProviderURL);
sso.logout(user);
}
%>

@ -1,41 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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;
}();

@ -1,47 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var WEB_APP_TITLE = "WSO2 IoT - IoT Server";
var WEB_APP_CONTEXT = "/iotserver";
var USER_SESSION_KEY = "USER";
var UNSPECIFIED = "Unspecified";
var DEVICES_UNIT_PATH="/units/";
var POLICY_REGISTRY_PATH="/_system/governance/policy_declarations/";
var DEVICE_IDENTIFIER = "deviceIdentifier";
var DEVICE_NAME = "name";
var DEVICE_OWNERSHIP = "ownership";
var DEVICE_OWNER = "owner";
var DEVICE_TYPE = "type";
var DEVICE_VENDOR = "vendor";
var DEVICE_MODEL = "model";
var DEVICE_PRODUCT = "PRODUCT";
var DEVICE_OS_VERSION = "osVersion";
var DEVICE_PROPERTIES = "properties";
var FEATURE_NAME = "featureName";
var FEATURE_DESCRIPTION = "featureDescription";
var PLATFORM_ANDROID = "android";
var PLATFORM_IOS = "ios";
var DEVICE_ENROLLMENT = "dateOfEnrolment";
var VENDOR_APPLE = "Apple";
var ERRORS = {
"USER_NOT_FOUND": "USER_NOT_FOUND"
};

@ -1,279 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var deviceModule;
deviceModule = function () {
var log = new Log("modules/device.js");
var constants = require("/modules/constants.js");
var utility = require("/modules/utility.js").utility;
var carbon = require('carbon');
var carbonHttpServletTransport = carbon.server.address('http');
var carbonHttpsServletTransport = carbon.server.address('https');
var ArrayList = Packages.java.util.ArrayList;
var Properties = Packages.java.util.Properties;
var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier;
var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation;
var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
var deviceManagementDAOFactory = Packages.org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
var deviceManagementService = utility.getDeviceManagementService();
var publicMethods = {};
var privateMethods = {};
privateMethods.validateAndReturn = function (value) {
return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
};
privateMethods.getStoreDefinition = function (deviceTypeStr) {
var storeJSON = new File(constants.DEVICES_UNIT_PATH + deviceTypeStr + "/public/store.json");
if (storeJSON.isExists()) {
storeJSON.open('r');
log.debug('reading file "' + storeJSON.getPath() + '"');
var content = storeJSON.readAll().trim();
storeJSON.close();
return parse(content);
}
return null;
};
publicMethods.listDevices = function () {
var devices = deviceManagementService.getAllDevices();
var deviceList = [];
var i, device, propertiesList, deviceObject;
for (i = 0; i < devices.size(); i++) {
device = devices.get(i);
propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());
deviceObject = {};
deviceObject[constants.DEVICE_IDENTIFIER] =
privateMethods.validateAndReturn(device.getDeviceIdentifier());
deviceObject[constants.DEVICE_NAME] =
privateMethods.validateAndReturn(device.getName());
deviceObject[constants.DEVICE_OWNERSHIP] =
privateMethods.validateAndReturn(device.getOwnership());
deviceObject[constants.DEVICE_OWNER] =
privateMethods.validateAndReturn(device.getOwner());
deviceObject[constants.DEVICE_TYPE] =
privateMethods.validateAndReturn(device.getType());
deviceObject[constants.DEVICE_PROPERTIES] = {};
if (device.getType() == constants.PLATFORM_IOS) {
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
} else {
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
}
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));
deviceList.push(deviceObject);
}
return deviceList;
};
publicMethods.listDevicesForUser = function (username) {
var devices = deviceManagementService.getDeviceListOfUser(username);
var deviceList = [];
var i, device, propertiesList, deviceObject;
for (i = 0; i < devices.size(); i++) {
device = devices.get(i);
propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());
deviceObject = {};
deviceObject[constants.DEVICE_IDENTIFIER] =
privateMethods.validateAndReturn(device.getDeviceIdentifier());
deviceObject[constants.DEVICE_NAME] =
privateMethods.validateAndReturn(device.getName());
deviceObject[constants.DEVICE_OWNERSHIP] =
privateMethods.validateAndReturn(device.getOwnership());
deviceObject[constants.DEVICE_OWNER] =
privateMethods.validateAndReturn(device.getOwner());
deviceObject[constants.DEVICE_TYPE] =
privateMethods.validateAndReturn(device.getType());
deviceObject[constants.DEVICE_PROPERTIES] = {};
if (device.getType() == constants.PLATFORM_IOS) {
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
} else {
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
}
deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));
deviceList.push(deviceObject);
}
return deviceList;
};
/**
* Return list of device types.
* Device types should be registered in CDMF and specific unit with name of '{devicetype}' should be presented.
* @returns {Array}
*/
publicMethods.listDeviceTypes = function () {
deviceManagementDAOFactory.openConnection();
var deviceTypes = deviceManagementDAOFactory.getDeviceTypeDAO().getDeviceTypes();
deviceManagementDAOFactory.closeConnection();
var deviceTypesList = [];
var i, deviceType, deviceTypeObject;
for (i = 0; i < deviceTypes.size(); i++) {
deviceType = deviceTypes.get(i);
var deviceUnit = new File(constants.DEVICES_UNIT_PATH + deviceType.getName());
if (deviceUnit.isExists()) {
deviceTypeObject = {};
deviceTypeObject["name"] = deviceType.getName();
deviceTypeObject["id"] = deviceType.getId();
var storeProperties = privateMethods.getStoreDefinition(deviceType.getName());
if (storeProperties) {
deviceTypeObject["storeTitle"] = storeProperties.title;
deviceTypeObject["storeDescription"] = storeProperties.description;
}
deviceTypesList.push(deviceTypeObject);
} else {
log.warn("Device type `" + deviceType.getName() + "` is missing unit implementation at: " + constants.DEVICES_UNIT_PATH);
}
}
return deviceTypesList;
};
publicMethods.removeDevice = function (deviceType, deviceId) {
//URL: https://localhost:9443/{deviceType}/manager/device/remove/{deviceId}
var deviceCloudService = carbonHttpsServletTransport + "/" + deviceType + "/manager",
removeDeviceEndpoint = deviceCloudService + "/device/remove/" + deviceId;
var data = {};
//XMLHTTPRequest's GET
//log.info(removeDeviceEndpoint);
return del(removeDeviceEndpoint, data, "text");
};
publicMethods.updateDevice = function (deviceType, deviceId, device) {
//URL: https://localhost:9443/{deviceType}/manager/device/update/{deviceId}
var deviceCloudService = carbonHttpsServletTransport + "/" + deviceType + "/manager",
updateDeviceEndpoint = deviceCloudService + "/device/update/" + deviceId;
var data = {};
//XMLHTTPRequest's POST
//log.info(updateDeviceEndpoint+ "?name="+device.name);
return post(updateDeviceEndpoint + "?name=" + encodeURIComponent(device.name), data, "text");
};
/*
Get the supported features by the device type
*/
publicMethods.getFeatures = function (deviceType) {
var features = deviceManagementService.getFeatureManager(deviceType).getFeatures();
var featuresConverted = {};
if (features) {
var i, feature, featureObject;
for (i = 0; i < features.size(); i++) {
feature = features.get(i);
featureObject = {};
featureObject[constants.FEATURE_NAME] = feature.getName();
featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription();
featuresConverted[feature.getName()] = featureObject;
}
}
return featuresConverted;
};
publicMethods.performOperation = function (devices, operation) {
var operationInstance;
if (operation.type == "COMMAND") {
operationInstance = new CommandOperation();
} else if (operation.type == "CONFIG") {
operationInstance = new ConfigOperation();
} else {
operationInstance = new SimpleOperation();
}
operationInstance.setCode(operation.featureName);
var props = new Properties();
var i, object;
for (i = 0; i < operation.properties.length; i++) {
object = properties[i];
props.setProperty(object.key, object.value);
}
operationInstance.setProperties(props);
var deviceList = new ArrayList();
var j, device, deviceIdentifier;
for (j = 0; j < devices.length; i++) {
device = devices[j];
deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(device.id);
deviceIdentifier.setType(device.type);
deviceList.add(deviceIdentifier);
}
deviceManagementService.addOperation(operationInstance, deviceList);
};
publicMethods.getDevice = function (type, deviceId) {
var deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setType(type);
deviceIdentifier.setId(deviceId);
return deviceManagementService.getDevice(deviceIdentifier);
};
publicMethods.viewDevice = function (type, deviceId) {
var device = publicMethods.getDevice(type, deviceId);
if (device) {
var propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());
var entries = propertiesList.entrySet();
var iterator = entries.iterator();
var properties = {};
var entry, key, value;
while (iterator.hasNext()) {
entry = iterator.next();
key = entry.getKey();
value = entry.getValue();
properties[key] = privateMethods.validateAndReturn(value);
}
var deviceObject = {};
deviceObject[constants.DEVICE_IDENTIFIER] = device.getDeviceIdentifier();
deviceObject[constants.DEVICE_NAME] = privateMethods.validateAndReturn(device.getName());
deviceObject[constants.DEVICE_OWNERSHIP] = privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
deviceObject[constants.DEVICE_OWNER] = device.getEnrolmentInfo().getOwner();
deviceObject[constants.DEVICE_TYPE] = device.getType();
if (device.getType() == constants.PLATFORM_IOS) {
properties[constants.DEVICE_MODEL] = properties[constants.DEVICE_PRODUCT];
delete properties[constants.DEVICE_PRODUCT];
properties[constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
}
deviceObject[constants.DEVICE_PROPERTIES] = properties;
deviceObject[constants.DEVICE_ENROLLMENT] = device.getEnrolmentInfo().getDateOfEnrolment();
return deviceObject;
}
};
return publicMethods;
}();

@ -1,68 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var downloadModule;
var Handlebars = require('../lib/handlebars-v2.0.0.js').Handlebars;
downloadModule = function () {
var log = new Log("modules/download.js");
var constants = require("/modules/constants.js");
var publicMethods = {};
var privateMethods = {};
/**
* Downloading a specified sketch file.
*
* @param file File name or file object of the downloading file
* @param replaceParams
*/
publicMethods.downloadSketch = function (file, response, replaceParams) {
var file = new File("../sketch/" + file);
file.open('r');
log.debug("Reading file '" + file.getPath() + "'");
var content = file.readAll().trim();
file.close();
var downloadFile = privateMethods.allReplace(content,replaceParams);
response.contentType = "application/octet-stream";
response.addHeader("Content-Disposition", "attachment; filename='sketch.hbs'");
response.addHeader("Content-Length", String(downloadFile.length));
response.content = downloadFile;
};
/**
* Find and replace all occurrences.
* @param inStr input string
* @param replaceParams key value array
* @returns retStr replaced string
*/
privateMethods.allReplace = function (inStr, replaceParams) {
var retStr = inStr;
for (var x in replaceParams) {
retStr = retStr.replace(new RegExp(x, 'g'), replaceParams[x])
}
return retStr;
};
return publicMethods;
}();

@ -1,57 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var eventModule;
eventModule = function () {
var log = new Log("modules/event.js");
var constants = require("/modules/constants.js");
var utility = require("/modules/utility.js").utility;
var publicMethods = {};
var privateMethods = {};
var statsClient = new Packages.org.wso2.carbon.device.mgt.iot.common.analytics.statistics.IoTEventsStatisticsClient;
publicMethods.getEventsData = function (username, recordLimit) {
var fetchedData = null;
try {
fetchedData = statsClient.getRecentDeviceStats(username, recordLimit);
} catch (error) {
log.error(error);
}
var eventsData = [];
for (var i = 0; i < fetchedData.size(); i++) {
eventsData.push({
time: fetchedData.get(i).getTime(),
deviceId: fetchedData.get(i).getDeviceId(),
activity: fetchedData.get(i).getDeviceActivity()
});
};
return eventsData;
};
return publicMethods;
}();

@ -1,27 +0,0 @@
/*
* Copyright (c) 2011 František Hába <hello@frantisekhaba.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the 'Software'), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Reference:- https://github.com/Baggz/Pinch
* Pinch is a small JavaScript utility which is able to replace any data in a JavaScript object (or JSON).
* */
(function(){var k=function(a,c){return a.length!==c.length?!1:a.every(function(a,b){return c[b]===a})},j=function(a,c,d){var b,e;if("[object Array]"===Object.prototype.toString.call(a)){b=0;for(e=a.length;b<e;b++)c.apply(d,[b,a[b],a])}else for(b in a)a.hasOwnProperty(b)&&c.apply(d,[b,a[b],a])},h=function(a){for(var c=[],d=!1,b=0,e=a.length,f="",g=function(){f&&(c.push(f),f="")};b<e;b++)a[b].match(/\[|\]/)?(g(),d="]"===a[b]?!1:!0):'"'!==a[b]&&"'"!==a[b]&&("."===a[b]&&!d?g():f+=a[b]),b===e-1&&g();return c},
g=function(a,c,d){var b=-1!==["string","object"].indexOf(typeof a),e="string"===typeof c||c&&c.test&&c.exec,f=-1!==["string","object","function"].indexOf(typeof d);b&&e&&f&&("string"===typeof a?(this.instance=JSON.parse(a),this.json=!0):this.instance=a,this.pattern="string"===typeof c?c.replace(/'/g,'"'):c,this.replacement=d,this.createIndex(this.instance))};g.prototype.createIndex=function(a,c){var d=this;this.index=this.index||[];c=c||"";j(a,function(a,e){var f,a=a+"";f=a.match(/^[a-zA-Z]+$/)?c?
c+"."+a:a:a.match(/\d+/)?c+"["+a+"]":c+'["'+a+'"]';d.index.push(f);"object"===typeof e&&d.createIndex(e,f)})};g.prototype.replace=function(){var a=this;j(this.index,function(c,d){if(a.pattern&&a.pattern.test&&a.pattern.exec&&d.match(a.pattern))return a.replaceValue(d);if("string"===typeof a.pattern){var b=h(d),e=h(a.pattern);if(k(b,e))return a.replaceValue(d)}});return this.json?JSON.stringify(this.instance):this.instance};g.prototype.replaceValue=function(a){var c=this,d=h(a);d.reduce(function(b,
e,f){if(f===d.length-1)f="function"===typeof c.replacement?c.replacement(a,e,b[e]):c.replacement,b[e]=f;else return b[e]},this.instance)};var i=function(a,c,d,b){a=(new g(a,c,d)).replace();return"function"===typeof b?b(null,a):a};"undefined"!==typeof module&&module.exports?module.exports=i:"undefined"!==typeof define?define(function(){return i}):this.pinch=i})();

@ -1,156 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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 publicMethods = {};
var privateMethods = {};
publicMethods.addPolicy = function (policyName, deviceType, policyDefinition, policyDescription) {
if (policyName && deviceType) {
var carbonModule = require("carbon");
var carbonServer = application.get("carbonServer");
var options = {system: true};
var carbonUser = session.get(constants.USER_SESSION_KEY);
var resource = {
name: policyName,
mediaType: 'text/plain',
content: policyDefinition,
description: policyDescription,
properties:{owner: carbonUser.username}
};
if (carbonUser) {
options.tenantId = carbonUser.tenantId;
var registry = new carbonModule.registry.Registry(carbonServer, options);
log.info("########### Policy name : " + policyName);
log.info("########### Policy type : " + deviceType);
log.info("########### Policy Declaration : " + policyDefinition);
log.info("########### Policy policyDescription: " + policyDescription);
registry.put(constants.POLICY_REGISTRY_PATH + deviceType + "/" + policyName, resource);
}
var mqttsenderClass = Packages.org.wso2.device.mgt.mqtt.policy.push.MqttPush;
var mqttsender = new mqttsenderClass();
var result = mqttsender.pushToMQTT("/iot/policymgt/govern/" + deviceType + "/" + carbonUser.username, policyDefinition, "tcp://localhost:1883", "Raspberry-Policy-sender");
mqttsender = null;
return true;
} else {
return false;
}
};
publicMethods.getPolicies = function () {
var carbonModule = require("carbon");
var carbonServer = application.get("carbonServer");
var options = {system: true};
var carbonUser = session.get(constants.USER_SESSION_KEY);
var policies = [];
if (carbonUser) {
options.tenantId = carbonUser.tenantId;
var registry = new carbonModule.registry.Registry(carbonServer, options);
var allPolicies = registry.get(constants.POLICY_REGISTRY_PATH);
if (allPolicies) {
//loop through all device types
for (var i = 0; i < allPolicies.content.length; i++) {
var deviceType = allPolicies.content[i].replace(constants.POLICY_REGISTRY_PATH, "");
var deviceTypePolicies = registry.get(allPolicies.content[i]);
//loop through policies
for (var j = 0; j < deviceTypePolicies.content.length; j++) {
var deviceTypePolicy = registry.get(deviceTypePolicies.content[j]);
if(stringify(registry.properties(deviceTypePolicies.content[j]).owner) != '["'+carbonUser.username+'"]'){
//not owned by current user, skip it
continue;
}
var policyObj = {
"id": deviceTypePolicy.uuid, // Identifier of the policy.
//"priorityId": 1, // Priority of the policies. This will be used only for simple evaluation.
//"profile": {}, // Profile
"policyName": deviceTypePolicy.name, // Name of the policy.
"updated": deviceTypePolicy.updated.time,
"deviceType": deviceType
//"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);
}//end of policy loop
}//end of device type policy loop
}
}
return policies;
};
publicMethods.removePolicy = function (name, deviceType) {
var carbonModule = require("carbon");
var carbonServer = application.get("carbonServer");
var options = {system: true};
var carbonUser = session.get(constants.USER_SESSION_KEY);
var bool = false;
if (carbonUser) {
options.tenantId = carbonUser.tenantId;
var registry = new carbonModule.registry.Registry(carbonServer, options);
log.info("########### Policy name : " + name);
log.info("########### Policy type : " + deviceType);
try {
registry.remove(constants.POLICY_REGISTRY_PATH + deviceType + "/" + name);
bool = true;
} catch (err) {
log.error("Error while trying to remove policy :" + name, err);
}
}
return bool;
};
return publicMethods;
}();

@ -1,161 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http:www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var sso = {};
var ssoMod = require("sso");
var log = new Log();
(function () {
var carbon = require("carbon");
var process = require("process");
var getSSOSessions = function () {
var sso_sessions = application.get('sso_sessions');
if (!sso_sessions) {
application.put('sso_sessions', {});
sso_sessions = application.get('sso_sessions');
}
return sso_sessions;
};
sso.configure = function (issuer, appName, keyStoreParams, address, transport, ssoService, responseSign) {
sso.issuer = issuer;
sso.appName = appName;
sso.relayState = "/" + appName;
sso.transport = (transport ? transport : "https");
sso.ssoService = (ssoService ? ssoService : "/samlsso");
sso.responseSign = (responseSign ? responseSign : true);
sso.log = new Log("SSO Module");
sso.address = carbon.server.address(sso.transport);
sso.keyStoreProps = {
KEY_STORE_NAME: process.getProperty('carbon.home') + keyStoreParams.keyStoreName,
KEY_STORE_PASSWORD: keyStoreParams.keyStorePassword,
IDP_ALIAS: keyStoreParams.identityAlias
};
};
sso.login = function () {
sso.sessionId = session.getId();
var referer = request.getHeader("referer");
sso.relayState = (referer ? referer : sso.relayState);
sso.relayState = sso.relayState;// append query string
var log = new Log();
if (request.getQueryString()) {
sso.relayState += request.getQueryString();
}
sso.encodedSAMLAuthRequest = ssoMod.client.getEncodedSAMLAuthRequest(sso.issuer);
var postUrl = sso.address + sso.ssoService;
if (log.isDebugEnabled()) {
log.debug("Request sent to IdP");
}
print("<div><p>You are now being redirected to SSO Provider. If the redirection fails, please click on the "+
"button below.</p> <form method='post' action='" + postUrl + "'><p><input type='hidden' " +
"name='SAMLRequest' value='" + sso.encodedSAMLAuthRequest + "'/><input type='hidden' " +
"name='RelayState' value='" + sso.relayState + "'/><input type='hidden' name='SSOAuthSessionID' " +
"value='" + sso.sessionId + "'/><button type='submit'>Redirect manually</button></p></form></div>" +
"<script type = 'text/javascript' >document.forms[0].submit();</script>");
};
sso.logout = function (user) {
var sso_sessions = getSSOSessions();
sso.sessionId = session.getId();
sso.sessionIndex = sso_sessions[sso.sessionId];
var referer = request.getHeader("referer");
sso.relayState = (referer ? referer : sso.relayState);
sso.relayState = sso.relayState + request.getQueryString(); // append query string
sso.encodedSAMLLogoutRequest = ssoMod.client.getEncodedSAMLLogoutRequest(user, sso.sessionIndex, sso.issuer);
var postUrl = sso.address + sso.ssoService;
if (log.isDebugEnabled()) {
sso.log.debug("Logout request recieved from session id ::: " + sso.sessionId);
}
print("<div><p>You are now redirected to Stratos Identity. If theredirection fails, please click the post " +
"button.</p> <form id='logoutForm' method='post' action='" + postUrl + "'> <p> <input type='hidden' " +
"name='SAMLRequest' value='" + sso.encodedSAMLLogoutRequest + "'/> <input type='hidden' " +
"name='RelayState' value='" + sso.relayState + "'/> <input type='hidden' name='SSOAuthSessionID' " +
"value='" + sso.sessionId + "'/> <button type='submit'>POST</button> </p> </form> </div> <script " +
"type = 'text/javascript' > document.forms[0].submit(); </script>");
};
sso.acs = function (loginCallback, logoutCallback) {
var sso_sessions = getSSOSessions();
sso.sessionId = session.getId();
var samlResponse = request.getParameter('SAMLResponse');
var samlRequest = request.getParameter('SAMLRequest');
var relayState = request.getParameter('RelayState');
var samlRespObj;
if (samlResponse != null) {
samlRespObj = ssoMod.client.getSamlObject(samlResponse);
if (ssoMod.client.isLogoutResponse(samlRespObj)) {
logoutCallback();
if (log.isDebugEnabled()) {
sso.log.debug('Session Id Invalidated :::' + sso.sessionId);
}
// Invalidating the session after the callback
session.invalidate();
} else {
if (log.isDebugEnabled()) {
sso.log.debug("Login request");
}
// validating the signature
if (sso.responseSign) {
if (ssoMod.client.validateSignature(samlRespObj, sso.keyStoreProps)) {
var sessionObj = ssoMod.client.decodeSAMLLoginResponse(samlRespObj, samlResponse,
sso.sessionId);
if (log.isDebugEnabled()) {
sso.log.debug("Saml object session ID :::" + sessionObj.sessionId);
}
if (sessionObj.sessionIndex != null || sessionObj.sessionIndex != 'undefined') {
sso_sessions[sso_sessions[sessionObj.sessionIndex] = sessionObj.sessionId] =
sessionObj.sessionIndex;
if (log.isDebugEnabled()) {
sso.log.debug("Login successful");
sso.log.debug('User is set :::' + sessionObj.loggedInUser);
}
loginCallback(sessionObj.loggedInUser);
} else {
sso.log.error("Session index invalid");
}
} else {
sso.log.error("Response Signing failed");
}
} else {
if (log.isDebugEnabled()) {
sso.log.debug("Response Signing is disabled");
}
}
}
}
/*
Executed for single logout requests
*/
if (samlRequest != null) {
var index = ssoMod.client.decodeSAMLLogoutRequest(ssoMod.client.getSamlObject(samlRequest));
var jSessionId = getSSOSessions()[index];
delete getSSOSessions()[index];
if (log.isDebugEnabled()) {
sso.log.debug('Backend logout received from store. The index is :::' + index);
sso.log.debug('Session Id Invalidated :::' + jSessionId);
}
session.invalidate();
}
}
})();

@ -1,357 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var userModule;
userModule = function () {
var log = new Log("modules/user.js");
var constants = require("/modules/constants.js");
var utility = require("/modules/utility.js").utility;
var publicMethods = {};
var privateMethods = {};
/**
* Authenticate a user when he or she attempts to login to DC.
*
* @param username Username of the user
* @param password Password of the user
* @param successCallback Function to be called at the event of successful authentication
* @param failureCallback Function to be called at the event of failed authentication
*/
publicMethods.login = function (username, password, successCallback, failureCallback) {
var carbonModule = require("carbon");
var carbonServer = application.get("carbonServer");
try {
// get tenant specific full user name.
username = username + "@" + carbonModule.server.tenantDomain();
// check if the user is an authenticated user.
var isAuthenticated = carbonServer.authenticate(username, password);
if (isAuthenticated) {
var tenantUser = carbonModule.server.tenantUser(username);
session.put(constants.USER_SESSION_KEY, tenantUser);
successCallback(tenantUser);
} else {
failureCallback();
}
} catch (e) {
throw e;
}
};
/**
* Register user to dc-user-store.
*
* @param username Username of the user
* @param firstname First name of the user
* @param lastname Last name of the user
* @param emailAddress Email address of the user
* @param password Password of the user
* @param userRoles Roles assigned to the user
*
* @returns {number} HTTP Status code 201 if succeeded, 409 if user already exists
*/
publicMethods.registerUser = function (username, firstname, lastname, emailAddress, password, userRoles) {
var carbon = require('carbon');
var tenantId = carbon.server.tenantId();
var url = carbon.server.address('https') + "/admin/services";
var server = new carbon.server.Server(url);
var userManager = new carbon.user.UserManager(server, tenantId);
try {
if (userManager.userExists(username)) {
if (log.isDebugEnabled()) {
log.debug("A user with name '" + username + "' already exists.");
}
// http status code 409 refers to - conflict.
return 409;
} else {
var defaultUserClaims = privateMethods.buildDefaultUserClaims(firstname, lastname, emailAddress);
userManager.addUser(username, password, userRoles, defaultUserClaims, "default");
if (log.isDebugEnabled()) {
log.debug("A new user with name '" + username + "' was created.");
}
// http status code 201 refers to - created.
return 201;
}
} catch (e) {
throw e;
}
};
/**
* Add user to dc-user-store.
*
* @param username Username of the user
* @param firstname First name of the user
* @param lastname Last name of the user
* @param emailAddress Email address of the user
* @param userRoles Roles assigned to the user
*
* @returns {number} HTTP Status code 201 if succeeded, 409 if user already exists
*/
publicMethods.addUser = function (username, firstname, lastname, emailAddress, userRoles) {
var carbon = require('carbon');
var tenantId = carbon.server.tenantId();
var url = carbon.server.address('https') + "/admin/services";
var server = new carbon.server.Server(url);
var userManager = new carbon.user.UserManager(server, tenantId);
try {
if (userManager.userExists(username)) {
if (log.isDebugEnabled()) {
log.debug("A user with name '" + username + "' already exists.");
}
// http status code 409 refers to - conflict.
return 409;
} else {
var initialUserPassword = privateMethods.generateInitialUserPassword();
var defaultUserClaims = privateMethods.buildDefaultUserClaims(firstname, lastname, emailAddress);
userManager.addUser(username, initialUserPassword, userRoles, defaultUserClaims, "default");
privateMethods.inviteUserToEnroll(username, initialUserPassword);
if (log.isDebugEnabled()) {
log.debug("A new user with name '" + username + "' was created.");
}
// http status code 201 refers to - created.
return 201;
}
} catch (e) {
throw e;
}
};
/**
* Remove an existing user from mdm-user-store.
*
* @param username Username of the user
* @returns {number} HTTP Status code 200 if succeeded, 409 if the user does not exist
*/
publicMethods.removeUser = function (username) {
var carbon = require('carbon');
var tenantId = carbon.server.tenantId();
var url = carbon.server.address('https') + "/admin/services";
var server = new carbon.server.Server(url);
var userManager = new carbon.user.UserManager(server, tenantId);
try {
if (userManager.userExists(username)) {
userManager.removeUser(username);
if (log.isDebugEnabled()) {
log.debug("An existing user with name '" + username + "' was removed.");
}
// http status code 200 refers to - success.
return 200;
} else {
if (log.isDebugEnabled()) {
log.debug("A user with name '" + username + "' does not exist to remove.");
}
// http status code 409 refers to - conflict.
return 409;
}
} catch (e) {
throw e;
}
};
/**
* Private method to be used by addUser() to
* generate an initial user password for a user.
* This will be the password used by a user for his initial login to the system.
*
* @returns {string} Initial User Password
*/
privateMethods.generateInitialUserPassword = function () {
var passwordLength = 6;
//defining the pool of characters to be used for initial password generation
var lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz";
var upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numericCharset = "0123456789";
var totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset;
var totalCharsetLength = totalCharset.length;
var initialUserPassword = "";
for (var i = 0; i < passwordLength; ++i) {
initialUserPassword += totalCharset.charAt(Math.floor(Math.random() * totalCharsetLength));
}
if (log.isDebugEnabled()) {
log.debug("Initial password created for new user : " + initialUserPassword);
}
return String(initialUserPassword);
};
/**
* Build default user claims.
*
* @param firstname First name of the user
* @param lastname Last name of the user
* @param emailAddress Email address of the user
*
* @returns {Object} Default user claims to be provided
*/
privateMethods.buildDefaultUserClaims = function (firstname, lastname, emailAddress) {
var defaultUserClaims = {
"http://wso2.org/claims/givenname": firstname,
"http://wso2.org/claims/lastname": lastname,
"http://wso2.org/claims/emailaddress": emailAddress
};
if (log.isDebugEnabled()) {
log.debug("ClaimMap created for new user : " + stringify(defaultUserClaims));
}
return defaultUserClaims;
};
publicMethods.addPermissions = function (permissionList, path, init) {
var carbonModule = require("carbon");
var carbonServer = application.get("carbonServer");
var options = {system: true};
if (init == "login") {
var carbonUser = session.get(constants.USER_SESSION_KEY);
if (carbonUser) {
options.tenantId = carbonUser.tenantId;
}
}
var registry = new carbonModule.registry.Registry(carbonServer, options);
var i, permission, resource;
for (i = 0; i < permissionList.length; i++) {
permission = permissionList[i];
resource = {
collection : true,
name : permission.name,
properties : {
name : permission.name
}
};
registry.put("/_system/governance/permission/" + path + "/" + permission.key, resource);
}
};
publicMethods.getUsers = function () {
var users = [];
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 carbon = require('carbon');
var tenantId = carbon.server.tenantId();
var url = carbon.server.address('https') + "/admin/services";
var server = new carbon.server.Server(url);
var userManager = new carbon.user.UserManager(server, tenantId);
var userList = userManager.listUsers();
var i, username, userObject, email, firstname, lastname;
for (i = 0; i < userList.length; i++) {
username = userList[i];
userObject = userManager.getUser(username);
email = userManager.getClaim(username,"http://wso2.org/claims/emailaddress", null);
firstname = userManager.getClaim(username,"http://wso2.org/claims/givenname", null);
lastname = userManager.getClaim(username,"http://wso2.org/claims/lastname", null);
//log.info(userManager.getClaimsForSet(username, "http://wso2.org/claims/emailaddress,http://wso2.org/claims/givenname,http://wso2.org/claims/lastname".split(","), null));
userObj = {
"username" : userObject.username,
"email" : email,
"name" : firstname + " " + lastname
};
if(userObj.username == "admin"){
userObj.name = "admin";
}
users.push(userObj);
}
return users;
};
publicMethods.isAuthorized = function (permission) {
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 user = new carbonModule.user.User(userManager, carbonUser.username);
return user.isAuthorized(permission, "ui.execute");
};
publicMethods.getUIPermissions = function(){
var permissions = {};
if (publicMethods.isAuthorized("/permission/device-mgt/admin/devices/list") ||
publicMethods.isAuthorized("/permission/device-mgt/user/devices/list")) {
permissions.LIST_DEVICES = true;
}
if (publicMethods.isAuthorized("/permission/device-mgt/admin/users/list")) {
permissions.LIST_USERS = true;
}
if (publicMethods.isAuthorized("/permission/device-mgt/admin/users/add")) {
permissions.ADD_USER = true;
}
if (publicMethods.isAuthorized("/permission/device-mgt/admin/policies/add")) {
permissions.ADD_POLICY = true;
}
if (publicMethods.isAuthorized("/permission/device-mgt/admin/policies/list")) {
permissions.LIST_POLICIES = true;
}
if (publicMethods.isAuthorized("/permission/device-mgt/admin/dashboard/view")) {
permissions.DASHBOARD_VIEW = true;
}
//TO-DO Apply followings in to carbon permissions
permissions.ADD_DEVICE = true;
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) {
session.invalidate();
successCallback();
};
return publicMethods;
}();

@ -1,89 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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;
}();

@ -1,127 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var utility;
utility = function () {
var JavaClass = Packages.java.lang.Class;
var PrivilegedCarbonContext = Packages.org.wso2.carbon.context.PrivilegedCarbonContext;
var getOsgiService = function (className) {
return PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(JavaClass.forName(className));
};
var publicMethods = {};
publicMethods.getDeviceManagementService = function () {
return getOsgiService('org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService');
};
publicMethods.getPolicyManagementService = function () {
return getOsgiService('org.wso2.carbon.policy.mgt.core.PolicyManagerService');
};
publicMethods.insertAppPermissions = function (userModule, type) {
userModule.addPermissions([{key: "device-mgt", name: "Device Management"}], "", type);
userModule.addPermissions([{
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/list",
name: "List Devices"
}], "device-mgt/admin", type);
userModule.addPermissions([{
key: "devices/operation",
name: "Perform Operation"
}], "device-mgt/admin", type);
userModule.addPermissions([{key: "groups", name: "Groups"}], "device-mgt/admin", type);
userModule.addPermissions([{
key: "groups/add_devices",
name: "Add Devices to Group"
}], "device-mgt/admin", type);
userModule.addPermissions([{
key: "groups/remove_devices",
name: "Remove Devices from Group"
}], "device-mgt/admin", type);
userModule.addPermissions([{
key: "groups/modify",
name: "Modify Group"
}], "device-mgt/admin", type);
userModule.addPermissions([{
key: "groups/share",
name: "Change Group Sharing"
}], "device-mgt/admin", type);
userModule.addPermissions([{
key: "groups/delete",
name: "Delete Group"
}], "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([{
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/list",
name: "List Devices"
}], "device-mgt/user", type);
userModule.addPermissions([{
key: "devices/operation",
name: "Perform Operation"
}], "device-mgt/user", "init");
userModule.addPermissions([{key: "groups", name: "Groups"}], "device-mgt/user", type);
userModule.addPermissions([{
key: "groups/device_monitor",
name: "Monitor Devices in Group"
}], "device-mgt/user", type);
userModule.addPermissions([{
key: "groups/device_operation",
name: "Perform Device Operation"
}], "device-mgt/user", type);
userModule.addPermissions([{
key: "groups/device_list",
name: "List Groups of User"
}], "device-mgt/user", type);
};
return publicMethods;
}();

@ -1,9 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
WSO2 DC | My Devices List
{{/zone}}
{{#zone "body"}}
{{unit "appbar"}}
{{unit "alldevices"}}
{{/zone}}

@ -1,9 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
WSO2 DC | Analytics
{{/zone}}
{{#zone "body"}}
{{unit "appbar" link="analytics" title="Analytics"}}
{{unit "analytics"}}
{{/zone}}

@ -1,9 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
WSO2 IoT | IoT Server
{{/zone}}
{{#zone "body"}}
{{unit "appbar" title="Dashboard"}}
{{unit "dashboard"}}
{{/zone}}

@ -1,12 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
Device Management
{{/zone}}
{{#zone "body"}}
{{unit "operation-mod"}}
{{unit "appbar" enableBack=true title="Device"}}
{{unit "device-detail"}}
{{/zone}}

@ -1,9 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
WSO2 IoT Server | Device Management
{{/zone}}
{{#zone "body"}}
{{unit "appbar" title="Add Device" enableBack="true"}}
{{unit "store-listing"}}
{{/zone}}

@ -1,23 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
Devices
{{/zone}}
{{#zone "body"}}
{{unit "appbar" link="device-mgt" title="My Devices"}}
{{unit "extended-search-box" item="Device"}}
{{unit "operation-mod"}}
<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 "operation-bar"}}
{{unit "device-listing"}}
</div>
<!-- /content -->
</div>
</div>
{{/zone}}

@ -1,9 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
Events
{{/zone}}
{{#zone "body"}}
{{unit "appbar" link="events" title="My Events"}}
{{unit "events"}}
{{/zone}}

@ -1,12 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
Group Management
{{/zone}}
{{#zone "body"}}
{{unit "operation-mod"}}
{{unit "appbar" enableBack=true title="Group"}}
{{unit "group-detail"}}
{{/zone}}

@ -1,9 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
WSO2 IoT Server | Group Management
{{/zone}}
{{#zone "body"}}
{{unit "appbar" title="Add Group" enableBack="true"}}
{{unit "group-add"}}
{{/zone}}

@ -1,23 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
Groups
{{/zone}}
{{#zone "body"}}
{{unit "appbar" link="group-mgt" title="My Groups"}}
{{unit "extended-search-box" item="Group"}}
{{unit "operation-mod"}}
<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 "operation-bar"}}
{{unit "group-listing"}}
</div>
<!-- /content -->
</div>
</div>
{{/zone}}

@ -1,8 +0,0 @@
{{layout "fluid"}}
{{#zone "title"}}
WSO2 IoT | IoT Server
{{/zone}}
{{#zone "body"}}
{{unit "appbar" link="dashboard" title="Device Management"}}
{{unit "showcase"}}
{{/zone}}

@ -1,7 +0,0 @@
{{layout "fluid"}}
{{#zone "title"}}
WSO2 IoT Server | Login
{{/zone}}
{{#zone "body"}}
{{unit "login"}}
{{/zone}}

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

@ -1,21 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
Policies
{{/zone}}
{{#zone "body"}}
{{unit "appbar" link="policies" title="My Policies"}}
{{unit "extended-search-box" item="Policie"}}
<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}}

@ -1,7 +0,0 @@
{{layout "fluid"}}
{{#zone "title"}}
WSO2 IoT Server | Register
{{/zone}}
{{#zone "body"}}
{{unit "register"}}
{{/zone}}

@ -1,9 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
WSO2 MDM | Add User
{{/zone}}
{{#zone "body"}}
{{unit "appbar" title="Add User"}}
{{unit "user-create"}}
{{/zone}}

@ -1,9 +0,0 @@
{{authorized}}
{{layout "fluid"}}
{{#zone "title"}}
User Management
{{/zone}}
{{#zone "body"}}
{{unit "appbar" link="users" title="User Management"}}
{{unit "user-listing"}}
{{/zone}}

@ -1,12 +0,0 @@
<%
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"));
%>

@ -1,100 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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();
}
});
});

@ -1,20 +0,0 @@
<%
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
require("jaggery-test").test.run();
%>

@ -1,88 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
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();
}
});
});

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

@ -1,39 +0,0 @@
{{#zone "main"}}
<div class="container container-bg white-bg " xmlns="http://www.w3.org/1999/html"
xmlns="http://www.w3.org/1999/html">
<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">
<h2 class="grey ">My Devices </h2>
<hr>
</div>
</div>
</div>
<div class="row margin-double padding-double">
<form method="GET" action="{{myDevicePath}}">
<table class="table table-hover border" id="devicesTable">
<thead>
<tr class="grey-bg">
<th class="uppercase">Device ID</th>
<th class="uppercase">Name</th>
<th class="uppercase">Type</th>
<th class="uppercase center">Action</th>
</tr>
</thead>
<tbody>
{{! All devices will be listed here @see: alldevices_util.js}}
<tr class="border-top">
<th scope="row"></th>
<td colspan="3">
No Devices available.
</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
{{/zone}}
{{#zone "bottomJs"}}
<script src="{{self.publicURL}}/js/alldevices_util.js"></script>
{{/zone}}

@ -1,4 +0,0 @@
function onRequest(context) {
context.myDevicePath = "/iotserver/mydevice";
return context;
}

@ -1,49 +0,0 @@
function getAllDevices() {
var getDevicesRequest = $.ajax({
url: "api/devices/all/",
method: "GET",
contentType: "application/json"
});
getDevicesRequest.done(function (data) {
updateDevicesTable(JSON.parse(data));
});
getDevicesRequest.fail(function (jqXHR, textStatus) {
var err = jqXHR;
alert("Request failed: " + textStatus);
});
}
function updateDevicesTable(data) {
devices = data.data.device;
if (devices.length > 0) {
clearTable('devicesTable');
for (var i = 0; i < devices.length; i++) {
var deviceIdentifier = devices[i].deviceIdentifier;
var deviceName = devices[i].name;
var deviceType = devices[i].type;
$('#devicesTable tbody').append(
"<tr class='border-top'><th scope='row'>" + deviceIdentifier + "</th>" +
"<td>" + deviceName + "</td>" +
"<td>" + deviceType + "</td>" +
"<td class='float-right border-top '>" +
"<input type='hidden' name='deviceType' value='" + deviceType + "' >" +
"<button class='btn-black-action' name='deviceId' value='" + deviceIdentifier + "'>" +
"<i class='fw fw-view padding-right'></i>View</button>" +
"<button class='btn-black-action' name='deviceId' value='" + deviceIdentifier + "'>" +
"<i class='fw fw-edit padding-right'></i>Edit</button>" +
"<button class='btn-black-action' name='deviceId' value='" + deviceIdentifier + "'>" +
"<i class='fw fw-delete padding-right'></i>Remove</button>" +
"</td></tr>");
}
}
}
function clearTable(tableId) {
$('#' + tableId + ' tbody > tr').remove();
}
$(document).ready(function () {
getAllDevices();
});

@ -1,7 +0,0 @@
{{#zone "topCss"}}
<link href="{{self.publicURL}}/css/daterangepicker.css" rel="stylesheet"/>
<link href="{{self.publicURL}}/css/graph.css" rel="stylesheet"/>
<link href="{{self.publicURL}}/css/lines.css" rel="stylesheet"/>
<link href="{{self.publicURL}}/css/legend.css" rel="stylesheet"/>
<link href="{{self.publicURL}}/css/detail.css" rel="stylesheet"/>
{{/zone}}

@ -1,331 +0,0 @@
.date-picker {
width: 170px;
height: 25px;
padding: 0;
border: 0;
line-height: 25px;
padding-left: 10px;
font-size: 12px;
font-family: Arial;
font-weight: bold;
cursor: pointer;
color: #303030;
position: relative;
z-index: 2;
}
.date-picker-wrapper {
position: absolute;
z-index: 1;
border: 1px solid #bfbfbf;
background-color: #efefef;
width: 448px;
padding: 5px 12px;
font-size: 12px;
line-height: 20px;
color: #aaa;
font-family: Arial;
box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.5);
}
.date-picker-wrapper.single-date {
width: auto;
}
.date-picker-wrapper.no-shortcuts {
padding-bottom: 12px;
}
.date-picker-wrapper .footer {
display: none;
font-size: 11px;
padding-top: 3px;
}
.date-picker-wrapper b {
color: #666;
font-weight: 700;
}
.date-picker-wrapper a {
color: rgb(107, 180, 214);
text-decoration: underline;
}
.date-picker-wrapper .month-wrapper {
border: 1px solid #bfbfbf;
border-radius: 3px;
background-color: #fff;
padding: 5px;
cursor: default;
position: relative;
_overflow: hidden;
}
.date-picker-wrapper .month-wrapper table {
width: 190px;
float: left;
}
.date-picker-wrapper .month-wrapper table.month2 {
width: 190px;
float: right;
}
.date-picker-wrapper .month-wrapper table th,
.date-picker-wrapper .month-wrapper table td {
vertical-align: middle;
text-align: center;
line-height: 14px;
margin: 0px;
padding: 0px;
}
.date-picker-wrapper .month-wrapper table .day {
height: 19px;
line-height: 19px;
font-size: 12px;
margin-bottom: 1px;
color: #999;
cursor: default;
}
.date-picker-wrapper .month-wrapper table div.day.lastMonth,
.date-picker-wrapper .month-wrapper table div.day.nextMonth {
color: #999;
cursor: default;
}
.date-picker-wrapper .month-wrapper table .day.checked {
background-color: rgb(156, 219, 247);
}
.date-picker-wrapper .month-wrapper table .week-name {
height: 20px;
line-height: 20px;
font-weight: 100;
}
.date-picker-wrapper .month-wrapper table .day.has-tooltip {
cursor: help !important;
}
.date-picker-wrapper .month-wrapper table .day.toMonth.valid {
color: #333;
cursor: pointer;
}
.date-picker-wrapper .month-wrapper table .day.real-today {
background-color: rgb(255, 230, 132);
}
.date-picker-wrapper .month-wrapper table .day.real-today.checked {
background-color: rgb(112, 204, 213);
}
.date-picker-wrapper table .caption {
height: 40px;
}
.date-picker-wrapper table .caption .next,
.date-picker-wrapper table .caption .prev {
padding: 0 5px;
cursor: pointer;
}
.date-picker-wrapper table .caption .next:hover,
.date-picker-wrapper table .caption .prev:hover {
background-color: #ccc;
color: white;
}
.date-picker-wrapper .gap {
position: absolute;
display: none;
top: 0px;
left: 204px;
z-index: 1;
width: 15px;
height: 100%;
background-color: red;
font-size: 0;
line-height: 0;
}
.date-picker-wrapper .gap .gap-lines {
height: 100%;
overflow: hidden;
}
.date-picker-wrapper .gap .gap-line {
height: 15px;
width: 15px;
position: relative;
}
.date-picker-wrapper .gap .gap-line .gap-1 {
z-index: 1;
height: 0;
border-left: 8px solid white;
border-top: 8px solid #eee;
border-bottom: 8px solid #eee;
}
.date-picker-wrapper .gap .gap-line .gap-2 {
position: absolute;
right: 0;
top: 0px;
z-index: 2;
height: 0;
border-left: 8px solid transparent;
border-top: 8px solid white;
}
.date-picker-wrapper .gap .gap-line .gap-3 {
position: absolute;
right: 0;
top: 8px;
z-index: 2;
height: 0;
border-left: 8px solid transparent;
border-bottom: 8px solid white;
}
.date-picker-wrapper .gap .gap-top-mask {
width: 6px;
height: 1px;
position: absolute;
top: -1px;
left: 1px;
background-color: #eee;
z-index: 3;
}
.date-picker-wrapper .gap .gap-bottom-mask {
width: 6px;
height: 1px;
position: absolute;
bottom: -1px;
left: 7px;
background-color: #eee;
z-index: 3;
}
.date-picker-wrapper .selected-days {
display: none;
}
.date-picker-wrapper .drp_top-bar {
line-height: 40px;
height: 40px;
position: relative;
}
.date-picker-wrapper .drp_top-bar .error-top {
display: none;
}
.date-picker-wrapper .drp_top-bar .normal-top {
display: none;
}
.date-picker-wrapper .drp_top-bar .default-top {
display: block;
}
.date-picker-wrapper .drp_top-bar.error .default-top {
display: none;
}
.date-picker-wrapper .drp_top-bar.error .error-top {
display: block;
color: red;
}
.date-picker-wrapper .drp_top-bar.normal .default-top {
display: none;
}
.date-picker-wrapper .drp_top-bar.normal .normal-top {
display: block;
}
.date-picker-wrapper .drp_top-bar .apply-btn {
position: absolute;
right: 0px;
top: 6px;
padding: 3px 5px;
margin: 0;
font-size: 12px;
border-radius: 4px;
cursor: pointer;
color: #d9eef7;
border: solid 1px #0076a3;
background: #0095cd;
background: -webkit-gradient(linear, left top, left bottom, from(#00adee), to(#0078a5));
background: -moz-linear-gradient(top, #00adee, #0078a5);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00adee', endColorstr='#0078a5');
color: white;
}
.date-picker-wrapper .drp_top-bar .apply-btn.disabled {
pointer-events: none;
color: #606060;
border: solid 1px #b7b7b7;
background: #fff;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#ededed));
background: -moz-linear-gradient(top, #fff, #ededed);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#ededed');
}
/*time styling*/
.time {
position: relative;
}
.time input[type=range] {
vertical-align: middle;
}
.time1, .time2 {
width: 180px;
padding: 0 5px;
text-align: center;
}
.time1 {
float: left;
}
.time2 {
float: right;
}
.hour, .minute {
text-align: left;
}
.hide {
display: none;
}
input.hour-range, input.minute-range {
width: 150px;
}
#dateRangePickerContainer .date-range, #dateRangePickerContainer .input-append {
background: none !important;
}
#date-range{
padding-right:30px;
width:300px;
height:100%;
display:inline-block;
}
#dateRangePickerContainer{
float:right;
margin-top:-6px;
}

@ -1,105 +0,0 @@
.rickshaw_graph .detail {
pointer-events: none;
position: absolute;
top: 0;
z-index: 2;
background: rgba(0, 0, 0, 0.1);
bottom: 0;
width: 1px;
transition: opacity 0.25s linear;
-moz-transition: opacity 0.25s linear;
-o-transition: opacity 0.25s linear;
-webkit-transition: opacity 0.25s linear;
}
.rickshaw_graph .detail.inactive {
opacity: 0;
}
.rickshaw_graph .detail .item.active {
opacity: 1;
}
.rickshaw_graph .detail .x_label {
font-family: Arial, sans-serif;
border-radius: 3px;
padding: 6px;
opacity: 0.5;
border: 1px solid #e0e0e0;
font-size: 12px;
position: absolute;
background: white;
white-space: nowrap;
}
.rickshaw_graph .detail .x_label.left {
left: 0;
}
.rickshaw_graph .detail .x_label.right {
right: 0;
}
.rickshaw_graph .detail .item {
position: absolute;
z-index: 2;
border-radius: 3px;
padding: 0.25em;
font-size: 12px;
font-family: Arial, sans-serif;
opacity: 0;
background: rgba(0, 0, 0, 0.4);
color: white;
border: 1px solid rgba(0, 0, 0, 0.4);
margin-left: 1em;
margin-right: 1em;
margin-top: -1em;
white-space: nowrap;
}
.rickshaw_graph .detail .item.left {
left: 0;
}
.rickshaw_graph .detail .item.right {
right: 0;
}
.rickshaw_graph .detail .item.active {
opacity: 1;
background: rgba(0, 0, 0, 0.8);
}
.rickshaw_graph .detail .item:after {
position: absolute;
display: block;
width: 0;
height: 0;
content: "";
border: 5px solid transparent;
}
.rickshaw_graph .detail .item.left:after {
top: 1em;
left: -5px;
margin-top: -5px;
border-right-color: rgba(0, 0, 0, 0.8);
border-left-width: 0;
}
.rickshaw_graph .detail .item.right:after {
top: 1em;
right: -5px;
margin-top: -5px;
border-left-color: rgba(0, 0, 0, 0.8);
border-right-width: 0;
}
.rickshaw_graph .detail .dot {
width: 4px;
height: 4px;
margin-left: -3px;
margin-top: -3.5px;
border-radius: 5px;
position: absolute;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.6);
box-sizing: content-box;
-moz-box-sizing: content-box;
background: white;
border-width: 2px;
border-style: solid;
display: none;
background-clip: padding-box;
}
.rickshaw_graph .detail .dot.active {
display: block;
}

@ -1,197 +0,0 @@
/* graph */
.rickshaw_graph {
position: relative;
}
.rickshaw_graph svg {
display: block;
overflow: hidden;
}
/* ticks */
.rickshaw_graph .x_tick {
position: absolute;
top: 0;
bottom: 0;
width: 0px;
border-left: 1px dotted rgba(0, 0, 0, 0.2);
pointer-events: none;
}
.rickshaw_graph .x_tick .title {
position: absolute;
font-size: 12px;
font-family: Arial, sans-serif;
opacity: 0.5;
white-space: nowrap;
margin-left: 3px;
bottom: -20px;
}
/* annotations */
.rickshaw_annotation_timeline {
height: 1px;
border-top: 1px solid #e0e0e0;
margin-top: 10px;
position: relative;
}
.rickshaw_annotation_timeline .annotation {
position: absolute;
height: 6px;
width: 6px;
margin-left: -2px;
top: -3px;
border-radius: 5px;
background-color: rgba(0, 0, 0, 0.25);
}
.rickshaw_graph .annotation_line {
position: absolute;
top: 0;
bottom: -6px;
width: 0px;
border-left: 2px solid rgba(0, 0, 0, 0.3);
display: none;
}
.rickshaw_graph .annotation_line.active {
display: block;
}
.rickshaw_graph .annotation_range {
background: rgba(0, 0, 0, 0.1);
display: none;
position: absolute;
top: 0;
bottom: -6px;
}
.rickshaw_graph .annotation_range.active {
display: block;
}
.rickshaw_graph .annotation_range.active.offscreen {
display: none;
}
.rickshaw_annotation_timeline .annotation .content {
background: white;
color: black;
opacity: 0.9;
padding: 5px 5px;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.8);
border-radius: 3px;
position: relative;
z-index: 20;
font-size: 12px;
padding: 6px 8px 8px;
top: 18px;
left: -11px;
width: 160px;
display: none;
cursor: pointer;
}
.rickshaw_annotation_timeline .annotation .content:before {
content: "\25b2";
position: absolute;
top: -11px;
color: white;
text-shadow: 0 -1px 1px rgba(0, 0, 0, 0.8);
}
.rickshaw_annotation_timeline .annotation.active,
.rickshaw_annotation_timeline .annotation:hover {
background-color: rgba(0, 0, 0, 0.8);
cursor: none;
}
.rickshaw_annotation_timeline .annotation .content:hover {
z-index: 50;
}
.rickshaw_annotation_timeline .annotation.active .content {
display: block;
}
.rickshaw_annotation_timeline .annotation:hover .content {
display: block;
z-index: 50;
}
.rickshaw_graph .y_axis,
.rickshaw_graph .x_axis_d3 {
fill: none;
}
.rickshaw_graph .y_ticks .tick line,
.rickshaw_graph .x_ticks_d3 .tick {
stroke: rgba(0, 0, 0, 0.16);
stroke-width: 2px;
shape-rendering: crisp-edges;
pointer-events: none;
}
.rickshaw_graph .y_grid .tick,
.rickshaw_graph .x_grid_d3 .tick {
z-index: -1;
stroke: rgba(0, 0, 0, 0.20);
stroke-width: 1px;
stroke-dasharray: 1 1;
}
.rickshaw_graph .y_grid .tick[data-y-value="0"] {
stroke-dasharray: 1 0;
}
.rickshaw_graph .y_grid path,
.rickshaw_graph .x_grid_d3 path {
fill: none;
stroke: none;
}
.rickshaw_graph .y_ticks path,
.rickshaw_graph .x_ticks_d3 path {
fill: none;
stroke: #808080;
}
.rickshaw_graph .y_ticks text,
.rickshaw_graph .x_ticks_d3 text {
opacity: 0.5;
font-size: 12px;
pointer-events: none;
}
.rickshaw_graph .x_tick.glow .title,
.rickshaw_graph .y_ticks.glow text {
fill: black;
color: black;
text-shadow:
-1px 1px 0 rgba(255, 255, 255, 0.1),
1px -1px 0 rgba(255, 255, 255, 0.1),
1px 1px 0 rgba(255, 255, 255, 0.1),
0px 1px 0 rgba(255, 255, 255, 0.1),
0px -1px 0 rgba(255, 255, 255, 0.1),
1px 0px 0 rgba(255, 255, 255, 0.1),
-1px 0px 0 rgba(255, 255, 255, 0.1),
-1px -1px 0 rgba(255, 255, 255, 0.1);
}
.rickshaw_graph .x_tick.inverse .title,
.rickshaw_graph .y_ticks.inverse text {
fill: white;
color: white;
text-shadow:
-1px 1px 0 rgba(0, 0, 0, 0.8),
1px -1px 0 rgba(0, 0, 0, 0.8),
1px 1px 0 rgba(0, 0, 0, 0.8),
0px 1px 0 rgba(0, 0, 0, 0.8),
0px -1px 0 rgba(0, 0, 0, 0.8),
1px 0px 0 rgba(0, 0, 0, 0.8),
-1px 0px 0 rgba(0, 0, 0, 0.8),
-1px -1px 0 rgba(0, 0, 0, 0.8);
}
.custom_rickshaw_graph {
position: relative;
left: 40px;
}
.custom_y_axis {
position: absolute;
width: 40px;
}
.custom_slider {
left: 40px;
}
.custom_x_axis {
position: relative;
left: 40px;
height: 30px;
}

@ -1,87 +0,0 @@
.rickshaw_legend {
font-family: Arial;
font-size: 12px;
color: white;
background: #404040;
display: inline-block;
padding: 12px 5px;
border-radius: 2px;
position: relative;
float: right;
}
.rickshaw_legend:hover {
z-index: 10;
}
.rickshaw_legend .swatch {
width: 10px;
height: 10px;
border: 1px solid rgba(0, 0, 0, 0.2);
}
.rickshaw_legend .line {
clear: both;
line-height: 140%;
padding-right: 15px;
}
.rickshaw_legend .line .swatch {
display: inline-block;
margin-right: 3px;
border-radius: 2px;
}
.rickshaw_legend .label {
margin: 0;
white-space: nowrap;
display: inline;
font-size: inherit;
background-color: transparent;
color: inherit;
font-weight: normal;
line-height: normal;
padding: 0px;
text-shadow: none;
}
.rickshaw_legend .action:hover {
opacity: 0.6;
}
.rickshaw_legend .action {
margin-right: 0.2em;
font-size: 10px;
opacity: 0.2;
cursor: pointer;
font-size: 14px;
}
.rickshaw_legend .line.disabled {
opacity: 0.4;
}
.rickshaw_legend ul {
list-style-type: none;
margin: 0;
padding: 0;
margin: 2px;
cursor: pointer;
}
.rickshaw_legend li {
padding: 0 0 0 2px;
min-width: 80px;
white-space: nowrap;
}
.rickshaw_legend li:hover {
background: rgba(255, 255, 255, 0.08);
border-radius: 3px;
}
.rickshaw_legend li:active {
background: rgba(255, 255, 255, 0.2);
border-radius: 3px;
}
.legend {
display: inline-block;
position: relative;
left: 8px;
}
.legend_container {
float: right;
padding-right: 10px;
width: 0;
z-index: 1;
position: relative;
opacity: 0.7;
}

@ -1,21 +0,0 @@
div, span, p, td {
font-family: Arial, sans-serif;
}
#chart {
display: inline-block;
}
#legend {
display: inline-block;
position: relative;
left: 8px;
}
#legend_container {
position: absolute;
right: 0;
bottom: 26px;
width: 0;
}
#chart_container {
float: left;
position: relative;
}

@ -1,67 +0,0 @@
{{#zone "main"}}
<span id="request-group-id" data-groupid="{{groupId}}"></span>
<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 ">{{title}}</h1>
<hr>
</div>
</div>
<div id="rangeSliderWrapper" class="pull-right" style="width: 620px;">
<div class="row-fluid">
<div class="span12">
<div id="dateRangePickerContainer">
<div class="btn-group" role="group">
<button id="hour-btn" type="button"
class="btn btn-default date-range">Hour
</button>
<button id="h12-btn" type="button"
class="btn btn-default date-range">12 Hours
</button>
<button id="h24-btn" type="button"
class="btn btn-default date-range">24 Hours
</button>
<button id="h48-btn" type="button"
class="btn btn-default date-range">48 Hours
</button>
<button id="date-range" type="button"
class="btn btn-default date-range last-child"
data-toggle="popup"
title="Click to set custom date range"></button>
</div>
<span class="add-on-cal"><i style="margin-right:0px;"
class="icon-calendar"></i></span>
</div>
</div>
</div>
</div>
<div class="clear"></div>
<div id="div-temperatureData">
</div>
<div id="div-lightData">
</div>
<div id="div-motionData">
</div>
<div id="div-sonarData">
</div>
<div id="div-fanData">
</div>
<div id="div-bulbData">
</div>
<div id="div-cpuTemperatureData">
</div>
<div id="div-CPUData">
</div>
<div id="div-RAMData">
</div>
</div>
</div>
{{/zone}}
{{#zone "bottomLibJs"}}
<script src="{{self.publicURL}}/js/d3.min.js"></script>
<script src="{{self.publicURL}}/js/rickshaw.min.js"></script>
<script src="{{self.publicURL}}/js/moment.min.js"></script>
<script src="{{self.publicURL}}/js/jquery.daterangepicker.js"></script>
<script src="{{self.publicURL}}/js/graph_util.js"></script>
{{/zone}}

@ -1,18 +0,0 @@
function onRequest(context){
var groupId = request.getParameter("groupId");
var title;
if (groupId){
context.groupId = groupId;
title = request.getParameter("name");
}else{
context.groupId = 0;
var deviceModule = require("/modules/device.js").deviceModule;
var deviceId = request.getParameter("deviceId");
var deviceType = request.getParameter("deviceType");
title = deviceModule.getDevice(deviceType, deviceId).name;
}
context.title = title + " Analytics";
return context;
}

@ -1,597 +0,0 @@
var fromDate;
var toDate;
var currentDay = new Date();
var startDate = new Date(currentDay.getTime() - (60 * 60 * 24 * 100));
var endDate = new Date(currentDay.getTime());
var groupId;
var color = ['#c05020', '#30c020', '#6060c0', '#170B3B', '#5E610B', '#2F0B3A', '#FF4000', '#2F0B3A', 'steelblue'];
// create a custom bar renderer that shift bars
Rickshaw.Graph.Renderer.BinaryBar = Rickshaw.Class.create(Rickshaw.Graph.Renderer.Bar, {
name: 'binary_bar',
render: function (args) {
args = args || {};
var graph = this.graph;
var series = args.series || graph.series;
var vis = args.vis || graph.vis;
vis.selectAll('*').remove();
var barWidth = this.barWidth(series.active()[0]);
var barXOffset = 0;
var activeSeriesCount = series.filter(function (s) {
return !s.disabled;
}).length;
var seriesBarWidth = this.unstack ? barWidth / activeSeriesCount : barWidth;
var transform = function (d) {
// add a matrix transform for negative values
var matrix = [1, 0, 0, (d.y < 0 ? -1 : 1), 0, (d.y < 0 ? graph.y.magnitude(Math.abs(d.y)) * 2 : 0)];
return "matrix(" + matrix.join(',') + ")";
};
var index = 0;
series.forEach(function (series) {
if (series.disabled) return;
var nodes = vis.selectAll("path")
.data(series.stack.filter(function (d) {
return d.y !== null
}))
.enter().append("svg:rect")
.attr("x", function (d) {
return graph.x(d.x) + barXOffset
})
.attr("y", function (d) {
return ((graph.y(index + Math.abs(d.y))) * (d.y < 0 ? -1 : 1 ))
})
.attr("width", seriesBarWidth)
.attr("height", function (d) {
return graph.y.magnitude(Math.abs(d.y))
})
.attr("transform", transform);
index++;
Array.prototype.forEach.call(nodes[0], function (n) {
n.setAttribute('fill', series.color);
});
if (this.unstack) barXOffset += seriesBarWidth;
}, this);
}
});
function initDate() {
currentDay = new Date();
}
var configObject = {
startOfWeek: 'monday',
separator: ' to ',
format: 'YYYY-MM-DD HH:mm',
autoClose: false,
time: {
enabled: true
},
shortcuts: 'hide',
endDate: currentDay,
maxDays: 2,
getValue: function () {
return this.value;
},
setValue: function (s) {
this.value = s;
}
};
var DateRange = convertDate(startDate) + " " + configObject.separator + " " + convertDate(endDate);
$(document).ready(function () {
initDate();
groupId = $("#request-group-id").data("groupid");
$('#date-range').html(DateRange);
$('#date-range').dateRangePicker(configObject)
.bind('datepicker-apply', function (event, dateRange) {
$(this).addClass('active');
$(this).siblings().removeClass('active');
fromDate = dateRange.date1 != "Invalid Date" ? dateRange.date1.getTime() / 1000 : null;
toDate = dateRange.date2 != "Invalid Date" ? dateRange.date2.getTime() / 1000 : null;
getStats(fromDate, toDate);
}
);
getDateTime(currentDay.getTime() - 3600000, currentDay.getTime());
$('#hour-btn').addClass('active');
});
//hour
$('#hour-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - 3600000, currentDay.getTime());
});
//12 hours
$('#h12-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - (3600000 * 12), currentDay.getTime());
});
//24 hours
$('#h24-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - (3600000 * 24), currentDay.getTime());
});
//48 hours
$('#h48-btn').on('click', function () {
initDate();
getDateTime(currentDay.getTime() - (3600000 * 48), currentDay.getTime());
});
$('body').on('click', '.btn-group button', function (e) {
$(this).addClass('active');
$(this).siblings().removeClass('active');
});
function getDateTime(from, to) {
fromDate = from;
toDate = to;
startDate = new Date(from);
endDate = new Date(to);
DateRange = convertDate(startDate) + " " + configObject.separator + " " + convertDate(endDate);
console.log(DateRange);
$('#date-range').html(DateRange);
getStats(from / 1000, to / 1000);
}
function getStats(from, to) {
var requestData = new Object();
var getStatsRequest;
if (from) {
requestData['from'] = from;
}
if (to) {
requestData['to'] = to;
}
if (groupId && groupId != "0") {
requestData['groupId'] = groupId;
getStatsRequest = $.ajax({
url: "api/stats/group",
method: "GET",
data: requestData
});
} else {
var deviceId = getUrlParameter('deviceId');
var deviceType = getUrlParameter('deviceType');
requestData['deviceId'] = deviceId;
requestData['deviceType'] = deviceType;
getStatsRequest = $.ajax({
url: "api/stats",
method: "GET",
data: requestData
});
}
getStatsRequest.done(function (stats) {
updateGraphs(JSON.parse(stats));
});
getStatsRequest.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
function getUrlParameter(paramName) {
var pageURL = window.location.search.substring(1);
var urlVariables = pageURL.split('&');
for (var i = 0; i < urlVariables.length; i++) {
var parameterName = urlVariables[i].split('=');
if (parameterName[0] == paramName) {
return parameterName[1];
}
}
}
function updateGraphs(stats) {
console.log(stats);
var temperatureData = stats['temperatureData'];
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>");
drawLineGraph(1, temperatureData);
} else {
$('#div-temperatureData').html("");
}
var lightData = stats['lightData'];
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>");
drawBarGraph(2, lightData);
} else {
$('#div-lightData').html("");
}
var motionData = stats['motionData'];
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>");
drawBarGraph(3, motionData);
} else {
$('#div-motionData').html("");
}
var sonarData = stats['sonarData'];
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>");
drawLineGraph(4, sonarData);
} else {
$('#div-sonarData').html("");
}
var fanData = stats['fanData'];
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>");
drawBarGraph(5, fanData);
} else {
$('#div-fanData').html("");
}
var bulbData = stats['bulbData'];
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>");
drawBarGraph(6, bulbData);
} else {
$('#div-bulbData').html("");
}
var cpuData = stats['cpuData'];
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>");
drawLineGraph(7, cpuData);
} else {
$('#div-CPUData').html("");
}
var ramData = stats['ramData'];
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>");
drawLineGraph(8, ramData);
} else {
$('#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>");
drawLineGraph(9, cpuTemperatureData);
} else {
$('#div-cpuTemperatureData').html("");
}
scaleGraphs();
}
function drawLineGraph(graphId, chartDataRaw) {
var chartWrapperElmId = "#canvas-wrapper" + graphId;
var graphWidth = $(chartWrapperElmId).width() - 50;
if (chartDataRaw.length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
}
var chartDiv = "chart" + graphId;
var sliderDiv = "slider" + graphId;
var y_axis = "y_axis" + graphId;
$(chartWrapperElmId).html("").html('<div id = "' + y_axis
+ '" class="custom_y_axis"></div><div class="legend_container" id="legend_container'
+ graphId + '"><div id="smoother' + graphId + '" title="Smoothing"></div><div class="legend" id="legend'
+ graphId + '"></div></div><div id="' + chartDiv
+ '" class="custom_rickshaw_graph"></div><div class="custom_x_axis"></div><div id="' + sliderDiv
+ '" class="custom_slider"></div>');
var graphConfig = {
element: document.getElementById(chartDiv),
width: graphWidth,
height: 400,
strokeWidth: 2,
renderer: 'line',
unstack: true,
stack: false,
xScale: d3.time.scale(),
padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0},
series: []
};
var k = 0;
var min = Number.MAX_VALUE;
var max = Number.MIN_VALUE;
var range_min = 99999, range_max = 0;
for (var i = 0; i < chartDataRaw.length; i++) {
var chartData = [];
if (chartDataRaw[i].stats.length > 0) {
var max_val = parseInt(chartDataRaw[i].stats[0].value);
var min_val = max_val;
for (var j = 0; j < chartDataRaw[i].stats.length; j++) {
var y_val = parseInt(chartDataRaw[i].stats[j].value);
if (y_val > max_val) {
max_val = y_val;
} else if (y_val < min_val) {
min_val = y_val;
}
chartData.push({
x: parseInt(chartDataRaw[i].stats[j].time),
y: y_val
});
}
if (range_max < max_val) {
range_max = max_val;
}
if (range_min > min_val) {
range_min = min_val;
}
graphConfig['series'].push({
'color': color[k],
'data': summerizeLine(chartData),
'name': chartDataRaw[i].device,
'scale': d3.scale.linear().domain([Math.min(min, min_val), Math.max(max, max_val)]).nice()
});
}
if (++k == color.length) {
k = 0;
}
}
if (graphConfig['series'].length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
}
var graph = new Rickshaw.Graph(graphConfig);
graph.render();
var xAxis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
xAxis.render();
var yAxis = new Rickshaw.Graph.Axis.Y.Scaled({
graph: graph,
orientation: 'left',
element: document.getElementById(y_axis),
width: 40,
height: 410,
'scale': d3.scale.linear().domain([Math.min(min, range_min), Math.max(max, range_max)]).nice()
});
yAxis.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: graph,
element: document.getElementById(sliderDiv)
});
var legend = new Rickshaw.Graph.Legend({
graph: graph,
element: document.getElementById('legend' + graphId)
});
var hoverDetail = new Rickshaw.Graph.HoverDetail({
graph: graph
});
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
graph: graph,
legend: legend
});
var order = new Rickshaw.Graph.Behavior.Series.Order({
graph: graph,
legend: legend
});
var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
graph: graph,
legend: legend
});
}
function drawBarGraph(graphId, chartDataRaw) {
var chartWrapperElmId = "#canvas-wrapper" + graphId;
var graphWidth = $(chartWrapperElmId).width() - 50;
if (chartDataRaw.length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
}
var chartDiv = "chart" + graphId;
var sliderDiv = "slider" + graphId;
var y_axis = "y_axis" + graphId;
$(chartWrapperElmId).html("").html('<div id = "' + y_axis
+ '" class="custom_y_axis"></div><div class="legend_container" id="legend_container'
+ graphId + '"><div id="smoother' + graphId + '" title="Smoothing"></div><div class="legend" id="legend'
+ graphId + '"></div></div><div id="' + chartDiv
+ '" class="custom_rickshaw_graph"></div><div class="custom_x_axis"></div><div id="' + sliderDiv
+ '" class="custom_slider"></div>');
var graphConfig = {
element: document.getElementById(chartDiv),
width: graphWidth,
height: 50 * chartDataRaw.length,
strokeWidth: 0.5,
renderer: 'binary_bar',
offset: 'zero',
xScale: d3.time.scale(),
padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0},
series: []
};
var k = 0;
for (var i = 0; i < chartDataRaw.length; i++) {
var chartData = [];
if (chartDataRaw[i].stats.length > 0) {
for (var j = 0; j < chartDataRaw[i].stats.length; j++) {
chartData.push({
x: parseInt(chartDataRaw[i].stats[j].time),
y: parseInt(chartDataRaw[i].stats[j].value)
});
}
graphConfig['series'].push({
'color': color[k],
'data': summerizeBar(chartData),
'name': chartDataRaw[i].device
});
}
if (++k == color.length) {
k = 0;
}
}
if (graphConfig['series'].length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
}
var graph = new Rickshaw.Graph(graphConfig);
graph.registerRenderer(new Rickshaw.Graph.Renderer.BinaryBar({graph: graph}));
graph.render();
var xAxis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
xAxis.render();
var yAxis = new Rickshaw.Graph.Axis.Y({
graph: graph,
orientation: 'left',
element: document.getElementById(y_axis),
width: 40,
height: 55 * chartDataRaw.length,
tickFormat: function (y) {
return '';
}
});
yAxis.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: graph,
element: document.getElementById(sliderDiv)
});
var legend = new Rickshaw.Graph.Legend({
graph: graph,
element: document.getElementById('legend' + graphId)
});
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
graph: graph,
legend: legend
});
var order = new Rickshaw.Graph.Behavior.Series.Order({
graph: graph,
legend: legend
});
var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
graph: graph,
legend: legend
});
}
function scaleGraphs() {
var sliders = $('.right_handle');
if (sliders.length == 0) {
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;
}
//Scale graphs
var sliderX = graphWidth * 60 * 60000 / (toDate - fromDate);
if (sliderX < graphWidth) {
// fake handle move
if (sliderX < 50) {
sliderX = 50;
}
var edown = document.createEvent("HTMLEvents");
edown.initEvent("mousedown", true, true);
edown.clientX = graphWidth;
var emove = document.createEvent("HTMLEvents");
emove.initEvent("mousemove", true, true);
emove.clientX = sliderX;
var eup = document.createEvent("HTMLEvents");
eup.initEvent("mouseup", true, true);
for (var slider in sliders) {
sliders[slider].dispatchEvent(edown);
document.dispatchEvent(emove);
document.dispatchEvent(eup);
}
}
}
function convertDate(date) {
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
return date.getFullYear() + '-' + (('' + month).length < 2 ? '0' : '')
+ month + '-' + (('' + day).length < 2 ? '0' : '') + day + " " + (('' + hour).length < 2 ? '0' : '')
+ hour + ":" + (('' + minute).length < 2 ? '0' : '') + minute;
}
function summerizeLine(data) {
if (data.length > 1500) {
var nData = [];
var i = 1;
while (i < data.length) {
var t_avg = (data[i - 1].x + data[i].x) / 2;
var v_avg = (data[i - 1].y + data[i].y) / 2;
nData.push({x: t_avg, y: v_avg});
i += 2;
}
return summerizeLine(nData);
} else {
return data;
}
}
function summerizeBar(data) {
if (data.length > 1500) {
var nData = [];
var i = 1;
while (i < data.length - 1) {
var t_avg = (data[i - 1].x + data[i].x) / 2;
var v_avg = (data[i - 1].y + data[i].y + data[i + 1].y) / 3;
nData.push({x: t_avg, y: Math.round(v_avg)});
i += 2;
}
return summerizeBar(nData);
} else {
return data;
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -1,56 +0,0 @@
{{#zone "main"}}
<!-- new markup -->
<!-- secondary header - app bar -->
<div id="nav" class="row wr-app-bar">
<div class="wr-action-container">
<div class="wr-action-btn-bar">
<a href="javascript:openCollapsedNav()" class="cu-btn wr-hidden-nav-toggle-btn">
<i class="fw fw-tiles fw-2x"></i>
</a><a class="cu-btn page-title" href='javascript:location.reload();'>
<span class="fw-stack"></span>
{{title}}
</a>{{#each currentActions}}<a href="{{url}}" class="cu-btn {{class}}">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw {{icon}} fw-stack-1x"></i>
</span>
{{title}}
</a>
{{/each}}{{#if enableBack}}<a href="javascript:history.go(-1)" class="cu-btn">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-left-arrow fw-stack-1x"></i>
</span>
Go Back
</a>
{{/if}}
<a href="javascript:toggleNotificationbar()" class="cu-btn wr-notification-toggle-btn">
<span class="fw-stack-md">
<i class="fw fw-bell fw-stack-1-5x"></i>
</span>
<span class="wr-notification-bubble">0</span>
</a>
</div>
</div>
</div>
<!-- secondary header - app bar -->
<!-- common navigation -->
<div id="hiddenNav" class="wr-hidden-nav">
<ul>
<li><a href="/iotserver/dashboard"><i class="fw fw-dashboard"></i>Dashboard</a></li>
<li><a href="/iotserver/devices"><i class="fw fw-devices"></i>My Devices</a></li>
<li><a href="/iotserver/groups"><i class="fw fw-grouping"></i>My Groups</a></li>
{{#if permissions.ADD_USER}}
<li><a href="/iotserver/users"><i class="fw fw-user"></i>User Management</a></li>
{{/if}}
<li><a href="/iotserver/policies"><i class="fw fw-policy"></i>Policy Management</a></li>
</ul>
</div>
<!-- /common navigation -->
{{/zone}}

@ -1,110 +0,0 @@
function onRequest(context) {
var constants = require("/modules/constants.js");
var carbonUser = session.get(constants.USER_SESSION_KEY);
var links = {
"users": [],
"policies": [],
"profiles": [],
"device-mgt": [],
"group-mgt": [],
"store": [],
"dashboard": [],
"analytics" : [],
"events" : []
};
var dashboardLink = {
title: "Go back to Dashboard",
icon: "fw-left-arrow",
url: "/iotserver/dashboard"
};
var deviceMgtLink = {
title: "Go back to My Devices",
icon: "fw-left-arrow",
url: "/iotserver/devices"
};
var groupMgtLink = {
title: "Go back to Groups",
icon: "fw-left-arrow",
url: "/iotserver/groups"
};
var storeLink = {
title: "Go back to Store",
icon: "fw-left-arrow",
url: "/iotserver"
};
links.users.push(dashboardLink);
links.policies.push(dashboardLink);
links.profiles.push(dashboardLink);
links.events.push(dashboardLink);
//links.store.push(dashboardLink);
links.store.push(storeLink);
links['group-mgt'].push(dashboardLink);
var groupId = request.getParameter("groupId");
if (groupId){
links.analytics.push(groupMgtLink);
links['device-mgt'].push(groupMgtLink);
}else{
links.analytics.push(deviceMgtLink);
links['device-mgt'].push(dashboardLink);
}
if (!carbonUser) {
//user is not logged in
}else{
var userModule = require("/modules/user.js").userModule;
var permissions = userModule.getUIPermissions();
context.permissions = permissions;
//if (permissions.ADD_USER) {
// links.users.push({
// title: "Add User",
// icon: "fw-add-user",
// url: "/iotserver/users/add-user"
// });
//}
if (permissions.ADD_POLICY) {
links.policies.push({
title: "Add Policy",
icon: "fw-policy",
url: "/iotserver/policies/add-policy"
});
}
//if (permissions.ADD_USER) {
// links.profiles.push({
// title: "Add Profile",
// icon: "fw-settings",
// url: "/iotserver/profiles/add-profile"
// });
//}
if (permissions.ADD_DEVICE) {
links["device-mgt"].push({
title: "Add Device",
icon: "fw-add",
url: "/iotserver/devices/add-device"
});
}
if (permissions.ADD_DEVICE) {
links["device-mgt"].push({
title: "Add Group",
icon: "fw-add",
url: "/iotserver/groups/add-group"
});
links["group-mgt"].push({
title: "Add Group",
icon: "fw-add",
url: "/iotserver/groups/add-group"
});
}
}// end-if-user
context.currentActions = links[context.link];
return context;
}

@ -1,147 +0,0 @@
{{#zone "main"}}
<!-- dashboard -->
<div class="container-fluid wr-content-alt">
<div class="row wr-stats-board">
<div class="col-md-4">
<div class="wr-stats-board-tile">
<div class="tile-name">Devices</div>
<div>
<div class="tile-icon"><i class="fw fw-devices"></i></div>
<div class="tile-stats">
<span id="device-count">Loading...</span>
<span class="tile-stats-free">
<a href="devices/">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
View
</a>
<a href="devices/add-device">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i>
</span>
Add
</a>
</span>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="wr-stats-board-tile">
<div class="tile-name">Groups</div>
<div>
<div class="tile-icon"><i class="fw fw-grouping"></i></div>
<div class="tile-stats">
<span id="group-count">Loading...</span>
<span class="tile-stats-free">
<a href="groups">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
View
</a>
<a href="groups/add-group">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i>
</span>
Add
</a>
</span>
</div>
</div>
</div>
</div>
{{#if permissions.ADD_USER}}
<div class="col-md-4">
<div class="wr-stats-board-tile">
<div class="tile-name">Users</div>
<div>
<div class="tile-icon"><i class="fw fw-user"></i></div>
<div class="tile-stats">
<span id="user-count">Loading...</span>
<span class="tile-stats-free">
<a href="users/">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
View
</a>
<!--<a href="user-create.html">-->
<!--<span class="fw-stack">-->
<!--<i class="fw fw-ring fw-stack-2x"></i>-->
<!--<i class="fw fw-add fw-stack-1x"></i>-->
<!--</span>-->
<!--Add-->
<!--</a>-->
</span>
</div>
</div>
</div>
</div>
{{/if}}
<div class="col-md-4">
<div class="wr-stats-board-tile">
<div class="tile-name">Policies</div>
<div>
<div class="tile-icon"><i class="fw fw-policy"></i></div>
<div class="tile-stats">
<span id="policy-count">Loading...</span>
<span class="tile-stats-free">
<a href="policies">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
View
</a>
<a href="policies/add-policy">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i>
</span>
Add
</a>
</span>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="wr-stats-board-tile">
<div class="tile-name">Events</div>
<div>
<div class="tile-icon"><i class="fw fw-apn"></i></div>
<div class="tile-stats">
<span id="events-count">&nbsp;</span>
<span class="tile-stats-free">
<a href="events">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-view fw-stack-1x"></i>
</span>
View
</a>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /dashboard -->
{{/zone}}
{{#zone "bottomJs"}}
<script src="{{self.publicURL}}/js/dashboard.js"></script>
{{/zone}}

@ -1,6 +0,0 @@
function onRequest(context){
var userModule = require("/modules/user.js").userModule;
var permissions = userModule.getUIPermissions();
context.permissions = permissions;
return context;
}

@ -1,17 +0,0 @@
var updateStats = function (serviceURL, id) {
invokerUtil.get(
serviceURL,
function (result) {
$(id).html(JSON.parse(result));
}, function (message) {
console.log(message);
}
);
};
$(document).ready(function () {
updateStats("/iotserver/api/devices/count", "#device-count");
updateStats("/iotserver/api/group/all/count", "#group-count");
updateStats("/iotserver/api/policies/count", "#policy-count");
updateStats("/iotserver/api/users/count", "#user-count");
});

@ -1,230 +0,0 @@
{{#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.dateOfEnrolment}}</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">
<!--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 fw-stack-1x"></i>
</span>
Device Details
</a>
</h2>
</div>
<div id="collapseOne" class="panel-collapse collapse in"
role="tabpanel" aria-labelledby="headingOne">
<div id="device-location" class="panel-body">
IP Address: 0.0.0.0
</div>
</div>
</div>
<!--/device location -->
<!-- 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 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="../../analytics?deviceId={{deviceId}}&deviceType={{deviceType}}"><i
class="fw fw-charts"></i> Show Statistics</a>
</div>
</div>
</div>
<!-- /statistics -->
<!-- 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 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}}

@ -1,59 +0,0 @@
var log = new Log("modules/device-detail.js");
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;
}

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

Loading…
Cancel
Save