Resolve conflicts.

application-manager-new
NuwanSameera 9 years ago
commit 77b4a51add

@ -48,7 +48,7 @@
<Listener className="org.wso2.carbon.apimgt.webapp.publisher.lifecycle.listener.APIPublisherLifecycleListener"/> <Listener className="org.wso2.carbon.apimgt.webapp.publisher.lifecycle.listener.APIPublisherLifecycleListener"/>
<!-- Listener responsible for reading device features --> <!-- Listener responsible for reading device features -->
<Listener className="org.wso2.carbon.apimgt.webapp.publisher.lifecycle.listener.FeatureManagementLifecycleListener"/> <Listener className="org.wso2.carbon.device.mgt.extensions.feature.mgt.lifecycle.listener.FeatureManagementLifecycleListener"/>
<!-- WebAppDeploymentLifecycleListener listens to webapp deployment events and adds the custom permissions defined in webapps' <!-- WebAppDeploymentLifecycleListener listens to webapp deployment events and adds the custom permissions defined in webapps'
META-INF/permissions.xml to the permissions/admin section of registry. Given below is a sample of permissions.xml file. META-INF/permissions.xml to the permissions/admin section of registry. Given below is a sample of permissions.xml file.

@ -95,35 +95,33 @@
<script src="js/libs/htmlpreview.min.js"></script> <script src="js/libs/htmlpreview.min.js"></script>
<script>HTMLPreview.replaceAssets();</script> <script>HTMLPreview.replaceAssets();</script>
<script> <script>
$("#order-cup").click(function() { $("#order-cup").click(function () {
var deviceId = '<%=request.getSession().getAttribute("deviceId")%>'; var deviceId = '<%=request.getSession().getAttribute("deviceId")%>';
var deviceOwner = '<%=request.getSession().getAttribute("deviceOwner")%>'; var deviceOwner = '<%=request.getSession().getAttribute("deviceOwner")%>';
var token = '<%=request.getSession().getAttribute("token")%>'; var token = '<%=request.getSession().getAttribute("token")%>';
var url = "/connectedcup/controller/ordercoffee?deviceId=" + deviceId +"&deviceOwner=" + var url = "/connectedcup/controller/ordercoffee?deviceId=" + deviceId + "&deviceOwner=" + deviceOwner;
deviceOwner;
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: url, url: url,
headers: { headers: {
"Authorization" : "Bearer " + token "Authorization": "Bearer " + token
} }
}); });
}); });
function sendData() function sendData() {
{
var deviceId = '<%=request.getSession().getAttribute("deviceId")%>'; var deviceId = '<%=request.getSession().getAttribute("deviceId")%>';
var deviceOwner = '<%=request.getSession().getAttribute("deviceOwner")%>'; var deviceOwner = '<%=request.getSession().getAttribute("deviceOwner")%>';
var tempPayload = "temperature:" + temperature; var tempPayload = "temperature:" + temperature;
var levelPayload = "coffeelevel:" + coffee_amount; var levelPayload = "coffeelevel:" + coffee_amount;
$.post( "/connected-cup-agent/push_temperature?deviceId=" + deviceId +"&deviceOwner=" + deviceOwner + $.post("/connected-cup-agent/push_temperature?deviceId=" + deviceId + "&deviceOwner=" + deviceOwner +
"&payload=" + tempPayload); "&payload=" + tempPayload);
$.post( "/connected-cup-agent/push_level?deviceId=" + deviceId +"&deviceOwner=" + deviceOwner + $.post("/connected-cup-agent/push_level?deviceId=" + deviceId + "&deviceOwner=" + deviceOwner +
"&payload=" + levelPayload); "&payload=" + levelPayload);
setTimeout(sendData, 5000); setTimeout(sendData, 5000);
} }

@ -28,6 +28,7 @@ import org.json.JSONObject;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType; import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.annotations.device.feature.Feature; import org.wso2.carbon.apimgt.annotations.device.feature.Feature;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.DeviceValidator; import org.wso2.carbon.device.mgt.iot.DeviceValidator;
@ -51,22 +52,19 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.Calendar; import java.util.Calendar;
@API( name="connectedcup", version="1.0.0", context="/connectedcup") @API(name = "connectedcup", version = "1.0.0", context = "/connectedcup")
@DeviceType( value = "connectedcup") @DeviceType(value = "connectedcup")
public class ConnectedCupControllerService { public class ConnectedCupControllerService {
private static Log log = LogFactory.getLog(ConnectedCupControllerService.class); private static Log log = LogFactory.getLog(ConnectedCupControllerService.class);
private static final String SUPER_TENANT = "carbon.super"; private static final String SUPER_TENANT = "carbon.super";
private static ConnectedCupMQTTConnector connectedCupMQTTConnector; private static ConnectedCupMQTTConnector connectedCupMQTTConnector;
public ConnectedCupMQTTConnector connectedCupMQTTConnector() { public ConnectedCupMQTTConnector connectedCupMQTTConnector() {
return ConnectedCupControllerService.connectedCupMQTTConnector; return ConnectedCupControllerService.connectedCupMQTTConnector;
} }
public void setconnectedCupMQTTConnector( public void setconnectedCupMQTTConnector(final ConnectedCupMQTTConnector connectedCupMQTTConnector) {
final ConnectedCupMQTTConnector connectedCupMQTTConnector) {
Runnable connector = new Runnable() { Runnable connector = new Runnable() {
public void run() { public void run() {
if (waitForServerStartup()) { if (waitForServerStartup()) {
@ -76,12 +74,10 @@ public class ConnectedCupControllerService {
if (MqttConfig.getInstance().isEnabled()) { if (MqttConfig.getInstance().isEnabled()) {
connectedCupMQTTConnector.connect(); connectedCupMQTTConnector.connect();
} else { } else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. " + log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, ConnectedCupMQTTConnector not started.");
"Hence, ConnectedCupMQTTConnector not started.");
} }
} }
}; };
Thread connectorThread = new Thread(connector); Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true); connectorThread.setDaemon(true);
connectorThread.start(); connectorThread.start();
@ -105,8 +101,8 @@ public class ConnectedCupControllerService {
@Path("controller/coffeelevel") @Path("controller/coffeelevel")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Feature( code="coffeelevel", name="Coffee Level", type="monitor", @Feature(code = "coffeelevel", name = "Coffee Level", type = "monitor",
description="Request Coffee Level from Connected cup") description = "Request Coffee Level from Connected cup")
public SensorRecord readCoffeeLevel(@HeaderParam("owner") String owner, public SensorRecord readCoffeeLevel(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId, @HeaderParam("deviceId") String deviceId,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
@ -117,91 +113,76 @@ public class ConnectedCupControllerService {
deviceId, ConnectedCupConstants.DEVICE_TYPE))) { deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} }
} catch (DeviceManagementException e) { if (log.isDebugEnabled()) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
} }
if (log.isDebugEnabled()) {
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
}
try {
String mqttResource = ConnectedCupConstants.LEVEL_CONTEXT.replace("/", ""); String mqttResource = ConnectedCupConstants.LEVEL_CONTEXT.replace("/", "");
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, ""); connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, ConnectedCupConstants.SENSOR_LEVEL);
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, } catch (DeviceControllerException | TransportHandlerException e) {
ConnectedCupConstants.SENSOR_LEVEL);
} catch ( DeviceControllerException | TransportHandlerException e ) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
} }
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord; return sensorRecord;
} }
@Path("controller/temperature") @Path("controller/temperature")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Feature( code="temperature", name="Temperature", type="monitor", @Feature(code = "temperature", name = "Temperature", type = "monitor",
description="Request Temperature reading from Connected cup") description = "Request Temperature reading from Connected cup")
public SensorRecord readTemperature(@HeaderParam("owner") String owner, public SensorRecord readTemperature(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId, @HeaderParam("deviceId") String deviceId,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
SensorRecord sensorRecord = null; SensorRecord sensorRecord = null;
DeviceValidator deviceValidator = new DeviceValidator(); DeviceValidator deviceValidator = new DeviceValidator();
try { try {
if (!deviceValidator.isExist(owner, SUPER_TENANT, if (!deviceValidator.isExist(owner, SUPER_TENANT,
new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE))) { new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} }
} catch (DeviceManagementException e) { if (log.isDebugEnabled()) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); log.debug("Sending request to read connected cup temperature of device [" + deviceId + "] via MQTT");
} }
if (log.isDebugEnabled()) {
log.debug("Sending request to read connected cup temperature of device " +
"[" + deviceId + "] via MQTT");
}
try {
String mqttResource = ConnectedCupConstants.TEMPERATURE_CONTEXT.replace("/", ""); String mqttResource = ConnectedCupConstants.TEMPERATURE_CONTEXT.replace("/", "");
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, ""); connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ConnectedCupConstants.SENSOR_TEMPERATURE); ConnectedCupConstants.SENSOR_TEMPERATURE);
} catch ( DeviceControllerException | TransportHandlerException e) { } catch (DeviceControllerException | TransportHandlerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
} }
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord; return sensorRecord;
} }
@Path("controller/ordercoffee") @Path("controller/ordercoffee")
@POST @POST
public void orderCoffee(@QueryParam("deviceId") String deviceId, @QueryParam("deviceOwner") String public void orderCoffee(@QueryParam("deviceId") String deviceId, @QueryParam("deviceOwner") String deviceOwner,
deviceOwner, @Context HttpServletResponse response){ @Context HttpServletResponse response) {
DeviceValidator deviceValidator = new DeviceValidator(); DeviceValidator deviceValidator = new DeviceValidator();
try { try {
if (!deviceValidator.isExist(deviceOwner, SUPER_TENANT, new DeviceIdentifier( if (!deviceValidator.isExist(deviceOwner, SUPER_TENANT, new DeviceIdentifier(
deviceId, ConnectedCupConstants.DEVICE_TYPE))) { deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} }
response.setStatus(Response.Status.ACCEPTED.getStatusCode());
log.info("Coffee ordered....!");
if (log.isDebugEnabled()) {
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
}
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
} }
response.setStatus(Response.Status.ACCEPTED.getStatusCode());
log.info("Coffee ordered....!");
if (log.isDebugEnabled()) {
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
}
// return response;
} }
}
}

