application-manager-new
charitha 9 years ago
parent c1bb8a0c6d
commit c9d51df3cb

@ -15,6 +15,7 @@
* specific language governing permissions and limitations
* under the License.
*/-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
@ -23,12 +24,14 @@
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${groupId}.watertank.analytics</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>${groupId}.watertank.analytics</name>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
@ -83,4 +86,4 @@
</plugin>
</plugins>
</build>
</project>
</project>

@ -33,4 +33,4 @@
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>
</assembly>
</assembly>

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

@ -2,19 +2,19 @@
<!--
~ 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
~ 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
~ 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.
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="relay_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">

@ -59,4 +59,4 @@
<Type>BOOLEAN</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>
</EventStoreConfiguration>

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

@ -59,4 +59,4 @@
<Type>FLOAT</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>
</EventStoreConfiguration>

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

@ -15,4 +15,4 @@ define stream waterLevelOutputMapper (meta_owner string, meta_deviceType string,
from waterLevelInputMapper#window.timeBatch(1 min)
select meta_owner, meta_deviceType, meta_deviceId, meta_time, waterlevel, 0.0 as waterLevelMargin, avg(waterlevel) as averageValue
group by meta_owner, meta_deviceType, meta_deviceId, meta_time
insert into waterLevelOutputMapper;
insert into waterLevelOutputMapper;

@ -74,4 +74,4 @@
</Source>
<MergeSchema>false</MergeSchema>
<RecordStoreName>EVENT_STORE</RecordStoreName>
</EventStoreConfiguration>
</EventStoreConfiguration>

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

@ -20,4 +20,3 @@
<artifact name="watertank_execution" version="1.0.0" type="event/execution-plan" serverRole="DataAnalyticsServer">
<file>watertank_execution.siddhiql</file>
</artifact>

@ -21,4 +21,4 @@ insert into relay;
from watertank
select meta_owner, 'watertank' as meta_deviceType, meta_deviceId, time:timestampInMilliseconds() as meta_time, waterlevel
insert into waterlevel;
insert into waterlevel;

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

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

@ -165,4 +165,4 @@
<scope>provided</scope>
</dependency>
</dependencies>
</project>
</project>

@ -38,7 +38,6 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* This is the controller API which is used to control agent side functionality
*/
@ -118,4 +117,5 @@ interface DeviceTypeService {
@Produces("application/zip")
@Permission(scope = "watertank_user", permissions = {"/permission/admin/device-mgt/download"})
Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType);
}
}

