Merge pull request #179 from charithag/master

Fix issues mentioned in PRs
application-manager-new
Ruwan 8 years ago committed by GitHub
commit 03fb29016c

@ -19,11 +19,9 @@
<html>
<head>
<title>Connected Coffee Cup</title>
<link rel="stylesheet" href="css/coffee.css">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
@ -48,7 +46,6 @@
if (token != null) {
request.getSession().setAttribute("token", token);
}
%>
<div class="container">
@ -100,22 +97,19 @@
<script src="js/libs/htmlpreview.min.js"></script>
<script>HTMLPreview.replaceAssets();</script>
<script>
$("#order-cup").click(function () {
$('#order-cup').click(function () {
var deviceId = '<%=request.getSession().getAttribute("deviceId")%>';
var deviceOwner = '<%=request.getSession().getAttribute("deviceOwner")%>';
var token = '<%=request.getSession().getAttribute("token")%>';
var url = "/connectedcup/controller/ordercoffee?deviceId=" + deviceId + "&deviceOwner=" + deviceOwner;
var url = '/connectedcup/controller/ordercoffee?deviceId=' + deviceId + '&deviceOwner=' + deviceOwner;
$.ajax({
type: 'POST',
url: url,
headers: {
"Authorization": "Bearer " + token
'Authorization': 'Bearer ' + token
}
});
});
function sendData() {
@ -123,19 +117,18 @@
var deviceOwner = '<%=request.getSession().getAttribute("deviceOwner")%>';
var tenantDomain = '<%=request.getSession().getAttribute("tenantDomain")%>';
if (tenantDomain == null) {
tenantDomain = "carbon.super";
tenantDomain = 'carbon.super';
}
var tempPayload = temperature;
var levelPayload = coffee_amount;
$.post("/connected-cup-agent/push_temperature?deviceId=" + deviceId + "&deviceOwner=" + deviceOwner +
"&payload=" + tempPayload + "&tenantDomain=" + tenantDomain );
$.post("/connected-cup-agent/push_level?deviceId=" + deviceId + "&deviceOwner=" + deviceOwner +
"&payload=" + levelPayload + "&tenantDomain=" + tenantDomain);
$.post('/connected-cup-agent/push_temperature?deviceId=' + deviceId + '&deviceOwner=' + deviceOwner +
'&payload=' + tempPayload + '&tenantDomain=' + tenantDomain);
$.post('/connected-cup-agent/push_level?deviceId=' + deviceId + '&deviceOwner=' + deviceOwner +
'&payload=' + levelPayload + '&tenantDomain=' + tenantDomain);
setTimeout(sendData, 5000);
}
sendData();
</script>
</body>
</html>

@ -19,21 +19,21 @@
var temperature = 0;
var coffee_amount = 0;
function updateCoffee(newValue){
var coffee_level = document.getElementById("coffee_level");
coffee_level.innerHTML = newValue + "%";
coffee_amount =newValue;
function updateCoffee(newValue) {
var coffee_level = document.getElementById('coffee_level');
coffee_level.innerHTML = newValue + '%';
coffee_amount = newValue;
var coffee = document.getElementById("water");
if(newValue == 0){
coffee.style.height= (newValue*3) + 'px';
}else{
coffee.style.height= (newValue*3) - 3 + 'px';
var coffee = document.getElementById('water');
if (newValue == 0) {
coffee.style.height = (newValue * 3) + 'px';
} else {
coffee.style.height = (newValue * 3) - 3 + 'px';
}
}
function updateTemperature(newValue){
function updateTemperature(newValue) {
temperature = newValue;
var temperature_level = document.getElementById("temperature_level");
temperature_level.innerHTML = newValue + " C";
}
var temperature_level = document.getElementById('temperature_level');
temperature_level.innerHTML = newValue + ' C';
}

@ -25,13 +25,11 @@ import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@API(name = "connectedcup", version = "1.0.0", context = "/connectedcup", tags = {"connectedcup"})
@ -53,7 +51,7 @@ public interface ConnectedCupService {
@Produces("application/json")
@Permission(scope = "connectedcup_user", permissions = {"/permission/admin/device-mgt/user/stats"})
Response getDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor,
@QueryParam("from") long from, @QueryParam("to") long to);
@QueryParam("from") long from, @QueryParam("to") long to);
@Path("device/register")
@POST

@ -23,14 +23,14 @@ import org.apache.commons.logging.LogFactory;
import org.coffeeking.api.util.APIUtil;
import org.coffeeking.api.util.SensorRecord;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.wso2.carbon.analytics.dataservice.commons.SORT;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.analytics.dataservice.commons.SORT;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import javax.ws.rs.Consumes;
@ -52,13 +52,19 @@ public class ConnectedCupServiceImpl implements ConnectedCupService {
private static Log log = LogFactory.getLog(ConnectedCupServiceImpl.class);
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
@Path("device/ordercoffee")
@POST
public Response orderCoffee(@QueryParam("deviceId") String deviceId) {
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
ConnectedCupConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.
DEFAULT_OPERATOR_PERMISSIONS)) {
if (!APIUtil.getDeviceAccessAuthorizationService()
.isUserAuthorized(new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE),
DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
log.info("Coffee ordered....!");
@ -77,16 +83,17 @@ public class ConnectedCupServiceImpl implements ConnectedCupService {
@Consumes("application/json")
@Produces("application/json")
public Response getDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor,
@QueryParam("from") long from, @QueryParam("to") long to) {
@QueryParam("from") long from, @QueryParam("to") long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String query = " deviceId:" + deviceId + " AND deviceType:" +
ConnectedCupConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
ConnectedCupConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = getSensorEventTableName(sensor);
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
ConnectedCupConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
if (!APIUtil.getDeviceAccessAuthorizationService()
.isUserAuthorized(new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE),
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
List<SensorRecord> sensorDatas;
@ -151,10 +158,4 @@ public class ConnectedCupServiceImpl implements ConnectedCupService {
}
}
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
}

@ -11,7 +11,7 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@ -20,10 +20,6 @@ package org.coffeeking.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry;
@ -31,6 +27,10 @@ import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils;
import org.wso2.carbon.analytics.datasource.commons.Record;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import java.util.ArrayList;
import java.util.HashMap;
@ -42,114 +42,108 @@ import java.util.Map;
*/
public class APIUtil {
private static Log log = LogFactory.getLog(APIUtil.class);
private static Log log = LogFactory.getLog(APIUtil.class);
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
if (username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@"));
}
return username;
}
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
if (username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@"));
}
return username;
}
public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
throw new IllegalStateException("Device Management service has not initialized");
}
return deviceManagementProviderService;
}
public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
(DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null);
if (deviceAccessAuthorizationService == null) {
String msg = "Device Authorization service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceAccessAuthorizationService;
}
public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
(DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null);
if (deviceAccessAuthorizationService == null) {
throw new IllegalStateException("Device Authorization service has not initialized");
}
return deviceAccessAuthorizationService;
}
public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI =
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
if (analyticsDataAPI == null) {
String msg = "Analytics api service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return analyticsDataAPI;
}
public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI =
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
if (analyticsDataAPI == null) {
throw new IllegalStateException("Analytics api service has not initialized");
}
return analyticsDataAPI;
}
public static List<SensorRecord> getAllEventsForDevice(String tableName, String query,
List<SortByField> sortByFields) throws AnalyticsException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI();
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
if (eventCount == 0) {
return null;
}
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount,
sortByFields);
List<String> recordIds = getRecordIds(resultEntries);
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
Map<String, SensorRecord> sensorDatas = createSensorData(AnalyticsDataServiceUtils.listRecords(
analyticsDataAPI, response));
List<SensorRecord> sortedSensorData = getSortedSensorData(sensorDatas, resultEntries);
return sortedSensorData;
}
public static List<SensorRecord> getAllEventsForDevice(String tableName, String query,
List<SortByField> sortByFields) throws AnalyticsException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI();
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
if (eventCount == 0) {
return null;
}
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount,
sortByFields);
List<String> recordIds = getRecordIds(resultEntries);
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
Map<String, SensorRecord> sensorDatas = createSensorData(AnalyticsDataServiceUtils.listRecords(
analyticsDataAPI, response));
List<SensorRecord> sortedSensorData = getSortedSensorData(sensorDatas, resultEntries);
return sortedSensorData;
}
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
List<String> ids = new ArrayList<>();
for (SearchResultEntry searchResult : searchResults) {
ids.add(searchResult.getId());
}
return ids;
}
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
List<String> ids = new ArrayList<>();
for (SearchResultEntry searchResult : searchResults) {
ids.add(searchResult.getId());
}
return ids;
}
public static List<SensorRecord> getSortedSensorData(Map<String, SensorRecord> sensorDatas,
List<SearchResultEntry> searchResults) {
List<SensorRecord> sortedRecords = new ArrayList<>();
for (SearchResultEntry searchResultEntry : searchResults) {
sortedRecords.add(sensorDatas.get(searchResultEntry.getId()));
}
return sortedRecords;
}
public static List<SensorRecord> getSortedSensorData(Map<String, SensorRecord> sensorDatas,
List<SearchResultEntry> searchResults) {
List<SensorRecord> sortedRecords = new ArrayList<>();
for (SearchResultEntry searchResultEntry : searchResults) {
sortedRecords.add(sensorDatas.get(searchResultEntry.getId()));
}
return sortedRecords;
}
/**
* Creates the SensorDatas from records.
*
* @param records the records
* @return the Map of SensorRecord <id, SensorRecord>
*/
public static Map<String, SensorRecord> createSensorData(List<Record> records) {
Map<String, SensorRecord> sensorDatas = new HashMap<>();
for (Record record : records) {
SensorRecord sensorData = createSensorData(record);
sensorDatas.put(sensorData.getId(), sensorData);
}
return sensorDatas;
}
/**
* Creates the SensorDatas from records.
*
* @param records the records
* @return the Map of SensorRecord <id, SensorRecord>
*/
public static Map<String, SensorRecord> createSensorData(List<Record> records) {
Map<String, SensorRecord> sensorDatas = new HashMap<>();
for (Record record : records) {
SensorRecord sensorData = createSensorData(record);
sensorDatas.put(sensorData.getId(), sensorData);
}
return sensorDatas;
}
/**
* Create a SensorRecord object out of a Record object
*
* @param record the record object
* @return SensorRecord object
*/
public static SensorRecord createSensorData(Record record) {
SensorRecord recordBean = new SensorRecord();
recordBean.setId(record.getId());
recordBean.setValues(record.getValues());
return recordBean;
}
/**
* Create a SensorRecord object out of a Record object
*
* @param record the record object
* @return SensorRecord object
*/
public static SensorRecord createSensorData(Record record) {
SensorRecord recordBean = new SensorRecord();
recordBean.setId(record.getId());
recordBean.setValues(record.getValues());
return recordBean;
}
}