@ -26,10 +26,18 @@ import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement @XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class DeviceJSON { public class DeviceJSON {
@XmlElement(required = true) public String owner;
@XmlElement(required = true) public String deviceId; @XmlElement(required = true)
@XmlElement(required = true) public String reply; public String owner;
@XmlElement public Long time; @XmlElement(required = true)
@XmlElement public String key; public String deviceId;
@XmlElement public float value; @XmlElement(required = true)
public String reply;
@XmlElement
public Long time;
@XmlElement
public String key;
@XmlElement
public float value;
} }

@ -19,6 +19,7 @@
package org.coffeeking.controller.service.exception; package org.coffeeking.controller.service.exception;
public class ConnectedCupException extends Exception { public class ConnectedCupException extends Exception {
private static final long serialVersionUID = 118512086957330189L; private static final long serialVersionUID = 118512086957330189L;
public ConnectedCupException(String errorMessage) { public ConnectedCupException(String errorMessage) {
@ -28,4 +29,5 @@ public class ConnectedCupException extends Exception {
public ConnectedCupException(String errorMessage, Throwable throwable) { public ConnectedCupException(String errorMessage, Throwable throwable) {
super(errorMessage, throwable); super(errorMessage, throwable);
} }
} }

@ -37,19 +37,16 @@ import java.util.UUID;
@SuppressWarnings("no JAX-WS annotation") @SuppressWarnings("no JAX-WS annotation")
public class ConnectedCupMQTTConnector extends MQTTTransportHandler { public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(ConnectedCupMQTTConnector.class);
private static Log log = LogFactory.getLog(ConnectedCupMQTTConnector.class);
private static String serverName = DeviceManagementConfigurationManager.getInstance(). private static String serverName = DeviceManagementConfigurationManager.getInstance().
getDeviceManagementServerInfo().getName();
private static String subscribeTopic = "wso2/+/" + ConnectedCupConstants.DEVICE_TYPE + "/+/" private static String subscribeTopic = "wso2/+/" + ConnectedCupConstants.DEVICE_TYPE + "/+/"
+ "connected_publisher"; + "connected_publisher";
private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5); private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
private ConnectedCupMQTTConnector() { private ConnectedCupMQTTConnector() {
super(iotServerSubscriber, ConnectedCupConstants.DEVICE_TYPE, super(iotServerSubscriber, ConnectedCupConstants.DEVICE_TYPE, MqttConfig.getInstance().getMqttQueueEndpoint(),
MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic); subscribeTopic);
} }
@Override @Override
@ -71,14 +68,11 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
} }
} }
}; };
Thread connectorThread = new Thread(connector); Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true); connectorThread.setDaemon(true);
connectorThread.start(); connectorThread.start();
} }
@Override @Override
public void publishDeviceData(String... publishData) throws TransportHandlerException { public void publishDeviceData(String... publishData) throws TransportHandlerException {
if (publishData.length != 4) { if (publishData.length != 4) {
@ -87,51 +81,43 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
log.error(errorMsg); log.error(errorMsg);
throw new TransportHandlerException(errorMsg); throw new TransportHandlerException(errorMsg);
} }
String deviceOwner = publishData[0]; String deviceOwner = publishData[0];
String deviceId = publishData[1]; String deviceId = publishData[1];
String resource = publishData[2]; String resource = publishData[2];
String state = publishData[3]; String state = publishData[3];
MqttMessage pushMessage = new MqttMessage(); MqttMessage pushMessage = new MqttMessage();
String publishTopic = String publishTopic = "wso2" + File.separator + deviceOwner + File.separator +
"wso2" + File.separator + deviceOwner + File.separator + ConnectedCupConstants.DEVICE_TYPE + File.separator + deviceId;
ConnectedCupConstants.DEVICE_TYPE + File.separator + deviceId;
try { try {
String actualMessage = resource + ":" + state; String actualMessage = resource + ":" + state;
pushMessage.setPayload(actualMessage.getBytes(StandardCharsets.UTF_8)); pushMessage.setPayload(actualMessage.getBytes(StandardCharsets.UTF_8));
pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE); pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);
pushMessage.setRetained(false); pushMessage.setRetained(false);
publishToQueue(publishTopic, pushMessage); publishToQueue(publishTopic, pushMessage);
} catch (Exception e) { } catch (Exception e) {
String errorMsg = "Preparing payload failed for device - [" + deviceId + "] of owner - " + String errorMsg = "Preparing payload failed for device - [" + deviceId + "] of owner-[" + deviceOwner + "].";
"[" + deviceOwner + "].";
log.error(errorMsg); log.error(errorMsg);
throw new TransportHandlerException(errorMsg, e); throw new TransportHandlerException(errorMsg, e);
} }
} }
@Override @Override
public void processIncomingMessage(MqttMessage mqttMessage, String... strings) throws TransportHandlerException { public void processIncomingMessage(MqttMessage mqttMessage, String... strings) throws TransportHandlerException {
String topic = strings[0]; String topic = strings[0];
<<<<<<< HEAD
=======
>>>>>>> origin/master
String ownerAndId = topic.replace("wso2" + File.separator, ""); String ownerAndId = topic.replace("wso2" + File.separator, "");
ownerAndId = ownerAndId.replace(File.separator + ConnectedCupConstants.DEVICE_TYPE + File.separator, ":"); ownerAndId = ownerAndId.replace(File.separator + ConnectedCupConstants.DEVICE_TYPE + File.separator, ":");
ownerAndId = ownerAndId.replace(File.separator + "connected_publisher", ""); ownerAndId = ownerAndId.replace(File.separator + "connected_publisher", "");
String owner = ownerAndId.split(":")[0]; String owner = ownerAndId.split(":")[0];
String deviceId = ownerAndId.split(":")[1]; String deviceId = ownerAndId.split(":")[1];
// String actualMessage = mqttMessage.toString();
String[] messageData = mqttMessage.toString().split(":"); String[] messageData = mqttMessage.toString().split(":");
Float value = Float.valueOf(messageData[1]); Float value = Float.valueOf(messageData[1]);
<<<<<<< HEAD
switch(messageData[0]) { switch(messageData[0]) {
case "temperature": case "temperature":
@ -143,19 +129,27 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_LEVEL, SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_LEVEL,
String.valueOf(messageData[1]), String.valueOf(messageData[1]),
Calendar.getInstance().getTimeInMillis()); Calendar.getInstance().getTimeInMillis());
=======
switch (messageData[0]) {
case "temperature":
SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_TEMPERATURE,
String.valueOf(messageData[1]),
Calendar.getInstance().getTimeInMillis());
break;
case "coffeelevel":
SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_LEVEL,
String.valueOf(messageData[1]),
Calendar.getInstance().getTimeInMillis());
>>>>>>> origin/master
break; break;
} }
ConnectedCupServiceUtils.publishToDAS(owner, deviceId, messageData[0], value); ConnectedCupServiceUtils.publishToDAS(owner, deviceId, messageData[0], value);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Received MQTT message for OWNER: " + owner + " DEVICE.ID: " + deviceId + " | Command: " + log.debug("Received MQTT message for OWNER: " + owner + " DEVICE.ID: " + deviceId + " | Command: " +
messageData[0] +" " + messageData[1] ); messageData[0] + " " + messageData[1]);
} }
} }
@Override @Override
public void disconnect() { public void disconnect() {
Runnable stopConnection = new Runnable() { Runnable stopConnection = new Runnable() {
@ -168,7 +162,6 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint
+ " for device-type - " + ConnectedCupConstants.DEVICE_TYPE, e); + " for device-type - " + ConnectedCupConstants.DEVICE_TYPE, e);
} }
try { try {
Thread.sleep(timeoutInterval); Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) { } catch (InterruptedException e1) {
@ -179,18 +172,15 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
} }
} }
}; };
Thread terminatorThread = new Thread(stopConnection); Thread terminatorThread = new Thread(stopConnection);
terminatorThread.setDaemon(true); terminatorThread.setDaemon(true);
terminatorThread.start(); terminatorThread.start();
} }
@Override @Override
public void publishDeviceData() { public void publishDeviceData() {
// nothing to do // nothing to do
} }
@Override @Override
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException { public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
// nothing to do // nothing to do

@ -30,6 +30,7 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService; import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import javax.ws.rs.HttpMethod; import javax.ws.rs.HttpMethod;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
@ -42,10 +43,8 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future; import java.util.concurrent.Future;
public class ConnectedCupServiceUtils { public class ConnectedCupServiceUtils {
private static final Log log = LogFactory.getLog(ConnectedCupServiceUtils.class);
//TODO; replace this tenant domain private static final Log log = LogFactory.getLog(ConnectedCupServiceUtils.class);
private static final String SUPER_TENANT = "carbon.super";
private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature"; private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature";
private static final String COFFEE_LEVEL_STREAM_DEFINITION = "org.wso2.iot.devices.coffeelevel"; private static final String COFFEE_LEVEL_STREAM_DEFINITION = "org.wso2.iot.devices.coffeelevel";
@ -61,23 +60,19 @@ public class ConnectedCupServiceUtils {
if (!fireAndForgot) { if (!fireAndForgot) {
HttpURLConnection httpConnection = getHttpConnection(urlString); HttpURLConnection httpConnection = getHttpConnection(urlString);
try { try {
httpConnection.setRequestMethod(HttpMethod.GET); httpConnection.setRequestMethod(HttpMethod.GET);
} catch (ProtocolException e) { } catch (ProtocolException e) {
String errorMsg = String errorMsg =
"Protocol specific error occurred when trying to set method to GET" + "Protocol specific error occurred when trying to set method to GET for:" + urlString;
" for:" + urlString;
log.error(errorMsg); log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e); throw new DeviceManagementException(errorMsg, e);
} }
responseMsg = readResponseFromGetRequest(httpConnection); responseMsg = readResponseFromGetRequest(httpConnection);
} else { } else {
CloseableHttpAsyncClient httpclient = null; CloseableHttpAsyncClient httpclient = null;
try { try {
httpclient = HttpAsyncClients.createDefault(); httpclient = HttpAsyncClients.createDefault();
httpclient.start(); httpclient.start();
HttpGet request = new HttpGet(urlString); HttpGet request = new HttpGet(urlString);
@ -99,9 +94,7 @@ public class ConnectedCupServiceUtils {
latch.countDown(); latch.countDown();
} }
}); });
latch.await(); latch.await();
} catch (InterruptedException e) { } catch (InterruptedException e) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Sync Interrupted"); log.debug("Sync Interrupted");
@ -110,7 +103,6 @@ public class ConnectedCupServiceUtils {
try { try {
if (httpclient != null) { if (httpclient != null) {
httpclient.close(); httpclient.close();
} }
} catch (IOException e) { } catch (IOException e) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -119,7 +111,6 @@ public class ConnectedCupServiceUtils {
} }
} }
} }
return responseMsg; return responseMsg;
} }
@ -129,57 +120,45 @@ public class ConnectedCupServiceUtils {
/* This methods creates and returns a http connection object */ /* This methods creates and returns a http connection object */
public static HttpURLConnection getHttpConnection(String urlString) throws public static HttpURLConnection getHttpConnection(String urlString) throws DeviceManagementException {
DeviceManagementException {
URL connectionUrl = null; URL connectionUrl = null;
HttpURLConnection httpConnection; HttpURLConnection httpConnection;
try { try {
connectionUrl = new URL(urlString); connectionUrl = new URL(urlString);
httpConnection = (HttpURLConnection) connectionUrl.openConnection(); httpConnection = (HttpURLConnection) connectionUrl.openConnection();
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
String errorMsg = String errorMsg = "Error occured whilst trying to form HTTP-URL from string: " + urlString;
"Error occured whilst trying to form HTTP-URL from string: " + urlString;
log.error(errorMsg); log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e); throw new DeviceManagementException(errorMsg, e);
} catch (IOException e) { } catch (IOException e) {
String errorMsg = "Error occured whilst trying to open a connection to: " + String errorMsg = "Error occured whilst trying to open a connection to: " + connectionUrl.toString();
connectionUrl.toString();
log.error(errorMsg); log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e); throw new DeviceManagementException(errorMsg, e);
} }
return httpConnection; return httpConnection;
} }
/* This methods reads and returns the response from the connection */ /* This methods reads and returns the response from the connection */
public static String readResponseFromGetRequest(HttpURLConnection httpConnection) public static String readResponseFromGetRequest(HttpURLConnection httpConnection) throws DeviceManagementException {
throws DeviceManagementException {
BufferedReader bufferedReader; BufferedReader bufferedReader;
try { try {
bufferedReader = new BufferedReader(new InputStreamReader( bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
httpConnection.getInputStream()));
} catch (IOException e) { } catch (IOException e) {
String errorMsg = String errorMsg =
"There is an issue with connecting the reader to the input stream at: " + "There is an issue with connecting the reader to the input stream at: " + httpConnection.getURL();
httpConnection.getURL();
log.error(errorMsg); log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e); throw new DeviceManagementException(errorMsg, e);
} }
String responseLine; String responseLine;
StringBuilder completeResponse = new StringBuilder(); StringBuilder completeResponse = new StringBuilder();
try { try {
while ((responseLine = bufferedReader.readLine()) != null) { while ((responseLine = bufferedReader.readLine()) != null) {
completeResponse.append(responseLine); completeResponse.append(responseLine);
} }
} catch (IOException e) { } catch (IOException e) {
String errorMsg = String errorMsg =
"Error occured whilst trying read from the connection stream at: " + "Error occured whilst trying read from the connection stream at: " + httpConnection.getURL();
httpConnection.getURL();
log.error(errorMsg); log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e); throw new DeviceManagementException(errorMsg, e);
} }
@ -187,25 +166,24 @@ public class ConnectedCupServiceUtils {
bufferedReader.close(); bufferedReader.close();
} catch (IOException e) { } catch (IOException e) {
log.error( log.error(
"Could not succesfully close the bufferedReader to the connection at: " + "Could not succesfully close the bufferedReader to the connection at: " + httpConnection.getURL());
httpConnection.getURL());
} }
return completeResponse.toString(); return completeResponse.toString();
} }
public static boolean publishToDAS(String owner, String deviceId, String sensor, float values) { public static boolean publishToDAS(String owner, String deviceId, String sensor, float values) {
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true); ctx.setUsername(owner);
if (ctx.getTenantDomain(true) == null) {
ctx.setTenantDomain("carbon.super", true);
}
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null); DeviceAnalyticsService.class, null);
Object metdaData[] = {owner, ConnectedCupConstants.DEVICE_TYPE, deviceId, Object metdaData[] = {owner, ConnectedCupConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
System.currentTimeMillis()};
Object payloadData[] = {values}; Object payloadData[] = {values};
try { try {
switch (sensor){ switch (sensor) {
case "temperature": case "temperature":
deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData, deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData); new Object[0], payloadData);
@ -214,7 +192,6 @@ public class ConnectedCupServiceUtils {
deviceAnalyticsService.publishEvent(COFFEE_LEVEL_STREAM_DEFINITION, "1.0.0", metdaData, deviceAnalyticsService.publishEvent(COFFEE_LEVEL_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData); new Object[0], payloadData);
} }
} catch (DataPublisherConfigurationException e) { } catch (DataPublisherConfigurationException e) {
return false; return false;
} finally { } finally {

@ -0,0 +1,52 @@
<?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.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Request coffee level</name>
<path>/device-mgt/devices/connectedcup/coffeelevel</path>
<url>/controller/coffeelevel</url>
<method>GET</method>
<scope>connectedcup_user</scope>
</Permission>
<Permission>
<name>Request temperature</name>
<path>/device-mgt/devices/connectedcup/temperature</path>
<url>/controller/temperature</url>
<method>GET</method>
<scope>connectedcup_user</scope>
</Permission>
<Permission>
<name>Order coffee cup</name>
<path>/device-mgt/devices/connectedcup/ordercoffee</path>
<url>/controller/ordercoffee</url>
<method>POST</method>
<scope>connectedcup_user</scope>
</Permission>
</PermissionConfiguration>

@ -21,9 +21,12 @@ package org.coffeeking.manager.service;
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.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants; import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.coffeeking.manager.service.util.APIUtil;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType; import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil;
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil; import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
@ -52,76 +55,62 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@API( name="connectedcup_mgt", version="1.0.0", context="/connectedcup_mgt") @API(name = "connectedcup_mgt", version = "1.0.0", context = "/connectedcup_mgt")
public class ConnectedCupManagerService { public class ConnectedCupManagerService {
private static Log log = LogFactory.getLog(ConnectedCupManagerService.class);
private static final String SUPER_TENANT = "carbon.super";
private static Log log = LogFactory.getLog(ConnectedCupManagerService.class);
@Context @Context
private HttpServletResponse response; private HttpServletResponse response;
/** /**
* @param name * @param name
* @param owner
* @return * @return
*/ */
@Path("cup/register") @Path("manager/device")
@POST @POST
public boolean register(@QueryParam("name") String name, @QueryParam("owner") String owner) { public boolean register(@QueryParam("name") String name) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
String deviceId = shortUUID(); String deviceId = shortUUID();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try { try {
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode()); response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false; return false;
} }
Device device = new Device(); Device device = new Device();
device.setDeviceIdentifier(deviceId); device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime()); enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name); device.setName(name);
device.setType(ConnectedCupConstants.DEVICE_TYPE); device.setType(ConnectedCupConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(owner); enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo); device.setEnrolmentInfo(enrolmentInfo);
KeyGenerationUtil.createApplicationKeys(ConnectedCupConstants.DEVICE_TYPE); KeyGenerationUtil.createApplicationKeys(ConnectedCupConstants.DEVICE_TYPE);
TokenClient accessTokenClient = new TokenClient(ConnectedCupConstants.DEVICE_TYPE); TokenClient accessTokenClient = new TokenClient(ConnectedCupConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(APIUtil.getAuthenticatedUser(), deviceId);
//create token
String accessToken = accessTokenInfo.getAccess_token(); String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token(); String refreshToken = accessTokenInfo.getRefresh_token();
List<Device.Property> properties = new ArrayList<>(); List<Device.Property> properties = new ArrayList<>();
Device.Property accessTokenProperty = new Device.Property(); Device.Property accessTokenProperty = new Device.Property();
accessTokenProperty.setName("accessToken"); accessTokenProperty.setName("accessToken");
accessTokenProperty.setValue(accessToken); accessTokenProperty.setValue(accessToken);
Device.Property refreshTokenProperty = new Device.Property(); Device.Property refreshTokenProperty = new Device.Property();
refreshTokenProperty.setName("refreshToken"); refreshTokenProperty.setName("refreshToken");
refreshTokenProperty.setValue(refreshToken); refreshTokenProperty.setValue(refreshToken);
properties.add(accessTokenProperty); properties.add(accessTokenProperty);
properties.add(refreshTokenProperty); properties.add(refreshTokenProperty);
device.setProperties(properties); device.setProperties(properties);
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) { if (added) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
} else { } else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
} }
return added; return added;
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
@ -129,108 +118,79 @@ public class ConnectedCupManagerService {
} catch (AccessTokenException e) { } catch (AccessTokenException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
deviceManagement.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
} }
return true; return true;
} }
@Path("/device/remove/{device_id}") @Path("manager/device/{device_id}")
@DELETE @DELETE
public void removeDevice(@PathParam("device_id") String deviceId, public void removeDevice(@PathParam("device_id") String deviceId,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try { try {
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier);
deviceIdentifier);
if (removed) { if (removed) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
} else { } else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally { } finally {
deviceManagement.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
} }
} }
@Path("/device/update/{device_id}") @Path("manager/device/{device_id}")
@POST @POST
public boolean updateDevice(@PathParam("device_id") String deviceId, public boolean updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name, @QueryParam("name") String name,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try { try {
Device device = deviceManagement.getDeviceManagementService().getDevice( Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
deviceIdentifier);
device.setDeviceIdentifier(deviceId); device.setDeviceIdentifier(deviceId);
// device.setDeviceTypeId(deviceTypeId); // device.setDeviceTypeId(deviceTypeId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name); device.setName(name);
device.setType(ConnectedCupConstants.DEVICE_TYPE); device.setType(ConnectedCupConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(
device);
if (updated) { if (updated) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
} else { } else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
} }
return updated; return updated;
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false; return false;
} finally { } finally {
deviceManagement.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
} }
} }
@Path("/device/{device_id}") @Path("manager/device/{device_id}")
@GET @GET
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Device getDevice(@PathParam("device_id") String deviceId) { public Device getDevice(@PathParam("device_id") String deviceId) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE); deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try { try {
Device device = deviceManagement.getDeviceManagementService().getDevice( Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
deviceIdentifier);
return device; return device;
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null; return null;
} finally { } finally {
deviceManagement.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
} }
} }
private static String shortUUID() { private static String shortUUID() {
@ -239,4 +199,4 @@ public class ConnectedCupManagerService {
return Long.toString(l, Character.MAX_RADIX); return Long.toString(l, Character.MAX_RADIX);
} }
} }

