Add permissions.xml to connected-cup device type.

application-manager-new
NuwanSameera 9 years ago
parent a52c1af457
commit ee250d25c5

@ -95,34 +95,32 @@
<script src="js/libs/htmlpreview.min.js"></script>
<script>HTMLPreview.replaceAssets();</script>
<script>
$("#order-cup").click(function() {
$("#order-cup").click(function () {
var deviceId = '<%=request.getSession().getAttribute("deviceId")%>';
var deviceOwner = '<%=request.getSession().getAttribute("deviceOwner")%>';
var token = '<%=request.getSession().getAttribute("token")%>';
var url = "/connectedcup/controller/ordercoffee?deviceId=" + deviceId +"&deviceOwner=" +
deviceOwner;
var url = "/connectedcup/controller/ordercoffee?deviceId=" + deviceId + "&deviceOwner=" + deviceOwner;
$.ajax({
type: 'POST',
url: url,
headers: {
"Authorization" : "Bearer " + token
"Authorization": "Bearer " + token
}
});
});
function sendData()
{
function sendData() {
var deviceId = '<%=request.getSession().getAttribute("deviceId")%>';
var deviceOwner = '<%=request.getSession().getAttribute("deviceOwner")%>';
var tempPayload = "temperature:" + temperature;
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);
$.post( "/connected-cup-agent/push_level?deviceId=" + deviceId +"&deviceOwner=" + deviceOwner +
$.post("/connected-cup-agent/push_level?deviceId=" + deviceId + "&deviceOwner=" + deviceOwner +
"&payload=" + levelPayload);
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.device.DeviceType;
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.DeviceManagementException;
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 java.util.Calendar;
@API( name="connectedcup", version="1.0.0", context="/connectedcup")
@DeviceType( value = "connectedcup")
@API(name = "connectedcup", version = "1.0.0", context = "/connectedcup")
@DeviceType(value = "connectedcup")
public class ConnectedCupControllerService {
private static Log log = LogFactory.getLog(ConnectedCupControllerService.class);
private static final String SUPER_TENANT = "carbon.super";
private static ConnectedCupMQTTConnector connectedCupMQTTConnector;
public ConnectedCupMQTTConnector connectedCupMQTTConnector() {
return ConnectedCupControllerService.connectedCupMQTTConnector;
}
public void setconnectedCupMQTTConnector(
final ConnectedCupMQTTConnector connectedCupMQTTConnector) {
public void setconnectedCupMQTTConnector(final ConnectedCupMQTTConnector connectedCupMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
@ -76,12 +74,10 @@ public class ConnectedCupControllerService {
if (MqttConfig.getInstance().isEnabled()) {
connectedCupMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. " +
"Hence, ConnectedCupMQTTConnector not started.");
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, ConnectedCupMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
@ -105,8 +101,8 @@ public class ConnectedCupControllerService {
@Path("controller/coffeelevel")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Feature( code="coffeelevel", name="Coffee Level", type="monitor",
description="Request Coffee Level from Connected cup")
@Feature(code = "coffeelevel", name = "Coffee Level", type = "monitor",
description = "Request Coffee Level from Connected cup")
public SensorRecord readCoffeeLevel(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@Context HttpServletResponse response) {
@ -117,91 +113,76 @@ public class ConnectedCupControllerService {
deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
if (log.isDebugEnabled()) {
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
}
try {
String mqttResource = ConnectedCupConstants.LEVEL_CONTEXT.replace("/", "");
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ConnectedCupConstants.SENSOR_LEVEL);
} catch ( DeviceControllerException | TransportHandlerException e ) {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, ConnectedCupConstants.SENSOR_LEVEL);
} catch (DeviceControllerException | TransportHandlerException e) {
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());
return sensorRecord;
}
@Path("controller/temperature")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Feature( code="temperature", name="Temperature", type="monitor",
description="Request Temperature reading from Connected cup")
@Feature(code = "temperature", name = "Temperature", type = "monitor",
description = "Request Temperature reading from Connected cup")
public SensorRecord readTemperature(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
DeviceValidator deviceValidator = new DeviceValidator();
try {
if (!deviceValidator.isExist(owner, SUPER_TENANT,
new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
if (log.isDebugEnabled()) {
log.debug("Sending request to read connected cup temperature of device " +
"[" + deviceId + "] via MQTT");
log.debug("Sending request to read connected cup temperature of device [" + deviceId + "] via MQTT");
}
try {
String mqttResource = ConnectedCupConstants.TEMPERATURE_CONTEXT.replace("/", "");
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ConnectedCupConstants.SENSOR_TEMPERATURE);
} catch ( DeviceControllerException | TransportHandlerException e) {
} catch (DeviceControllerException | TransportHandlerException e) {
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());
return sensorRecord;
}
@Path("controller/ordercoffee")
@POST
public void orderCoffee(@QueryParam("deviceId") String deviceId, @QueryParam("deviceOwner") String
deviceOwner, @Context HttpServletResponse response){
public void orderCoffee(@QueryParam("deviceId") String deviceId, @QueryParam("deviceOwner") String deviceOwner,
@Context HttpServletResponse response) {
DeviceValidator deviceValidator = new DeviceValidator();
try {
if (!deviceValidator.isExist(deviceOwner, SUPER_TENANT, new DeviceIdentifier(
deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.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");
}
// return response;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}

@ -26,10 +26,18 @@ import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class DeviceJSON {
@XmlElement(required = true) public String owner;
@XmlElement(required = true) public String deviceId;
@XmlElement(required = true) public String reply;
@XmlElement public Long time;
@XmlElement public String key;
@XmlElement public float value;
@XmlElement(required = true)
public String owner;
@XmlElement(required = true)
public String deviceId;
@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;
public class ConnectedCupException extends Exception {
private static final long serialVersionUID = 118512086957330189L;
public ConnectedCupException(String errorMessage) {
@ -28,4 +29,5 @@ public class ConnectedCupException extends Exception {
public ConnectedCupException(String errorMessage, Throwable throwable) {
super(errorMessage, throwable);
}
}

@ -37,20 +37,18 @@ import java.util.UUID;
@SuppressWarnings("no JAX-WS annotation")
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().
getDeviceManagementServerInfo().getName();
private static String subscribeTopic = "wso2" + File.separator + "+" + File.separator +
ConnectedCupConstants.DEVICE_TYPE + File.separator + "+" + File.separator
+ "connected_publisher";
private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
private ConnectedCupMQTTConnector() {
super(iotServerSubscriber, ConnectedCupConstants.DEVICE_TYPE,
MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic);
super(iotServerSubscriber, ConnectedCupConstants.DEVICE_TYPE, MqttConfig.getInstance().getMqttQueueEndpoint(),
subscribeTopic);
}
@Override
@ -72,14 +70,11 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
if (publishData.length != 4) {
@ -88,92 +83,56 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
log.error(errorMsg);
throw new TransportHandlerException(errorMsg);
}
String deviceOwner = publishData[0];
String deviceId = publishData[1];
String resource = publishData[2];
String state = publishData[3];
MqttMessage pushMessage = new MqttMessage();
String publishTopic =
"wso2" + File.separator + deviceOwner + File.separator +
String publishTopic = "wso2" + File.separator + deviceOwner + File.separator +
ConnectedCupConstants.DEVICE_TYPE + File.separator + deviceId;
try {
String actualMessage = resource + ":" + state;
pushMessage.setPayload(actualMessage.getBytes(StandardCharsets.UTF_8));
pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);
pushMessage.setRetained(false);
publishToQueue(publishTopic, pushMessage);
} catch (Exception e) {
String errorMsg = "Preparing payload failed for device - [" + deviceId + "] of owner - " +
"[" + deviceOwner + "].";
String errorMsg = "Preparing payload failed for device - [" + deviceId + "] of owner-[" + deviceOwner + "].";
log.error(errorMsg);
throw new TransportHandlerException(errorMsg, e);
}
}
@Override
public void processIncomingMessage(MqttMessage mqttMessage, String... strings) throws TransportHandlerException {
String topic = strings[0];
String ownerAndId = topic.replace("wso2" + File.separator, "");
ownerAndId = ownerAndId.replace(File.separator + ConnectedCupConstants.DEVICE_TYPE + File.separator, ":");
ownerAndId = ownerAndId.replace(File.separator + "connected_publisher", "");
String owner = ownerAndId.split(":")[0];
String deviceId = ownerAndId.split(":")[1];
// String actualMessage = mqttMessage.toString();
String[] messageData = mqttMessage.toString().split(":");
Float value = Float.valueOf(messageData[1]);
// if (actualMessage.contains("PUBLISHER")) {
// float temperature = Float.parseFloat(actualMessage.split(":")[2]);
//
// if (!ConnectedCupServiceUtils.publishToDAS(owner, deviceId, messageData[0], value)) {
// log.error("MQTT Subscriber: Publishing data to DAS failed.");
// }
//
// if (log.isDebugEnabled()) {
// log.debug("MQTT Subscriber: Published data to DAS successfully.");
// }
//
// } else if (actualMessage.contains("TEMPERATURE")) {
// String temperatureValue = actualMessage.split(":")[1];
// SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_TEMPERATURE,
// temperatureValue,
// Calendar.getInstance().getTimeInMillis());
// }
//
//
switch(messageData[0]) {
case "temperature": SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_TEMPERATURE,
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,
case "coffeelevel":
SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_LEVEL,
String.valueOf(messageData[1]),
Calendar.getInstance().getTimeInMillis());
break;
}
ConnectedCupServiceUtils.publishToDAS(owner, deviceId, messageData[0], value);
if (log.isDebugEnabled()) {
log.debug("Received MQTT message for OWNER: " + owner + " DEVICE.ID: " + deviceId + " | Command: " +
messageData[0] +" " + messageData[1] );
messageData[0] + " " + messageData[1]);
}
}
@Override
public void disconnect() {
Runnable stopConnection = new Runnable() {
@ -186,7 +145,6 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint
+ " for device-type - " + ConnectedCupConstants.DEVICE_TYPE, e);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
@ -197,18 +155,15 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
}
}
};
Thread terminatorThread = new Thread(stopConnection);
terminatorThread.setDaemon(true);
terminatorThread.start();
}
@Override
public void publishDeviceData() {
// nothing to do
}
@Override
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
// 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.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import javax.ws.rs.HttpMethod;
import java.io.BufferedReader;
import java.io.IOException;
@ -42,10 +43,8 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
public class ConnectedCupServiceUtils {
private static final Log log = LogFactory.getLog(ConnectedCupServiceUtils.class);
//TODO; replace this tenant domain
private static final String SUPER_TENANT = "carbon.super";
private static final Log log = LogFactory.getLog(ConnectedCupServiceUtils.class);
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";
@ -61,23 +60,19 @@ public class ConnectedCupServiceUtils {
if (!fireAndForgot) {
HttpURLConnection httpConnection = getHttpConnection(urlString);
try {
httpConnection.setRequestMethod(HttpMethod.GET);
} catch (ProtocolException e) {
String errorMsg =
"Protocol specific error occurred when trying to set method to GET" +
" for:" + urlString;
"Protocol specific error occurred when trying to set method to GET for:" + urlString;
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
}
responseMsg = readResponseFromGetRequest(httpConnection);
} else {
CloseableHttpAsyncClient httpclient = null;
try {
httpclient = HttpAsyncClients.createDefault();
httpclient.start();
HttpGet request = new HttpGet(urlString);
@ -99,9 +94,7 @@ public class ConnectedCupServiceUtils {
latch.countDown();
}
});
latch.await();
} catch (InterruptedException e) {
if (log.isDebugEnabled()) {
log.debug("Sync Interrupted");
@ -110,7 +103,6 @@ public class ConnectedCupServiceUtils {
try {
if (httpclient != null) {
httpclient.close();
}
} catch (IOException e) {
if (log.isDebugEnabled()) {
@ -119,7 +111,6 @@ public class ConnectedCupServiceUtils {
}
}
}
return responseMsg;
}
@ -129,57 +120,45 @@ public class ConnectedCupServiceUtils {
/* This methods creates and returns a http connection object */
public static HttpURLConnection getHttpConnection(String urlString) throws
DeviceManagementException {
public static HttpURLConnection getHttpConnection(String urlString) throws DeviceManagementException {
URL connectionUrl = null;
HttpURLConnection httpConnection;
try {
connectionUrl = new URL(urlString);
httpConnection = (HttpURLConnection) connectionUrl.openConnection();
} catch (MalformedURLException e) {
String errorMsg =
"Error occured whilst trying to form HTTP-URL from string: " + urlString;
String errorMsg = "Error occured whilst trying to form HTTP-URL from string: " + urlString;
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
} catch (IOException e) {
String errorMsg = "Error occured whilst trying to open a connection to: " +
connectionUrl.toString();
String errorMsg = "Error occured whilst trying to open a connection to: " + connectionUrl.toString();
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
}
return httpConnection;
}
/* This methods reads and returns the response from the connection */
public static String readResponseFromGetRequest(HttpURLConnection httpConnection)
throws DeviceManagementException {
public static String readResponseFromGetRequest(HttpURLConnection httpConnection) throws DeviceManagementException {
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new InputStreamReader(
httpConnection.getInputStream()));
bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
} catch (IOException e) {
String errorMsg =
"There is an issue with connecting the reader to the input stream at: " +
httpConnection.getURL();
"There is an issue with connecting the reader to the input stream at: " + httpConnection.getURL();
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
}
String responseLine;
StringBuilder completeResponse = new StringBuilder();
try {
while ((responseLine = bufferedReader.readLine()) != null) {
completeResponse.append(responseLine);
}
} catch (IOException e) {
String errorMsg =
"Error occured whilst trying read from the connection stream at: " +
httpConnection.getURL();
"Error occured whilst trying read from the connection stream at: " + httpConnection.getURL();
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
}
@ -187,25 +166,24 @@ public class ConnectedCupServiceUtils {
bufferedReader.close();
} catch (IOException e) {
log.error(
"Could not succesfully close the bufferedReader to the connection at: " +
httpConnection.getURL());
"Could not succesfully close the bufferedReader to the connection at: " + httpConnection.getURL());
}
return completeResponse.toString();
}
public static boolean publishToDAS(String owner, String deviceId, String sensor, float values) {
PrivilegedCarbonContext.startTenantFlow();
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.class, null);
Object metdaData[] = {owner, ConnectedCupConstants.DEVICE_TYPE, deviceId,
System.currentTimeMillis()};
Object metdaData[] = {owner, ConnectedCupConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payloadData[] = {values};
try {
switch (sensor){
switch (sensor) {
case "temperature":
deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData);
@ -214,7 +192,6 @@ public class ConnectedCupServiceUtils {
deviceAnalyticsService.publishEvent(COFFEE_LEVEL_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData);
}
} catch (DataPublisherConfigurationException e) {
return false;
} 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.LogFactory;
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.device.DeviceType;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil;
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.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
@ -52,76 +55,62 @@ import java.util.Date;
import java.util.List;
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 {
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
private HttpServletResponse response;
/**
* @param name
* @param owner
* @return
*/
@Path("cup/register")
@Path("manager/device")
@POST
public boolean register(@QueryParam("name") String name, @QueryParam("owner") String owner) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
public boolean register(@QueryParam("name") String name) {
String deviceId = shortUUID();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name);
device.setType(ConnectedCupConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(owner);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
KeyGenerationUtil.createApplicationKeys(ConnectedCupConstants.DEVICE_TYPE);
TokenClient accessTokenClient = new TokenClient(ConnectedCupConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
//create token
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(APIUtil.getAuthenticatedUser(), deviceId);
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
List<Device.Property> properties = new ArrayList<>();
Device.Property accessTokenProperty = new Device.Property();
accessTokenProperty.setName("accessToken");
accessTokenProperty.setValue(accessToken);
Device.Property refreshTokenProperty = new Device.Property();
refreshTokenProperty.setName("refreshToken");
refreshTokenProperty.setValue(refreshToken);
properties.add(accessTokenProperty);
properties.add(refreshTokenProperty);
device.setProperties(properties);
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return added;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
@ -129,108 +118,79 @@ public class ConnectedCupManagerService {
} catch (AccessTokenException e) {
e.printStackTrace();
} finally {
deviceManagement.endTenantFlow();
PrivilegedCarbonContext.endTenantFlow();
}
return true;
}
@Path("/device/remove/{device_id}")
@Path("manager/device/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId,
@Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
deviceManagement.endTenantFlow();
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("/device/update/{device_id}")
@Path("manager/device/{device_id}")
@POST
public boolean updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name,
@Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
Device device = deviceManagement.getDeviceManagementService().getDevice(
deviceIdentifier);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
// device.setDeviceTypeId(deviceTypeId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(ConnectedCupConstants.DEVICE_TYPE);
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(
device);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return updated;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} finally {
deviceManagement.endTenantFlow();
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("/device/{device_id}")
@Path("manager/device/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Device getDevice(@PathParam("device_id") String deviceId) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
Device device = deviceManagement.getDeviceManagementService().getDevice(
deviceIdentifier);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return device;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null;
} finally {
deviceManagement.endTenantFlow();
PrivilegedCarbonContext.endTenantFlow();
}
}
private static String shortUUID() {

@ -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">
<jaxrs:server id="ConnectedCupmanager" address="/connectedcup">
<jaxrs:server id="ConnectedCupmanager" address="/">
<jaxrs:serviceBeans>
<bean id="ConnectedCupManagerService"
class="org.coffeeking.manager.service.ConnectedCupManagerService">

@ -56,11 +56,11 @@ function showPopup() {
deviceType = this.value;
}
});
if (deviceType == 'digitaldisplay'){
if (deviceType == 'digitaldisplay') {
$('.sketchType').remove();
$('input[name="sketchType"][value="digitaldisplay"]').prop('checked', true);
$("label[for='digitaldisplay']").text("Simple Agent");
}else{
} else {
$('.sketchTypes').remove();
}
}
@ -115,7 +115,7 @@ function attachEvents() {
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>');
$('.control-group').removeClass('success').addClass('error');
} else {
@ -137,7 +137,7 @@ function downloadAgent() {
var $inputs = $('#downloadForm :input');
var values = {};
$inputs.each(function() {
$inputs.each(function () {
values[this.name] = $(this).val();
});
@ -145,8 +145,7 @@ function downloadAgent() {
payload.name = $inputs[0].value;
payload.owner = $inputs[1].value;
var connectedCupRegisterURL = "/connectedcup_mgt/connectedcup/cup/register?" +
"name=" + encodeURI(payload.name) + "&owner=" + payload.owner;
var connectedCupRegisterURL = "/connectedcup_mgt/manager/device?name=" + encodeURI(payload.name);
invokerUtil.post(
connectedCupRegisterURL,

@ -134,7 +134,7 @@ public class CurrentSensorControllerService {
@GET
@Consumes(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")
public SensorRecord requestPower(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@ -164,7 +164,7 @@ public class CurrentSensorControllerService {
@GET
@Consumes(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")
public SensorRecord requestFlowRate(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@ -227,11 +227,11 @@ public class CurrentSensorControllerService {
Calendar.getInstance().getTimeInMillis());
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_POWER,
String.valueOf(current * 230 / 100),
String.valueOf(current * 230),
Calendar.getInstance().getTimeInMillis());
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_FLOWRATE,
String.valueOf(flow_rate/100),
String.valueOf(flow_rate),
Calendar.getInstance().getTimeInMillis());
if (!CurrentSensorServiceUtils.publishToDASCurrent(dataMsg.owner, dataMsg.deviceId, current)) {
@ -240,13 +240,13 @@ public class CurrentSensorControllerService {
"] of owner [" + owner + "]");
}
if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.owner, dataMsg.deviceId, current * 230 / 100)) {
if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.owner, dataMsg.deviceId, current * 230)) {
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)) {
if (!CurrentSensorServiceUtils.publishToDASFlowRate(dataMsg.owner, dataMsg.deviceId, flow_rate)) {
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 + "]");

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

@ -16,7 +16,7 @@
}
},
{
"name": "Power x100",
"name": "Power",
"table": "DEVICE_POWER_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
@ -27,13 +27,13 @@
}
},
{
"name": "Flow Rate x100",
"name": "Flow Rate",
"table": "DEVICE_FLOWRATE_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"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
@Consumes(MediaType.APPLICATION_JSON)
public Response registerDevice(final DeviceJSON agentInfo) {
try {
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();
}
}
/**
@ -130,14 +134,17 @@ public class ControllerService {
@HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
if (isPermitted(owner, deviceId, response)) {
try {
if (isPermitted(owner, deviceId, response)) {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
DeviceTypeConstants.SENSOR_TEMPERATURE);
response.setStatus(Response.Status.OK.getStatusCode());
}
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.OK.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return sensorRecord;
}
@ -160,14 +167,16 @@ public class ControllerService {
@HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
if (isPermitted(owner, deviceId, response)) {
try {
if (isPermitted(owner, deviceId, response)) {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
DeviceTypeConstants.SENSOR_HUMIDITY);
response.setStatus(Response.Status.OK.getStatusCode());
}
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.OK.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return sensorRecord;
}
@ -198,6 +207,8 @@ public class ControllerService {
} catch (DeviceTypeException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
@ -214,6 +225,8 @@ public class ControllerService {
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return false;
}

Loading…
Cancel
Save