@ -37,12 +37,12 @@ public class SensorRecord {
@XmlElementWrapper(required = true, name = "values")
private Map<String, Object> values;
/** The id. */
@XmlElement(required = false, name = "id")
private String id;
/**
* Gets the values.
*
* @return the values
*/
public Map<String, Object> getValues() {
@ -51,30 +51,33 @@ public class SensorRecord {
/**
* Sets the values.
*
* @param values the values
*/
public void setValues(Map<String, Object> values) {
this.values = values;
}
/**
* Sets the id.
* @param id the new id
*/
public void setId(String id) {
this.id = id;
}
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(String id) {
this.id = id;
}
@Override
public String toString(){
public String toString() {
List<String> valueList = new ArrayList<String>();
for (Map.Entry<String, Object> entry : values.entrySet()) {
valueList.add(entry.getKey() + ":" + entry.getValue());

@ -18,6 +18,7 @@
package org.coffeeking.connectedcup.plugin.constants;
public class ConnectedCupConstants {
public final static String DEVICE_TYPE = "connectedcup";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "CONNECTED_CUP_DEVICE_ID";

@ -17,19 +17,10 @@
*/
package org.coffeeking.connectedcup.plugin.exception;
public class ConnectedCupDeviceMgtPluginException extends Exception{
public class ConnectedCupDeviceMgtPluginException extends Exception {
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public ConnectedCupDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
@ -53,4 +44,12 @@ public class ConnectedCupDeviceMgtPluginException extends Exception{
super(cause);
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -44,7 +44,7 @@ public class ConnectedCupServiceComponent {
BundleContext bundleContext = ctx.getBundleContext();
connectedCupServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(),
new ConnectedCupManagerService(), null);
new ConnectedCupManagerService(), null);
if (log.isDebugEnabled()) {
log.debug("Connected Cup Service Component has been successfully activated");
@ -70,4 +70,5 @@ public class ConnectedCupServiceComponent {
log.error("Error occurred while de-activating Connected Cup Service Component", e);
}
}
}

@ -1,4 +1,3 @@
<iframe src="{{dashboardserverURL}}/portal/gadgets/connected-cup-analytics/landing" width="100%" height="1700" frameBorder="0"></iframe>
<style>
@ -7,4 +6,4 @@
{{#zone "bottomJs"}}
{{js "js/connectedcup.js"}}
{{/zone}}
{{/zone}}

@ -21,26 +21,26 @@ function onRequest(context) {
var devices = context.unit.params.devices;
var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("deviceId");
var deviceId = request.getParameter('deviceId');
if (devices) {
return {
"devices": stringify(devices),
"backendApiUri": devicemgtProps["httpsURL"] + "/connectedcup/stats/",
"dashboardserverURL" : devicemgtProps["dashboardserverURL"]
'devices': stringify(devices),
'backendApiUri': devicemgtProps['httpsURL'] + '/connectedcup/stats/',
'dashboardserverURL': devicemgtProps['dashboardserverURL']
};
} else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule;
} else if (deviceType && deviceId) {
var deviceModule = require('/app/modules/device.js').deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") {
if (device && device.status != 'error') {
return {
"device": device,
"backendApiUri": devicemgtProps["httpsURL"] + "/connectedcup/stats/" + deviceId,
"dashboardserverURL" : devicemgtProps["dashboardserverURL"]
'device': device,
'backendApiUri': devicemgtProps['httpsURL'] + '/connectedcup/stats/' + deviceId,
'dashboardserverURL': devicemgtProps['dashboardserverURL']
};
} else {
response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!");
response.sendError(404, 'Device Id ' + deviceId + ' of type ' + deviceType + ' cannot be found!');
exit();
}
}
}
}

@ -16,35 +16,35 @@
* under the License.
*/
var palette = new Rickshaw.Color.Palette({scheme: "classic9"});
var palette = new Rickshaw.Color.Palette({scheme: 'classic9'});
function drawGraph_connectedcup(from, to) {
$("#y_axis-temperature").html("");
$("#smoother-temperature").html("");
$("#legend-temperature").html("");
$("#chart-temperature").html("");
$("#x_axis-temperature").html("");
$("#slider-temperature").html("");
$("#y_axis-coffeelevel").html("");
$("#smoother-coffeelevel").html("");
$("#legend-coffeelevel").html("");
$("#chart-coffeelevel").html("");
$("#x_axis-coffeelevel").html("");
$("#slider-coffeelevel").html("");
var devices = $("#connectedcup-details").data("devices");
$('#y_axis-temperature').html('');
$('#smoother-temperature').html('');
$('#legend-temperature').html('');
$('#chart-temperature').html('');
$('#x_axis-temperature').html('');
$('#slider-temperature').html('');
$('#y_axis-coffeelevel').html('');
$('#smoother-coffeelevel').html('');
$('#legend-coffeelevel').html('');
$('#chart-coffeelevel').html('');
$('#x_axis-coffeelevel').html('');
$('#slider-coffeelevel').html('');
var devices = $('#connectedcup-details').data('devices');
var tzOffset = new Date().getTimezoneOffset() * 60;
var chartWrapperElmId = "#connectedcup-div-chart";
var chartWrapperElmId = '#connectedcup-div-chart';
var graphWidth = $(chartWrapperElmId).width() - 50;
var temperatureGraphConfig = {
element: document.getElementById("chart-temperature"),
element: document.getElementById('chart-temperature'),
width: graphWidth,
height: 400,
strokeWidth: 2,
renderer: 'line',
interpolation: "linear",
interpolation: 'linear',
unstack: true,
stack: false,
xScale: d3.time.scale(),
@ -53,12 +53,12 @@ function drawGraph_connectedcup(from, to) {
};
var coffeelevelGraphConfig = {
element: document.getElementById("chart-coffeelevel"),
element: document.getElementById('chart-coffeelevel'),
width: graphWidth,
height: 400,
strokeWidth: 2,
renderer: 'line',
interpolation: "linear",
interpolation: 'linear',
unstack: true,
stack: false,
xScale: d3.time.scale(),
@ -79,34 +79,34 @@ function drawGraph_connectedcup(from, to) {
});
coffeelevelGraphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': devices[i].name
});
}
} else {
temperatureGraphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': devices[i].name
'name': $('#connectedcup-details').data('devicename')
});
}
} else {
temperatureGraphConfig['series'].push(
coffeelevelGraphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': $("#connectedcup-details").data("devicename")
'name': $('#connectedcup-details').data('devicename')
});
coffeelevelGraphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': $("#connectedcup-details").data("devicename")
});
}
var temperatureGraph = new Rickshaw.Graph(temperatureGraphConfig);
@ -130,7 +130,7 @@ function drawGraph_connectedcup(from, to) {
var yAxisTemperature = new Rickshaw.Graph.Axis.Y({
graph: temperatureGraph,
orientation: 'left',
element: document.getElementById("y_axis-temperature"),
element: document.getElementById('y_axis-temperature'),
width: 40,
height: 410
});
@ -140,7 +140,7 @@ function drawGraph_connectedcup(from, to) {
var yAxisCoffeelevel = new Rickshaw.Graph.Axis.Y({
graph: coffeelevelGraph,
orientation: 'left',
element: document.getElementById("y_axis-coffeelevel"),
element: document.getElementById('y_axis-coffeelevel'),
width: 40,
height: 410
});
@ -149,7 +149,7 @@ function drawGraph_connectedcup(from, to) {
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: temperatureGraph,
element: document.getElementById("slider-temperature")
element: document.getElementById('slider-temperature')
});
var legend = new Rickshaw.Graph.Legend({
@ -159,7 +159,7 @@ function drawGraph_connectedcup(from, to) {
var sliderCoffee = new Rickshaw.Graph.RangeSlider.Preview({
graph: coffeelevelGraph,
element: document.getElementById("slider-coffeelevel")
element: document.getElementById('slider-coffeelevel')
});
var legendCoffee = new Rickshaw.Graph.Legend({
@ -174,7 +174,7 @@ function drawGraph_connectedcup(from, to) {
moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
var swatch = '<span class="detail_swatch" style="background-color: ' +
series.color + '"></span>';
return swatch + series.name + ": " + parseInt(y) + '<br>' + date;
return swatch + series.name + ': ' + parseInt(y) + '<br>' + date;
}
});
@ -182,10 +182,10 @@ function drawGraph_connectedcup(from, to) {
graph: coffeelevelGraph,
formatter: function (series, x, y) {
var date = '<span class="date">' +
moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
var swatch = '<span class="detail_swatch" style="background-color: ' +
series.color + '"></span>';
return swatch + series.name + ": " + parseInt(y) + '<br>' + date;
series.color + '"></span>';
return swatch + series.name + ': ' + parseInt(y) + '<br>' + date;
}
});
@ -224,7 +224,7 @@ function drawGraph_connectedcup(from, to) {
if (devices) {
getData();
} else {
var backendApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + "/sensors/temperature" + "?from=" + from + "&to=" + to;
var backendApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + '/sensors/temperature' + '?from=' + from + '&to=' + to;
var successCallback = function (data) {
if (data) {
drawTemperatureLineGraph(JSON.parse(data));
@ -234,8 +234,8 @@ function drawGraph_connectedcup(from, to) {
console.log(message);
});
var coffeeLevelApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + "/sensors/coffeelevel"
+ "?from=" + from + "&to=" + to;
var coffeeLevelApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + '/sensors/coffeelevel'
+ '?from=' + from + '&to=' + to;
var successCallbackCoffeeLevel = function (data) {
if (data) {
drawCoffeeLevelLineGraph(JSON.parse(data));
@ -250,9 +250,9 @@ function drawGraph_connectedcup(from, to) {
if (deviceIndex >= devices.length) {
return;
}
var backendApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + devices[deviceIndex].deviceIdentifier
+ "/sensors/temperature"
+ "?from=" + from + "&to=" + to;
var backendApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + devices[deviceIndex].deviceIdentifier
+ '/sensors/temperature'
+ '?from=' + from + '&to=' + to;
var successCallback = function (data) {
if (data) {
drawTemperatureLineGraph(JSON.parse(data));
@ -265,8 +265,8 @@ function drawGraph_connectedcup(from, to) {
deviceIndex++;
getData();
});
var coffeeLevelApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + devices[deviceIndex].deviceIdentifier
+ "/sensors/coffeelevel" + "?from=" + from + "&to=" + to;
var coffeeLevelApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + devices[deviceIndex].deviceIdentifier
+ '/sensors/coffeelevel' + '?from=' + from + '&to=' + to;
var successCallbackCoffeeLevel = function (data) {
if (data) {
@ -305,10 +305,10 @@ function drawGraph_connectedcup(from, to) {
var chartData = [];
for (var i = 0; i < data.length; i++) {
chartData.push(
{
x: parseInt(data[i].values.time) - tzOffset,
y: parseInt(data[i].values.coffeelevel)
}
{
x: parseInt(data[i].values.time) - tzOffset,
y: parseInt(data[i].values.coffeelevel)
}
);
}

@ -18,28 +18,27 @@
function onRequest(context) {
var log = new Log("detail.js");
var log = new Log('detail.js');
var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("id");
var deviceId = request.getParameter('id');
var property = require("process").getProperty;
var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule;
if (deviceType && deviceId) {
var deviceModule = require('/app/modules/device.js').deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") {
if (device && device.status != 'error') {
log.info(device);
var constants = require("/app/modules/constants.js");
var constants = require('/app/modules/constants.js');
var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER);
var token = "";
var token = '';
if (tokenPair) {
token = tokenPair.accessToken;
token = tokenPair.accessToken;
}
device.accessToken = token;
device.ip = devicemgtProps["httpsWebURL"];
return {"device": device};
device.ip = devicemgtProps['httpsWebURL'];
return {'device': device};
}
}
}
}

@ -17,17 +17,16 @@
*/
function onRequest(context) {
var log = new Log("stats.js");
var device = context.unit.params.device;
var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
var constants = require("/app/modules/constants.js");
var websocketEndpoint = devicemgtProps["wssURL"].replace("https", "wss");
var constants = require('/app/modules/constants.js');
var websocketEndpoint = devicemgtProps['wssURL'].replace('https', 'wss');
var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER);
var token = "";
var token = '';
if (tokenPair) {
token = tokenPair.accessToken;
token = tokenPair.accessToken;
}
websocketEndpoint = websocketEndpoint + "/secured-outputui/org.wso2.iot.connectedcup/1.0.0?" +
"token="+ token +"&deviceId=" + device.deviceIdentifier;
return {"device": device, "websocketEndpoint" : websocketEndpoint};
}
websocketEndpoint = websocketEndpoint + '/secured-outputui/org.wso2.iot.connectedcup/1.0.0?' +
'token=' + token + '&deviceId=' + device.deviceIdentifier;
return {'device': device, 'websocketEndpoint': websocketEndpoint};
}

@ -23,7 +23,7 @@ var coffeeData = [];
var temperature = 0;
var coffeelevel = 0;
var lastTime = 0;
var palette = new Rickshaw.Color.Palette({scheme: "classic9"});
var palette = new Rickshaw.Color.Palette({scheme: 'classic9'});
$(window).load(function () {
var tNow = new Date().getTime() / 1000;
@ -39,20 +39,20 @@ $(window).load(function () {
}
graph = new Rickshaw.Graph({
element: document.getElementById("chart"),
width: $("#div-chart").width() - 50,
element: document.getElementById('chart'),
width: $('#div-chart').width() - 50,
height: 300,
renderer: "line",
renderer: 'line',
padding: {top: 0.2, left: 0.0, right: 0.0, bottom: 0.2},
xScale: d3.time.scale(),
series: [{
'color': palette.color(),
'data': coffeeData,
'name': "Coffee Level"
},{
'name': 'Coffee Level'
}, {
'color': palette.color(),
'data': temperatureData,
'name': "Temperature"
'name': 'Temperature'
}]
});
@ -77,11 +77,11 @@ $(window).load(function () {
formatter: function (series, x, y) {
var date = '<span class="date">' + moment(x * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
var swatch = '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>';
return swatch + series.name + ": " + parseInt(y) + '<br>' + date;
return swatch + series.name + ': ' + parseInt(y) + '<br>' + date;
}
});
var websocketUrl = $("#div-chart").data("websocketurl");
var websocketUrl = $('#div-chart').data('websocketurl');
connect(websocketUrl)
});
@ -103,9 +103,9 @@ function connect(target) {
var dataPoint = JSON.parse(event.data);
if (lastTime < parseInt(dataPoint[4]) / 1000) {
lastTime = parseInt(dataPoint[4]) / 1000;
if (dataPoint[3] == "temperature") {
if (dataPoint[3] == 'temperature') {
temperature = parseFloat(dataPoint[5]);
} else if (dataPoint[3] == "coffeelevel") {
} else if (dataPoint[3] == 'coffeelevel') {
coffeelevel = parseFloat(dataPoint[6]);
}
temperatureData.push({

@ -1,21 +1,3 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//! moment.js
//! version : 2.10.2
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors

@ -16,10 +16,10 @@
* under the License.
*/
var modalPopup = ".wr-modalpopup";
var modalPopupContainer = modalPopup + " .modalpopup-container";
var modalPopupContent = modalPopup + " .modalpopup-content";
var body = "body";
var modalPopup = '.wr-modalpopup';
var modalPopupContainer = modalPopup + ' .modalpopup-container';
var modalPopupContent = modalPopup + ' .modalpopup-content';
var body = 'body';
/*
* set popup maximum height function.
@ -50,16 +50,16 @@ function showPopup() {
$('label[for=deviceName]').remove();
}
});
var deviceType = "";
var deviceType = '';
$('.deviceType').each(function () {
if (this.value != "") {
if (this.value != '') {
deviceType = this.value;
}
});
if (deviceType == 'digitaldisplay') {
$('.sketchType').remove();
$('input[name="sketchType"][value="digitaldisplay"]').prop('checked', true);
$("label[for='digitaldisplay']").text("Simple Agent");
$('label[for="digitaldisplay"]').text('Simple Agent');
} else {
$('.sketchTypes').remove();
}
@ -88,17 +88,17 @@ function attachEvents() {
* when a user clicks on "Download" link
* on Device Management page in WSO2 DC Console.
*/
$("a.download-link").click(function () {
var sketchType = $(this).data("sketchtype");
var deviceType = $(this).data("devicetype");
var downloadDeviceAPI = "/devicemgt/api/devices/sketch/generate_link";
var payload = {"sketchType": sketchType, "deviceType": deviceType};
$('a.download-link').click(function () {
var sketchType = $(this).data('sketchtype');
var deviceType = $(this).data('devicetype');
var downloadDeviceAPI = '/devicemgt/api/devices/sketch/generate_link';
var payload = {'sketchType': sketchType, 'deviceType': deviceType};
$(modalPopupContent).html($('#download-device-modal-content').html());
showPopup();
var deviceName;
$("a#download-device-download-link").click(function () {
$('a#download-device-download-link').click(function () {
$('.new-device-name').each(function () {
if (this.value != "") {
if (this.value != '') {
deviceName = this.value;
}
});
@ -124,7 +124,7 @@ function attachEvents() {
}
});
$("a#download-device-cancel-link").click(function () {
$('a#download-device-cancel-link').click(function () {
hidePopup();
});
@ -145,7 +145,7 @@ function downloadAgent() {
payload.name = $inputs[0].value;
payload.owner = $inputs[1].value;
var connectedCupRegisterURL = "/connectedcup/device/register?name=" + encodeURI(payload.name);
var connectedCupRegisterURL = '/connectedcup/device/register?name=' + encodeURI(payload.name);
invokerUtil.post(
connectedCupRegisterURL,
@ -160,7 +160,7 @@ function downloadAgent() {
var deviceName;
$('.new-device-name').each(function () {
if (this.value != "") {
if (this.value != '') {
deviceName = this.value;
}
});
@ -177,29 +177,29 @@ function doAction(data) {
document.write(data);
}
if (data.status == "200") {
if (data.status == 200) {
$(modalPopupContent).html($('#download-device-modal-content-links').html());
$("input#download-device-url").val(data.responseText);
$("input#download-device-url").focus(function () {
$('input#download-device-url').val(data.responseText);
$('input#download-device-url').focus(function () {
$(this).select();
});
showPopup();
} else if (data.status == "401") {
} else if (data.status == 401) {
$(modalPopupContent).html($('#device-401-content').html());
$("#device-401-link").click(function () {
window.location = "/devicemgt/login";
$('#device-401-link').click(function () {
window.location = '/devicemgt/login';
});
showPopup();
} else if (data == "403") {
} else if (data == 403) {
$(modalPopupContent).html($('#device-403-content').html());
$("#device-403-link").click(function () {
window.location = "/devicemgt/login";
$('#device-403-link').click(function () {
window.location = '/devicemgt/login';
});
showPopup();
} else {
$(modalPopupContent).html($('#device-unexpected-error-content').html());
$("a#device-unexpected-error-link").click(function () {
$('a#device-unexpected-error-link').click(function () {
hidePopup();
});
}
}
}

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

Loading…
Cancel
Save