@ -0,0 +1,36 @@
package org.coffeeking.manager.service.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
/**
* This class provides utility functions used by REST-API.
*/
public class APIUtil {
private static Log log = LogFactory.getLog(APIUtil.class);
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
if (username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@"));
}
return username;
}
public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
}

@ -0,0 +1,59 @@
<?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.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/manager/device/{device_id}</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Add device</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/manager/device/{device_id}</url>
<method>DELETE</method>
<scope></scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/manager/device/{device_id}</url>
<method>POST</method>
<scope></scope>
</Permission>
</PermissionConfiguration>

@ -25,7 +25,7 @@
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="ConnectedCupmanager" address="/connectedcup"> <jaxrs:server id="ConnectedCupmanager" address="/">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<bean id="ConnectedCupManagerService" <bean id="ConnectedCupManagerService"
class="org.coffeeking.manager.service.ConnectedCupManagerService"> class="org.coffeeking.manager.service.ConnectedCupManagerService">

@ -36,31 +36,31 @@ function showPopup() {
$(modalPopup).show(); $(modalPopup).show();
setPopupMaxHeight(); setPopupMaxHeight();
$('#downloadForm').validate({ $('#downloadForm').validate({
rules: { rules: {
deviceName: { deviceName: {
minlength: 4, minlength: 4,
required: true required: true
} }
}, },
highlight: function (element) { highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error'); $(element).closest('.control-group').removeClass('success').addClass('error');
}, },
success: function (element) { success: function (element) {
$(element).closest('.control-group').removeClass('error').addClass('success'); $(element).closest('.control-group').removeClass('error').addClass('success');
$('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;
} }
}); });
if (deviceType == 'digitaldisplay'){ if (deviceType == 'digitaldisplay') {
$('.sketchType').remove(); $('.sketchType').remove();
$('input[name="sketchType"][value="digitaldisplay"]').prop('checked', true); $('input[name="sketchType"][value="digitaldisplay"]').prop('checked', true);
$("label[for='digitaldisplay']").text("Simple Agent"); $("label[for='digitaldisplay']").text("Simple Agent");
}else{ } else {
$('.sketchTypes').remove(); $('.sketchTypes').remove();
} }
} }
@ -106,16 +106,16 @@ function attachEvents() {
if (deviceName && deviceName.length >= 4) { if (deviceName && deviceName.length >= 4) {
payload.deviceName = deviceName; payload.deviceName = deviceName;
invokerUtil.post( invokerUtil.post(
downloadDeviceAPI, downloadDeviceAPI,
payload, payload,
function (data, textStatus, jqxhr) { function (data, textStatus, jqxhr) {
doAction(data); doAction(data);
}, },
function (data) { function (data) {
doAction(data); doAction(data);
} }
); );
}else if(deviceName){ } else if (deviceName) {
$('.controls').append('<label for="deviceName" generated="true" class="error" style="display: inline-block;">Please enter at least 4 characters.</label>'); $('.controls').append('<label for="deviceName" generated="true" class="error" style="display: inline-block;">Please enter at least 4 characters.</label>');
$('.control-group').removeClass('success').addClass('error'); $('.control-group').removeClass('success').addClass('error');
} else { } else {
@ -137,7 +137,7 @@ function downloadAgent() {
var $inputs = $('#downloadForm :input'); var $inputs = $('#downloadForm :input');
var values = {}; var values = {};
$inputs.each(function() { $inputs.each(function () {
values[this.name] = $(this).val(); values[this.name] = $(this).val();
}); });
@ -145,18 +145,17 @@ function downloadAgent() {
payload.name = $inputs[0].value; payload.name = $inputs[0].value;
payload.owner = $inputs[1].value; payload.owner = $inputs[1].value;
var connectedCupRegisterURL = "/connectedcup_mgt/connectedcup/cup/register?" + var connectedCupRegisterURL = "/connectedcup_mgt/manager/device?name=" + encodeURI(payload.name);
"name=" + encodeURI(payload.name) + "&owner=" + payload.owner;
invokerUtil.post( invokerUtil.post(
connectedCupRegisterURL, connectedCupRegisterURL,
payload, payload,
function (data, textStatus, jqxhr) { function (data, textStatus, jqxhr) {
hidePopup(); hidePopup();
}, },
function (data) { function (data) {
hidePopup(); hidePopup();
} }
); );
var deviceName; var deviceName;

@ -49,7 +49,6 @@ public class CurrentSensorControllerService {
private static Log log = LogFactory.getLog(CurrentSensorControllerService.class); private static Log log = LogFactory.getLog(CurrentSensorControllerService.class);
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private static final String SUPER_TENANT = "carbon.super";
private boolean waitForServerStartup() { private boolean waitForServerStartup() {
while (!DeviceManagement.isServerReady()) { while (!DeviceManagement.isServerReady()) {
@ -62,7 +61,6 @@ public class CurrentSensorControllerService {
return false; return false;
} }
@Path("controller/register/{owner}/{deviceId}/{ip}/{port}") @Path("controller/register/{owner}/{deviceId}/{ip}/{port}")
@POST @POST
public String registerDeviceIP(@PathParam("owner") String owner, public String registerDeviceIP(@PathParam("owner") String owner,
@ -71,28 +69,21 @@ public class CurrentSensorControllerService {
@PathParam("port") String devicePort, @PathParam("port") String devicePort,
@Context HttpServletResponse response, @Context HttpServletResponse response,
@Context HttpServletRequest request) { @Context HttpServletRequest request) {
System.out.println("Register Call..");
//TODO:: Need to get IP from the request itself //TODO:: Need to get IP from the request itself
String result; String result;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: " + owner); log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: " + owner);
} }
String deviceHttpEndpoint = deviceIP + ":" + devicePort; String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint); deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered"; result = "Device-IP Registered";
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug(result); log.debug(result);
} }
return result; return result;
} }
/** /**
* @param owner * @param owner
* @param deviceId * @param deviceId
@ -111,14 +102,12 @@ public class CurrentSensorControllerService {
@HeaderParam("protocol") String protocol, @HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
SensorRecord sensorRecord = null; SensorRecord sensorRecord = null;
try { try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
CurrentSensorConstants.SENSOR_CURRENT); CurrentSensorConstants.SENSOR_CURRENT);
} catch (DeviceControllerException e) { } catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} }
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord; return sensorRecord;
} }
@ -134,21 +123,19 @@ public class CurrentSensorControllerService {
@GET @GET
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Feature(code = "read-power", name = "Power x100", type = "monitor", @Feature(code = "read-power", name = "Power", type = "monitor",
description = "Request power reading from Arduino agent") description = "Request power reading from Arduino agent")
public SensorRecord requestPower(@HeaderParam("owner") String owner, public SensorRecord requestPower(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId, @HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol, @HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
SensorRecord sensorRecord = null; SensorRecord sensorRecord = null;
try { try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
CurrentSensorConstants.SENSOR_POWER); CurrentSensorConstants.SENSOR_POWER);
} catch (DeviceControllerException e) { } catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} }
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord; return sensorRecord;
} }
@ -164,21 +151,19 @@ public class CurrentSensorControllerService {
@GET @GET
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Feature(code = "read-flowrate", name = "Flow Rate x100", type = "monitor", @Feature(code = "read-flowrate", name = "Flow Rate", type = "monitor",
description = "Request flow rate reading from Arduino agent") description = "Request flow rate reading from Arduino agent")
public SensorRecord requestFlowRate(@HeaderParam("owner") String owner, public SensorRecord requestFlowRate(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId, @HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol, @HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
SensorRecord sensorRecord = null; SensorRecord sensorRecord = null;
try { try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
CurrentSensorConstants.SENSOR_FLOWRATE); CurrentSensorConstants.SENSOR_FLOWRATE);
} catch (DeviceControllerException e) { } catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} }
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord; return sensorRecord;
} }
@ -191,69 +176,47 @@ public class CurrentSensorControllerService {
@POST @POST
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public void pushData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { public void pushData(final DeviceJSON dataMsg, @Context HttpServletResponse response) {
String owner = dataMsg.owner; String owner = dataMsg.owner;
String deviceId = dataMsg.deviceId; String deviceId = dataMsg.deviceId;
String deviceIp = dataMsg.reply; String deviceIp = dataMsg.reply;
float current = dataMsg.current; float current = dataMsg.current;
float flow_rate = dataMsg.flow_rate; float flow_rate = dataMsg.flow_rate;
try { String registeredIp = deviceToIpMap.get(deviceId);
DeviceValidator deviceValidator = new DeviceValidator(); if (registeredIp == null) {
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp +
CurrentSensorConstants.DEVICE_TYPE))) { " for device ID - " + deviceId);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
log.warn("Temperature data Received from unregistered raspberrypi device [" + deviceId + return;
"] for owner [" + owner + "]"); } else if (!registeredIp.equals(deviceIp)) {
return; log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId +
} " is already registered under some other IP. Re-registration required");
response.setStatus(Response.Status.CONFLICT.getStatusCode());
String registeredIp = deviceToIpMap.get(deviceId); return;
}
if (registeredIp == null) { SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_CURRENT,
log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp + String.valueOf(current),
" for device ID - " + deviceId); Calendar.getInstance().getTimeInMillis());
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_POWER,
return; String.valueOf(current * 230),
} else if (!registeredIp.equals(deviceIp)) { Calendar.getInstance().getTimeInMillis());
log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId + SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_FLOWRATE,
" is already registered under some other IP. Re-registration required"); String.valueOf(flow_rate),
response.setStatus(Response.Status.CONFLICT.getStatusCode()); Calendar.getInstance().getTimeInMillis());
return; if (!CurrentSensorServiceUtils.publishToDASCurrent(dataMsg.deviceId, current)) {
} response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" +
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_CURRENT, deviceId + "] of owner [" + owner + "]");
String.valueOf(current), }
Calendar.getInstance().getTimeInMillis()); if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.deviceId, current * 230)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_POWER, log.warn("An error occured whilst trying to publish pin data of Power Sensor Data with ID [" +
String.valueOf(current * 230 / 100), deviceId + "] of owner [" + owner + "]");
Calendar.getInstance().getTimeInMillis()); }
if (!CurrentSensorServiceUtils.publishToDASFlowRate(dataMsg.deviceId, flow_rate)) {
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_FLOWRATE, response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
String.valueOf(flow_rate/100), log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" +
Calendar.getInstance().getTimeInMillis()); deviceId + "] of owner [" + owner + "]");
if (!CurrentSensorServiceUtils.publishToDASCurrent(dataMsg.owner, dataMsg.deviceId, current)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId +
"] of owner [" + owner + "]");
}
if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.owner, dataMsg.deviceId, current * 230 / 100)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.warn("An error occured whilst trying to publish pin data of Power Sensor Data with ID [" + deviceId +
"] of owner [" + owner + "]");
}
if (!CurrentSensorServiceUtils.publishToDASFlowRate(dataMsg.owner, dataMsg.deviceId, flow_rate/100)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId +
"] of owner [" + owner + "]");
}
} catch (DeviceManagementException e) {
String errorMsg = "Validation attempt for deviceId [" + deviceId + "] of owner [" + owner + "] failed.\n";
log.error(errorMsg + Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase() + "\n" + e.getErrorMessage());
} }
} }

@ -27,11 +27,20 @@ import javax.xml.bind.annotation.XmlRootElement;
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class DeviceJSON { public class DeviceJSON {
@XmlElement(required = true) public String owner;
@XmlElement(required = true) public String deviceId; @XmlElement(required = true)
@XmlElement(required = true) public String reply; public String owner;
@XmlElement public Long time; @XmlElement(required = true)
@XmlElement public String key; public String deviceId;
@XmlElement public float current; @XmlElement(required = true)
@XmlElement public float flow_rate; public String reply;
@XmlElement
public Long time;
@XmlElement
public String key;
@XmlElement
public float current;
@XmlElement
public float flow_rate;
} }

@ -26,23 +26,19 @@ import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfiguration
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService; import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
public class CurrentSensorServiceUtils { public class CurrentSensorServiceUtils {
private static final Log log = LogFactory.getLog(CurrentSensorServiceUtils.class);
//TODO; replace this tenant domain private static final Log log = LogFactory.getLog(CurrentSensorServiceUtils.class);
private static final String SUPER_TENANT = "carbon.super";
private static final String CURRENT_STREAM_DEFINITION = "org.wso2.iot.devices.current"; private static final String CURRENT_STREAM_DEFINITION = "org.wso2.iot.devices.current";
private static final String POWER_STREAM_DEFINITION = "org.wso2.iot.devices.power"; private static final String POWER_STREAM_DEFINITION = "org.wso2.iot.devices.power";
private static final String FLOWRATE_STREAM_DEFINITION = "org.wso2.iot.devices.flowrate"; private static final String FLOWRATE_STREAM_DEFINITION = "org.wso2.iot.devices.flowrate";
public static boolean publishToDASCurrent(String owner, String deviceId, float current) { public static boolean publishToDASCurrent(String deviceId, float current) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true); String owner = ctx.getUsername();
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null); DeviceAnalyticsService.class, null);
Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payloadCurrent[] = {current}; Object payloadCurrent[] = {current};
try { try {
deviceAnalyticsService.publishEvent(CURRENT_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadCurrent); deviceAnalyticsService.publishEvent(CURRENT_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadCurrent);
} catch (DataPublisherConfigurationException e) { } catch (DataPublisherConfigurationException e) {
@ -53,15 +49,13 @@ public class CurrentSensorServiceUtils {
return true; return true;
} }
public static boolean publishToDASPower(String owner, String deviceId, float power) { public static boolean publishToDASPower(String deviceId, float power) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true); String owner = ctx.getUsername();
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null); DeviceAnalyticsService.class, null);
Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payloadPower[] = {power}; Object payloadPower[] = {power};
try { try {
deviceAnalyticsService.publishEvent(POWER_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadPower); deviceAnalyticsService.publishEvent(POWER_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadPower);
} catch (DataPublisherConfigurationException e) { } catch (DataPublisherConfigurationException e) {
@ -72,15 +66,13 @@ public class CurrentSensorServiceUtils {
return true; return true;
} }
public static boolean publishToDASFlowRate(String owner, String deviceId, float flowRate) { public static boolean publishToDASFlowRate(String deviceId, float flowRate) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true); String owner = ctx.getUsername();
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null); DeviceAnalyticsService.class, null);
Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payload[] = {flowRate}; Object payload[] = {flowRate};
try { try {
deviceAnalyticsService.publishEvent(FLOWRATE_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payload); deviceAnalyticsService.publishEvent(FLOWRATE_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payload);
} catch (DataPublisherConfigurationException e) { } catch (DataPublisherConfigurationException e) {

@ -0,0 +1,66 @@
<?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.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name></name>
<path>/device-mgt/devices/currentsensor/register</path>
<url>/controller/register/{owner}/{deviceId}/{ip}/{port}</url>
<method>POST</method>
<scope>currentsensor_device</scope>
</Permission>
<Permission>
<name></name>
<path>/device-mgt/devices/currentsensor/read-current</path>
<url>/controller/read-current</url>
<method>GET</method>
<scope>currentsensor_user</scope>
</Permission>
<Permission>
<name></name>
<path>/device-mgt/devices/currentsensor/read-power</path>
<url>/controller/read-power</url>
<method>GET</method>
<scope>currentsensor_user</scope>
</Permission>
<Permission>
<name></name>
<path>/device-mgt/devices/currentsensor/read-flowrate</path>
<url>/controller/read-flowrate</url>
<method>GET</method>
<scope>currentsensor_user</scope>
</Permission>
<Permission>
<name></name>
<path>/device-mgt/devices/currentsensor/push-data</path>
<url>/controller/push-data</url>
<method>POST</method>
<scope>currentsensor_device</scope>
</Permission>
</PermissionConfiguration>

@ -21,9 +21,12 @@ package org.homeautomation.currentsensor.manager.api;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
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.currentsensor.manager.api.util.APIUtil;
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants; import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType; import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil; import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
@ -50,205 +53,176 @@ import java.util.UUID;
@DeviceType(value = "currentsensor") @DeviceType(value = "currentsensor")
public class CurrentSensorManagerService { public class CurrentSensorManagerService {
private static Log log = LogFactory.getLog(CurrentSensorManagerService.class); private static Log log = LogFactory.getLog(CurrentSensorManagerService.class);
//TODO; replace this tenant domain @Context //injected response proxy supporting multiple thread
private final String SUPER_TENANT = "carbon.super"; private HttpServletResponse response;
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response; @Path("manager/device")
@PUT
@Path("manager/device/register") public boolean register(@QueryParam("name") String name) {
@PUT String deviceId = shortUUID();
public boolean register(@QueryParam("deviceId") String deviceId, DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
@QueryParam("name") String name, @QueryParam("owner") String owner) { deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); response.setStatus(Response.Status.CONFLICT.getStatusCode());
deviceIdentifier.setId(deviceId); return false;
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); }
try { Device device = new Device();
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { device.setDeviceIdentifier(deviceId);
response.setStatus(Response.Status.CONFLICT.getStatusCode()); EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
return false; enrolmentInfo.setDateOfEnrolment(new Date().getTime());
} enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
Device device = new Device(); device.setName(name);
device.setDeviceIdentifier(deviceId); device.setType(CurrentSensorConstants.DEVICE_TYPE);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
enrolmentInfo.setDateOfEnrolment(new Date().getTime()); device.setEnrolmentInfo(enrolmentInfo);
enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); if (added) {
device.setName(name); response.setStatus(Response.Status.OK.getStatusCode());
device.setType(CurrentSensorConstants.DEVICE_TYPE); } else {
enrolmentInfo.setOwner(owner); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
device.setEnrolmentInfo(enrolmentInfo); }
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); return added;
if (added) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} else { return false;
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); } finally {
} PrivilegedCarbonContext.endTenantFlow();
}
return added; }
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); @Path("manager/device/remove/{device_id}")
return false; @DELETE
} finally { public void removeDevice(@PathParam("device_id") String deviceId,
deviceManagement.endTenantFlow(); @Context HttpServletResponse response) {
} DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
} deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
@Path("manager/device/remove/{device_id}") try {
@DELETE boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
public void removeDevice(@PathParam("device_id") String deviceId, deviceIdentifier);
@Context HttpServletResponse response) { if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); } else {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
deviceIdentifier.setId(deviceId); }
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); } catch (DeviceManagementException e) {
try { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( } finally {
deviceIdentifier); PrivilegedCarbonContext.endTenantFlow();
if (removed) { }
response.setStatus(Response.Status.OK.getStatusCode()); }
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); @Path("manager/device/update/{device_id}")
} @POST
} catch (DeviceManagementException e) { public boolean updateDevice(@PathParam("device_id") String deviceId,
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); @QueryParam("name") String name,
} finally { @Context HttpServletResponse response) {
deviceManagement.endTenantFlow(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
} deviceIdentifier.setId(deviceId);
} deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
try {
@Path("manager/device/update/{device_id}") Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
@POST device.setDeviceIdentifier(deviceId);
public boolean updateDevice(@PathParam("device_id") String deviceId, device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
@QueryParam("name") String name, device.setName(name);
@Context HttpServletResponse response) { device.setType(CurrentSensorConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
if (updated) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); response.setStatus(Response.Status.OK.getStatusCode());
deviceIdentifier.setId(deviceId); } else {
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
try { }
Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); return updated;
device.setDeviceIdentifier(deviceId);
} catch (DeviceManagementException e) {
// device.setDeviceTypeId(deviceTypeId); log.error(e.getErrorMessage());
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); return false;
} finally {
device.setName(name); PrivilegedCarbonContext.endTenantFlow();
device.setType(CurrentSensorConstants.DEVICE_TYPE); }
}
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device);
@Path("manager/device/{device_id}")
if (updated) { @GET
response.setStatus(Response.Status.OK.getStatusCode()); @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
} else { public Device getDevice(@PathParam("device_id") String deviceId) {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
} deviceIdentifier.setId(deviceId);
return updated; deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
} catch (DeviceManagementException e) { try {
log.error(e.getErrorMessage()); return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return false; } catch (DeviceManagementException ex) {
} finally { log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
deviceManagement.endTenantFlow(); return null;
} } finally {
} PrivilegedCarbonContext.endTenantFlow();
}
@Path("manager/device/{device_id}") }
@GET
@Consumes(MediaType.APPLICATION_JSON) @Path("manager/device/{sketch_type}/download")
@Produces(MediaType.APPLICATION_JSON) @GET
public Device getDevice(@PathParam("device_id") String deviceId) { @Produces(MediaType.APPLICATION_JSON)
public Response downloadSketch(@QueryParam("owner") String owner,
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); @QueryParam("deviceName") String deviceName,
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); @PathParam("sketch_type") String sketchType) {
deviceIdentifier.setId(deviceId); try {
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE); ZipArchive zipFile = createDownloadFile(owner, deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
try { response.type("application/zip");
return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
} catch (DeviceManagementException ex) { return response.build();
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex); } catch (IllegalArgumentException ex) {
return null; return Response.status(400).entity(ex.getMessage()).build();//bad request
} finally { } catch (DeviceManagementException ex) {
deviceManagement.endTenantFlow(); return Response.status(500).entity(ex.getMessage()).build();
} } catch (AccessTokenException ex) {
} return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
@Path("manager/device/{sketch_type}/download") return Response.status(500).entity(ex.getMessage()).build();
@GET } catch (IOException ex) {
@Produces(MediaType.APPLICATION_JSON) return Response.status(500).entity(ex.getMessage()).build();
public Response downloadSketch(@QueryParam("owner") String owner, }
@QueryParam("deviceName") String deviceName, }
@PathParam("sketch_type") String
sketchType) { private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
throws DeviceManagementException, AccessTokenException, DeviceControllerException {
try { if (owner == null) {
ZipArchive zipFile = createDownloadFile(owner, deviceName, sketchType); throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); }
response.type("application/zip"); String deviceId = shortUUID();
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); KeyGenerationUtil.createApplicationKeys("currentsensor");
return response.build(); TokenClient accessTokenClient = new TokenClient(CurrentSensorConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
} catch (IllegalArgumentException ex) { //create token
return Response.status(400).entity(ex.getMessage()).build();//bad request String accessToken = accessTokenInfo.getAccess_token();
} catch (DeviceManagementException ex) { String refreshToken = accessTokenInfo.getRefresh_token();
return Response.status(500).entity(ex.getMessage()).build(); //adding registering data
} catch (AccessTokenException ex) { boolean status;
return Response.status(500).entity(ex.getMessage()).build(); //Register the device with CDMF
} catch (DeviceControllerException ex) { status = register(deviceId, deviceName, owner);
return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) { if (!status) {
return Response.status(500).entity(ex.getMessage()).build(); String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
} throw new DeviceManagementException(msg);
} }
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) ZipUtil ziputil = new ZipUtil();
throws DeviceManagementException, AccessTokenException, DeviceControllerException { ZipArchive zipFile = ziputil.createZipFile(owner, SUPER_TENANT, sketchType, deviceId, deviceName, accessToken,
if (owner == null) { refreshToken);
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!"); zipFile.setDeviceId(deviceId);
} return zipFile;
}
//create new device id
String deviceId = shortUUID(); private static String shortUUID() {
UUID uuid = UUID.randomUUID();
KeyGenerationUtil.createApplicationKeys("currentsensor"); long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
TokenClient accessTokenClient = new TokenClient(CurrentSensorConstants.DEVICE_TYPE); }
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
//adding registering data
boolean status;
//Register the device with CDMF
status = register(deviceId, deviceName, owner);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, SUPER_TENANT, sketchType, deviceId, deviceName, accessToken,
refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
} }

@ -0,0 +1,36 @@
package org.homeautomation.currentsensor.manager.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
/**
* This class provides utility functions used by REST-API.
*/
public class APIUtil {
private static Log log = LogFactory.getLog(APIUtil.class);
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
if (username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@"));
}
return username;
}
public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
}

@ -0,0 +1,66 @@
<?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.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/manager/device/{device_id}</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Add device</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/manager/device/{device_id}</url>
<method>DELETE</method>
<scope></scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device/{sketch_type}/download</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/manager/device/{device_id}</url>
<method>POST</method>
<scope></scope>
</Permission>
</PermissionConfiguration>

@ -27,4 +27,5 @@ public class CurrentSensorConstants {
public final static String SENSOR_POWER = "power"; public final static String SENSOR_POWER = "power";
public final static String SENSOR_FLOWRATE = "flowrate"; public final static String SENSOR_FLOWRATE = "flowrate";
public static final String DATA_SOURCE_NAME = "jdbc/currentsensorDM_DB"; public static final String DATA_SOURCE_NAME = "jdbc/currentsensorDM_DB";
} }

@ -18,7 +18,6 @@
package org.homeautomation.currentsensor.plugin.impl; package org.homeautomation.currentsensor.plugin.impl;
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.currentsensor.plugin.impl.dao.CurrentSensorDAO; import org.homeautomation.currentsensor.plugin.impl.dao.CurrentSensorDAO;
@ -34,7 +33,6 @@ import org.wso2.carbon.device.mgt.iot.util.iotdevice.util.IotDeviceManagementUti
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* This represents the Current Sensor implementation of DeviceManagerService. * This represents the Current Sensor implementation of DeviceManagerService.
*/ */
@ -43,8 +41,6 @@ public class CurrentSensorManager implements DeviceManager {
private static final IotDeviceManagementDAOFactoryInterface iotDeviceManagementDAOFactory = new CurrentSensorDAO(); private static final IotDeviceManagementDAOFactoryInterface iotDeviceManagementDAOFactory = new CurrentSensorDAO();
private static final Log log = LogFactory.getLog(CurrentSensorManager.class); private static final Log log = LogFactory.getLog(CurrentSensorManager.class);
@Override @Override
public FeatureManager getFeatureManager() { public FeatureManager getFeatureManager() {
return null; return null;
@ -72,8 +68,7 @@ public class CurrentSensorManager implements DeviceManager {
log.debug("Enrolling a new Current Sensor device : " + device.getDeviceIdentifier()); log.debug("Enrolling a new Current Sensor device : " + device.getDeviceIdentifier());
} }
CurrentSensorDAO.beginTransaction(); CurrentSensorDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice( status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice(iotDevice);
iotDevice);
CurrentSensorDAO.commitTransaction(); CurrentSensorDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) { } catch (IotDeviceManagementDAOException e) {
try { try {
@ -98,8 +93,7 @@ public class CurrentSensorManager implements DeviceManager {
log.debug("Modifying the Current Sensor device enrollment data"); log.debug("Modifying the Current Sensor device enrollment data");
} }
CurrentSensorDAO.beginTransaction(); CurrentSensorDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO() status = iotDeviceManagementDAOFactory.getIotDeviceDAO().updateIotDevice(iotDevice);
.updateIotDevice(iotDevice);
CurrentSensorDAO.commitTransaction(); CurrentSensorDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) { } catch (IotDeviceManagementDAOException e) {
try { try {
@ -109,7 +103,7 @@ public class CurrentSensorManager implements DeviceManager {
log.warn(msg, iotDAOEx); log.warn(msg, iotDAOEx);
} }
String msg = "Error while updating the enrollment of the Current Sensor device : " + String msg = "Error while updating the enrollment of the Current Sensor device : " +
device.getDeviceIdentifier(); device.getDeviceIdentifier();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} }
@ -124,8 +118,7 @@ public class CurrentSensorManager implements DeviceManager {
log.debug("Dis-enrolling Current Sensor device : " + deviceId); log.debug("Dis-enrolling Current Sensor device : " + deviceId);
} }
CurrentSensorDAO.beginTransaction(); CurrentSensorDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO() status = iotDeviceManagementDAOFactory.getIotDeviceDAO().deleteIotDevice(deviceId.getId());
.deleteIotDevice(deviceId.getId());
CurrentSensorDAO.commitTransaction(); CurrentSensorDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) { } catch (IotDeviceManagementDAOException e) {
try { try {
@ -148,15 +141,12 @@ public class CurrentSensorManager implements DeviceManager {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Current Sensor device : " + deviceId.getId()); log.debug("Checking the enrollment of Current Sensor device : " + deviceId.getId());
} }
IotDevice iotDevice = IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO().getIotDevice(deviceId.getId());
iotDeviceManagementDAOFactory.getIotDeviceDAO().getIotDevice(
deviceId.getId());
if (iotDevice != null) { if (iotDevice != null) {
isEnrolled = true; isEnrolled = true;
} }
} catch (IotDeviceManagementDAOException e) { } catch (IotDeviceManagementDAOException e) {
String msg = "Error while checking the enrollment status of Current Sensor device : " + String msg = "Error while checking the enrollment status of Current Sensor device : " + deviceId.getId();
deviceId.getId();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} }
@ -193,8 +183,7 @@ public class CurrentSensorManager implements DeviceManager {
} }
@Override @Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) throws DeviceManagementException {
throws DeviceManagementException {
return true; return true;
} }
@ -203,8 +192,8 @@ public class CurrentSensorManager implements DeviceManager {
} }
@Override @Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrolmentInfo.Status status)
EnrolmentInfo.Status status) throws DeviceManagementException { throws DeviceManagementException {
return false; return false;
} }
@ -233,8 +222,7 @@ public class CurrentSensorManager implements DeviceManager {
"updating the details of Current Sensor device : " + deviceIdentifier); "updating the details of Current Sensor device : " + deviceIdentifier);
} }
CurrentSensorDAO.beginTransaction(); CurrentSensorDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO() status = iotDeviceManagementDAOFactory.getIotDeviceDAO().updateIotDevice(iotDevice);
.updateIotDevice(iotDevice);
CurrentSensorDAO.commitTransaction(); CurrentSensorDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) { } catch (IotDeviceManagementDAOException e) {
try { try {
@ -243,8 +231,7 @@ public class CurrentSensorManager implements DeviceManager {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString(); String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx); log.warn(msg, iotDAOEx);
} }
String msg = String msg = "Error while updating the Current Sensor device : " + deviceIdentifier;
"Error while updating the Current Sensor device : " + deviceIdentifier;
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} }
@ -258,8 +245,7 @@ public class CurrentSensorManager implements DeviceManager {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Current Sensor devices"); log.debug("Fetching the details of all Current Sensor devices");
} }
List<IotDevice> iotDevices = List<IotDevice> iotDevices = iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices();
iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices();
if (iotDevices != null) { if (iotDevices != null) {
devices = new ArrayList<Device>(); devices = new ArrayList<Device>();
for (IotDevice iotDevice : iotDevices) { for (IotDevice iotDevice : iotDevices) {
@ -274,4 +260,4 @@ public class CurrentSensorManager implements DeviceManager {
return devices; return devices;
} }
} }

@ -30,79 +30,84 @@ import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List; import java.util.List;
public class CurrentSensorManagerService implements DeviceManagementService{ public class CurrentSensorManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
@Override
public String getType() {
return CurrentSensorConstants.DEVICE_TYPE;
}
@Override private DeviceManager deviceManager;
public String getProviderTenantDomain() {
return "carbon.super";
}
@Override @Override
public boolean isSharedWithAllTenants() { public String getType() {
return true; return CurrentSensorConstants.DEVICE_TYPE;
} }
@Override @Override
public String[] getSharedTenantsDomain() { public String getProviderTenantDomain() {
return new String[0]; return "carbon.super";
} }
@Override @Override
public void init() throws DeviceManagementException { public boolean isSharedWithAllTenants() {
deviceManager= new CurrentSensorManager(); return true;
} }
@Override @Override
public DeviceManager getDeviceManager() { public String[] getSharedTenantsDomain() {
return deviceManager; return new String[0];
} }
@Override @Override
public ApplicationManager getApplicationManager() { public void init() throws DeviceManagementException {
return null; deviceManager = new CurrentSensorManager();
} }
@Override @Override
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> list) throws DeviceManagementException { public DeviceManager getDeviceManager() {
return deviceManager;
}
} @Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override @Override
public Application[] getApplications(String domain, int pageNumber, int size) public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> list)
throws ApplicationManagementException { throws DeviceManagementException {
return new Application[0]; }
}
@Override @Override
public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, public Application[] getApplications(String domain, int pageNumber, int size)
String status) throws ApplicationManagementException { throws ApplicationManagementException {
return new Application[0];
}
} @Override
public void updateApplicationStatus(DeviceIdentifier deviceId, Application application,
String status) throws ApplicationManagementException {
@Override }
public String getApplicationStatus(DeviceIdentifier deviceId, Application application)
throws ApplicationManagementException {
return null;
}
@Override @Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> list) throws ApplicationManagementException { public String getApplicationStatus(DeviceIdentifier deviceId, Application application)
throws ApplicationManagementException {
return null;
}
} @Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> list)
throws ApplicationManagementException {
@Override }
public void installApplicationForUsers(Operation operation, List<String> list) throws ApplicationManagementException {
} @Override
public void installApplicationForUsers(Operation operation, List<String> list)
throws ApplicationManagementException {
@Override }
public void installApplicationForUserRoles(Operation operation, List<String> list) throws ApplicationManagementException {
} @Override
public void installApplicationForUserRoles(Operation operation, List<String> list)
throws ApplicationManagementException {
}
} }

