Merge pull request #178 from charithag/master

Fix issues in PR https://github.com/wso2/product-iots/pull/151
merge-requests/1/head
Ruwan 8 years ago committed by GitHub
commit 2c97db014a

@ -1,21 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!--/* <!--
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* ~
* WSO2 Inc. licenses this file to you under the Apache License, ~ WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except ~ Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. ~ in compliance with the License.
* You may obtain a copy of the License at ~ You may obtain a copy of the License at
* ~
* http://www.apache.org/licenses/LICENSE-2.0 ~ http://www.apache.org/licenses/LICENSE-2.0
* ~
* Unless required by applicable law or agreed to in writing, ~ Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an ~ software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ "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 ~ specific language governing permissions and limitations
* under the License. ~ under the License.
*/--> -->
<project name="create-sample-sensor-capps" default="zip" basedir="."> <project name="create-sample-sensor-capps" default="zip" basedir=".">
<property name="project-name" value="${ant.project.name}"/> <property name="project-name" value="${ant.project.name}"/>
<property name="target-dir" value="target/carbonapps"/> <property name="target-dir" value="target/carbonapps"/>
@ -39,4 +40,3 @@
</zip> </zip>
</target> </target>
</project> </project>

@ -1,20 +1,21 @@
<!--/* <!--
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* ~
* WSO2 Inc. licenses this file to you under the Apache License, ~ WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except ~ Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. ~ in compliance with the License.
* You may obtain a copy of the License at ~ You may obtain a copy of the License at
* ~
* http://www.apache.org/licenses/LICENSE-2.0 ~ http://www.apache.org/licenses/LICENSE-2.0
* ~
* Unless required by applicable law or agreed to in writing, ~ Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an ~ software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ "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 ~ specific language governing permissions and limitations
* under the License. ~ under the License.
*/--> -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>

@ -22,4 +22,3 @@
<mapping customMapping="disable" type="wso2event"/> <mapping customMapping="disable" type="wso2event"/>
<to eventAdapterType="iot-ui"/> <to eventAdapterType="iot-ui"/>
</eventPublisher> </eventPublisher>

@ -31,4 +31,3 @@
<mapping customMapping="disable" type="json"/> <mapping customMapping="disable" type="json"/>
<to streamName="org.wso2.iot.firealarm" version="1.0.0"/> <to streamName="org.wso2.iot.firealarm" version="1.0.0"/>
</eventReceiver> </eventReceiver>

@ -20,4 +20,3 @@
<artifact name="firealarm_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer"> <artifact name="firealarm_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.firealarm_1.0.0.json</file> <file>org.wso2.iot.firealarm_1.0.0.json</file>
</artifact> </artifact>

@ -4,11 +4,23 @@
"nickName": "firealarm_stream", "nickName": "firealarm_stream",
"description": "This hold the device type stream of firealarm", "description": "This hold the device type stream of firealarm",
"metaData": [ "metaData": [
{"name": "owner", "type": "STRING"}, {
{"name": "deviceId", "type": "STRING"} "name": "owner",
"type": "STRING"
},
{
"name": "deviceId",
"type": "STRING"
}
], ],
"payloadData": [ "payloadData": [
{"name": "temperature", "type": "FLOAT"}, {
{"name": "humidity", "type": "FLOAT"} "name": "temperature",
"type": "FLOAT"
},
{
"name": "humidity",
"type": "FLOAT"
}
] ]
} }

@ -20,4 +20,3 @@
<artifact name="humidity_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer"> <artifact name="humidity_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.humidity_1.0.0.json</file> <file>org.wso2.iot.devices.humidity_1.0.0.json</file>
</artifact> </artifact>

@ -4,17 +4,27 @@
"nickName": "Humidity Data", "nickName": "Humidity Data",
"description": "Humidity data received from the Device", "description": "Humidity data received from the Device",
"metaData": [ "metaData": [
{"name":"owner","type":"STRING"}, {
{"name":"deviceType","type":"STRING"}, "name": "owner",
{"name":"deviceId","type":"STRING"}, "type": "STRING"
{"name":"time","type":"LONG"} },
{
"name": "deviceType",
"type": "STRING"
},
{
"name": "deviceId",
"type": "STRING"
},
{
"name": "time",
"type": "LONG"
}
], ],
"payloadData": [ "payloadData": [
{ {
"name": "humidity","type": "FLOAT" "name": "humidity",
"type": "FLOAT"
} }
] ]
} }

@ -22,4 +22,3 @@
<mapping customMapping="disable" type="wso2event"/> <mapping customMapping="disable" type="wso2event"/>
<to eventAdapterType="iot-ui"/> <to eventAdapterType="iot-ui"/>
</eventPublisher> </eventPublisher>

@ -20,4 +20,3 @@
<artifact name="temperature_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer"> <artifact name="temperature_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.temperature_1.0.0.json</file> <file>org.wso2.iot.devices.temperature_1.0.0.json</file>
</artifact> </artifact>