@ -69,11 +69,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
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")
@API(name = "watertank", version = "1.0.0", context = "/watertank", tags = "watertank")
@ -83,7 +81,6 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
private static final String KEY_TYPE = "PRODUCTION";
private static Log log = LogFactory.getLog(DeviceTypeService.class);
private static ApiApplicationKey apiApplicationKey;
private ConcurrentHashMap<String, DeviceJSON> deviceToIpMap = new ConcurrentHashMap<>();
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
@ -92,26 +89,28 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
}
/**
* @param agentInfo device owner,id
* @return true if device instance is added to map
* Validate registration information.
*
* @param agentInfo device owner,id.
* @return true if device instance is added to map.
*/
@Path("device/register")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response registerDevice(final DeviceJSON agentInfo) {
String deviceId = agentInfo.deviceId;
if ((agentInfo.deviceId != null) && (agentInfo.owner != null)) {
deviceToIpMap.put(deviceId, agentInfo);
return Response.status(Response.Status.OK).build();
}
return Response.status(Response.Status.NOT_ACCEPTABLE).build();
}
/**
* @param deviceId unique identifier for given device type
* @param onLevel level to turn on the relay
* @param offLevel level to turn off the relay
* @param sensorHeight height to water level sensor from bottom of the tank
* Update watertank configurations.
*
* @param deviceId unique identifier for given device type.
* @param onLevel level to turn on the relay.
* @param offLevel level to turn off the relay.
* @param sensorHeight height to water level sensor from bottom of the tank.
*/
@Path("device/{deviceId}/change-levels")
@POST
@ -125,7 +124,7 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
try {
if (!APIUtil.getDeviceAccessAuthorizationService()
.isUserAuthorized(new DeviceIdentifier(deviceId, DeviceTypeConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
return Response.status(Response.Status.UNAUTHORIZED).build();
}
String configs = onLevel + "," + offLevel + "," + sensorHeight;
@ -137,19 +136,19 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
dynamicProperties, configs);
return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
log.error("Unable to update configs", e);
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 sensorName name of the sensor
* @param from starting time
* @param to ending time
* @return response with List<SensorRecord> object which includes sensor data which is requested
* @param deviceId unique identifier for given device type instance.
* @param sensorName name of the sensor.
* @param from starting time.
* @param to ending time.
* @return response with List<SensorRecord> object which includes sensor data which is requested.
*/
@Path("device/stats/{deviceId}/sensors/{sensorName}")
@GET
@ -170,33 +169,30 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
sensorTableName = DeviceTypeConstants.WATERLEVEL_EVENT_TABLE;
break;
default:
return Response.status(Response.Status.BAD_REQUEST).entity("Invalid event stream").build();
return Response.status(Response.Status.BAD_REQUEST).entity("Invalid event stream name").build();
}
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
DeviceTypeConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
if (!APIUtil.getDeviceAccessAuthorizationService()
.isUserAuthorized(new DeviceIdentifier(deviceId, DeviceTypeConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("time", SORT.ASC, false);
sortByFields.add(sortByField);
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
} catch (AnalyticsException e) {
return Response.status(Response.Status.OK).entity(sensorRecords).build();
} catch (AnalyticsException | DeviceAccessAuthorizationException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMsg).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}")
@DELETE
@ -206,29 +202,26 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
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(
deviceIdentifier);
if (removed) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
return Response.status(Response.Status.NOT_ACCEPTABLE).build();
}
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceManagementException | DeviceAccessAuthorizationException e) {
log.error("Unable to remove the device", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
/**
* Update device instance name
* Update device instance name.
*
* @param deviceId unique identifier for given device type instance
* @param name new name for the device type instance
* @param deviceId unique identifier for given device type instance.
* @param name new name for the device type instance.
*/
@Path("/device/{deviceId}")
@PUT
@ -238,7 +231,7 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
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.setDeviceIdentifier(deviceId);
@ -249,22 +242,19 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
if (updated) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
return Response.status(Response.Status.NOT_ACCEPTABLE).build();
}
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceManagementException | DeviceAccessAuthorizationException e) {
log.error("Unable to update the device", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
/**
* To get device information
* To get device information.
*
* @param deviceId unique identifier for given device type instance
* @return
* @param deviceId unique identifier for given device type instance.
* @return device object.
*/
@Path("/device/{deviceId}")
@GET
@ -276,23 +266,20 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
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);
return Response.ok().entity(device).build();
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceManagementException | DeviceAccessAuthorizationException e) {
log.error("Unable to get the device", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).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")
@GET
@ -302,27 +289,27 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
try {
List<Device> userDevices =
APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser());
ArrayList<Device> userDevicesforwatertank = new ArrayList<>();
ArrayList<Device> waterTankDevices = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(DeviceTypeConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
userDevicesforwatertank.add(device);
waterTankDevices.add(device);
}
}
Device[] devices = userDevicesforwatertank.toArray(new Device[]{});
Device[] devices = waterTankDevices.toArray(new Device[]{});
return Response.ok().entity(devices).build();
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
log.error("Unable to get all devices", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).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 sketchType folder name where device type agent was installed into server
* @return 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")
@GET
@ -331,70 +318,65 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
@QueryParam("sketchType") String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
zipFile.getZipFile().delete();
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.status(Response.Status.OK);
response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
Response resp = response.build();
zipFile.getZipFile().delete();
return resp;
return response.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
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();
return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException | JWTClientException | APIManagerException | IOException
| UserStoreException ex) {
log.error("Unable to download sketch", ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).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 name name for the device type instance
* @return check whether device is installed into cdmf
* @param deviceId unique identifier for given device type instance.
* @param name name for the device type instance.
* @return whether device is installed into cdmf or not.
*/
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
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);
private boolean register(String deviceId, String name) throws DeviceManagementException {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
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;
}
/**
* 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)
throws DeviceManagementException, JWTClientException, APIManagerException,
UserStoreException {
@ -412,8 +394,9 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(), scopes);
apiApplicationKey.getConsumerSecret(),
owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(),
scopes);
//create token
String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken();
@ -423,9 +406,8 @@ public class DeviceTypeServiceImpl implements DeviceTypeService {
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
deviceId, deviceName, accessToken, refreshToken);
return zipFile;
return ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
deviceId, deviceName, accessToken, refreshToken);
}
}
}

@ -19,6 +19,7 @@
package org.homeautomation.watertank.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@ -28,10 +29,12 @@ import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class DeviceJSON {
@XmlElement(required = true)
public String owner;
@XmlElement(required = true)
public String deviceId;
@XmlElement(required = true)
public Float sensorValue;
}

@ -38,14 +38,14 @@ public class SensorRecord {
private Map<String, Object> values;
/**
* Unique identifier for each recode
* Unique identifier for each recode.
*/
@XmlElement(required = false, name = "id")
private String id;
/**
* Gets the values.
* @return the values
* @return the values.
*/
public Map<String, Object> getValues() {
return values;
@ -53,23 +53,23 @@ public class SensorRecord {
/**
* Sets the values.
* @param values
* @param values of the sensor readings.
*/
public void setValues(Map<String, Object> values) {
this.values = values;
}
/**
* Gets the id.
* @return the id
* Gets the sensor id.
* @return the sensor id.
*/
public String getId() {
return id;
}
/**
* Sets the id.
* @param id set unique identifier
* Sets sensor unique identifier.
* @param id of the sensor.
*/
public void setId(String id) {
this.id = id;
@ -77,12 +77,11 @@ public class SensorRecord {
@Override
public String toString() {
List<String> valueList = new ArrayList<String>();
List<String> valueList = new ArrayList<>();
for (Map.Entry<String, Object> entry : values.entrySet()) {
valueList.add(entry.getKey() + ":" + entry.getValue());
}
return valueList.toString();
}
}

@ -1,23 +1,26 @@
/*
* 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
* 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
* 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.
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.watertank.api.exception;
/**
* Wraps device type specific exceptions
*/
public class DeviceTypeException extends Exception {
private static final long serialVersionUID = 2736466563251105441L;
@ -54,4 +57,5 @@ public class DeviceTypeException extends Exception {
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -84,4 +84,4 @@
<method>GET</method>
<scope>watertank_device</scope>
</Permission>
</PermissionConfiguration>
</PermissionConfiguration>

@ -17,7 +17,8 @@
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual
webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
@ -25,9 +26,9 @@
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by
specifying required environments Tomcat environment is the default and every webapps gets it even if they didn't
specify it. e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -33,4 +33,4 @@
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
</beans>
</beans>

@ -1,9 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
metadata-complete="true">
<display-name>WSO2 IoT Server</display-name>
<description>WSO2 IoT Server</description>
@ -43,4 +62,4 @@
<param-value>admin</param-value>
</context-param>
</web-app>
</web-app>

@ -130,4 +130,4 @@
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
</dependency>
</dependencies>
</project>
</project>

@ -21,12 +21,14 @@ package org.homeautomation.watertank.plugin.constants;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
/**
* Device type specific constants.
*/
public class DeviceTypeConstants {
public final static String DEVICE_TYPE = "watertank";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "watertank_DEVICE_ID";
public final static String STATE_ON = "ON";
public final static String STATE_OFF = "OFF";
//sensor events summarized table name
public final static String STREAM_RELAY = "relay";
@ -60,4 +62,3 @@ public class DeviceTypeConstants {
public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator
+ "mqtt.properties";
}

@ -18,6 +18,9 @@
package org.homeautomation.watertank.plugin.exception;
/**
* Custom exception implementation to wrap device management plugin related errors.
*/
public class DeviceMgtPluginException extends Exception {
private String errorMessage;
@ -53,4 +56,4 @@ public class DeviceMgtPluginException extends Exception {
this.errorMessage = errorMessage;
}
}
}

@ -18,10 +18,11 @@
package org.homeautomation.watertank.plugin.impl;
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.watertank.plugin.impl.dao.DeviceTypeDAO;
import org.homeautomation.watertank.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.watertank.plugin.impl.dao.DeviceTypeDAO;
import org.homeautomation.watertank.plugin.impl.feature.DeviceTypeFeatureManager;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
@ -104,7 +105,7 @@ public class DeviceTypeManager implements DeviceManager {
log.warn(msg, iotDAOEx);
}
String msg = "Error while updating the enrollment of the watertank device : " +
device.getDeviceIdentifier();
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -149,7 +150,7 @@ public class DeviceTypeManager implements DeviceManager {
}
} catch (DeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of watertank device : " +
deviceId.getId();
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -164,7 +165,8 @@ public class DeviceTypeManager implements DeviceManager {
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
//Status is not implemented for this device type.
throw new NotImplementedException();
}
@Override
@ -186,7 +188,8 @@ public class DeviceTypeManager implements DeviceManager {
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
//Ownership changing is not implemented for this device type.
throw new NotImplementedException();
}
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
@ -196,17 +199,20 @@ public class DeviceTypeManager implements DeviceManager {
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
//Status is not implemented for this device type.
throw new NotImplementedException();
}
@Override
public License getLicense(String s) throws LicenseManagementException {
return null;
//License is not implemented for this device type.
throw new NotImplementedException();
}
@Override
public void addLicense(License license) throws LicenseManagementException {
//License is not implemented for this device type.
throw new NotImplementedException();
}
@Override

@ -19,14 +19,15 @@
package org.homeautomation.watertank.plugin.impl;
import org.homeautomation.watertank.plugin.constants.DeviceTypeConstants;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
public class DeviceTypeManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
@Override

@ -32,6 +32,9 @@ import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Device type data transfer object implementation.
*/
public class DeviceTypeDAO {
private static final Log log = LogFactory.getLog(DeviceTypeDAO.class);
@ -42,6 +45,9 @@ public class DeviceTypeDAO {
initDeviceTypeDAO();
}
/**
* Initialize the device type.
*/
public static void initDeviceTypeDAO() {
try {
Context ctx = new InitialContext();
@ -52,6 +58,11 @@ public class DeviceTypeDAO {
}
}
/**
* Begin transactions with data sources.
*
* @throws DeviceMgtPluginException
*/
public static void beginTransaction() throws DeviceMgtPluginException {
try {
Connection conn = dataSource.getConnection();
@ -62,6 +73,12 @@ public class DeviceTypeDAO {
}
}
/**
* Get connection to the datasource.
*
* @return the datasource connection.
* @throws DeviceMgtPluginException
*/
public static Connection getConnection() throws DeviceMgtPluginException {
if (currentConnection.get() == null) {
try {
@ -74,6 +91,11 @@ public class DeviceTypeDAO {
return currentConnection.get();
}
/**
* Commit transaction after editing.
*
* @throws DeviceMgtPluginException
*/
public static void commitTransaction() throws DeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
@ -92,6 +114,11 @@ public class DeviceTypeDAO {
}
}
/**
* Close current connection with the datasource.
*
* @throws DeviceMgtPluginException
*/
public static void closeConnection() throws DeviceMgtPluginException {
Connection con = currentConnection.get();
@ -105,6 +132,11 @@ public class DeviceTypeDAO {
currentConnection.remove();
}
/**
* Rollback transactions to recover from failure.
*
* @throws DeviceMgtPluginException
*/
public static void rollbackTransaction() throws DeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
@ -123,6 +155,11 @@ public class DeviceTypeDAO {
}
}
/**
* Get device type specific data object.
*
* @return device type specific data object.
*/
public DeviceTypeDAOImpl getDeviceTypeDAO() {
return new DeviceTypeDAOImpl();
}

@ -43,16 +43,22 @@ public class DeviceTypeDAOImpl {
private static final Log log = LogFactory.getLog(DeviceTypeDAOImpl.class);
/**
* Get device from the database.
*
* @param deviceId to retive the device.
* @return device object.
* @throws DeviceMgtPluginException
*/
public Device getDevice(String deviceId) throws DeviceMgtPluginException {
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
Device iotDevice = null;
ResultSet resultSet = null;
try {
conn = DeviceTypeDAO.getConnection();
String selectDBQuery =
"SELECT watertank_DEVICE_ID, DEVICE_NAME" +
" FROM watertank_DEVICE WHERE watertank_DEVICE_ID = ?";
"SELECT watertank_DEVICE_ID, DEVICE_NAME FROM watertank_DEVICE WHERE watertank_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, deviceId);
resultSet = stmt.executeQuery();
@ -77,6 +83,13 @@ public class DeviceTypeDAOImpl {
return iotDevice;
}
/**
* Add new device.
*
* @param device to be added.
* @return added or not.
* @throws DeviceMgtPluginException
*/
public boolean addDevice(Device device) throws DeviceMgtPluginException {
boolean status = false;
Connection conn;
@ -107,9 +120,16 @@ public class DeviceTypeDAOImpl {
return status;
}
/**
* Update existing device.
*
* @param device to be updated.
* @return updated or not.
* @throws DeviceMgtPluginException
*/
public boolean updateDevice(Device device) throws DeviceMgtPluginException {
boolean status = false;
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
try {
conn = DeviceTypeDAO.getConnection();
@ -140,14 +160,20 @@ public class DeviceTypeDAOImpl {
return status;
}
/**
* Delete device.
*
* @param deviceId of the device to be deleted.
* @return deleted or not.
* @throws DeviceMgtPluginException
*/
public boolean deleteDevice(String deviceId) throws DeviceMgtPluginException {
boolean status = false;
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
try {
conn = DeviceTypeDAO.getConnection();
String deleteDBQuery =
"DELETE FROM watertank_DEVICE WHERE watertank_DEVICE_ID = ?";
String deleteDBQuery = "DELETE FROM watertank_DEVICE WHERE watertank_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, deviceId);
int rows = stmt.executeUpdate();
@ -168,8 +194,14 @@ public class DeviceTypeDAOImpl {
return status;
}
/**
* Get all watertank devices.
*
* @return list of devices.
* @throws DeviceMgtPluginException
*/
public List<Device> getAllDevices() throws DeviceMgtPluginException {
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device device;

@ -15,6 +15,7 @@
*/
package org.homeautomation.watertank.plugin.impl.feature;
import org.apache.commons.lang.NotImplementedException;
import org.homeautomation.watertank.plugin.constants.DeviceTypeConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
@ -26,12 +27,14 @@ import java.util.List;
public class DeviceTypeFeatureManager implements FeatureManager {
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
return false;
//Features are not used for this device type.
throw new NotImplementedException();
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
return false;
//Features are not used for this device type.
throw new NotImplementedException();
}
@Override
@ -48,7 +51,8 @@ public class DeviceTypeFeatureManager implements FeatureManager {
@Override
public boolean removeFeature(String name) throws DeviceManagementException {
return false;
//Features are not used for this device type.
throw new NotImplementedException();
}
@Override

@ -28,22 +28,23 @@ import java.io.File;
/**
* Provides methods for initializing the database script.
*/
public class DeviceSchemaInitializer extends DatabaseCreator{
public class DeviceSchemaInitializer extends DatabaseCreator {
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
+ File.separator + "cdm" + File.separator + "plugins" + File.separator;
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
+ File.separator + "cdm" + File.separator + "plugins"
+ File.separator;
public DeviceSchemaInitializer(DataSource dataSource) {
super(dataSource);
}
public DeviceSchemaInitializer(DataSource dataSource) {
super(dataSource);
}
@Override
protected String getDbScriptLocation(String databaseType) {
String scriptName = databaseType + ".sql";
if (log.isDebugEnabled()) {
log.debug("Loading database script from :" + scriptName);
}
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
}
@Override
protected String getDbScriptLocation(String databaseType) {
String scriptName = databaseType + ".sql";
if (log.isDebugEnabled()) {
log.debug("Loading database script from :" + scriptName);
}
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
}
}

@ -18,11 +18,11 @@
package org.homeautomation.watertank.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.watertank.plugin.constants.DeviceTypeConstants;
import org.homeautomation.watertank.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.watertank.plugin.internal.DeviceTypeManagementDataHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils;
@ -52,7 +52,7 @@ public class DeviceTypeUtils {
private static Log log = LogFactory.getLog(DeviceTypeUtils.class);
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
private static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
@ -95,24 +95,26 @@ public class DeviceTypeUtils {
log.error("Error while looking up the data source: " + DeviceTypeConstants.DATA_SOURCE_NAME);
} catch (Exception e) {
throw new DeviceMgtPluginException("Error occurred while initializing Iot Device " +
"Management database schema", e);
"Management database schema", e);
}
}
public static String replaceMqttProperty(String urlWithPlaceholders) {
String MQTT_BROKER_HOST = null;
String MQTT_PORT = null;
if(!DeviceTypeConstants.MQTT_BROKER_HOST.startsWith("$")){
if (!DeviceTypeConstants.MQTT_BROKER_HOST.startsWith("$")) {
MQTT_BROKER_HOST = "\\$".concat(DeviceTypeConstants.MQTT_BROKER_HOST);
}
if(!DeviceTypeConstants.MQTT_PORT.startsWith("$")){
if (!DeviceTypeConstants.MQTT_PORT.startsWith("$")) {
MQTT_PORT = "\\$".concat(DeviceTypeConstants.MQTT_PORT);
}
urlWithPlaceholders = Utils.replaceSystemProperty(urlWithPlaceholders);
urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_PORT, "" +
(DeviceTypeConstants.DEFAULT_MQTT_PORT + getPortOffset()));
(DeviceTypeConstants.DEFAULT_MQTT_PORT
+ getPortOffset()));
urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_BROKER_HOST,
System.getProperty(DeviceTypeConstants.DEFAULT_CARBON_LOCAL_IP_PROPERTY, "localhost"));
System.getProperty(DeviceTypeConstants.DEFAULT_CARBON_LOCAL_IP_PROPERTY,
"localhost"));
return urlWithPlaceholders;
}
@ -131,10 +133,10 @@ public class DeviceTypeUtils {
}
}
public static void setupMqttOutputAdapter() throws IOException {
static void setupMqttOutputAdapter() throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration =
createMqttOutputEventAdapterConfiguration(DeviceTypeConstants.MQTT_ADAPTER_NAME,
DeviceTypeConstants.MQTT_ADAPTER_TYPE, MessageType.TEXT);
DeviceTypeConstants.MQTT_ADAPTER_TYPE, MessageType.TEXT);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
@ -157,7 +159,8 @@ public class DeviceTypeUtils {
* @return OutputEventAdapterConfiguration instance for given configuration
*/
private static OutputEventAdapterConfiguration createMqttOutputEventAdapterConfiguration(String name, String type,
String msgFormat) throws IOException {
String msgFormat)
throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
outputEventAdapterConfiguration.setName(name);
outputEventAdapterConfiguration.setType(type);

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

@ -16,6 +16,7 @@
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
@ -53,4 +54,4 @@
</plugin>
</plugins>
</build>
</project>
</project>

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

@ -17,24 +17,24 @@
*/
function onRequest(context) {
var log = new Log("cdmf.unit.device.type.watertank.device-view.js");
var log = new Log('cdmf.unit.device.type.watertank.device-view.js');
var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("id");
var deviceId = request.getParameter('id');
var autoCompleteParams = [
{"name": "deviceId", "value": deviceId}
{'name': 'deviceId', 'value': deviceId}
];
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') {
return {
"device": device,
"backendApiUri": devicemgtProps["httpsURL"] + "/" + deviceType + "/",
"autoCompleteParams": autoCompleteParams
'device': device,
'backendApiUri': devicemgtProps['httpsURL'] + '/' + deviceType + '/',
'autoCompleteParams': autoCompleteParams
};
} 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();
}
}

@ -19,14 +19,14 @@
function onRequest(context) {
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["httpsURL"].replace("https", "wss");
var constants = require('/app/modules/constants.js');
var websocketEndpoint = devicemgtProps['httpsURL'].replace('https', 'wss');
var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER);
var token = "";
var token = '';
if (tokenPair) {
token = tokenPair.accessToken;
}
websocketEndpoint = websocketEndpoint + "/secured-outputui/org.wso2.iot.watertank/1.0.0?" +
"token=" + token + "&deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type;
return {"device": device, "websocketEndpoint": websocketEndpoint};
websocketEndpoint = websocketEndpoint + '/secured-outputui/org.wso2.iot.watertank/1.0.0?' +
'token=' + token + '&deviceId=' + device.deviceIdentifier + '&deviceType=' + device.type;
return {'device': device, 'websocketEndpoint': websocketEndpoint};
}

@ -17,10 +17,9 @@
*/
var ws;
var coffee_amount = 0;
$(window).load(function () {
var websocketUrl = $("#div-chart").data("websocketurl");
var websocketUrl = $('#div-chart').data('websocketurl');
connect(websocketUrl);
});
@ -55,8 +54,8 @@ function disconnect() {
}
function updateWaterLevel(newValue) {
var waterLevel = document.getElementById("water");
waterLevel.innerHTML = (newValue | 0) + "%";
var waterLevel = document.getElementById('water');
waterLevel.innerHTML = (newValue | 0) + '%';
if (newValue == 0) {
waterLevel.style.height = (newValue * 3) + 'px';
waterLevel.style.paddingTop = 0;

@ -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,9 +50,9 @@ function showPopup() {
$('label[for=deviceName]').remove();
}
});
var deviceType = "";
var deviceType = '';
$('.deviceType').each(function () {
if (this.value != "") {
if (this.value != '') {
deviceType = this.value;
}
});
@ -81,17 +81,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;
}
});
@ -121,7 +121,7 @@ function attachEvents() {
}
});
$("a#download-device-cancel-link").click(function () {
$('a#download-device-cancel-link').click(function () {
hidePopup();
});
});
@ -130,11 +130,11 @@ function attachEvents() {
function downloadAgent() {
var deviceName;
$('.new-device-name').each(function () {
if (this.value != "") {
if (this.value != '') {
deviceName = this.value;
}
});
var deviceNameFormat = /^[^~?!#$:;%^*`+={}\[\]\\()|<>,'"]{1,30}$/;
var deviceNameFormat = /^[^~?!#$:;%^*`+={}\[\]\\()|<>,""]{1,30}$/;
if (deviceName && deviceNameFormat.test(deviceName)) {
$('#downloadForm').submit();
hidePopup();
@ -144,8 +144,8 @@ function downloadAgent() {
hidePopup();
}, 1000);
} else {
$("#invalid-username-error-msg span").text("Invalid device name");
$("#invalid-username-error-msg").removeClass("hidden");
$('#invalid-username-error-msg span').text('Invalid device name');
$('#invalid-username-error-msg').removeClass('hidden');
}
}
@ -155,29 +155,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();
});
}
}
}

@ -16,6 +16,7 @@
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
@ -31,4 +32,4 @@
<modules>
<module>feature</module>
</modules>
</project>
</project>

@ -16,6 +16,7 @@
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
@ -415,4 +416,5 @@
<org.eclipse.osgi.services.version>3.3.100.v20120522-1822</org.eclipse.osgi.services.version>
<eclipse.equinox.common.version>3.6.100.v20120522-1841</eclipse.equinox.common.version>
</properties>
</project>
</project>

Loading…
Cancel
Save