@ -34,8 +34,7 @@ import javax.sql.DataSource;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
public class CurrentSensorDAO extends IotDeviceManagementDAOFactory public class CurrentSensorDAO extends IotDeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface {
implements IotDeviceManagementDAOFactoryInterface {
private static final Log log = LogFactory.getLog(CurrentSensorDAO.class); private static final Log log = LogFactory.getLog(CurrentSensorDAO.class);
static DataSource dataSource; // package local variable static DataSource dataSource; // package local variable
@ -50,13 +49,12 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory
return new CurrentSensorDeviceDAOImpl(); return new CurrentSensorDeviceDAOImpl();
} }
public static void initCurrentSensorDAO(){ public static void initCurrentSensorDAO() {
try { try {
Context ctx = new InitialContext(); Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(CurrentSensorConstants.DATA_SOURCE_NAME); dataSource = (DataSource) ctx.lookup(CurrentSensorConstants.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: " + CurrentSensorConstants.DATA_SOURCE_NAME);
CurrentSensorConstants.DATA_SOURCE_NAME);
} }
} }
@ -75,8 +73,7 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory
try { try {
currentConnection.set(dataSource.getConnection()); currentConnection.set(dataSource.getConnection());
} catch (SQLException e) { } catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e);
e);
} }
} }
return currentConnection.get(); return currentConnection.get();
@ -90,7 +87,7 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory
} 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) {
@ -101,15 +98,14 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory
} }
public static void closeConnection() throws IotDeviceManagementDAOException { public static void closeConnection() throws IotDeviceManagementDAOException {
Connection con = currentConnection.get();
Connection con = currentConnection.get(); if (con != null) {
if(con != null){ try {
try { con.close();
con.close(); } catch (SQLException e) {
} catch (SQLException e) { log.error("Error occurred while close the connection");
log.error("Error occurred while close the connection"); }
} }
}
currentConnection.remove(); currentConnection.remove();
} }
@ -121,7 +117,7 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory
} 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) {
@ -130,4 +126,5 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory
closeConnection(); closeConnection();
} }
} }
}
}