@ -4,17 +4,27 @@
"nickName": "Temperature Data", "nickName": "Temperature Data",
"description": "Temperature data received from the Device", "description": "Temperature data received from the Device",
"metaData": [ "metaData": [
{"name":"owner","type":"STRING"}, {
{"name":"deviceType","type":"STRING"}, "name": "owner",
{"name":"deviceId","type":"STRING"}, "type": "STRING"
{"name":"time","type":"LONG"} },
{
"name": "deviceType",
"type": "STRING"
},
{
"name": "deviceId",
"type": "STRING"
},
{
"name": "time",
"type": "LONG"
}
], ],
"payloadData": [ "payloadData": [
{ {
"name": "temperature","type": "FLOAT" "name": "temperature",
"type": "FLOAT"
} }
] ]
} }

@ -19,29 +19,27 @@
package org.homeautomation.firealarm.api; package org.homeautomation.firealarm.api;
import org.homeautomation.firealarm.api.dto.DeviceJSON; import org.homeautomation.firealarm.api.dto.DeviceJSON;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.Produces; import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.core.Context; import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
/** /**
* This is the controller API which is used to control agent side functionality * This is the controller API which is used to control agent side functionality.
*/ */
@SuppressWarnings("NonJaxWsWebServices") @SuppressWarnings("NonJaxWsWebServices")
@API(name = "firealarm", version = "1.0.0", context = "/firealarm", tags = "firealarm") @API(name = "firealarm", version = "1.0.0", context = "/firealarm", tags = "firealarm")
@ -49,8 +47,10 @@ import javax.ws.rs.core.Response;
public interface DeviceTypeService { public interface DeviceTypeService {
/** /**
* @param agentInfo device owner,id and sensor value * Validate registration information.
* @return *
* @param agentInfo device owner,id.
* @return true if device instance is added to map.
*/ */
@Path("device/register") @Path("device/register")
@POST @POST
@ -59,9 +59,11 @@ public interface DeviceTypeService {
Response registerDevice(final DeviceJSON agentInfo); Response registerDevice(final DeviceJSON agentInfo);
/** /**
* @param deviceId unique identifier for given device type * Change buzzer status.
* @param state change status of sensor: on/off *
* @param response * @param deviceId unique identifier for given device type.
* @param state change status of buzzer: on/off.
* @param response operation is success or not.
*/ */
@Path("device/{deviceId}/change-status") @Path("device/{deviceId}/change-status")
@POST @POST
@ -73,30 +75,48 @@ public interface DeviceTypeService {
@Context HttpServletResponse response); @Context HttpServletResponse response);
/** /**
* Retrieve Sensor data for the given time period * Retrieve Sensor data for the given time period.
* @param deviceId unique identifier for given device type instance *
* @param sensorName name of the sensor * @param deviceId unique identifier for given device type instance.
* @param from starting time * @param sensorName name of the sensor.
* @param to ending time * @param from starting time.
* @return response with List<SensorRecord> object which includes sensor data which is requested * @param to ending time.
* @return response with List<SensorRecord> object which includes sensor data which is requested.
*/ */
@Path("device/stats/{deviceId}/sensors/{sensorName}") @Path("device/stats/{deviceId}/sensors/{sensorName}")
@GET @GET
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
Response getSensorStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensorName, Response getSensorStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensorName,
@QueryParam("from") long from, @QueryParam("to") long to); @QueryParam("from") long from, @QueryParam("to") long to);
/**
* Remove device type instance using device id.
*
* @param deviceId unique identifier for given device type instance.
*/
@Path("/device/{device_id}") @Path("/device/{device_id}")
@DELETE @DELETE
@Permission(scope = "firealarm_user", permissions = {"/permission/admin/device-mgt/removeDevice"}) @Permission(scope = "firealarm_user", permissions = {"/permission/admin/device-mgt/removeDevice"})
Response removeDevice(@PathParam("device_id") String deviceId); Response removeDevice(@PathParam("device_id") String deviceId);
/**
* Update device instance name.
*
* @param deviceId unique identifier for given device type instance.
* @param name new name for the device type instance.
*/
@Path("/device/{device_id}") @Path("/device/{device_id}")
@PUT @PUT
@Permission(scope = "firealarm_user", permissions = {"/permission/admin/device-mgt/updateDevice"}) @Permission(scope = "firealarm_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name); Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
/**
* To get device information.
*
* @param deviceId unique identifier for given device type instance.
* @return firealarm device.
*/
@Path("/device/{device_id}") @Path("/device/{device_id}")
@GET @GET
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ -104,6 +124,11 @@ public interface DeviceTypeService {
@Permission(scope = "firealarm_user", permissions = {"/permission/admin/device-mgt/updateDevice"}) @Permission(scope = "firealarm_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
Response getDevice(@PathParam("device_id") String deviceId); Response getDevice(@PathParam("device_id") String deviceId);
/**
* Get all device type instance which belongs to user.
*
* @return Array of devices which includes device's information.
*/
@Path("/devices") @Path("/devices")
@GET @GET
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ -111,6 +136,13 @@ public interface DeviceTypeService {
@Permission(scope = "firealarm_user", permissions = {"/permission/admin/device-mgt/devices"}) @Permission(scope = "firealarm_user", permissions = {"/permission/admin/device-mgt/devices"})
Response getAllDevices(); Response getAllDevices();
/**
* To download device type agent source code as zip file.
*
* @param deviceName name for the device type instance.
* @param sketchType folder name where device type agent was installed into server.
* @return Agent source code as zip file.
*/
@Path("/device/download") @Path("/device/download")
@GET @GET
@Produces("application/zip") @Produces("application/zip")

@ -69,11 +69,9 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* This is the API which is used to control and manage device type functionality * This is the API which is used to control and manage device type functionality.
*/ */
@SuppressWarnings("NonJaxWsWebServices") @SuppressWarnings("NonJaxWsWebServices")
@API(name = "firealarm", version = "1.0.0", context = "/firealarm", tags = "firealarm") @API(name = "firealarm", version = "1.0.0", context = "/firealarm", tags = "firealarm")
@ -83,7 +81,6 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
private static final String KEY_TYPE = "PRODUCTION"; private static final String KEY_TYPE = "PRODUCTION";
private static Log log = LogFactory.getLog(DeviceTypeService.class); private static Log log = LogFactory.getLog(DeviceTypeService.class);
private static ApiApplicationKey apiApplicationKey; private static ApiApplicationKey apiApplicationKey;
private ConcurrentHashMap<String, DeviceJSON> deviceToIpMap = new ConcurrentHashMap<>();
private static String shortUUID() { private static String shortUUID() {
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();
@ -92,8 +89,10 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
} }
/** /**
* @param agentInfo device owner,id * Validate registration information.
* @return true if device instance is added to map *
* @param agentInfo device owner,id.
* @return true if device instance is added to map.
*/ */
@Path("device/register") @Path("device/register")
@POST @POST
@ -101,15 +100,17 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
public Response registerDevice(final DeviceJSON agentInfo) { public Response registerDevice(final DeviceJSON agentInfo) {
String deviceId = agentInfo.deviceId; String deviceId = agentInfo.deviceId;
if ((agentInfo.deviceId != null) && (agentInfo.owner != null)) { if ((agentInfo.deviceId != null) && (agentInfo.owner != null)) {
deviceToIpMap.put(deviceId, agentInfo);
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} }
return Response.status(Response.Status.NOT_ACCEPTABLE).build(); return Response.status(Response.Status.NOT_ACCEPTABLE).build();
} }
/** /**
* @param deviceId unique identifier for given device type instance * Change buzzer status.
* @param state change status of sensor: on/off *
* @param deviceId unique identifier for given device type.
* @param state change status of buzzer: on/off.
* @param response operation is success or not.
*/ */
@Path("device/{deviceId}/change-status") @Path("device/{deviceId}/change-status")
@POST @POST
@ -119,15 +120,18 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
@QueryParam("state") String state, @QueryParam("state") String state,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService()
DeviceTypeConstants.DEVICE_TYPE))) { .isUserAuthorized(new DeviceIdentifier(deviceId, DeviceTypeConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED).build();
}
if (state == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
} }
String sensorState = state.toUpperCase(); String sensorState = state.toUpperCase();
if (!sensorState.equals(DeviceTypeConstants.STATE_ON) && !sensorState.equals( if (!DeviceTypeConstants.STATE_ON.equals(sensorState)
DeviceTypeConstants.STATE_OFF)) { && !DeviceTypeConstants.STATE_OFF.equals(sensorState)) {
log.error("The requested state change should be either - 'ON' or 'OFF'"); log.error("The requested state change should be either - 'ON' or 'OFF'");
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build(); return Response.status(Response.Status.BAD_REQUEST).build();
} }
Map<String, String> dynamicProperties = new HashMap<>(); Map<String, String> dynamicProperties = new HashMap<>();
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain() String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
@ -137,19 +141,19 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
dynamicProperties, state); dynamicProperties, state);
return Response.ok().build(); return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) { } catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e); log.error("Unable to change buzzer status", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
} }
} }
/** /**
* Retrieve Sensor data for the given time period * Retrieve Sensor data for the given time period.
* *
* @param deviceId unique identifier for given device type instance * @param deviceId unique identifier for given device type instance.
* @param sensorName name of the sensor * @param sensorName name of the sensor.
* @param from starting time * @param from starting time.
* @param to ending time * @param to ending time.
* @return response with List<SensorRecord> object which includes sensor data which is requested * @return response with List<SensorRecord> object which includes sensor data which is requested.
*/ */
@Path("device/stats/{deviceId}/sensors/{sensorName}") @Path("device/stats/{deviceId}/sensors/{sensorName}")
@GET @GET
@ -174,29 +178,29 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
} }
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService()
DeviceTypeConstants.DEVICE_TYPE))) { .isUserAuthorized(new DeviceIdentifier(deviceId, DeviceTypeConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED).build();
} }
List<SortByField> sortByFields = new ArrayList<>(); List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("time", SORT.ASC, false); SortByField sortByField = new SortByField("time", SORT.ASC, false);
sortByFields.add(sortByField); sortByFields.add(sortByField);
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields); List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build(); return Response.status(Response.Status.OK).entity(sensorRecords).build();
} catch (AnalyticsException e) { } catch (AnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg); log.error(errorMsg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).build();
} catch (DeviceAccessAuthorizationException e) { } catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e); log.error("Unable to get sensor stats", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
} }
} }
/** /**
* Remove device type instance using device id * Remove device type instance using device id.
* *
* @param deviceId unique identifier for given device type instance * @param deviceId unique identifier for given device type instance.
*/ */
@Path("/device/{deviceId}") @Path("/device/{deviceId}")
@DELETE @DELETE
@ -206,29 +210,26 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED).build();
} }
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice( boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier); deviceIdentifier);
if (removed) { if (removed) {
return Response.ok().build(); return Response.ok().build();
} else { } else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build(); return Response.status(Response.Status.NOT_ACCEPTABLE).build();
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException | DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e); log.error("Unable to remove device", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} }
} }
/** /**
* Update device instance name * Update device instance name.
* *
* @param deviceId unique identifier for given device type instance * @param deviceId unique identifier for given device type instance.
* @param name new name for the device type instance * @param name new name for the device type instance.
*/ */
@Path("/device/{deviceId}") @Path("/device/{deviceId}")
@PUT @PUT
@ -238,7 +239,7 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED).build();
} }
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId); device.setDeviceIdentifier(deviceId);
@ -249,22 +250,19 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
if (updated) { if (updated) {
return Response.ok().build(); return Response.ok().build();
} else { } else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build(); return Response.status(Response.Status.NOT_ACCEPTABLE).build();
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException | DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e); log.error("Unable to update device", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} }
} }
/** /**
* To get device information * To get device information.
* *
* @param deviceId unique identifier for given device type instance * @param deviceId unique identifier for given device type instance.
* @return * @return firealarm device.
*/ */
@Path("/device/{deviceId}") @Path("/device/{deviceId}")
@GET @GET
@ -276,23 +274,20 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED).build();
} }
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build(); return Response.ok().entity(device).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException | DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e); log.error("Unable to get device", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} }
} }
/** /**
* Get all device type instance which belongs to user * Get all device type instance which belongs to user.
* *
* @return Array of devices which includes device's information * @return Array of devices which includes device's information.
*/ */
@Path("/devices") @Path("/devices")
@GET @GET
@ -312,17 +307,17 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
Device[] devices = userDevicesforFirealarm.toArray(new Device[]{}); Device[] devices = userDevicesforFirealarm.toArray(new Device[]{});
return Response.ok().entity(devices).build(); return Response.ok().entity(devices).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e); log.error("Unable to get all devices", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} }
} }
/** /**
* To download device type agent source code as zip file * To download device type agent source code as zip file.
* *
* @param deviceName name for the device type instance * @param deviceName name for the device type instance.
* @param sketchType folder name where device type agent was installed into server * @param sketchType folder name where device type agent was installed into server.
* @return Agent source code as zip file * @return Agent source code as zip file.
*/ */
@Path("/device/download") @Path("/device/download")
@GET @GET
@ -339,62 +334,58 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
zipFile.getZipFile().delete(); zipFile.getZipFile().delete();
return resp; return resp;
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) { } catch (DeviceManagementException | JWTClientException | APIManagerException | IOException
log.error(ex.getMessage(), ex); | UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build(); log.error("Unable to download sketch", ex);
} catch (JWTClientException ex) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} }
} }
/** /**
* Register device into device management service * Register device into device management service.
* *
* @param deviceId unique identifier for given device type instance * @param deviceId unique identifier for given device type instance.
* @param name name for the device type instance * @param name name for the device type instance.
* @return check whether device is installed into cdmf * @return whether device is installed into cdmf or not.
*/ */
private boolean register(String deviceId, String name) { private boolean register(String deviceId, String name) throws DeviceManagementException {
try { DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId);
deviceIdentifier.setId(deviceId); deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name);
device.setType(DeviceTypeConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
APIUtil.registerApiAccessRoles(APIUtil.getAuthenticatedUser());
}
return added;
} catch (DeviceManagementException e) {
log.error(e.getMessage(), e);
return false; return false;
} }
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name);
device.setType(DeviceTypeConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
APIUtil.registerApiAccessRoles(APIUtil.getAuthenticatedUser());
}
return added;
} }
/**
* Generates zip archive with the device agent.
*
* @param owner of the device.
* @param deviceName given to the device.
* @param sketchType of the device.
* @return zip archive to download.
* @throws DeviceManagementException
* @throws JWTClientException
* @throws APIManagerException
* @throws UserStoreException
*/
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
throws DeviceManagementException, JWTClientException, APIManagerException, throws DeviceManagementException, JWTClientException, APIManagerException,
UserStoreException { UserStoreException {
@ -412,8 +403,9 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient(); JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId; String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(), scopes); apiApplicationKey.getConsumerSecret(),
owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(),
scopes);
//create token //create token
String accessToken = accessTokenInfo.getAccessToken(); String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken(); String refreshToken = accessTokenInfo.getRefreshToken();
@ -423,9 +415,8 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
ZipUtil ziputil = new ZipUtil(); ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, return ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
deviceId, deviceName, accessToken, refreshToken); deviceId, deviceName, accessToken, refreshToken);
return zipFile;
} }
}
}