@ -41,12 +41,10 @@ import java.util.Map;
*/ */
public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO { public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
private static final Log log = LogFactory.getLog(CurrentSensorDeviceDAOImpl.class); private static final Log log = LogFactory.getLog(CurrentSensorDeviceDAOImpl.class);
@Override @Override
public IotDevice getIotDevice(String iotDeviceId) public IotDevice getIotDevice(String iotDeviceId) throws IotDeviceManagementDAOException {
throws IotDeviceManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
IotDevice iotDevice = null; IotDevice iotDevice = null;
@ -54,24 +52,20 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
try { try {
conn = CurrentSensorDAO.getConnection(); conn = CurrentSensorDAO.getConnection();
String selectDBQuery = String selectDBQuery =
"SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME" + "SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME FROM CURRENT_SENSOR_DEVICE WHERE " +
" FROM CURRENT_SENSOR_DEVICE WHERE CURRENT_SENSOR_DEVICE_ID = ?"; "CURRENT_SENSOR_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery); stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, iotDeviceId); stmt.setString(1, iotDeviceId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
iotDevice = new IotDevice(); iotDevice = new IotDevice();
iotDevice.setIotDeviceName(resultSet.getString( iotDevice.setIotDeviceName(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME));
CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME));
Map<String, String> propertyMap = new HashMap<String, String>(); Map<String, String> propertyMap = new HashMap<String, String>();
iotDevice.setDeviceProperties(propertyMap); iotDevice.setDeviceProperties(propertyMap);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Current Sensor device " + iotDeviceId + " data has been fetched from " + log.debug("Current Sensor device " + iotDeviceId + " data has been fetched from " +
"Current Sensor database."); "Current Sensor database.");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -82,7 +76,6 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet);
CurrentSensorDAO.closeConnection(); CurrentSensorDAO.closeConnection();
} }
return iotDevice; return iotDevice;
} }
@ -96,26 +89,23 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
conn = CurrentSensorDAO.getConnection(); conn = CurrentSensorDAO.getConnection();
String createDBQuery = String createDBQuery =
"INSERT INTO CURRENT_SENSOR_DEVICE(CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)"; "INSERT INTO CURRENT_SENSOR_DEVICE(CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery); stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, iotDevice.getIotDeviceId()); stmt.setString(1, iotDevice.getIotDeviceId());
stmt.setString(2, iotDevice.getIotDeviceName()); stmt.setString(2, iotDevice.getIotDeviceName());
if (iotDevice.getDeviceProperties() == null) { if (iotDevice.getDeviceProperties() == null) {
iotDevice.setDeviceProperties(new HashMap<String, String>()); iotDevice.setDeviceProperties(new HashMap<String, String>());
} }
int rows = stmt.executeUpdate(); int rows = stmt.executeUpdate();
if (rows > 0) { if (rows > 0) {
status = true; status = true;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Current Sensor device " + iotDevice.getIotDeviceId() + " data has been" + log.debug("Current Sensor device " + iotDevice.getIotDeviceId() + " data has been" +
" added to the Current Sensor database."); " added to the Current Sensor database.");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while adding the Current Sensor device '" + String msg = "Error occurred while adding the Current Sensor device '" +
iotDevice.getIotDeviceId() + "' to the Current Sensor db."; iotDevice.getIotDeviceId() + "' to the Current Sensor db.";
log.error(msg, e); log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e); throw new IotDeviceManagementDAOException(msg, e);
} finally { } finally {
@ -125,8 +115,7 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
} }
@Override @Override
public boolean updateIotDevice(IotDevice iotDevice) public boolean updateIotDevice(IotDevice iotDevice) throws IotDeviceManagementDAOException {
throws IotDeviceManagementDAOException {
boolean status = false; boolean status = false;
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -134,26 +123,23 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
conn = CurrentSensorDAO.getConnection(); conn = CurrentSensorDAO.getConnection();
String updateDBQuery = String updateDBQuery =
"UPDATE CURRENT_SENSOR_DEVICE SET DEVICE_NAME = ? WHERE CURRENT_SENSOR_DEVICE_ID = ?"; "UPDATE CURRENT_SENSOR_DEVICE SET DEVICE_NAME = ? WHERE CURRENT_SENSOR_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery); stmt = conn.prepareStatement(updateDBQuery);
if (iotDevice.getDeviceProperties() == null) { if (iotDevice.getDeviceProperties() == null) {
iotDevice.setDeviceProperties(new HashMap<String, String>()); iotDevice.setDeviceProperties(new HashMap<String, String>());
} }
stmt.setString(1, iotDevice.getIotDeviceName()); stmt.setString(1, iotDevice.getIotDeviceName());
stmt.setString(2, iotDevice.getIotDeviceId()); stmt.setString(2, iotDevice.getIotDeviceId());
int rows = stmt.executeUpdate(); int rows = stmt.executeUpdate();
if (rows > 0) { if (rows > 0) {
status = true; status = true;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Current Sensor device " + iotDevice.getIotDeviceId() + " data has been" + log.debug("Current Sensor device " + iotDevice.getIotDeviceId() + " data has been" +
" modified."); " modified.");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while modifying the Current Sensor device '" + String msg = "Error occurred while modifying the Current Sensor device '" +
iotDevice.getIotDeviceId() + "' data."; iotDevice.getIotDeviceId() + "' data.";
log.error(msg, e); log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e); throw new IotDeviceManagementDAOException(msg, e);
} finally { } finally {
@ -163,8 +149,7 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
} }
@Override @Override
public boolean deleteIotDevice(String iotDeviceId) public boolean deleteIotDevice(String iotDeviceId) throws IotDeviceManagementDAOException {
throws IotDeviceManagementDAOException {
boolean status = false; boolean status = false;
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -179,7 +164,7 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
status = true; status = true;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Current Sensor device " + iotDeviceId + " data has deleted" + log.debug("Current Sensor device " + iotDeviceId + " data has deleted" +
" from the Current Sensor database."); " from the Current Sensor database.");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -193,9 +178,7 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
} }
@Override @Override
public List<IotDevice> getAllIotDevices() public List<IotDevice> getAllIotDevices() throws IotDeviceManagementDAOException {
throws IotDeviceManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
@ -205,17 +188,14 @@ public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
try { try {
conn = CurrentSensorDAO.getConnection(); conn = CurrentSensorDAO.getConnection();
String selectDBQuery = String selectDBQuery =
"SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME " + "SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME FROM CURRENT_SENSOR_DEVICE";
"FROM CURRENT_SENSOR_DEVICE";
stmt = conn.prepareStatement(selectDBQuery); stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
iotDevice = new IotDevice(); iotDevice = new IotDevice();
iotDevice.setIotDeviceId(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_ID)); iotDevice.setIotDeviceId(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_ID));
iotDevice.setIotDeviceName(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME)); iotDevice.setIotDeviceName(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME));
Map<String, String> propertyMap = new HashMap<String, String>(); Map<String, String> propertyMap = new HashMap<String, String>();
iotDevice.setDeviceProperties(propertyMap); iotDevice.setDeviceProperties(propertyMap);
iotDevices.add(iotDevice); iotDevices.add(iotDevice);
} }

@ -31,15 +31,11 @@ public class CurrentSensorUtils {
private static Log log = LogFactory.getLog(CurrentSensorUtils.class); private static Log log = LogFactory.getLog(CurrentSensorUtils.class);
public static String getDeviceProperty(Map<String, String> deviceProperties, String property) { public static String getDeviceProperty(Map<String, String> deviceProperties, String property) {
String deviceProperty = deviceProperties.get(property); String deviceProperty = deviceProperties.get(property);
if (deviceProperty == null) { if (deviceProperty == null) {
return ""; return "";
} }
return deviceProperty; return deviceProperty;
} }
} }

@ -40,11 +40,7 @@ import org.wso2.carbon.device.mgt.iot.service.DeviceTypeService;
public class ServiceComponent { public class ServiceComponent {
private ServiceRegistration currentSensorServiceRegRef; private ServiceRegistration currentSensorServiceRegRef;
private static final Log log = LogFactory.getLog(ServiceComponent.class); private static final Log log = LogFactory.getLog(ServiceComponent.class);
protected void activate(ComponentContext ctx) { protected void activate(ComponentContext ctx) {
@ -53,15 +49,8 @@ public class ServiceComponent {
} }
try { try {
BundleContext bundleContext = ctx.getBundleContext(); BundleContext bundleContext = ctx.getBundleContext();
currentSensorServiceRegRef = bundleContext.registerService(DeviceManagementService.class.getName(),
new CurrentSensorManagerService(), null);
currentSensorServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(), new
CurrentSensorManagerService(),
null);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Current Sensor Management Service Component has been successfully activated"); log.debug("Current Sensor Management Service Component has been successfully activated");
} }
@ -70,7 +59,6 @@ public class ServiceComponent {
} }
} }
protected void deactivate(ComponentContext ctx) { protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("De-activating Current Sensor Management Service Component"); log.debug("De-activating Current Sensor Management Service Component");
@ -79,7 +67,6 @@ public class ServiceComponent {
if (currentSensorServiceRegRef != null) { if (currentSensorServiceRegRef != null) {
currentSensorServiceRegRef.unregister(); currentSensorServiceRegRef.unregister();
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug( log.debug(
"Current Sensor Management Service Component has been successfully de-activated"); "Current Sensor Management Service Component has been successfully de-activated");
@ -89,20 +76,16 @@ public class ServiceComponent {
} }
} }
protected void setDeviceTypeService(DeviceTypeService deviceTypeService) { protected void setDeviceTypeService(DeviceTypeService deviceTypeService) {
/* This is to avoid this component getting initialized before the /* This is to avoid this component getting initialized before the
common registered */ common registered */
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Data source service set to mobile service component"); log.debug("Data source service set to mobile service component");
} }
} }
protected void unsetDeviceTypeService(DeviceTypeService deviceTypeService) { protected void unsetDeviceTypeService(DeviceTypeService deviceTypeService) {
//do nothing //do nothing
} }
}
}