@ -28,10 +28,12 @@ import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement @XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class DeviceJSON { public class DeviceJSON {
@XmlElement(required = true) @XmlElement(required = true)
public String owner; public String owner;
@XmlElement(required = true) @XmlElement(required = true)
public String deviceId; public String deviceId;
@XmlElement(required = true) @XmlElement(required = true)
public Float sensorValue; public Float sensorValue;
} }

@ -82,7 +82,6 @@ public class SensorRecord {
valueList.add(entry.getKey() + ":" + entry.getValue()); valueList.add(entry.getKey() + ":" + entry.getValue());
} }
return valueList.toString(); return valueList.toString();
} }
} }

@ -20,10 +20,9 @@ package org.homeautomation.firealarm.plugin.impl.dao;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.homeautomation.firealarm.plugin.constants.DeviceTypeConstants; import org.homeautomation.firealarm.plugin.constants.DeviceTypeConstants;
import org.homeautomation.firealarm.plugin.impl.dao.impl.DeviceTypeDAOImpl;
import org.homeautomation.firealarm.plugin.exception.DeviceMgtPluginException; import org.homeautomation.firealarm.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.firealarm.plugin.impl.dao.impl.DeviceTypeDAOImpl;
import javax.naming.Context; import javax.naming.Context;
import javax.naming.InitialContext; import javax.naming.InitialContext;
@ -32,6 +31,9 @@ import javax.sql.DataSource;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
/**
* Device type data transfer object implementation.
*/
public class DeviceTypeDAO { public class DeviceTypeDAO {
private static final Log log = LogFactory.getLog(DeviceTypeDAO.class); private static final Log log = LogFactory.getLog(DeviceTypeDAO.class);
@ -42,16 +44,24 @@ public class DeviceTypeDAO {
initDeviceTypeDAO(); initDeviceTypeDAO();
} }
/**
* Initialize the device type.
*/
public static void initDeviceTypeDAO() { public static void initDeviceTypeDAO() {
try { try {
Context ctx = new InitialContext(); Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(DeviceTypeConstants.DATA_SOURCE_NAME); dataSource = (DataSource) ctx.lookup(DeviceTypeConstants.DATA_SOURCE_NAME);
} catch (NamingException e) { } catch (NamingException e) {
log.error("Error while looking up the data source: " + log.error("Error while looking up the data source: " +
DeviceTypeConstants.DATA_SOURCE_NAME); DeviceTypeConstants.DATA_SOURCE_NAME);
} }
} }
/**
* Begin transactions with data sources.
*
* @throws DeviceMgtPluginException
*/
public static void beginTransaction() throws DeviceMgtPluginException { public static void beginTransaction() throws DeviceMgtPluginException {
try { try {
Connection conn = dataSource.getConnection(); Connection conn = dataSource.getConnection();
@ -62,18 +72,29 @@ public class DeviceTypeDAO {
} }
} }
/**
* Get connection to the datasource.
*
* @return the datasource connection.
* @throws DeviceMgtPluginException
*/
public static Connection getConnection() throws DeviceMgtPluginException { public static Connection getConnection() throws DeviceMgtPluginException {
if (currentConnection.get() == null) { if (currentConnection.get() == null) {
try { try {
currentConnection.set(dataSource.getConnection()); currentConnection.set(dataSource.getConnection());
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceMgtPluginException("Error occurred while retrieving data source connection", throw new DeviceMgtPluginException("Error occurred while retrieving data source connection",
e); e);
} }
} }
return currentConnection.get(); return currentConnection.get();
} }
/**
* Commit transaction after editing.
*
* @throws DeviceMgtPluginException
*/
public static void commitTransaction() throws DeviceMgtPluginException { public static void commitTransaction() throws DeviceMgtPluginException {
try { try {
Connection conn = currentConnection.get(); Connection conn = currentConnection.get();
@ -82,7 +103,7 @@ public class DeviceTypeDAO {
} else { } else {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit " + log.debug("Datasource connection associated with the current thread is null, hence commit " +
"has not been attempted"); "has not been attempted");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -92,6 +113,11 @@ public class DeviceTypeDAO {
} }
} }
/**
* Close current connection with the datasource.
*
* @throws DeviceMgtPluginException
*/
public static void closeConnection() throws DeviceMgtPluginException { public static void closeConnection() throws DeviceMgtPluginException {
Connection con = currentConnection.get(); Connection con = currentConnection.get();
@ -105,6 +131,11 @@ public class DeviceTypeDAO {
currentConnection.remove(); currentConnection.remove();
} }
/**
* Rollback transactions to recover from failure.
*
* @throws DeviceMgtPluginException
*/
public static void rollbackTransaction() throws DeviceMgtPluginException { public static void rollbackTransaction() throws DeviceMgtPluginException {
try { try {
Connection conn = currentConnection.get(); Connection conn = currentConnection.get();
@ -113,7 +144,7 @@ public class DeviceTypeDAO {
} else { } else {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback " + log.debug("Datasource connection associated with the current thread is null, hence rollback " +
"has not been attempted"); "has not been attempted");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -123,7 +154,13 @@ public class DeviceTypeDAO {
} }
} }
/**
* Get device type specific data object.
*
* @return device type specific data object.
*/
public DeviceTypeDAOImpl getDeviceTypeDAO() { public DeviceTypeDAOImpl getDeviceTypeDAO() {
return new DeviceTypeDAOImpl(); return new DeviceTypeDAOImpl();
} }
} }

@ -42,7 +42,6 @@
<div id="x_axis-humidity" class="custom_x_axis"></div> <div id="x_axis-humidity" class="custom_x_axis"></div>
<div id="slider-humidity" class="custom_slider"></div> <div id="slider-humidity" class="custom_slider"></div>
</div> </div>
</div> </div>
{{#zone "bottomJs"}} {{#zone "bottomJs"}}

@ -19,23 +19,23 @@
function onRequest(context) { function onRequest(context) {
var devices = context.unit.params.devices; var devices = context.unit.params.devices;
var deviceType = context.uriParams.deviceType; var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("deviceId"); var deviceId = request.getParameter('deviceId');
if (devices) { if (devices) {
return { return {
"devices": stringify(devices), 'devices': stringify(devices),
"backendApiUri": devicemgtProps["httpsURL"] + "/firealarm/device/stats/" 'backendApiUri': devicemgtProps['httpsURL'] + '/firealarm/device/stats/'
}; };
} else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { } else if (deviceType && deviceId) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require('/app/modules/device.js').deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") { if (device && device.status != 'error') {
return { return {
"device": device, 'device': device,
"backendApiUrl": devicemgtProps["httpsURL"] + "/firealarm/device/stats/" + deviceId + "/sensors/" 'backendApiUrl': devicemgtProps['httpsURL'] + '/firealarm/device/stats/' + deviceId + '/sensors/'
}; };
} else { } 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(); exit();
} }
} }

@ -16,15 +16,15 @@
* under the License. * under the License.
*/ */
var palette = new Rickshaw.Color.Palette({scheme: "classic9"}); var palette = new Rickshaw.Color.Palette({scheme: 'classic9'});
var graphMap = {}; var graphMap = {};
function drawGraph_firealarm(from, to) { function drawGraph_firealarm(from, to) {
var devices = $("#firealarm-details").data("devices"); var devices = $('#firealarm-details').data('devices');
var tzOffset = new Date().getTimezoneOffset() * 60; var tzOffset = new Date().getTimezoneOffset() * 60;
var streamIndex = 0; var streamIndex = 0;
var streams = ["temperature", "humidity"]; var streams = ['temperature', 'humidity'];
populateGraph(); populateGraph();
@ -34,12 +34,12 @@ function drawGraph_firealarm(from, to) {
} }
function clearContent(type) { function clearContent(type) {
$("#y_axis-" + type).html(""); $('#y_axis-' + type).html('');
$("#smoother-" + type).html(""); $('#smoother-' + type).html('');
$("#legend-" + type).html(""); $('#legend-' + type).html('');
$("#chart-" + type).html(""); $('#chart-' + type).html('');
$("#x_axis-" + type).html(""); $('#x_axis-' + type).html('');
$("#slider-" + type).html(""); $('#slider-' + type).html('');
} }
function initGraph(type) { function initGraph(type) {
@ -47,16 +47,16 @@ function drawGraph_firealarm(from, to) {
return graphMap[type]; return graphMap[type];
} }
var chartWrapperElmId = "#firealarm-div-chart"; var chartWrapperElmId = '#firealarm-div-chart';
var graphWidth = $(chartWrapperElmId).width() - 50; var graphWidth = $(chartWrapperElmId).width() - 50;
var graphConfig = { var graphConfig = {
element: document.getElementById("chart-" + type), element: document.getElementById('chart-' + type),
width: graphWidth, width: graphWidth,
height: 400, height: 400,
strokeWidth: 2, strokeWidth: 2,
renderer: 'line', renderer: 'line',
interpolation: "linear", interpolation: 'linear',
unstack: true, unstack: true,
stack: false, stack: false,
xScale: d3.time.scale(), xScale: d3.time.scale(),
@ -84,7 +84,7 @@ function drawGraph_firealarm(from, to) {
x: parseInt(new Date().getTime() / 1000), x: parseInt(new Date().getTime() / 1000),
y: 0 y: 0
}], }],
'name': $("#firealarm-details").data("devicename") 'name': $('#firealarm-details').data('devicename')
}); });
} }
@ -99,7 +99,7 @@ function drawGraph_firealarm(from, to) {
var yAxis = new Rickshaw.Graph.Axis.Y({ var yAxis = new Rickshaw.Graph.Axis.Y({
graph: graph, graph: graph,
orientation: 'left', orientation: 'left',
element: document.getElementById("y_axis-" + type), element: document.getElementById('y_axis-' + type),
width: 40, width: 40,
height: 410 height: 410
}); });
@ -107,12 +107,12 @@ function drawGraph_firealarm(from, to) {
var slider = new Rickshaw.Graph.RangeSlider.Preview({ var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: graph, graph: graph,
element: document.getElementById("slider-" + type) element: document.getElementById('slider-' + type)
}); });
var legend = new Rickshaw.Graph.Legend({ var legend = new Rickshaw.Graph.Legend({
graph: graph, graph: graph,
element: document.getElementById("legend-" + type) element: document.getElementById('legend-' + type)
}); });
var hoverDetail = new Rickshaw.Graph.HoverDetail({ var hoverDetail = new Rickshaw.Graph.HoverDetail({
@ -122,7 +122,7 @@ function drawGraph_firealarm(from, to) {
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: ' + var swatch = '<span class="detail_swatch" style="background-color: ' +
series.color + '"></span>'; series.color + '"></span>';
return swatch + series.name + ": " + parseInt(y) + '<br>' + date; return swatch + series.name + ': ' + parseInt(y) + '<br>' + date;
} }
}); });
@ -159,7 +159,7 @@ function drawGraph_firealarm(from, to) {
if (devices) { if (devices) {
getData(); getData();
} else { } else {
var backendApiUrl = $("#firealarm-div-chart").data("backend-api-url") + type + "?from=" + from + "&to=" + to; var backendApiUrl = $('#firealarm-div-chart').data('backend-api-url') + type + '?from=' + from + '&to=' + to;
var successCallback = function (data) { var successCallback = function (data) {
if (data) { if (data) {
drawLineGraph(JSON.parse(data)); drawLineGraph(JSON.parse(data));
@ -175,8 +175,8 @@ function drawGraph_firealarm(from, to) {
if (deviceIndex >= devices.length) { if (deviceIndex >= devices.length) {
return; return;
} }
var backendApiUrl = $("#firealarm-div-chart").data("backend-api-url") + devices[deviceIndex].deviceIdentifier var backendApiUrl = $('#firealarm-div-chart').data('backend-api-url') + devices[deviceIndex].deviceIdentifier
+ "/sensors/" + type + "?from=" + from + "&to=" + to; + '/sensors/' + type + '?from=' + from + '&to=' + to;
var successCallback = function (data) { var successCallback = function (data) {
if (data) { if (data) {
drawLineGraph(JSON.parse(data)); drawLineGraph(JSON.parse(data));
@ -214,10 +214,10 @@ function drawGraph_firealarm(from, to) {
function getFieldData(data, type) { function getFieldData(data, type) {
var columnData; var columnData;
switch (type) { switch (type) {
case "temperature" : case 'temperature' :
columnData = data.values.temperature; columnData = data.values.temperature;
break; break;
case "humidity" : case 'humidity' :
columnData = data.values.humidity; columnData = data.values.humidity;
break; break;
} }

@ -17,20 +17,24 @@
*/ */
function onRequest(context) { function onRequest(context) {
var log = new Log("device-view.js");
var deviceType = context.uriParams.deviceType; var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("id"); var deviceId = request.getParameter('id');
var autoCompleteParams = [ var autoCompleteParams = [
{"name" : "deviceId", "value" : deviceId} {'name': 'deviceId', 'value': deviceId}
]; ];
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { if (deviceType && deviceId) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require('/app/modules/device.js').deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") { if (device && device.status != 'error') {
return {"device": device, "backendApiUri" : devicemgtProps["httpsURL"] + "/"+deviceType+"/", "autoCompleteParams" : autoCompleteParams}; return {
'device': device,
'backendApiUri': devicemgtProps['httpsURL'] + '/' + deviceType + '/',
'autoCompleteParams': autoCompleteParams
};
} else { } 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(); exit();
} }
} }

@ -19,14 +19,14 @@
function onRequest(context) { function onRequest(context) {
var device = context.unit.params.device; var device = context.unit.params.device;
var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
var constants = require("/app/modules/constants.js"); var constants = require('/app/modules/constants.js');
var websocketEndpoint = devicemgtProps["httpsURL"].replace("https", "wss"); var websocketEndpoint = devicemgtProps['httpsURL'].replace('https', 'wss');
var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER); var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER);
var token = ""; var token = '';
if (tokenPair) { if (tokenPair) {
token = tokenPair.accessToken; token = tokenPair.accessToken;
} }
websocketEndpoint = websocketEndpoint + "/secured-outputui/org.wso2.iot.firealarm/1.0.0?" + websocketEndpoint = websocketEndpoint + '/secured-outputui/org.wso2.iot.firealarm/1.0.0?' +
"token="+ token +"&deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type; 'token=' + token + '&deviceId=' + device.deviceIdentifier + '&deviceType=' + device.type;
return {"device": device, "websocketEndpoint" : websocketEndpoint}; return {'device': device, 'websocketEndpoint': websocketEndpoint};
} }

@ -24,14 +24,14 @@ var temperatureData = [];
var humidity; var humidity;
var humidityData = []; var humidityData = [];
var palette = new Rickshaw.Color.Palette({scheme: "classic9"}); var palette = new Rickshaw.Color.Palette({scheme: 'classic9'});
$(window).load(function () { $(window).load(function () {
temperature = lineGraph("temperature", temperatureData); temperature = lineGraph('temperature', temperatureData);
humidity = lineGraph("humidity", humidityData); humidity = lineGraph('humidity', humidityData);
var websocketUrl = $("#div-chart").data("websocketurl"); var websocketUrl = $('#div-chart').data('websocketurl');
connect(websocketUrl) connect(websocketUrl)
}); });
@ -49,10 +49,10 @@ function lineGraph(type, chartData) {
} }
var graph = new Rickshaw.Graph({ var graph = new Rickshaw.Graph({
element: document.getElementById("chart-" + type), element: document.getElementById('chart-' + type),
width: $("#div-chart").width() - 50, width: $('#div-chart').width() - 50,
height: 300, height: 300,
renderer: "line", renderer: 'line',
padding: {top: 0.2, left: 0.0, right: 0.0, bottom: 0.2}, padding: {top: 0.2, left: 0.0, right: 0.0, bottom: 0.2},
xScale: d3.time.scale(), xScale: d3.time.scale(),
series: [{ series: [{
@ -83,7 +83,7 @@ function lineGraph(type, chartData) {
formatter: function (series, x, y) { formatter: function (series, x, y) {
var date = '<span class="date">' + moment(x * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>'; 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>'; 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;
} }
}); });

@ -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 //! moment.js
//! version : 2.10.2 //! version : 2.10.2
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! authors : Tim Wood, Iskren Chernev, Moment.js contributors

@ -16,10 +16,10 @@
* under the License. * under the License.
*/ */
var modalPopup = ".wr-modalpopup"; var modalPopup = '.wr-modalpopup';
var modalPopupContainer = modalPopup + " .modalpopup-container"; var modalPopupContainer = modalPopup + ' .modalpopup-container';
var modalPopupContent = modalPopup + " .modalpopup-content"; var modalPopupContent = modalPopup + ' .modalpopup-content';
var body = "body"; var body = 'body';
/* /*
* set popup maximum height function. * set popup maximum height function.
@ -50,9 +50,9 @@ function showPopup() {
$('label[for=deviceName]').remove(); $('label[for=deviceName]').remove();
} }
}); });
var deviceType = ""; var deviceType = '';
$('.deviceType').each(function () { $('.deviceType').each(function () {
if (this.value != "") { if (this.value != '') {
deviceType = this.value; deviceType = this.value;
} }
}); });
@ -81,17 +81,17 @@ function attachEvents() {
* when a user clicks on "Download" link * when a user clicks on "Download" link
* on Device Management page in WSO2 DC Console. * on Device Management page in WSO2 DC Console.
*/ */
$("a.download-link").click(function () { $('a.download-link').click(function () {
var sketchType = $(this).data("sketchtype"); var sketchType = $(this).data('sketchtype');
var deviceType = $(this).data("devicetype"); var deviceType = $(this).data('devicetype');
var downloadDeviceAPI = "/devicemgt/api/devices/sketch/generate_link"; var downloadDeviceAPI = '/devicemgt/api/devices/sketch/generate_link';
var payload = {"sketchType": sketchType, "deviceType": deviceType}; var payload = {'sketchType': sketchType, 'deviceType': deviceType};
$(modalPopupContent).html($('#download-device-modal-content').html()); $(modalPopupContent).html($('#download-device-modal-content').html());
showPopup(); showPopup();
var deviceName; var deviceName;
$("a#download-device-download-link").click(function () { $('a#download-device-download-link').click(function () {
$('.new-device-name').each(function () { $('.new-device-name').each(function () {
if (this.value != "") { if (this.value != '') {
deviceName = this.value; deviceName = this.value;
} }
}); });
@ -121,7 +121,7 @@ function attachEvents() {
} }
}); });
$("a#download-device-cancel-link").click(function () { $('a#download-device-cancel-link').click(function () {
hidePopup(); hidePopup();
}); });
}); });
@ -130,7 +130,7 @@ function attachEvents() {
function downloadAgent() { function downloadAgent() {
var deviceName; var deviceName;
$('.new-device-name').each(function () { $('.new-device-name').each(function () {
if (this.value != "") { if (this.value != '') {
deviceName = this.value; deviceName = this.value;
} }
}); });
@ -144,8 +144,8 @@ function downloadAgent() {
hidePopup(); hidePopup();
}, 1000); }, 1000);
}else { }else {
$("#invalid-username-error-msg span").text("Invalid device name"); $('#invalid-username-error-msg span').text('Invalid device name');
$("#invalid-username-error-msg").removeClass("hidden"); $('#invalid-username-error-msg').removeClass('hidden');
} }
} }
@ -155,28 +155,28 @@ function doAction(data) {
document.write(data); document.write(data);
} }
if (data.status == "200") { if (data.status == 200) {
$(modalPopupContent).html($('#download-device-modal-content-links').html()); $(modalPopupContent).html($('#download-device-modal-content-links').html());
$("input#download-device-url").val(data.responseText); $('input#download-device-url').val(data.responseText);
$("input#download-device-url").focus(function () { $('input#download-device-url').focus(function () {
$(this).select(); $(this).select();
}); });
showPopup(); showPopup();
} else if (data.status == "401") { } else if (data.status == 401) {
$(modalPopupContent).html($('#device-401-content').html()); $(modalPopupContent).html($('#device-401-content').html());
$("#device-401-link").click(function () { $('#device-401-link').click(function () {
window.location = "/devicemgt/login"; window.location = '/devicemgt/login';
}); });
showPopup(); showPopup();
} else if (data == "403") { } else if (data == 403) {
$(modalPopupContent).html($('#device-403-content').html()); $(modalPopupContent).html($('#device-403-content').html());
$("#device-403-link").click(function () { $('#device-403-link').click(function () {
window.location = "/devicemgt/login"; window.location = '/devicemgt/login';
}); });
showPopup(); showPopup();
} else { } else {
$(modalPopupContent).html($('#device-unexpected-error-content').html()); $(modalPopupContent).html($('#device-unexpected-error-content').html());
$("a#device-unexpected-error-link").click(function () { $('a#device-unexpected-error-link').click(function () {
hidePopup(); 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($) { (function($) {
$.extend($.fn, { $.extend($.fn, {

Loading…
Cancel
Save