@ -1,5 +1,5 @@
<div class="col-lg-12 margin-top-double"> <div class="col-lg-12 margin-top-double">
<h1 class="grey ">Smart Meeter</h1> <h1 class="grey ">Smart Meter</h1>
<hr> <hr>
</div> </div>

@ -16,7 +16,7 @@
} }
}, },
{ {
"name": "Power x100", "name": "Power",
"table": "DEVICE_POWER_SUMMARY", "table": "DEVICE_POWER_SUMMARY",
"ui_unit": { "ui_unit": {
"name": "cdmf.unit.analytics.line-chart", "name": "cdmf.unit.analytics.line-chart",
@ -27,13 +27,13 @@
} }
}, },
{ {
"name": "Flow Rate x100", "name": "Flow Rate",
"table": "DEVICE_FLOWRATE_SUMMARY", "table": "DEVICE_FLOWRATE_SUMMARY",
"ui_unit": { "ui_unit": {
"name": "cdmf.unit.analytics.line-chart", "name": "cdmf.unit.analytics.line-chart",
"data":[ "data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}}, {"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"FlowRate", "label":"flowrate", "ui-mapping":"y-axis"}} {"column": {"name":"Flow Rate", "label":"flowrate", "ui-mapping":"y-axis"}}
] ]
} }
} }

@ -105,11 +105,15 @@ public class ControllerService {
@POST @POST
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public Response registerDevice(final DeviceJSON agentInfo) { public Response registerDevice(final DeviceJSON agentInfo) {
if ((agentInfo.deviceId != null) && (agentInfo.owner != null)) { try {
return Response.status(Response.Status.OK).entity("Device has been registered successfully").build(); if ((agentInfo.deviceId != null) && (agentInfo.owner != null)) {
return Response.status(Response.Status.OK).entity("Device has been registered successfully").build();
}
return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Message body not " +
"well-formed and still invalid").build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
} }
return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Message body not " +
"well-formed and still invalid").build();
} }
/** /**
@ -130,14 +134,17 @@ public class ControllerService {
@HeaderParam("protocol") String protocol, @HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
SensorRecord sensorRecord = null; SensorRecord sensorRecord = null;
if (isPermitted(owner, deviceId, response)) { try {
try { if (isPermitted(owner, deviceId, response)) {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
DeviceTypeConstants.SENSOR_TEMPERATURE); DeviceTypeConstants.SENSOR_TEMPERATURE);
} catch (DeviceControllerException e) { response.setStatus(Response.Status.OK.getStatusCode());
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} }
response.setStatus(Response.Status.OK.getStatusCode()); } catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
} }
return sensorRecord; return sensorRecord;
} }
@ -160,14 +167,16 @@ public class ControllerService {
@HeaderParam("protocol") String protocol, @HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
SensorRecord sensorRecord = null; SensorRecord sensorRecord = null;
if (isPermitted(owner, deviceId, response)) { try {
try { if (isPermitted(owner, deviceId, response)) {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
DeviceTypeConstants.SENSOR_HUMIDITY); DeviceTypeConstants.SENSOR_HUMIDITY);
} catch (DeviceControllerException e) { response.setStatus(Response.Status.OK.getStatusCode());
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} }
response.setStatus(Response.Status.OK.getStatusCode()); } catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
} }
return sensorRecord; return sensorRecord;
} }
@ -198,6 +207,8 @@ public class ControllerService {
} catch (DeviceTypeException e) { } catch (DeviceTypeException e) {
log.error(e); log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
} }
} }
} }
@ -214,6 +225,8 @@ public class ControllerService {
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
} }
return false; return false;
} }

Loading…
Cancel
Save