merged with upstream

merge-requests/1/head
ayyoob 9 years ago
commit 70483aacde

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

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

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

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

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

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

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

@ -17,8 +17,7 @@
*/
package org.coffeeking.connectedcup.plugin.exception;
public class ConnectedCupDeviceMgtPluginException extends Exception{
public class ConnectedCupDeviceMgtPluginException extends Exception {
public ConnectedCupDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);

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

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

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

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

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

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

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

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

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

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

@ -132,7 +132,7 @@
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps/
</outputDirectory>
<destFileName>CONNECTEDLAP.war</destFileName>
<destFileName>connectedlap.war</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.wso2</groupId>

@ -20,14 +20,22 @@
<property name="project-name" value="${ant.project.name}"/>
<property name="target-dir" value="target/carbonapps"/>
<property name="src-dir" value="src/main/resources/carbonapps"/>
<property name="sensor_dir" value="smartLock"/>
<property name="sensorType1_dir" value="smartLock"/>
<property name="sensorType2_dir" value="smartFan"/>
<property name="sensorType3_dir" value="smartBulb"/>
<target name="clean">
<delete dir="${target-dir}"/>
<delete dir="${target-dir}" />
</target>
<target name="zip" depends="clean">
<mkdir dir="${target-dir}"/>
<zip destfile="${target-dir}/${sensor_dir}.car">
<zipfileset dir="${src-dir}/${sensor_dir}"/>
<zip destfile="${target-dir}/${sensorType1_dir}.car">
<zipfileset dir="${src-dir}/${sensorType1_dir}"/>
</zip>
<zip destfile="${target-dir}/${sensorType2_dir}.car">
<zipfileset dir="${src-dir}/${sensorType2_dir}"/>
</zip>
<zip destfile="${target-dir}/${sensorType3_dir}.car">
<zipfileset dir="${src-dir}/${sensorType3_dir}"/>
</zip>
</target>
</project>

@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
@ -25,10 +25,10 @@
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.homeautomation.doormanager.analytics</artifactId>
<artifactId>${groupId}.doormanager.analytics</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>org.homeautomation.doormanager.analytics</name>
<name> ${groupId}.doormanager.analytics </name>
<url>http://wso2.org</url>
<build>
<plugins>
@ -64,9 +64,9 @@
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<version>${maven-assembly-plugin.version}</version>
<configuration>
<finalName>org.homeautomation.doormanager.analytics-1.0.0-SNAPSHOT</finalName>
<finalName>${project.artifactId}-1.0.0-SNAPSHOT</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/src.xml</descriptor>

@ -1,4 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
@ -18,8 +17,8 @@
-->
<assembly
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>src</id>
<formats>

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifacts>
<artifact name="smartBulb_CAPP" version="1.0.0" type="carbon/application">
<dependency artifact="smartBulb_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartBulb_store" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartBulb_mqtt_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartBulb_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartBulb_spark_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -17,6 +17,6 @@
~ under the License.
-->
<artifact name="Eventreceiver_smartLock" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>EventReceiver_smartLock.xml</file>
<artifact name="smartBulb_mqtt_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>smartBulb_mqtt_receiver.xml</file>
</artifact>

@ -0,0 +1,32 @@
<?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.
-->
<eventReceiver name="smartBulb-mqtt" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="oauth-mqtt">
<property name="topic">carbon.super/doormanager/+/smartBulb</property>
<property name="username">admin</property>
<property name="contentValidatorParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:2</property>
<property name="contentValidator">org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTContentValidator</property>
<property name="contentTransformer">default</property>
<property name="dcrUrl">https://localhost:${carbon.https.port}/dynamic-client-web/register</property>
<property name="url">tcp://${mqtt.broker.host}:${mqtt.broker.port}</property>
<property name="cleanSession">true</property>
</from>
<mapping customMapping="disable" type="json"/>
<to streamName="org.wso2.iot.devices.smartBulb" version="1.0.0"/>
</eventReceiver>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="smartBulb_publisher" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
<file>smartBulb_publisher.xml</file>
</artifact>

@ -0,0 +1,25 @@
<?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.
-->
<eventPublisher name="EventPublisher_smartBulb" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.iot.devices.smartBulb" version="1.0.0"/>
<mapping customMapping="disable" type="wso2event"/>
<to eventAdapterType="iot-ui"/>
</eventPublisher>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="smartBulb_spark_script" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
<file>smartBulb_spark_script.xml</file>
</artifact>

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<Analytics>
<Name>smartBulb_spark_script</Name>
<Script>
CREATE TEMPORARY TABLE DevicesmartBulbData USING CarbonAnalytics OPTIONS(tableName "ORG_WSO2_IOT_DEVICES_smartBulb");
CREATE TEMPORARY TABLE DevicesmartBulbSummaryData USING CarbonAnalytics OPTIONS (tableName "DEVICE_smartBulb_SUMMARY", schema "smartBulb FLOAT, deviceType STRING -i, deviceId STRING -i, owner STRING -i, time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
insert overwrite table DevicesmartBulbSummaryData select smartBulb, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DevicesmartBulbData group by smartBulb, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
</Analytics>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="smartBulb_store" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_smartBulb.xml</file>
</artifact>

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<EventStoreConfiguration>
<Source>
<StreamId>org.wso2.iot.devices.smartBulb:1.0.0</StreamId>
</Source>
<RecordStoreName>EVENT_STORE</RecordStoreName>
<TableSchema>
<ColumnDefinition>
<Name>meta_owner</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceType</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceId</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_time</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>smartBulb</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>FLOAT</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>

@ -17,7 +17,7 @@
~ under the License.
-->
<artifact name="Eventstream_smartLock" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.smartLock_1.0.0.json</file>
<artifact name="smartBulb_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.smartBulb_1.0.0.json</file>
</artifact>

@ -0,0 +1,20 @@
{
"name": "org.wso2.iot.devices.smartBulb",
"version": "1.0.0",
"nickName": "smartBulb",
"description": "smartBulb data received from the Device",
"metaData": [
{"name":"owner","type":"STRING"},
{"name":"deviceType","type":"STRING"},
{"name":"deviceId","type":"STRING"},
{"name":"time","type":"LONG"}
],
"payloadData": [
{
"name": "smartBulb","type": "FLOAT"
}
]
}

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifacts>
<artifact name="smartFan_CAPP" version="1.0.0" type="carbon/application">
<dependency artifact="smartFan_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartFan_store" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartFan_mqtt_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartFan_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartFan_spark_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="smartFan_mqtt_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>smartFan_mqtt_receiver.xml</file>
</artifact>

@ -0,0 +1,32 @@
<?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.
-->
<eventReceiver name="smartFan-mqtt" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="oauth-mqtt">
<property name="topic">carbon.super/doormanager/+/smartFan</property>
<property name="username">admin</property>
<property name="contentValidatorParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:2</property>
<property name="contentValidator">org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTContentValidator</property>
<property name="contentTransformer">default</property>
<property name="dcrUrl">https://localhost:${carbon.https.port}/dynamic-client-web/register</property>
<property name="url">tcp://${mqtt.broker.host}:${mqtt.broker.port}</property>
<property name="cleanSession">true</property>
</from>
<mapping customMapping="disable" type="json"/>
<to streamName="org.wso2.iot.devices.smartFan" version="1.0.0"/>
</eventReceiver>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="smartFan_publisher" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
<file>smartFan_publisher.xml</file>
</artifact>

@ -0,0 +1,25 @@
<?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.
-->
<eventPublisher name="EventPublisher_smartFan" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.iot.devices.smartFan" version="1.0.0"/>
<mapping customMapping="disable" type="wso2event"/>
<to eventAdapterType="iot-ui"/>
</eventPublisher>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="smartFan_spark_script" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
<file>smartFan_spark_script.xml</file>
</artifact>

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<Analytics>
<Name>smartFan_spark_script</Name>
<Script>
CREATE TEMPORARY TABLE DevicesmartFanData USING CarbonAnalytics OPTIONS(tableName "ORG_WSO2_IOT_DEVICES_smartFan");
CREATE TEMPORARY TABLE DevicesmartFanSummaryData USING CarbonAnalytics OPTIONS (tableName "DEVICE_smartFan_SUMMARY", schema "smartFan FLOAT, deviceType STRING -i, deviceId STRING -i, owner STRING -i, time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
insert overwrite table DevicesmartFanSummaryData select smartFan, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DevicesmartFanData group by smartFan, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
</Analytics>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="smartFan_store" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_smartFan.xml</file>
</artifact>

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<EventStoreConfiguration>
<Source>
<StreamId>org.wso2.iot.devices.smartFan:1.0.0</StreamId>
</Source>
<RecordStoreName>EVENT_STORE</RecordStoreName>
<TableSchema>
<ColumnDefinition>
<Name>meta_owner</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceType</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceId</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_time</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>smartFan</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>FLOAT</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>

@ -0,0 +1,23 @@
<?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.
-->
<artifact name="smartFan_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.smartFan_1.0.0.json</file>
</artifact>

@ -0,0 +1,20 @@
{
"name": "org.wso2.iot.devices.smartFan",
"version": "1.0.0",
"nickName": "smartFan",
"description": "smartFan data received from the Device",
"metaData": [
{"name":"owner","type":"STRING"},
{"name":"deviceType","type":"STRING"},
{"name":"deviceId","type":"STRING"},
{"name":"time","type":"LONG"}
],
"payloadData": [
{
"name": "smartFan","type": "FLOAT"
}
]
}

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<Analytics>
<Name>IoTServer_smartLock_Script</Name>
<Script>
CREATE TEMPORARY TABLE DevicesmartLockData USING CarbonAnalytics OPTIONS(tableName
"ORG_WSO2_IOT_DEVICES_smartLock");
CREATE TEMPORARY TABLE DevicesmartLockSummaryData USING CarbonAnalytics OPTIONS (tableName
"DEVICE_smartLock_SUMMARY", schema "smartLock FLOAT, deviceType STRING -i, deviceId STRING -i, owner STRING -i,
time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
insert overwrite table DevicesmartLockSummaryData select smartLock, meta_deviceType as deviceType, meta_deviceId
as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DevicesmartLockData group by
smartLock, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
</Analytics>

@ -19,9 +19,10 @@
<artifacts>
<artifact name="smartLock_CAPP" version="1.0.0" type="carbon/application">
<dependency artifact="Eventstream_smartLock" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventstore_smartLock" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventreceiver_smartLock" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Sparkscripts" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartLock_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartLock_store" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartLock_mqtt_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartLock_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="smartLock_spark_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="smartLock_mqtt_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>smartLock_mqtt_receiver.xml</file>
</artifact>

@ -0,0 +1,32 @@
<?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.
-->
<eventReceiver name="smartLock-mqtt" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="oauth-mqtt">
<property name="topic">carbon.super/doormanager/+/smartLock</property>
<property name="username">admin</property>
<property name="contentValidatorParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:2</property>
<property name="contentValidator">org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTContentValidator</property>
<property name="contentTransformer">default</property>
<property name="dcrUrl">https://localhost:${carbon.https.port}/dynamic-client-web/register</property>
<property name="url">tcp://${mqtt.broker.host}:${mqtt.broker.port}</property>
<property name="cleanSession">true</property>
</from>
<mapping customMapping="disable" type="json"/>
<to streamName="org.wso2.iot.devices.smartLock" version="1.0.0"/>
</eventReceiver>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="smartLock_publisher" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
<file>smartLock_publisher.xml</file>
</artifact>

@ -0,0 +1,25 @@
<?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.
-->
<eventPublisher name="EventPublisher_smartLock" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.iot.devices.smartLock" version="1.0.0"/>
<mapping customMapping="disable" type="wso2event"/>
<to eventAdapterType="iot-ui"/>
</eventPublisher>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="smartLock_spark_script" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
<file>smartLock_spark_script.xml</file>
</artifact>

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<Analytics>
<Name>smartLock_spark_script</Name>
<Script>
CREATE TEMPORARY TABLE DevicesmartLockData USING CarbonAnalytics OPTIONS(tableName "ORG_WSO2_IOT_DEVICES_smartLock");
CREATE TEMPORARY TABLE DevicesmartLockSummaryData USING CarbonAnalytics OPTIONS (tableName "DEVICE_smartLock_SUMMARY", schema "smartLock FLOAT, deviceType STRING -i, deviceId STRING -i, owner STRING -i, time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
insert overwrite table DevicesmartLockSummaryData select smartLock, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DevicesmartLockData group by smartLock, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
</Analytics>

@ -17,6 +17,6 @@
~ under the License.
-->
<artifact name="Eventstore_smartLock" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<artifact name="smartLock_store" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_smartLock.xml</file>
</artifact>

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<EventStoreConfiguration>
<Source>
<StreamId>org.wso2.iot.devices.smartLock:1.0.0</StreamId>
</Source>
<RecordStoreName>EVENT_STORE</RecordStoreName>
<TableSchema>
<ColumnDefinition>
<Name>meta_owner</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceType</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceId</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_time</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>smartLock</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>FLOAT</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>

@ -0,0 +1,23 @@
<?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.
-->
<artifact name="smartLock_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.smartLock_1.0.0.json</file>
</artifact>

@ -0,0 +1,20 @@
{
"name": "org.wso2.iot.devices.smartLock",
"version": "1.0.0",
"nickName": "smartLock",
"description": "smartLock data received from the Device",
"metaData": [
{"name":"owner","type":"STRING"},
{"name":"deviceType","type":"STRING"},
{"name":"deviceId","type":"STRING"},
{"name":"time","type":"LONG"}
],
"payloadData": [
{
"name": "smartLock","type": "FLOAT"
}
]
}

@ -1,83 +1,69 @@
<!--/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager-component</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.homeautomation.doormanager.api</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>org.homeautomation.doormanager.api </name>
<url>http://wso2.org</url>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warName>org.homeautomation.doormanager.manager_mgt</warName>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>org.homeautomation.doormanager.plugin</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<?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.
-->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager-component</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${project-base-package}.api</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>${project-base-package}.api</name>
<url>http://wso2.com</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warName>${project-base-package}.api</warName>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
@ -86,172 +72,102 @@
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<scope>provided</scope>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.wso2v1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
</dependencies>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,142 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api;
import org.homeautomation.doormanager.api.dto.DeviceJSON;
import org.homeautomation.doormanager.api.dto.UserInfo;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* This is the API which is used to control and manage device type functionality
*/
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "doormanager", version = "1.0.0", context = "/doormanager", tags = "doormanager")
@DeviceType(value = "doormanager")
public interface DoorManagerService {
/**
* @param deviceId unique identifier for given device type instance
* @param state change status of sensor: on/off
*/
@Path("device/{deviceId}/change-status")
@POST
@Feature(code = "change-status", name = "Change status of door lock: lock/unlock",
description = "Change status of door lock: lock/unlock")
Response changeStatusOfDoorLockSafe(@PathParam("deviceId") String deviceId,
@QueryParam("state") String state,
@Context HttpServletResponse response);
/**
* Retrieve Sensor data for the given time period
* @param deviceId unique identifier for given device type instance
* @param from starting time
* @param to ending time
* @return response with List<SensorRecord> object which includes sensor data which is requested
*/
@Path("device/stats/{deviceId}")
@GET
@Consumes("application/json")
@Produces("application/json")
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/stats"})
Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to, @QueryParam("sensorType") String sensorType);
/**
* Remove device type instance using device id
* @param deviceId unique identifier for given device type instance
*/
@Path("/device/{device_id}")
@DELETE
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/removeDevice"})
Response removeDevice(@PathParam("device_id") String deviceId);
/**
* Update device instance name
* @param deviceId unique identifier for given device type instance
* @param name new name for the device type instance
*/
@Path("/device/{device_id}")
@PUT
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
/**
* To get device information
* @param deviceId unique identifier for given device type instance
* @return Device object which carries all information related to a managed device
*/
@Path("/device/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
Response getDevice(@PathParam("device_id") String deviceId);
/**
* Get all device type instance which belongs to user
* @return Array of devices which includes device's information
*/
@Path("/devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/devices"})
Response getAllDevices();
/**
* To download device type agent source code as zip file
* @param deviceName name for the device type instance
* @param sketchType folder name where device type agent was installed into server
* @return Agent source code as zip file
*/
@Path("/device/download")
@GET
@Produces("application/zip")
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/download"})
Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType);
@Path("device/assign-user/{deviceId}")
@POST
@Feature(code = "assign-user", name = "Assign new user to lock",
description = "Add new access card to user to control the lock ")
Response assignUserToLock(@QueryParam("cardNumber") String cardNumber,
@QueryParam("userName") String userName,
@QueryParam("emailAddress") String emailAddress,
@PathParam("deviceId") String deviceId);
/**
* @param userInfo user information which are required to test given user is authorized to open requested door
* @return if user is authorized open the the door allow to open it
*/
@POST
@Path("/device/is-user-authorized")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
Response isUserAuthorized(final UserInfo userInfo);
}

@ -0,0 +1,629 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.api.dto.SensorRecord;
import org.homeautomation.doormanager.api.dto.UserInfo;
import org.homeautomation.doormanager.api.util.APIUtil;
import org.homeautomation.doormanager.api.util.ZipUtil;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.DoorManagerManager;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.wso2.carbon.analytics.dataservice.commons.SORT;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
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;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* This is the API which is used to control and manage device type functionality
*/
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "doormanager", version = "1.0.0", context = "/doormanager", tags = "doormanager")
@DeviceType(value = "doormanager")
public class DoorManagerServiceImpl implements DoorManagerService {
private static final String KEY_TYPE = "PRODUCTION";
private static Log log = LogFactory.getLog(DoorManagerService.class);
private static volatile ApiApplicationKey apiApplicationKey;
private DoorManagerManager doorManagerManager;
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);
}
DoorManagerServiceImpl(){
doorManagerManager = new DoorManagerManager();
}
/**
* @param deviceId unique identifier for given device type instance
* @param state change status of sensor: on/off
*/
@Path("device/change-locker-status/{deviceId}")
@POST
@Feature(code = "change-locker-status", name = "Change status of door lock: lock/unlock",
description = "Change status of door lock: lock/unlock")
public Response changeStatusOfDoorLockSafe(@PathParam("deviceId") String deviceId,
@QueryParam("state") String state,
@Context HttpServletResponse response) {
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
DoorManagerConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
String sensorState = state.toUpperCase();
if (!sensorState.equals(DoorManagerConstants.STATE_LOCK) && !sensorState.equals(
DoorManagerConstants.STATE_UNLOCK)) {
log.error("The requested state change should be either - 'lock' or 'unlock'");
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
+ "/" + DoorManagerConstants.DEVICE_TYPE + "/" + deviceId + DoorManagerConstants.MQTT_TOPIC_FOR_LOCK;
Operation commandOp = new CommandOperation();
commandOp.setCode("change-locker-status");
commandOp.setType(Operation.Type.COMMAND);
commandOp.setEnabled(true);
commandOp.setPayLoad(sensorState);
Properties props = new Properties();
props.setProperty(DoorManagerConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
commandOp.setProperties(props);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE));
APIUtil.getDeviceManagementService().addOperation(DoorManagerConstants.DEVICE_TYPE, commandOp, deviceIdentifiers);
return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (OperationManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
/**
* @param deviceId unique identifier for given device type instance
* @param currentValue change voltage
*/
@Path("device/change-light-intensity/{deviceId}")
@POST
@Feature(code = "change-light-intensity", name = "Change bulb intensity",
description = "Change status of door lock: lock/unlock")
public Response changeLightIntensity(@PathParam("deviceId") String deviceId,
@QueryParam("currentValue") String currentValue,
@Context HttpServletResponse response) {
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
DoorManagerConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
+ "/" + DoorManagerConstants.DEVICE_TYPE + "/" + deviceId + DoorManagerConstants.MQTT_TOPIC_FOR_BULB;
Operation commandOp = new CommandOperation();
commandOp.setCode("change-light-intensity");
commandOp.setType(Operation.Type.COMMAND);
commandOp.setEnabled(true);
commandOp.setPayLoad(currentValue);
Properties props = new Properties();
props.setProperty(DoorManagerConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
commandOp.setProperties(props);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE));
APIUtil.getDeviceManagementService().addOperation(DoorManagerConstants.DEVICE_TYPE, commandOp, deviceIdentifiers);
return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (OperationManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
/**
* @param deviceId unique identifier for given device type instance
* @param state change status of sensor: on/off
*/
@Path("device/change-fan-status/{deviceId}")
@POST
@Feature(code = "change-fan-state", name = "Change status of door lock: lock/unlock",
description = "Change status of door lock: lock/unlock")
public Response changeFanState(@PathParam("deviceId") String deviceId,
@QueryParam("state") String state,
@Context HttpServletResponse response) {
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
DoorManagerConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
String sensorState = state.toUpperCase();
if (!sensorState.equals(DoorManagerConstants.STATE_BULB_ON) && !sensorState.equals(DoorManagerConstants.STATE_BULB_OFF)){
log.error("The requested state change should be either - 'ON' or 'OFF'");
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
+ "/" + DoorManagerConstants.DEVICE_TYPE + "/" + deviceId + DoorManagerConstants.MQTT_TOPIC_FOR_FAN;
Operation commandOp = new CommandOperation();
commandOp.setCode("change-fan-state");
commandOp.setType(Operation.Type.COMMAND);
commandOp.setEnabled(true);
commandOp.setPayLoad(sensorState);
Properties props = new Properties();
props.setProperty(DoorManagerConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
commandOp.setProperties(props);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE));
APIUtil.getDeviceManagementService().addOperation(DoorManagerConstants.DEVICE_TYPE, commandOp, deviceIdentifiers);
return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (OperationManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@Path("device/assign-user/{deviceId}")
@POST
@Feature(code = "assign-user", name = "Assign new user to lock",
description = "Add new access card to user to control the lock ")
public Response assignUserToLock(@QueryParam("cardNumber") String cardNumber,
@QueryParam("userName") String userName,
@QueryParam("emailAddress") String emailAddress,
@PathParam("deviceId") String deviceId) {
try {
if (userName != null && cardNumber != null) {
UserStoreManager userStoreManager = APIUtil.getUserStoreManager();
DoorLockSafe doorLockSafe = new DoorLockSafe();
String applicationUsername = null;
if (userStoreManager.isExistingUser(userName)) {
if (apiApplicationKey == null) {
applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName();
applicationUsername = applicationUsername + "@" + APIUtil.getAuthenticatedUserTenantDomain();
APIManagementProviderService apiManagementProviderService
= APIUtil.getAPIManagementProviderService();
String[] tags = {DoorManagerConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DoorManagerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = DoorManagerConstants.DEVICE_SCOPE_INFO_DEVICE_TYPE
+ DoorManagerConstants.DEVICE_TYPE + DoorManagerConstants.DEVICE_SCOPE_INFO_DEVICE_ID
+ deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), APIUtil.getAuthenticatedUser() + "@"
+ APIUtil.getAuthenticatedUserTenantDomain(), scopes);
String accessToken = accessTokenInfo.getAccessToken();
if (accessToken == null) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
doorLockSafe.setAccessToken(accessTokenInfo.getAccessToken());
doorLockSafe.setRefreshToken(accessTokenInfo.getRefreshToken());
doorLockSafe.setDeviceId(deviceId);
doorLockSafe.setOwner(applicationUsername);
doorLockSafe.setEmailAddress(emailAddress);
doorLockSafe.setUIDofUser(cardNumber);
doorLockSafe.setSerialNumber(deviceId);
//DoorManagerManager doorManager = APIUtil.getDoorManagerManagerService();
if (doorManagerManager.assignUserToLock(doorLockSafe)) {
return Response.ok().build();
} else {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
} else {
return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
}
} else {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
} catch (UserStoreException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (JWTClientException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (APIManagerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DoorManagerDeviceMgtPluginException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* Retrieve Sensor data for the given time period
* @param deviceId unique identifier for given device type instance
* @param from starting time
* @param to ending time
* @return response with List<SensorRecord> object which includes sensor data which is requested
*/
@Path("device/stats/{deviceId}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to, @QueryParam("sensorType") String sensorType) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String query = DoorManagerConstants.DEVICE_META_INFO_DEVICE_ID + deviceId + " AND " + DoorManagerConstants.DEVICE_META_INFO_DEVICE_TYPE +
DoorManagerConstants.DEVICE_TYPE + " AND "+ DoorManagerConstants.DEVICE_META_INFO_TIME +" : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = null;
if(sensorType.equals(DoorManagerConstants.SENSOR_TYPE1)){
sensorTableName = DoorManagerConstants.SENSOR_TYPE1_EVENT_TABLE;
}else if(sensorType.equals(DoorManagerConstants.SENSOR_TYPE2)){
sensorTableName = DoorManagerConstants.SENSOR_TYPE2_EVENT_TABLE;
}
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
DoorManagerConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
if (sensorTableName != null) {
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField(DoorManagerConstants.DEVICE_META_INFO_TIME, SORT.ASC, false);
sortByFields.add(sortByField);
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
}
} catch (AnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.status(Response.Status.BAD_REQUEST).build();
}
/**
* Remove device type instance using device id
* @param deviceId unique identifier for given device type instance
*/
@Path("/device/{deviceId}")
@DELETE
public Response removeDevice(@PathParam("deviceId") String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* Update device instance name
* @param deviceId unique identifier for given device type instance
* @param name new name for the device type instance
*/
@Path("/device/{deviceId}")
@PUT
public Response updateDevice(@PathParam("deviceId") String deviceId, @QueryParam("name") String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DoorManagerConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* To get device information
* @param deviceId unique identifier for given device type instance
* @return return Device object which carries all information related to a managed device
*/
@Path("/device/{deviceId}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getDevice(@PathParam("deviceId") String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* Get all device type instance which belongs to user
* @return Array of devices which includes device's information
*/
@Path("/devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getAllDevices() {
try {
List<Device> userDevices =
APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser());
ArrayList<Device> deviceList = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(DoorManagerConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
deviceList.add(device);
}
}
Device[] devices = deviceList.toArray(new Device[]{});
return Response.ok().entity(devices).build();
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* To download device type agent source code as zip file
* @param deviceName name for the device type instance
* @param sketchType folder name where device type agent was installed into server
* @return Agent source code as zip file
*/
@Path("/device/download")
@GET
@Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
@QueryParam("sketchType") String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.status(Response.Status.OK);
response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
Response requestedFile = response.build();
File file = zipFile.getZipFile();
if (!file.delete()) {
String message = file.exists() ? "is in use by another process" : "does not exist " + sketchType;
throw new IOException("Cannot delete file, because file " + message + ".");
} else {
return requestedFile;
}
} catch (IllegalArgumentException ex) {
return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
} catch (DeviceManagementException ex) {
log.error(ex.getMessage(), ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
log.error(ex.getMessage(), ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
log.error(ex.getMessage(), ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
log.error(ex.getMessage(), ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
}
}
/**
* Register device into device management service
* @param deviceId unique identifier for given device type instance
* @param name name for the device type instance
* @return check whether device is installed into cdmf
*/
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name);
device.setType(DoorManagerConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
APIUtil.registerApiAccessRoles(APIUtil.getAuthenticatedUser());
}
return added;
} catch (DeviceManagementException e) {
log.error(e.getMessage(), e);
return false;
}
}
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
throws DeviceManagementException, JWTClientException, APIManagerException,
UserStoreException {
//create new device id
String deviceId = shortUUID();
if (apiApplicationKey == null) {
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName();
applicationUsername = applicationUsername + "@" + APIUtil.getAuthenticatedUserTenantDomain();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DoorManagerConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DoorManagerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = DoorManagerConstants.DEVICE_SCOPE_INFO_DEVICE_TYPE
+ DoorManagerConstants.DEVICE_TYPE + DoorManagerConstants.DEVICE_SCOPE_INFO_DEVICE_ID
+ deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(), scopes);
String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken();
boolean status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
return ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
deviceId, deviceName, accessToken, refreshToken, apiApplicationKey.toString());
}
/**
* @param userInfo user information which are required to test given user is authorized to open requested door
* @return if user is authorized open the the door allow to open it
*/
@POST
@Path("/device/is-user-authorized")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@SuppressWarnings("unchecked") //This is to avoid unchecked call to put(k, v) into jsonObject. org.json.simple
// library uses raw type collections internally.
public Response isUserAuthorized(final UserInfo userInfo) {
if (userInfo.cardNumber != null && userInfo.deviceId != null) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(userInfo.deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
if (doorManagerManager.checkCardDoorAssociation(userInfo.cardNumber, userInfo.deviceId)) {
return Response.status(Response.Status.OK).build();
} else {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} catch (DeviceAccessAuthorizationException e) {
return Response.status(Response.Status.UNAUTHORIZED).build();
} catch (DoorManagerDeviceMgtPluginException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
return Response.status(Response.Status.BAD_REQUEST).build();
}
/* private void sendCEPEvent(String deviceId, String cardId, boolean accessStatus){
String cepEventReciever = "http://localhost:9768/endpoints/LockEventReciever";
HttpClient httpClient = new SystemDefaultHttpClient();
HttpPost method = new HttpPost(cepEventReciever);
JsonObject event = new JsonObject();
JsonObject metaData = new JsonObject();
metaData.addProperty("deviceID", deviceId);
metaData.addProperty("cardID", cardId);
event.add("metaData", metaData);
String eventString = "{\"event\": " + event + "}";
try {
StringEntity entity = new StringEntity(eventString);
method.setEntity(entity);
if (cepEventReciever.startsWith("https")) {
method.setHeader("Authorization", "Basic " + Base64.encode(("admin" + ":" + "admin").getBytes()));
}
httpClient.execute(method).getEntity().getContent().close();
} catch (UnsupportedEncodingException e) {
log.error("Error while constituting CEP event"+ e.getMessage());
} catch (ClientProtocolException e) {
log.error("Error while sending message to CEP "+ e.getMessage());
} catch (IOException e) {
log.error("Error while sending message to CEP "+ e.getMessage());
}
}*/
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
@ -11,7 +11,7 @@
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@ -23,16 +23,14 @@ import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* These information are sent by agent in each request to server
*/
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class DeviceJSON {
@XmlElement(required = true)
public String owner;
@XmlElement(required = true)
public String deviceId;
@XmlElement(required = true)
public String UIDofUser;
@XmlElement(required = true)
public String serialNumber;
}

@ -0,0 +1,88 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* This stores sensor event data for doormanager.
*/
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class SensorRecord {
@XmlElementWrapper(required = true, name = "values")
private Map<String, Object> values;
/**
* Unique identifier for each recode
*/
@XmlElement(required = false, name = "id")
private String id;
/**
* Gets the values.
* @return the values
*/
public Map<String, Object> getValues() {
return values;
}
/**
* Sets the values.
* @param values set corresponding values
*/
public void setValues(Map<String, Object> values) {
this.values = values;
}
/**
* Gets the id.
* @return the id
*/
public String getId() {
return id;
}
/**
* Sets the id.
* @param id set unique identifier
*/
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
List<String> valueList = new ArrayList<>();
for (Map.Entry<String, Object> entry : values.entrySet()) {
valueList.add(entry.getKey() + ":" + entry.getValue());
}
return valueList.toString();
}
}

@ -31,6 +31,4 @@ public class UserInfo {
public String deviceId;
@XmlElement(required = true)
public String cardNumber;
@XmlElement(required = true)
public String userName;
}

@ -11,20 +11,22 @@
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.api.exception;
/**
* Device specific exception handler
*/
public class DoorManagerException extends Exception {
private static final long serialVersionUID = 2736466230451105441L;
private String errorMessage;
@SuppressWarnings("unused")
public DoorManagerException(String msg, DoorManagerException nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
@ -35,23 +37,19 @@ public class DoorManagerException extends Exception {
setErrorMessage(message);
}
@SuppressWarnings("unused")
public DoorManagerException(String msg) {
super(msg);
setErrorMessage(msg);
}
@SuppressWarnings("unused")
public DoorManagerException() {
super();
}
@SuppressWarnings("unused")
public DoorManagerException(Throwable cause) {
super(cause);
}
@SuppressWarnings("unused")
public String getErrorMessage() {
return errorMessage;
}
@ -59,6 +57,4 @@ public class DoorManagerException extends Exception {
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -0,0 +1,271 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.api.dto.SensorRecord;
import org.homeautomation.doormanager.plugin.impl.DoorManagerManager;
import org.homeautomation.doormanager.plugin.impl.DoorManagerManagerService;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils;
import org.wso2.carbon.analytics.datasource.commons.Record;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.Permission;
import org.wso2.carbon.user.core.service.RealmService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 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;
}
public static APIManagementProviderService getAPIManagementProviderService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
APIManagementProviderService apiManagementProviderService =
(APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null);
if (apiManagementProviderService == null) {
String msg = "API management provider service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return apiManagementProviderService;
}
public static JWTClientManagerService getJWTClientManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
JWTClientManagerService jwtClientManagerService =
(JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null);
if (jwtClientManagerService == null) {
String msg = "JWT Client manager service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return jwtClientManagerService;
}
public static String getTenantDomainOftheUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
return threadLocalCarbonContext.getTenantDomain();
}
public static UserStoreManager getUserStoreManager() {
RealmService realmService;
UserStoreManager userStoreManager;
try {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
if (realmService == null) {
String msg = "Realm service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
int tenantId = ctx.getTenantId();
userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving current user store manager";
log.error(msg, e);
throw new IllegalStateException(msg);
}
return userStoreManager;
}
public static void registerApiAccessRoles(String user) {
UserStoreManager userStoreManager;
try {
userStoreManager = getUserStoreManager();
String[] userList = new String[]{user};
if (userStoreManager != null) {
String rolesOfUser[] = userStoreManager.getRoleListOfUser(user);
if (!userStoreManager.isExistingRole(DoorManagerUtilConstants.DEFAULT_ROLE_NAME)) {
userStoreManager.addRole(DoorManagerUtilConstants.DEFAULT_ROLE_NAME, userList, getDefaultPermissions());
} else if (rolesOfUser == null) {
userStoreManager.updateUserListOfRole(DoorManagerUtilConstants.DEFAULT_ROLE_NAME, new String[0], userList);
}
}
} catch (UserStoreException e) {
log.error("Error while creating a role and adding a user for virtual_firealarm.", e);
}
}
public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
(DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null);
if (deviceAccessAuthorizationService == null) {
String msg = "Device Authorization service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceAccessAuthorizationService;
}
public static List<SensorRecord> getAllEventsForDevice(String tableName, String query,
List<SortByField> sortByFields) throws AnalyticsException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI();
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
if (eventCount == 0) {
return null;
}
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount,
sortByFields);
List<String> recordIds = getRecordIds(resultEntries);
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
Map<String, SensorRecord> sensorDatas = createSensorData(AnalyticsDataServiceUtils.listRecords(
analyticsDataAPI, response));
return getSortedSensorData(sensorDatas, resultEntries);
}
public static List<SensorRecord> getSortedSensorData(Map<String, SensorRecord> sensorDatas,
List<SearchResultEntry> searchResults) {
List<SensorRecord> sortedRecords = new ArrayList<>();
for (SearchResultEntry searchResultEntry : searchResults) {
sortedRecords.add(sensorDatas.get(searchResultEntry.getId()));
}
return sortedRecords;
}
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
List<String> ids = new ArrayList<>();
for (SearchResultEntry searchResult : searchResults) {
ids.add(searchResult.getId());
}
return ids;
}
public static Map<String, SensorRecord> createSensorData(List<Record> records) {
Map<String, SensorRecord> sensorDatas = new HashMap<>();
for (Record record : records) {
SensorRecord sensorData = createSensorData(record);
sensorDatas.put(sensorData.getId(), sensorData);
}
return sensorDatas;
}
public static SensorRecord createSensorData(Record record) {
SensorRecord recordBean = new SensorRecord();
recordBean.setId(record.getId());
recordBean.setValues(record.getValues());
return recordBean;
}
public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI =
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
if (analyticsDataAPI == null) {
String msg = "Analytics api service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return analyticsDataAPI;
}
public static String getAuthenticatedUserTenantDomain() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
return threadLocalCarbonContext.getTenantDomain();
}
public static OutputEventAdapterService getOutputEventAdapterService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
OutputEventAdapterService outputEventAdapterService =
(OutputEventAdapterService) ctx.getOSGiService(OutputEventAdapterService.class, null);
if (outputEventAdapterService == null) {
String msg = "Device Authorization service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return outputEventAdapterService;
}
public static Permission[] getDefaultPermissions() {
return new Permission[]{new org.wso2.carbon.user.core
.Permission(DoorManagerUtilConstants.DEFAULT_PERMISSION_RESOURCE, "ui.execute")};
}
public static PlatformConfigurationManagementService getTenantConfigurationManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
PlatformConfigurationManagementService tenantConfigurationManagementService =
(PlatformConfigurationManagementService) ctx.getOSGiService(PlatformConfigurationManagementService.class, null);
if (tenantConfigurationManagementService == null) {
String msg = "Tenant configuration Management service not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return tenantConfigurationManagementService;
}
public static DoorManagerManager getDoorManagerManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementService deviceManagementProviderService =
(DeviceManagementService) ctx.getOSGiService(DoorManagerManagerService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
DoorManagerManager doorManagerManager = (DoorManagerManager)deviceManagementProviderService.getDeviceManager();
return doorManagerManager;
}
}

@ -0,0 +1,50 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api.util;
/**
* This hold the constants related to the device type.
*/
public class DoorManagerUtilConstants {
public static final String DEFAULT_PERMISSION_RESOURCE = "/permission/admin/device-mgt/doormanager/user";
public static final String DEFAULT_ROLE_NAME = "doormanager_user";
public final static String APPLICATION_ZIP = "application/zip";
public final static String CONTENT_DISPOSITION = "Content-Disposition";
public final static String ATTACHMENT_FILENAME = "attachment; filename=\"";
public static final String TENANT_DOMAIN = "TENANT_DOMAIN";
public static final String DEVICE_OWNER = "DEVICE_OWNER";
public static final String DEVICE_ID = "DEVICE_ID";
public static final String DEVICE_NAME = "DEVICE_NAME";
public static final String HTTPS_EP = "HTTPS_EP";
public static final String HTTP_EP = "HTTP_EP";
public static final String APIM_EP = "APIM_EP";
public static final String MQTT_EP = "MQTT_EP";
public static final String XMPP_EP = "XMPP_EP";
public static final String DOORMANAGER_HTTPS_EP = "DOORMANAGER_HTTPS_EP";
public static final String DOORMANAGER_HTTP_EP = "DOORMANAGER_HTTP_EP";
public static final String DOORMANAGER_APIM_EP = "DOORMANAGER_APIM_EP";
public static final String DOORMANAGER_MQTT_EP = "DOORMANAGER_MQTT_EP";
public static final String DOORMANAGER_XMPP_EP = "DOORMANAGER_XMPP_EP";
public static final String API_APPLICATION_KEY = "API_APPLICATION_KEY";
public static final String DEVICE_TOKEN = "DEVICE_TOKEN";
public static final String DEVICE_REFRESH_TOKEN = "DEVICE_REFRESH_TOKEN";
public static final String SERVER_NAME = "SERVER_NAME";
public static final String SERVER_JID = "SERVER_JID";
}

@ -0,0 +1,123 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api.util;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This is used to create a zip file that includes the necessary configuration required for the agent.
*/
public class ZipUtil {
private static final String HTTPS_PORT_PROPERTY = "httpsPort";
private static final String HTTP_PORT_PROPERTY = "httpPort";
private static final String LOCALHOST = "localhost";
private static final String HTTPS_PROTOCOL_APPENDER = "https://";
private static final String HTTP_PROTOCOL_APPENDER = "http://";
private static final String CONFIG_TYPE = "general";
private static final String DEFAULT_MQTT_ENDPOINT = "tcp://localhost:1883";
public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType,
String deviceId, String deviceName, String token,
String refreshToken, String apiApplicationKey) throws DeviceManagementException {
String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches";
String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" +
File.separator + deviceId;
String templateSketchPath = sketchFolder + File.separator + deviceType;
String iotServerIP;
try {
iotServerIP = Utils.getServerUrl();
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort;
String mqttEndpoint = DEFAULT_MQTT_ENDPOINT;
if (mqttEndpoint.contains(LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
}
PlatformConfiguration configuration = APIUtil.getTenantConfigurationManagementService().getConfiguration(
CONFIG_TYPE);
if (configuration != null && configuration.getConfiguration() != null && configuration
.getConfiguration().size() > 0) {
List<ConfigurationEntry> configurations = configuration.getConfiguration();
for (ConfigurationEntry configurationEntry : configurations) {
switch (configurationEntry.getName()) {
case DoorManagerUtilConstants.DOORMANAGER_HTTPS_EP:
httpsServerEP = (String)configurationEntry.getValue();
break;
case DoorManagerUtilConstants.DOORMANAGER_HTTP_EP:
httpServerEP = (String)configurationEntry.getValue();
break;
case DoorManagerUtilConstants.DOORMANAGER_MQTT_EP:
mqttEndpoint = (String)configurationEntry.getValue();
break;
}
}
}
String base64EncodedApplicationKey = getBase64EncodedAPIAppKey(apiApplicationKey).trim();
Map<String, String> contextParams = new HashMap<>();
contextParams.put(DoorManagerUtilConstants.TENANT_DOMAIN, APIUtil.getTenantDomainOftheUser());
contextParams.put(DoorManagerUtilConstants.DEVICE_OWNER, owner);
contextParams.put(DoorManagerUtilConstants.DEVICE_ID, deviceId);
contextParams.put(DoorManagerUtilConstants.DEVICE_NAME, deviceName);
contextParams.put(DoorManagerUtilConstants.HTTPS_EP, httpsServerEP);
contextParams.put(DoorManagerUtilConstants.HTTP_EP, httpServerEP);
contextParams.put(DoorManagerUtilConstants.APIM_EP, httpServerEP);
contextParams.put(DoorManagerUtilConstants.MQTT_EP, mqttEndpoint);
contextParams.put(DoorManagerUtilConstants.API_APPLICATION_KEY, base64EncodedApplicationKey);
contextParams.put(DoorManagerUtilConstants.DEVICE_TOKEN, token);
contextParams.put(DoorManagerUtilConstants.DEVICE_REFRESH_TOKEN, refreshToken);
ZipArchive zipFile;
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
return zipFile;
} catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e);
} catch (ConfigurationManagementException e) {
throw new DeviceManagementException("Failed to retrieve configuration", e);
}
}
private String getBase64EncodedAPIAppKey(String apiAppCredentialsAsJSONString) {
JSONObject jsonObject = new JSONObject(apiAppCredentialsAsJSONString);
String consumerKey = jsonObject.get(ApiApplicationConstants.OAUTH_CLIENT_ID).toString();
String consumerSecret = jsonObject.get(ApiApplicationConstants.OAUTH_CLIENT_SECRET).toString();
String stringToEncode = consumerKey + ":" + consumerSecret;
return Base64.encodeBase64String(stringToEncode.getBytes());
}
}

@ -1,93 +0,0 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api;
import org.homeautomation.doormanager.api.dto.UserInfo;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "doormanager", version = "1.0.0", context = "/doormanager", tags = {"doormanager"})
@DeviceType(value = "doormanager")
public interface DoorManagerControllerService {
/**
* Assign new user to lock
*
* @param owner owner of the device
* @param deviceId unique identifier for given device
* @param protocol transport protocol which is being using here MQTT
* @param cardNumber RFID card number
* @param userName user name of RFID card owner
* @param emailAddress email address of RFID card owner
*/
@Path("device/assign-user")
@POST
@Feature(code = "assign_user", name = "Assign new user to lock", type = "operation",
description = "Add new access card to user to control the lock ")
Response assignUserToLock(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("cardNumber") String cardNumber,
@FormParam("userName") String userName,
@FormParam("emailAddress") String emailAddress);
/**
* Change status of door lock safe: LOCK/UNLOCK
*
* @param owner owner of the device
* @param deviceId unique identifier for given device
* @param protocol transport protocol which is being using here MQTT
* @param state status of lock safe: lock/unlock
*/
@Path("device/change-status")
@POST
@Feature(code = "change-status", name = "Change status of door lock safe: LOCK/UNLOCK", type = "operation",
description = "Change status of door lock safe: LOCK/UNLOCK")
Response changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("state") String state);
/**
* @param userInfo user information which are required to test given user is authorized to open requested door
* @return if user is authorized open the the door allow to open it
*/
@GET
@Path("device/get-user-info")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@SuppressWarnings("unchecked")
//This is to avoid unchecked call to put(k, v) into jsonObject. org.json.simple
// library uses raw type collections internally.
Response get_user_info(final UserInfo userInfo);
}

@ -1,233 +0,0 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.api.exception.DoorManagerException;
import org.homeautomation.doormanager.api.transport.DoorManagerMQTTConnector;
import org.homeautomation.doormanager.api.dto.UserInfo;
import org.homeautomation.doormanager.api.util.APIUtil;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.DoorManager;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.json.simple.JSONObject;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class DoorManagerControllerServiceImpl implements DoorManagerControllerService {
private static Log log = LogFactory.getLog(DoorManagerControllerServiceImpl.class);
private static String CURRENT_STATUS = "doorLockerCurrentStatus";
private DoorManager doorManager;
private DoorManagerMQTTConnector doorManagerMQTTConnector;
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
DoorManagerControllerServiceImpl() {
doorManager = new DoorManager();
}
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public DoorManagerMQTTConnector getDoorManagerMQTTConnector() {
return doorManagerMQTTConnector;
}
public void setDoorManagerMQTTConnector(final DoorManagerMQTTConnector MQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
DoorManagerControllerServiceImpl.this.doorManagerMQTTConnector = MQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
doorManagerMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, DoorManagerMQTTConnector" +
" not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
@Path("device/assign-user")
@POST
public Response assignUserToLock(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("cardNumber") String cardNumber,
@FormParam("userName") String userName,
@FormParam("emailAddress") String emailAddress) {
if (userName != null && cardNumber != null && deviceId != null) {
try {
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
DoorLockSafe doorLockSafe = new DoorLockSafe();
if (userStoreManager.isExistingUser(userName)) {
if (apiApplicationKey == null) {
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DoorManagerConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DoorManagerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + DoorManagerConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes);
String accessToken = accessTokenInfo.getAccessToken();
if (accessToken == null) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
Map<String, String> claims = new HashMap<>();
claims.put(DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, accessToken);
claims.put(DoorManagerConstants.DEVICE_CLAIMS_REFRESH_TOKEN,
accessTokenInfo.getRefreshToken());
claims.put(DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, cardNumber);
userStoreManager.setUserClaimValues(userName, claims, null);
doorLockSafe.setAccessToken(accessTokenInfo.getAccessToken());
doorLockSafe.setRefreshToken(accessTokenInfo.getRefreshToken());
doorLockSafe.setDeviceId(deviceId);
doorLockSafe.setOwner(owner);
doorLockSafe.setEmailAddress(emailAddress);
doorLockSafe.setUIDofUser(cardNumber);
doorLockSafe.setSerialNumber(deviceId);
if (doorManager.assignUserToLock(doorLockSafe)) {
return Response.ok().build();
} else {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
} else {
return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
}
} catch (UserStoreException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (JWTClientException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (APIManagerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DoorManagerDeviceMgtPluginException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
} else {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
}
@Path("device/change-status")
@POST
public Response changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("state") String state) {
try {
int lockerCurrentState;
if (state.toUpperCase().equals("LOCK")) {
lockerCurrentState = 0;
} else {
lockerCurrentState = 1;
}
doorManagerMQTTConnector.sendCommandViaMQTT(owner, deviceId, "DoorManager:", state.toUpperCase());
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DoorManagerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@GET
@Path("device/get-user-info")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@SuppressWarnings("unchecked")
public Response get_user_info(final UserInfo userInfo) {
if (userInfo.userName != null && userInfo.cardNumber != null && userInfo.deviceId != null) {
try {
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
if (userStoreManager.isExistingUser(userInfo.userName)) {
String accessToken = userStoreManager.getUserClaimValue(userInfo.userName,
DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, null);
String cardNumber = userStoreManager.getUserClaimValue(userInfo.userName,
DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, null);
if (cardNumber != null) {
if (cardNumber.equals(userInfo.cardNumber)) {
if (accessToken != null) {
JSONObject credentials = new JSONObject();
credentials.put(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN, accessToken);
//return Response.ok(credentials, MediaType.APPLICATION_JSON_TYPE).build();
return Response.status(Response.Status.OK).build();
}
}
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} else {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} catch (UserStoreException e) {
log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
return Response.status(Response.Status.BAD_REQUEST).build();
}
}

@ -1,65 +0,0 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("enrollment")
@SuppressWarnings("NonJaxWsWebServices")
@DeviceType(value = "doormanager")
@API(name = "doormanager_mgt", version = "1.0.0", context = "/doormanager_mgt" , tags = {"doormanager"})
public interface DoorManagerManagerService {
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
Response downloadSketch(@QueryParam("deviceName") String deviceName);
@Path("devices/generate_link")
@GET
Response generateSketchLink(@QueryParam("deviceName") String deviceName);
}

@ -1,251 +0,0 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.api.util.APIUtil;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
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;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
@Path("enrollment")
public class DoorManagerManagerServiceImpl implements DoorManagerManagerService {
private static Log log = LogFactory.getLog(DoorManagerManagerServiceImpl.class);
private static ApiApplicationKey apiApplicationKey;
private static final String KEY_TYPE = "PRODUCTION";
@Path("devices/{device_id}")
@DELETE
public Response removeDevice(@PathParam("device_id") String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("devices/{device_id}")
@PUT
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DoorManagerConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getDevice(@PathParam("device_id") String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("devices/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response downloadSketch(@QueryParam("deviceName") String deviceName) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return response.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
@Path("devices/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName){
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String owner, String deviceName)
throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException,
UserStoreException {
if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
if (apiApplicationKey == null) {
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DoorManagerConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DoorManagerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + DoorManagerConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner,
scopes);
//create token
String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken();
//Register the device with CDMF
boolean status = register(deviceId, deviceName);
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, APIUtil.getTenantDomainOftheUser(),
DoorManagerConstants.DEVICE_TYPE, deviceId,
deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
/**
* Generate UUID
*
* @return generated UUID
*/
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);
}
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(DoorManagerConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
}
}
}

@ -1,236 +0,0 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.homeautomation.doormanager.api.exception.DoorManagerException;
import org.homeautomation.doormanager.api.util.DoorManagerServiceUtils;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler;
import java.io.File;
import java.util.Calendar;
import java.util.UUID;
/**
* MQTT is used as transport protocol. So this will provide basic functional requirement in order to communicate over
* MQTT
*/
@SuppressWarnings("no JAX-WS annotation")
public class DoorManagerMQTTConnector extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(DoorManagerMQTTConnector.class);
private static String PUBLISHER_CONTEXT = "publisher";
private static String SUBCRIBER_TOPIC = "wso2/" + DoorManagerConstants.DEVICE_TYPE + "/+/publisher";
private static String PUBLISHER_TOPIC = "wso2/"+ DoorManagerConstants.DEVICE_TYPE + "/%s/subscriber";
private static String SUBSCRIBER = UUID.randomUUID().toString().substring(0, 5);
private DoorManagerMQTTConnector() {
super(SUBSCRIBER, DoorManagerConstants.DEVICE_TYPE,
MqttConfig.getInstance().getMqttQueueEndpoint(), SUBCRIBER_TOPIC);
}
/**
* This method will initialize connection with message broker
*/
@Override
public void connect() {
Runnable connector = new Runnable() {
public void run() {
while (!isConnected()) {
try {
String brokerUsername = MqttConfig.getInstance().getMqttQueueUsername();
String brokerPassword = MqttConfig.getInstance().getMqttQueuePassword();
setUsernameAndPassword(brokerUsername, brokerPassword);
connectToQueue();
} catch (TransportHandlerException e) {
log.error("Connection to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException ex) {
log.error("MQTT-Connector: Thread Sleep Interrupt Exception.", ex);
}
}
try {
subscribeToQueue();
} catch (TransportHandlerException e) {
log.warn("Subscription to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
}
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
/**
* This callback function will be called by message broker when some messages available to subscribed topic
*
* @param message mqtt message which is coming form agent side
* @param messageParams metadata of mqtt message
*/
@Override
public void processIncomingMessage(MqttMessage message, String... messageParams) {
String topic = messageParams[0];
String ownerAndId = topic.replace("wso2" + File.separator + "iot" + File.separator, "");
ownerAndId = ownerAndId.replace(File.separator + DoorManagerConstants.DEVICE_TYPE
+ File.separator, ":");
ownerAndId = ownerAndId.replace(File.separator + PUBLISHER_CONTEXT, "");
String owner = ownerAndId.split(":")[0];
String deviceId = ownerAndId.split(":")[1];
log.warn(deviceId);
String[] messageData = message.toString().split(":");
if (log.isDebugEnabled()) {
log.debug("Received MQTT message for: [OWNER-" + owner + "] & [DEVICE.ID-" + deviceId + "]");
}
if (messageData.length == 2) {
String lockerCurrentState = messageData[1];
float lockerStatus;
if (lockerCurrentState.equals("LOCKED")) {
lockerStatus = 0;
} else {
lockerStatus = 1;
}
try {
if (!DoorManagerServiceUtils.publishToDASLockerStatus(owner, deviceId, lockerStatus)) {
log.warn("An error occurred while trying to publish with ID [" + deviceId + "] of owner ["
+ owner + "]");
}
} catch (Exception e) {
log.error(e);
}
}
}
/**
* Publish a MQTT message to device through message broker
*
* @param topic mqtt topic which will be used to uniquely identify who are the subscribers to this topic
* @param payLoad message is to be published
* @param qos level of qos(quality of service):1,2,3
* @param retained klkkl
* @throws TransportHandlerException
*/
private void publishToAutomaticDoorLocker(String topic, String payLoad, int qos, boolean retained)
throws TransportHandlerException {
if (log.isDebugEnabled()) {
log.debug("Publishing message [" + payLoad + "to topic [" + topic + "].");
}
publishToQueue(topic, payLoad, qos, retained);
}
/**
* Publish a MQTT message to device through message broker
*
* @param deviceOwner person who own the device
* @param deviceId unique identifier for each device
* @param operation command is to executed at agent side e.g: off, on
* @param param additional payload
* @throws DeviceManagementException
* @throws DoorManagerException
*/
public void sendCommandViaMQTT(String deviceOwner, String deviceId, String operation, String param)
throws DeviceManagementException, DoorManagerException {
String topic = String.format(PUBLISHER_TOPIC, deviceOwner, deviceId);
String payload = operation + param;
try {
publishToAutomaticDoorLocker(topic, payload, 2, false);
if (param.toUpperCase().equals("LOCK")) {
if (!DoorManagerServiceUtils.publishToDASLockerStatus(deviceOwner, deviceId, 0)) {
log.warn("An error occurred whilst trying to publish with ID [" + deviceId + "] of owner [" +
deviceOwner + "]");
}
} else if (param.toUpperCase().equals("UNLOCK")) {
if (!DoorManagerServiceUtils.publishToDASLockerStatus(deviceOwner, deviceId, 1)) {
log.warn("An error occurred whilst trying to publish with ID [" + deviceId + "] of owner [" +
deviceOwner + "]");
}
}
} catch (TransportHandlerException e) {
String errorMessage = "Error publishing data to device with ID " + deviceId;
throw new DoorManagerException(errorMessage, e);
} catch (DataPublisherConfigurationException e) {
String errorMessage = "Error publishing data to DAS with ID " + deviceId;
throw new DoorManagerException(errorMessage, e);
}
}
/**
* Connection with message broker can be terminated
*/
@Override
public void disconnect() {
Runnable stopConnection = new Runnable() {
public void run() {
while (isConnected()) {
try {
closeConnection();
} catch (MqttException e) {
if (log.isDebugEnabled()) {
log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
log.error("MQTT-Terminator: Thread Sleep Interrupt Exception");
}
}
}
}
};
Thread terminatorThread = new Thread(stopConnection);
terminatorThread.setDaemon(true);
terminatorThread.start();
}
@Override
public void publishDeviceData() throws TransportHandlerException {
}
@Override
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
}
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
}
@Override
public void processIncomingMessage() {
}
@Override
public void processIncomingMessage(MqttMessage message) throws TransportHandlerException {
}
}

@ -1,81 +0,0 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api.util;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
/**
* This class provides utility functions used by REST-API.
*/
public class APIUtil {
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
if (username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@"));
}
return username;
}
public static String getTenantDomainOftheUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
return tenantDomain;
}
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.";
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
public static APIManagementProviderService getAPIManagementProviderService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
APIManagementProviderService apiManagementProviderService =
(APIManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (apiManagementProviderService == null) {
String msg = "API management provider service has not initialized.";
throw new IllegalStateException(msg);
}
return apiManagementProviderService;
}
public static JWTClientManagerService getJWTClientManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
JWTClientManagerService jwtClientManagerService =
(JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null);
if (jwtClientManagerService == null) {
String msg = "JWT Client manager service has not initialized.";
throw new IllegalStateException(msg);
}
return jwtClientManagerService;
}
}

@ -1,68 +0,0 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
public class DoorManagerServiceUtils {
private static final Log log = LogFactory.getLog(DoorManagerServiceUtils.class);
private static final String STREAM_DEFINITION = "org.wso2.iot.devices.smartLock";
private static final String STREAM_DEFINITION_VERSION = "1.0.0";
/**
* Publish door locker current status to DAS
*
* @param owner owner of the device
* @param deviceId unique identifier of device
* @param status current status of lock:- 1: open, 0: close
* @return status
*/
public static boolean publishToDASLockerStatus(String owner, String deviceId, float status)
throws DataPublisherConfigurationException {
Object payloadCurrent[] = {status};
return publishToDAS(owner, deviceId, payloadCurrent, STREAM_DEFINITION);
}
private static boolean publishToDAS(String owner, String deviceId, Object[] payloadCurrent,
String definition) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setUsername(owner);
if (ctx.getTenantDomain(true) == null) {
ctx.setTenantDomain("carbon.super", true);
}
EventsPublisherService deviceAnalyticsService = (EventsPublisherService) ctx.getOSGiService(
EventsPublisherService.class, null);
Object metaData[] = {owner, DoorManagerConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
try {
deviceAnalyticsService.publishEvent(definition, STREAM_DEFINITION_VERSION, metaData,
new Object[0], payloadCurrent);
} catch (DataPublisherConfigurationException e) {
log.error(e);
return false;
}
return true;
}
}

@ -1,108 +0,0 @@
/*
* 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.
*/
package org.homeautomation.doormanager.api.util;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class ResponsePayload {
private int statusCode;
private String messageFromServer;
private Object responseContent;
public static ResponsePayload.ResponsePayloadBuilder statusCode(int statusCode) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().statusCode(statusCode);
}
public static ResponsePayload.ResponsePayloadBuilder messageFromServer(
String messageFromServer) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().messageFromServer(messageFromServer);
}
public static ResponsePayload.ResponsePayloadBuilder responseContent(String responseContent) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().responseContent(responseContent);
}
@XmlElement
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
@XmlElement
public String getMessageFromServer() {
return messageFromServer;
}
public void setMessageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
}
@XmlElement
public Object getResponseContent() {
return responseContent;
}
public void setResponseContent(Object responseContent) {
this.responseContent = responseContent;
}
private ResponsePayload.ResponsePayloadBuilder getBuilder() {
return new ResponsePayload.ResponsePayloadBuilder();
}
public class ResponsePayloadBuilder {
private int statusCode;
private String messageFromServer;
private Object responseContent;
public ResponsePayloadBuilder statusCode(int statusCode) {
this.statusCode = statusCode;
return this;
}
public ResponsePayloadBuilder messageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
return this;
}
public ResponsePayloadBuilder responseContent(String responseContent) {
this.responseContent = responseContent;
return this;
}
public ResponsePayload build() {
ResponsePayload payload = new ResponsePayload();
payload.setStatusCode(statusCode);
payload.setMessageFromServer(messageFromServer);
payload.setResponseContent(responseContent);
return payload;
}
}
}

@ -1,5 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
@ -30,72 +29,58 @@
<!-- Device related APIs -->
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/devices/*</url>
<path>/device-mgt/doormanager/user</path>
<url>/device/*</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
<scope>doormanager_user</scope>
</Permission>
<Permission>
<name>Add device</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/register</url>
<method>PUT</method>
<scope>emm_admin,emm_user</scope>
<name>Remove device</name>
<path>/device-mgt/doormanager/user</path>
<url>/device/*</url>
<method>DELETE</method>
<scope>doormanager_user</scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/doormanager/download</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Generate link to download</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/doormanager/generate_link</url>
<path>/device-mgt/doormanager/user</path>
<url>/device/download</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
<scope>doormanager_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/devices/update/*</url>
<path>/device-mgt/doormanager/user</path>
<url>/device/*</url>
<method>POST</method>
<scope>emm_admin,emm_user</scope>
<scope>doormanager_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/devices/remove/*</url>
<method>DELETE</method>
<scope>emm_admin,emm_user</scope>
<name>Get Devices</name>
<path>/device-mgt/doormanager/user</path>
<url>/device</url>
<method>GET</method>
<scope>doormanager_user</scope>
</Permission>
<Permission>
<name>Assign user</name>
<path>/device-mgt/user/device/assign-user</path>
<url>/device/assign-user</url>
<name>Register Device</name>
<path>/device-mgt/doormanager/user</path>
<url>/device/register</url>
<method>POST</method>
<scope>emm_admin,emm_user</scope>
<scope>doormanager_device</scope>
</Permission>
<Permission>
<name>Change status</name>
<path>/device-mgt/user/device/change-status</path>
<url>/device/change-status</url>
<name>Control Sensor</name>
<path>/device-mgt/doormanager/user</path>
<url>/device/*/change-status</url>
<method>POST</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Get current status</name>
<path>/device-mgt/user/device/</path>
<url>/device/current-status</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
<scope>doormanager_user</scope>
</Permission>
<Permission>
<name>Get user Info</name>
<path>/device-mgt/user/device/</path>
<url>/device/get-user-info</url>
<name>Get Stats</name>
<path>/device-mgt/doormanager/user</path>
<url>/device/stats/*</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
<scope>doormanager_device</scope>
</Permission>
</PermissionConfiguration>

@ -1,20 +1,19 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~ Copyright 2005-2013 WSO2, Inc. (http://wso2.com)
~
~ 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.
~ Licensed 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.
~ 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.
-->
<!--

@ -1,19 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ 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.
~ 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.
-->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
@ -22,24 +23,14 @@
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="DoorManagerController" address="/">
<jaxrs:server id="doormanager" address="/">
<jaxrs:serviceBeans>
<bean id="DoorManagerControllerService"
class="org.homeautomation.doormanager.api.DoorManagerControllerServiceImpl">
<property name="DoorManagerMQTTConnector" ref="communicationHandler"/>
</bean>
<bean id="DoorManagerManagerService"
class="org.homeautomation.doormanager.api.DoorManagerManagerServiceImpl">
<bean id="DoorManagerService"
class="org.homeautomation.doormanager.api.DoorManagerServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
<bean id="communicationHandler"
class="org.homeautomation.doormanager.api.transport.DoorManagerMQTTConnector">
</bean>
</beans>
</beans>

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
@ -16,11 +16,13 @@
~ specific language governing permissions and limitations
~ under the License.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Sample-Webapp-Controller</display-name>
metadata-complete="true">
<display-name>WSO2 IoT Server</display-name>
<description>WSO2 IoT Server</description>
<servlet>
<servlet-name>CXFServlet</servlet-name>
@ -41,7 +43,7 @@
</context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>providerTenantDomain</param-name>
@ -58,4 +60,4 @@
<param-value>admin</param-value>
</context-param>
</web-app>
</web-app>

@ -1,21 +1,24 @@
<!--/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<?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.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
@ -25,9 +28,9 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<version>1.0.0-SNAPSHOT</version>
<artifactId>org.homeautomation.doormanager.plugin</artifactId>
<artifactId>${project-base-package}.plugin</artifactId>
<packaging>bundle</packaging>
<name>org.homeautomation.doormanager.plugin</name>
<name>${project-base-package}.plugin</name>
<url>http://wso2.org</url>
<build>
<plugins>
@ -41,8 +44,8 @@
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
@ -52,32 +55,32 @@
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>org.homeautomation.doormanager.plugin</Bundle-SymbolicName>
<Bundle-Name>org.homeautomation.doormanager.plugin</Bundle-Name>
<Bundle-SymbolicName>${project-base-package}.plugin</Bundle-SymbolicName>
<Bundle-Name>${project-base-package}.plugin</Bundle-Name>
<Bundle-Version>1.0.0-SNAPSHOT</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.homeautomation.doormanager.plugin.internal</Private-Package>
<Private-Package>${project-base-package}.plugin.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.naming,
javax.sql,
javax.xml.parsers,
javax.net,
javax.net.ssl,
org.w3c.dom,
javax.naming;resolution:=optional,
javax.sql;resolution:=optional,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.context.*,
org.wso2.carbon.ndatasource.core,
org.wso2.carbon.device.mgt.iot.*,
org.wso2.carbon.user.api.*,
org.wso2.carbon.user.core.service.*
org.wso2.carbon.device.mgt.extensions.feature.mgt.*,
org.wso2.carbon.utils.*,
org.wso2.carbon.base,
org.wso2.carbon.context,
org.wso2.carbon.core,
org.wso2.carbon.core.util,
org.wso2.carbon.ndatasource.core,
org.wso2.carbon.device.mgt.iot.devicetype.*
</Import-Package>
<Export-Package>
!org.homeautomation.doormanager.plugin.internal,
org.homeautomation.doormanager.plugin.*
!${project-base-package}.plugin.internal,
${project-base-package}.plugin.*
</Export-Package>
</instructions>
</configuration>
@ -85,6 +88,10 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
@ -101,13 +108,25 @@
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
@ -118,66 +137,8 @@
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
</dependencies>
</project>

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
@ -18,17 +18,46 @@
package org.homeautomation.doormanager.plugin.constants;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
/**
* Device type specific constants which includes all transport protocols configurations,
* stream definition and device specific dome constants
*/
public class DoorManagerConstants {
public final static String STATE_LOCK = "LOCK";
public final static String STATE_UNLOCK = "UNLOCK";
public final static String STATE_BULB_ON = "ON";
public final static String STATE_BULB_OFF = "OFF";
//sensor events summerized table name
public static final String SENSOR_TYPE1_EVENT_TABLE = "ORG_WSO2_IOT_DEVICES_smartLock";
public static final String SENSOR_TYPE2_EVENT_TABLE = "ORG_WSO2_IOT_DEVICES_smartFan";
public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
public final static String SENSOR_TYPE1 = "smartLock";
public final static String SENSOR_TYPE2 = "smartFan";
//mqtt transport related constants
//mqtt tranport related constants
public static final String MQTT_ADAPTER_TOPIC_PROPERTY_NAME = "mqtt.adapter.topic";
public static final String ADAPTER_TOPIC_PROPERTY = "topic";
public static final String MQTT_TOPIC_FOR_BULB = "/bulb/command";
public static final String MQTT_TOPIC_FOR_FAN = "/fan/command";
public static final String MQTT_TOPIC_FOR_LOCK ="/lock/command";
public final static String DEVICE_TYPE = "doormanager";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "doormanager_DEVICE_ID";
public final static String DEVICE_PLUGIN_DEVICE_SERIAL_NUMBER = "SERIAL_NUMBER";
public final static String DEVICE_PLUGIN_DEVICE_UID_OF_USER = "UID_of_USER";
public static final String DATA_SOURCE_NAME = "jdbc/doormanagerDM_DB";
public final static String DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN = "ACCESS_TOKEN";
public final static String DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN = "REFRESH_TOKEN";
public final static String DEVICE_CLAIMS_ACCESS_TOKEN = "http://wso2.org/claims/lock/accesstoken";
public final static String DEVICE_CLAIMS_REFRESH_TOKEN = "http://wso2.org/claims/lock/refreshtoken";
public final static String DEVICE_CLAIMS_CARD_NUMBER = "http://wso2.org/claims/lock/cardnumber";
public final static String DEVICE_META_INFO_DEVICE_ID = "meta_deviceId:";
public final static String DEVICE_META_INFO_DEVICE_TYPE = "meta_deviceType:";
public final static String DEVICE_META_INFO_TIME = "meta_time";
public final static String DEVICE_SCOPE_INFO_DEVICE_TYPE = "device_type_";
public final static String DEVICE_SCOPE_INFO_DEVICE_ID = " device_";
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
@ -11,13 +11,16 @@
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.plugin.exception;
package org.homeautomation.doormanager.plugin.exception;
/**
* Device type plugin exception handler
*/
public class DoorManagerDeviceMgtPluginException extends Exception {
private String errorMessage;
@ -53,4 +56,4 @@ public class DoorManagerDeviceMgtPluginException extends Exception {
this.errorMessage = errorMessage;
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
@ -11,23 +11,23 @@
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAOUtil;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAO;
import org.homeautomation.doormanager.plugin.impl.feature.DoorManagerFeatureManager;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.user.api.UserStoreException;
@ -36,25 +36,28 @@ import org.wso2.carbon.user.core.service.RealmService;
import java.util.List;
public class DoorManager implements DeviceManager {
private static final Log log = LogFactory.getLog(DoorManager.class);
private static final DoorManagerDAOUtil DOOR_MANAGER_DAO = new DoorManagerDAOUtil();
private PrivilegedCarbonContext ctx;
/**
* This represents the door manager implementation of DeviceManagerService.
*/
public class DoorManagerManager implements DeviceManager {
private static final Log log = LogFactory.getLog(DoorManagerManager.class);
private static final DoorManagerDAO deviceTypeDAO = new DoorManagerDAO();
private FeatureManager featureManager = new DoorManagerFeatureManager();
@Override
public FeatureManager getFeatureManager() {
return null;
return featureManager;
}
@Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration)
throws DeviceManagementException {
public boolean saveConfiguration(PlatformConfiguration platformConfiguration) throws DeviceManagementException {
return false;
}
@Override
public TenantConfiguration getConfiguration() throws DeviceManagementException {
public PlatformConfiguration getConfiguration() throws DeviceManagementException {
return null;
}
@ -63,18 +66,18 @@ public class DoorManager implements DeviceManager {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new Automatic Door Locker device : " + device.getDeviceIdentifier());
log.debug("Enrolling a new doormanager device : " + device.getDeviceIdentifier());
}
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().addDevice(device);
DoorManagerDAOUtil.commitTransaction();
DoorManagerDAO.beginTransaction();
status = deviceTypeDAO.getDoorManagerDAO().addDevice(device);
DoorManagerDAO.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAOUtil.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
e1.printStackTrace();
DoorManagerDAO.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException iotDAOEx) {
log.warn("Error occurred while roll back the device enrol transaction :" + device.toString(), iotDAOEx);
}
String msg = "Error while enrolling the Automatic Door Locker device : " + device.getDeviceIdentifier();
String msg = "Error while enrolling the door manager device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -86,18 +89,19 @@ public class DoorManager implements DeviceManager {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Automatic Door Locker device enrollment data");
log.debug("Modifying the door manager device enrollment data");
}
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().updateDevice(device);
DoorManagerDAOUtil.commitTransaction();
DoorManagerDAO.beginTransaction();
status = deviceTypeDAO.getDoorManagerDAO().updateDevice(device);
DoorManagerDAO.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAOUtil.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
e1.printStackTrace();
DoorManagerDAO.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while updating the enrollment of the Automatic Door Locker device : " +
String msg = "Error while updating the enrollment of the door manager device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
@ -110,18 +114,19 @@ public class DoorManager implements DeviceManager {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling Automatic Door Locker device : " + deviceId);
log.debug("Dis-enrolling door manager device : " + deviceId);
}
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().deleteDevice(deviceId.getId());
DoorManagerDAOUtil.commitTransaction();
DoorManagerDAO.beginTransaction();
status = deviceTypeDAO.getDoorManagerDAO().deleteDevice(deviceId.getId());
DoorManagerDAO.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAOUtil.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
e1.printStackTrace();
DoorManagerDAO.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while removing the Automatic Door Locker device : " + deviceId.getId();
String msg = "Error while removing the door manager device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -133,14 +138,15 @@ public class DoorManager implements DeviceManager {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Automatic Door Locker device : " + deviceId.getId());
log.debug("Checking the enrollment of door manager device : " + deviceId.getId());
}
Device iotDevice = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().getDevice(deviceId.getId());
Device iotDevice =
deviceTypeDAO.getDoorManagerDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (DoorManagerDeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of Automatic Door Locker device : " +
String msg = "Error while checking the enrollment status of door manager device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
@ -164,12 +170,11 @@ public class DoorManager implements DeviceManager {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Automatic Door Locker device : " + deviceId.getId());
log.debug("Getting the details of door manager device : " + deviceId.getId());
}
device = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().getDevice(deviceId.getId());
device = deviceTypeDAO.getDoorManagerDAO().getDevice(deviceId.getId());
} catch (DoorManagerDeviceMgtPluginException e) {
String msg = "Error while fetching the Automatic Door Locker device : " + deviceId.getId();
String msg = "Error while fetching the door manager device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -204,7 +209,7 @@ public class DoorManager implements DeviceManager {
@Override
public boolean requireDeviceAuthorization() {
return false;
return true;
}
@Override
@ -212,21 +217,20 @@ public class DoorManager implements DeviceManager {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug(
"updating the details of Automatic Door Locker device : " + deviceIdentifier);
log.debug("updating the details of door manager device : " + deviceIdentifier);
}
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().updateDevice(device);
DoorManagerDAOUtil.commitTransaction();
DoorManagerDAO.beginTransaction();
status = deviceTypeDAO.getDoorManagerDAO().updateDevice(device);
DoorManagerDAO.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAOUtil.rollbackTransaction();
DoorManagerDAO.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg =
"Error while updating the Automatic Door Locker device : " + deviceIdentifier;
"Error while updating the door manager device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -238,45 +242,27 @@ public class DoorManager implements DeviceManager {
List<Device> devices;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Automatic Door Locker devices");
log.debug("Fetching the details of all door manager devices");
}
devices = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().getAllDevices();
devices = deviceTypeDAO.getDoorManagerDAO().getAllDevices();
} catch (DoorManagerDeviceMgtPluginException e) {
String msg = "Error while fetching all Automatic Door Locker devices.";
String msg = "Error while fetching all door manager devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return devices;
}
/**
* Get userStore manager
*
* @return
* @throws UserStoreException
*/
public UserStoreManager getUserStoreManager() throws UserStoreException {
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
PrivilegedCarbonContext.startTenantFlow();
ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(tenantDomain, true);
if (log.isDebugEnabled()) {
log.debug("Getting thread local carbon context for tenant domain: " + tenantDomain);
}
RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
return realmService.getTenantUserRealm(ctx.getTenantId()).getUserStoreManager();
}
public boolean assignUserToLock(DoorLockSafe doorLockSafe) throws DoorManagerDeviceMgtPluginException {
boolean status;
try {
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().registerDoorLockSafe(doorLockSafe);
DoorManagerDAOUtil.commitTransaction();
DoorManagerDAO.beginTransaction();
status = deviceTypeDAO.getDoorManagerDAO().registerDoorLockSafe(doorLockSafe);
DoorManagerDAO.commitTransaction();
return status;
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAOUtil.rollbackTransaction();
DoorManagerDAO.rollbackTransaction();
throw new DoorManagerDeviceMgtPluginException(e);
} catch (DoorManagerDeviceMgtPluginException e1) {
String msg = "Error while adding new access card to user to control the lock "
@ -290,10 +276,9 @@ public class DoorManager implements DeviceManager {
public boolean checkCardDoorAssociation(String cardNumber, String deviceId)
throws DoorManagerDeviceMgtPluginException {
boolean status;
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().checkCardDoorAssociation(cardNumber, deviceId);
DoorManagerDAOUtil.commitTransaction();
DoorManagerDAO.beginTransaction();
status = deviceTypeDAO.getDoorManagerDAO().checkCardDoorAssociation(cardNumber, deviceId);
DoorManagerDAO.commitTransaction();
return status;
}
}
}

@ -0,0 +1,91 @@
/*
* 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.
*/
package org.homeautomation.doormanager.plugin.impl;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.internal.DoorManagerManagementDataHolder;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import java.util.HashMap;
import java.util.Map;
public class DoorManagerManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
private PushNotificationConfig pushNotificationConfig;
@Override
public String getType() {
return DoorManagerConstants.DEVICE_TYPE;
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager = new DoorManagerManager();
this.pushNotificationConfig = this.populatePushNotificationConfig();
}
private PushNotificationConfig populatePushNotificationConfig() {
DeviceManagementConfiguration deviceManagementConfiguration = DoorManagerManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(DoorManagerConstants.DEVICE_TYPE,
DoorManagerConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig sourceConfig =
deviceManagementConfiguration.getPushNotificationConfig();
Map<String, String> staticProps = new HashMap<>();
for (org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig.Property
property : sourceConfig.getProperties()) {
staticProps.put(property.getName(), property.getValue());
}
return new PushNotificationConfig(sourceConfig.getPushNotificationProvider(), staticProps);
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public ProvisioningConfig getProvisioningConfig() {
DeviceManagementConfiguration deviceManagementConfiguration = DoorManagerManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(DoorManagerConstants.DEVICE_TYPE,
DoorManagerConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
boolean sharedWithAllTenants = deviceManagementConfiguration.getDeviceManagementConfigRepository()
.getProvisioningConfig().isSharedWithAllTenants();
return new ProvisioningConfig(DoorManagerConstants.DEVICE_TYPE_PROVIDER_DOMAIN, sharedWithAllTenants);
}
@Override
public PushNotificationConfig getPushNotificationConfig() {
return pushNotificationConfig;
}
}

@ -1,108 +0,0 @@
/*
* 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.
*/
package org.homeautomation.doormanager.plugin.impl;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List;
public class DoorManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
@Override
public String getType() {
return DoorManagerConstants.DEVICE_TYPE;
}
@Override
public String getProviderTenantDomain() {
return "carbon.super";
}
@Override
public boolean isSharedWithAllTenants() {
return true;
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager = new DoorManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> deviceIds)
throws DeviceManagementException {
}
@Override
public Application[] getApplications(String domain, int pageNumber, int size)
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
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> deviceIdentifiers)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUsers(Operation operation, List<String> userNameList)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUserRoles(Operation operation, List<String> userRoleList)
throws ApplicationManagementException {
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
@ -11,7 +11,7 @@
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@ -22,7 +22,9 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.dao.impl.DoorManagerDAO;
import org.homeautomation.doormanager.plugin.impl.dao.impl.DoorManagerDAOImpl;
import org.homeautomation.doormanager.plugin.internal.DoorManagerManagementDataHolder;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import javax.naming.Context;
import javax.naming.InitialContext;
@ -31,25 +33,31 @@ import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DoorManagerDAOUtil {
/**
* Database handler which is specified for door manager type
*/
public class DoorManagerDAO {
private static final Log log = LogFactory.getLog(DoorManagerDAOUtil.class);
private static final Log log = LogFactory.getLog(DoorManagerDAO.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
public DoorManagerDAOUtil() {
initAutomaticDoorLOckerDAO();
public DoorManagerDAO() {
initDoorManagerDAO();
}
public static void initAutomaticDoorLOckerDAO() {
public static void initDoorManagerDAO() {
DeviceManagementConfiguration deviceManagementConfiguration = DoorManagerManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(DoorManagerConstants.DEVICE_TYPE,
DoorManagerConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
String datasource = deviceManagementConfiguration.getDeviceManagementConfigRepository().getDataSourceConfig()
.getJndiLookupDefinition().getJndiName();
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(DoorManagerConstants.DATA_SOURCE_NAME);
dataSource = (DataSource) ctx.lookup(datasource);
} catch (NamingException e) {
log.error("Error while looking up the data source: " +
DoorManagerConstants.DATA_SOURCE_NAME);
log.error("Error while looking up the data source: " + datasource, e);
}
}
public static void beginTransaction() throws DoorManagerDeviceMgtPluginException {
@ -58,8 +66,7 @@ public class DoorManagerDAOUtil {
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new DoorManagerDeviceMgtPluginException(
"Error occurred while retrieving datasource connection", e);
throw new DoorManagerDeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
}
}
@ -68,8 +75,8 @@ public class DoorManagerDAOUtil {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new DoorManagerDeviceMgtPluginException(
"Error occurred while retrieving data source connection", e);
throw new DoorManagerDeviceMgtPluginException("Error occurred while retrieving data source connection",
e);
}
}
return currentConnection.get();
@ -82,13 +89,12 @@ public class DoorManagerDAOUtil {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, " +
"hence commit has not been attempted");
log.debug("Datasource connection associated with the current thread is null, hence commit " +
"has not been attempted");
}
}
} catch (SQLException e) {
throw new DoorManagerDeviceMgtPluginException(
"Error occurred while committing the transaction", e);
throw new DoorManagerDeviceMgtPluginException("Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
@ -114,9 +120,8 @@ public class DoorManagerDAOUtil {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug(
"Datasource connection associated with the current thread is null, " +
"hence rollback has not been attempted");
log.debug("Datasource connection associated with the current thread is null, hence rollback " +
"has not been attempted");
}
}
} catch (SQLException e) {
@ -126,7 +131,7 @@ public class DoorManagerDAOUtil {
}
}
public DoorManagerDAO getAutomaticDoorLockerDeviceDAO() {
return new DoorManagerDAO();
public DoorManagerDAOImpl getDoorManagerDAO() {
return new DoorManagerDAOImpl();
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
@ -11,7 +11,7 @@
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@ -23,8 +23,8 @@ import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAOUtil;
import org.homeautomation.doormanager.plugin.impl.dao.util.DoorManagerUtils;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAO;
import org.homeautomation.doormanager.plugin.impl.util.DoorManagerUtils;
import org.wso2.carbon.device.mgt.common.Device;
import java.sql.Connection;
@ -35,78 +35,129 @@ import java.util.ArrayList;
import java.util.List;
/**
* Device Dao for automatic door locker Devices.
* Implements IotDeviceDAO for door manager Devices.
*/
public class DoorManagerDAO {
public class DoorManagerDAOImpl {
private static final Log log = LogFactory.getLog(DoorManagerDAO.class);
private static final Log log = LogFactory.getLog(DoorManagerDAOImpl.class);
public Device getDevice(String deviceId) throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
Device automaticDoorLockerDevice = null;
Device iotDevice = null;
ResultSet resultSet = null;
try {
conn = DoorManagerDAOUtil.getConnection();
conn = DoorManagerDAO.getConnection();
String selectDBQuery =
"SELECT doormanager_DEVICE_ID, DEVICE_NAME" +
" FROM doormanager_DEVICE WHERE doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, deviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
automaticDoorLockerDevice = new Device();
automaticDoorLockerDevice.setName(resultSet.getString(
iotDevice = new Device();
iotDevice.setName(resultSet.getString(
DoorManagerConstants.DEVICE_PLUGIN_DEVICE_NAME));
List<Device.Property> properties = new ArrayList<>();
automaticDoorLockerDevice.setProperties(properties);
if (log.isDebugEnabled()) {
log.debug("Locker Manager service " + deviceId + " data has been fetched from" +
"Locker Manager database.");
log.debug("doormanager device " + deviceId + " data has been fetched from " +
"doormanager database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching Locker Manager device : '" + deviceId + "'";
String msg = "Error occurred while fetching doormanager device : '" + deviceId + "'";
log.error(msg, e);
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAOUtil.closeConnection();
DoorManagerDAO.closeConnection();
}
return automaticDoorLockerDevice;
return iotDevice;
}
public boolean addDevice(Device automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
public boolean addDevice(Device device) throws DoorManagerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAOUtil.getConnection();
conn = DoorManagerDAO.getConnection();
String createDBQuery =
"INSERT INTO doormanager_DEVICE(doormanager_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?)";
"INSERT INTO doormanager_DEVICE(doormanager_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, automaticDoorLOcker.getDeviceIdentifier());
stmt.setString(2, automaticDoorLOcker.getName());
stmt.setString(3, DoorManagerUtils.getDeviceProperty(
automaticDoorLOcker.getProperties(),
DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN));
stmt.setString(4, DoorManagerUtils.getDeviceProperty(
automaticDoorLOcker.getProperties(),
DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN));
stmt.setString(1, device.getDeviceIdentifier());
stmt.setString(2, device.getName());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Locker Manager device " + automaticDoorLOcker.getDeviceIdentifier() +
" data has been added to the Locker Manager database.");
log.debug("doormanager device " + device.getDeviceIdentifier() + " data has been" +
" added to the doormanager database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the Locker Manager device '" +
automaticDoorLOcker.getDeviceIdentifier() + "' to the Locker Manager db.";
String msg = "Error occurred while adding the doormanager device '" +
device.getDeviceIdentifier() + "' to the doormanager db.";
log.error(msg, e);
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean updateDevice(Device device) throws DoorManagerDeviceMgtPluginException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAO.getConnection();
String updateDBQuery =
"UPDATE doormanager_DEVICE SET DEVICE_NAME = ? WHERE doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
if (device.getProperties() == null) {
device.setProperties(new ArrayList<Device.Property>());
}
stmt.setString(1, device.getName());
stmt.setString(2, device.getDeviceIdentifier());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("doormanager device " + device.getDeviceIdentifier() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the doormanager device '" +
device.getDeviceIdentifier() + "' data.";
log.error(msg, e);
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean deleteDevice(String deviceId) throws DoorManagerDeviceMgtPluginException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAO.getConnection();
String deleteDBQuery =
"DELETE FROM doormanager_DEVICE WHERE doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, deviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("doormanager device " + deviceId + " data has deleted" +
" from the doormanager database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting doormanager device " + deviceId;
log.error(msg, e);
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
@ -115,12 +166,46 @@ public class DoorManagerDAO {
return status;
}
public List<Device> getAllDevices() throws DoorManagerDeviceMgtPluginException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device device;
List<Device> iotDevices = new ArrayList<>();
try {
conn = DoorManagerDAO.getConnection();
String selectDBQuery =
"SELECT doormanager_DEVICE_ID, DEVICE_NAME " +
"FROM doormanager_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
device = new Device();
device.setDeviceIdentifier(resultSet.getString(DoorManagerConstants.DEVICE_PLUGIN_DEVICE_ID));
device.setName(resultSet.getString(DoorManagerConstants.DEVICE_PLUGIN_DEVICE_NAME));
List<Device.Property> propertyList = new ArrayList<>();
device.setProperties(propertyList);
}
if (log.isDebugEnabled()) {
log.debug("All doormanager device details have fetched from doormanager database.");
}
return iotDevices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all doormanager device data'";
log.error(msg, e);
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAO.closeConnection();
}
}
public boolean registerDoorLockSafe(DoorLockSafe automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAOUtil.getConnection();
conn = DoorManagerDAO.getConnection();
String createDBQuery =
"INSERT INTO REGISTERED_DOORLOCK_SAFE(doormanager_DEVICE_ID, SERIAL_NUMBER, UID_of_USER, POLICY, " +
"EMAIL_ADDRESS, ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?, ?, ?, ?)";
@ -153,11 +238,11 @@ public class DoorManagerDAO {
public boolean isDoorLockSafeRegistered(String serialNumber, String deviceId) throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
conn = DoorManagerDAOUtil.getConnection();
conn = DoorManagerDAO.getConnection();
String selectDBQuery =
"SELECT SERIAL_NUMBER FROM REGISTERED_DOORLOCK_SAFE WHERE SERIAL_NUMBER = ? AND doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
@ -178,17 +263,17 @@ public class DoorManagerDAO {
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAOUtil.closeConnection();
DoorManagerDAO.closeConnection();
}
}
public boolean isUserAllowed(String serialNumber, String UIDofUser, String deviceId) throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
conn = DoorManagerDAOUtil.getConnection();
conn = DoorManagerDAO.getConnection();
String selectDBQuery =
"SELECT UID_OF_USER FROM REGISTERED_DOORLOCK_SAFE WHERE SERIAL_NUMBER = ? AND DOORMANAGER_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
@ -221,7 +306,7 @@ public class DoorManagerDAO {
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAOUtil.closeConnection();
DoorManagerDAO.closeConnection();
}
}
@ -229,10 +314,10 @@ public class DoorManagerDAO {
public boolean shareDoorLockSafe(DoorLockSafe automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAOUtil.getConnection();
conn = DoorManagerDAO.getConnection();
String createDBQuery =
"INSERT INTO SHARED_DOORLOCK_SAFE(doormanager_DEVICE_ID, SERIAL_NUMBER, UID_of_USER, POLICY) VALUES (?, ?, ?, ?)";
stmt = conn.prepareStatement(createDBQuery);
@ -262,15 +347,14 @@ public class DoorManagerDAO {
public boolean checkCardDoorAssociation(String cardNum, String deviceID) throws DoorManagerDeviceMgtPluginException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
ResultSet resultSet;
try {
conn = DoorManagerDAOUtil.getConnection();
conn = DoorManagerDAO.getConnection();
String selectDBQuery = "SELECT * FROM REGISTERED_DOORLOCK_SAFE WHERE UID_of_USER = ? AND doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, cardNum);
stmt.setString(2, deviceID);
resultSet = stmt.executeQuery();
String result;
if (resultSet.next()) {
return true;
} else {
@ -288,10 +372,10 @@ public class DoorManagerDAO {
public String getUserEmailAddress(String cardNum) throws DoorManagerDeviceMgtPluginException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
ResultSet resultSet;
String email;
try {
conn = DoorManagerDAOUtil.getConnection();
conn = DoorManagerDAO.getConnection();
String selectDBQuery = "SELECT EMAIL_ADDRESS FROM REGISTERED_DOORLOCK_SAFE WHERE UID_of_USER = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, cardNum);
@ -312,12 +396,12 @@ public class DoorManagerDAO {
public List<String> getUserCredentials(String deviceId, String UIDofUser) throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<String> userCredentials = new ArrayList<>();
try {
conn = DoorManagerDAOUtil.getConnection();
conn = DoorManagerDAO.getConnection();
String selectDBQuery =
"SELECT ACCESS_TOKEN, REFRESH_TOKEN FROM REGISTERED_DOORLOCK_SAFE WHERE DOORMANAGER_DEVICE_ID = ? AND UID_OF_USER = ?";
stmt = conn.prepareStatement(selectDBQuery);
@ -342,133 +426,7 @@ public class DoorManagerDAO {
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAOUtil.closeConnection();
}
}
public List<String> getRegisteredDoorLocks(String deviceId) throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<String> doorLockSafes = new ArrayList<>();
try {
conn = DoorManagerDAOUtil.getConnection();
String selectDBQuery =
"SELECT SERIAL_NUMBER FROM REGISTERED_DOORLOCK_SAFE WHERE doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, deviceId);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
doorLockSafes.add(resultSet.getString(DoorManagerConstants.DEVICE_PLUGIN_DEVICE_SERIAL_NUMBER));
}
if (log.isDebugEnabled()) {
log.debug("All Locker Manager device details have fetched from Automatic Door Locker database.");
}
return doorLockSafes;
} catch (SQLException e) {
String msg = "Error occurred while fetching all Automatic Door Locker device data'";
log.error(msg, e);
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAOUtil.closeConnection();
}
}
public boolean updateDevice(Device automaticDoorLocker) throws DoorManagerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAOUtil.getConnection();
String updateDBQuery =
"UPDATE doormanager_DEVICE SET DEVICE_NAME = ? WHERE doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
if (automaticDoorLocker.getProperties() == null) {
automaticDoorLocker.setProperties(new ArrayList<Device.Property>());
}
stmt.setString(1, automaticDoorLocker.getName());
stmt.setString(2, automaticDoorLocker.getDeviceIdentifier());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Locker Manager device " + automaticDoorLocker.getDeviceIdentifier() +
" data has been modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Locker Manager device '" +
automaticDoorLocker.getDeviceIdentifier() + "' data.";
log.error(msg, e);
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean deleteDevice(String deviceId) throws DoorManagerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAOUtil.getConnection();
String deleteDBQuery =
"DELETE FROM doormanager_DEVICE WHERE doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, deviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Automatic Door Locker device " + deviceId + " data has deleted" +
" from the Automatic Door Locker database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting Automatic Door Locker device " + deviceId;
log.error(msg, e);
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, null);
}
return status;
}
public List<Device> getAllDevices() throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device connectedCupDevice;
List<Device> iotDevices = new ArrayList<>();
try {
conn = DoorManagerDAOUtil.getConnection();
String selectDBQuery =
"SELECT doormanager_DEVICE_ID, DEVICE_NAME FROM doormanager_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
connectedCupDevice = new Device();
connectedCupDevice.setDeviceIdentifier(resultSet.getString(
DoorManagerConstants.DEVICE_PLUGIN_DEVICE_ID));
connectedCupDevice.setName(resultSet.getString(
DoorManagerConstants.DEVICE_PLUGIN_DEVICE_NAME));
}
if (log.isDebugEnabled()) {
log.debug("All Locker Manager device details have fetched from Automatic Door Locker database.");
}
return iotDevices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all Automatic Door Locker device data'";
log.error(msg, e);
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAOUtil.closeConnection();
DoorManagerDAO.closeConnection();
}
}
}
}

@ -1,86 +0,0 @@
/*
* Copyright (c) 2015, 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.
*/
package org.homeautomation.doormanager.plugin.impl.dao.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Contains utility methods used by Automatic Door Locker
*/
public class DoorManagerUtils {
private static Log log = LogFactory.getLog(DoorManagerUtils.class);
public static String getDeviceProperty(List<Device.Property> deviceProperties, String propertyKey) {
String deviceProperty = "";
for (Device.Property property : deviceProperties) {
if (propertyKey.equals(property.getName())) {
deviceProperty = property.getValue();
}
}
return deviceProperty;
}
public static Device.Property getProperty(String property, String value) {
if (property != null) {
Device.Property prop = new Device.Property();
prop.setName(property);
prop.setValue(value);
return prop;
}
return null;
}
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}
}

@ -0,0 +1,61 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.
*/
package org.homeautomation.doormanager.plugin.impl.feature;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
import java.util.List;
/**
* Device type specific feature management server
*/
public class DoorManagerFeatureManager implements FeatureManager {
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
return false;
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
return false;
}
@Override
public Feature getFeature(String name) throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeature(DoorManagerConstants.DEVICE_TYPE, name);
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeatures(DoorManagerConstants.DEVICE_TYPE);
}
@Override
public boolean removeFeature(String name) throws DeviceManagementException {
return false;
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
return false;
}
}

@ -0,0 +1,50 @@
/*
* 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.
*/
package org.homeautomation.doormanager.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource;
import java.io.File;
/**
* Provides methods for initializing the database script.
*/
public class DeviceSchemaInitializer extends DatabaseCreator{
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
+ File.separator + "cdm" + File.separator + "plugins" + File.separator;
public DeviceSchemaInitializer(DataSource dataSource) {
super(dataSource);
}
@Override
protected String getDbScriptLocation(String databaseType) {
String scriptName = databaseType + ".sql";
if (log.isDebugEnabled()) {
log.debug("Loading database script from :" + scriptName);
}
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
}
}

@ -0,0 +1,103 @@
/*
* 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.
*/
package org.homeautomation.doormanager.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.internal.DoorManagerManagementDataHolder;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.event.output.adapter.core.MessageType;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* Contains utility methods used by doormanager plugin.
*/
public class DoorManagerUtils {
private static Log log = LogFactory.getLog(org.homeautomation.doormanager.plugin.impl.util.DoorManagerUtils.class);
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}
public static void setupDeviceManagementSchema() throws DoorManagerDeviceMgtPluginException {
DeviceManagementConfiguration deviceManagementConfiguration = DoorManagerManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(DoorManagerConstants.DEVICE_TYPE,
DoorManagerConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
String datasource = deviceManagementConfiguration.getDeviceManagementConfigRepository().getDataSourceConfig()
.getJndiLookupDefinition().getJndiName();
try {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(datasource);
DeviceSchemaInitializer initializer = new DeviceSchemaInitializer(dataSource);
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} catch (NamingException e) {
log.error("Error while looking up the data source: " + datasource, e);
} catch (Exception e) {
throw new DoorManagerDeviceMgtPluginException("Error occurred while initializing Iot Device " +
"Management database schema", e);
}
}
}

@ -0,0 +1,49 @@
/*
* 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.
*/
package org.homeautomation.doormanager.plugin.internal;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
/**
* DataHolder class of doormanager plugins component.
*/
public class DoorManagerManagementDataHolder {
private DeviceTypeConfigService deviceTypeConfigService;
private static DoorManagerManagementDataHolder thisInstance = new DoorManagerManagementDataHolder();
private DoorManagerManagementDataHolder() {
}
public static DoorManagerManagementDataHolder getInstance() {
return thisInstance;
}
public DeviceTypeConfigService getDeviceTypeConfigService() {
return deviceTypeConfigService;
}
public void setDeviceTypeConfigService(
DeviceTypeConfigService deviceTypeConfigService) {
this.deviceTypeConfigService = deviceTypeConfigService;
}
}

@ -1,74 +0,0 @@
/*
* 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.
*/
package org.homeautomation.doormanager.plugin.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.impl.DoorManagerService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
/**
* @scr.component name="org.homeautomation.doormanager.plugin.internal.DoorManagerManagementServiceComponent"
* immediate="true"
*/
public class DoorManagerManagementServiceComponent {
private static final Log log = LogFactory.getLog(DoorManagerManagementServiceComponent.class);
private ServiceRegistration automaticDoorLocker;
protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("Activating Door Opener Device Management Service Component");
}
try {
BundleContext bundleContext = ctx.getBundleContext();
automaticDoorLocker =
bundleContext.registerService(DeviceManagementService.class.getName(),
new DoorManagerService(), null);
if (log.isDebugEnabled()) {
log.debug("DoorOpener Device Management Service Component has been successfully activated");
}
} catch (Throwable e) {
log.error("Error occurred while activating DoorOpener Device Management Service Component", e);
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating Door Opener Device Management Service Component");
}
try {
if (automaticDoorLocker != null) {
automaticDoorLocker.unregister();
}
if (log.isDebugEnabled()) {
log.debug(
"Door Opener Device Management Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error(
"Error occurred while de-activating Door Locker Device Management bundle", e);
}
}
}

@ -0,0 +1,121 @@
/*
* 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.
*/
package org.homeautomation.doormanager.plugin.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.DoorManagerManagerService;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
import org.homeautomation.doormanager.plugin.impl.util.DoorManagerUtils;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
import org.wso2.carbon.ndatasource.core.DataSourceService;
/**
* @scr.component name="org.homeautomation.doormanager.plugin.internal.ServiceComponent"
* immediate="true"
* @scr.reference name="org.wso2.carbon.ndatasource"
* interface="org.wso2.carbon.ndatasource.core.DataSourceService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDataSourceService"
* unbind="unsetDataSourceService"
* @scr.reference name="devicetype.configuration.service"
* interface="org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDeviceTypeConfigService"
* unbind="unsetDeviceTypeConfigService"
*/
public class ServiceComponent {
private static final Log log = LogFactory.getLog(ServiceComponent.class);
private ServiceRegistration serviceRegistration;
protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("Activating b Management Service Component");
}
try {
DoorManagerManagerService deviceTypeManagerService = new DoorManagerManagerService();
BundleContext bundleContext = ctx.getBundleContext();
serviceRegistration =
bundleContext.registerService(DeviceManagementService.class.getName(),
deviceTypeManagerService, null);
String setupOption = System.getProperty("setup");
if (setupOption != null) {
if (log.isDebugEnabled()) {
log.debug("-Dsetup is enabled. Iot Device management repository schema initialization is about " +
"to begin");
}
try {
DoorManagerUtils.setupDeviceManagementSchema();
} catch (DoorManagerDeviceMgtPluginException e) {
log.error("Exception occurred while initializing device management database schema", e);
}
}
if (log.isDebugEnabled()) {
log.debug("b Management Service Component has been successfully activated");
}
} catch (Throwable e) {
log.error("Error occurred while activating Current Sensor Management Service Component", e);
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating b Management Service Component");
}
try {
if (serviceRegistration != null) {
serviceRegistration.unregister();
}
if (log.isDebugEnabled()) {
log.debug("Current Sensor Management Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error("Error occurred while de-activating Iot Device Management bundle", e);
}
}
protected void setDataSourceService(DataSourceService dataSourceService) {
/* This is to avoid mobile device management component getting initialized before the underlying datasources
are registered */
if (log.isDebugEnabled()) {
log.debug("Data source service set to service component");
}
}
protected void unsetDataSourceService(DataSourceService dataSourceService) {
//do nothing
}
protected void setDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
DoorManagerManagementDataHolder.getInstance().setDeviceTypeConfigService(deviceTypeConfigService);
}
protected void unsetDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
DoorManagerManagementDataHolder.getInstance().setDeviceTypeConfigService(null);
}
}

@ -15,9 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
*/--><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager</artifactId>
@ -47,10 +45,10 @@
</plugins>
</pluginManagement>
</build>
<modules>
<module>plugin</module>
<module>api</module>
<module>analytics</module>
<module>ui</module>
</modules>
</project>
<modules>
<module>plugin</module>
<module>api</module>
<module>ui</module>
<module>analytics</module>
</modules>
</project>

@ -16,8 +16,8 @@
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
@ -26,16 +26,16 @@
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.homeautomation.doormanager.ui</artifactId>
<name>org.homeautomation.doormanager.ui</name>
<artifactId>${project-base-package}.ui</artifactId>
<name>${project-base-package}.ui</name>
<packaging>pom</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<version>${maven-assembly-plugin.version}</version>
<configuration>
<finalName>org.homeautomation.doormanager.ui-1.0.0-SNAPSHOT</finalName>
<finalName>${project.artifactId}-1.0.0-SNAPSHOT</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/src.xml</descriptor>

@ -1,3 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
@ -17,8 +18,8 @@
-->
<assembly
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>src</id>
<formats>
@ -28,7 +29,7 @@
<baseDirectory>${basedir}/src</baseDirectory>
<fileSets>
<fileSet>
<directory>${basedir}/src/main/resources/jaggeryapps/</directory>
<directory>${basedir}/src/main/resources/jaggeryapps/devicemgt</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>

@ -0,0 +1,37 @@
{{#zone "topCss"}}
{{css "css/graph.css"}}
{{/zone}}
<span id="details" data-devicename="{{device.name}}" data-deviceid="{{device.deviceIdentifier}}"
data-appcontext="{{@app.context}}"></span>
<div id="chartDivSensorType1">
<div class="chartWrapper" id="chartWrapper">
<span id="sensorType1Title">smartLock</span>
<div id="sensorType1yAxis" class="custom_y_axis"></div>
<div class="legend_container">
<div id="smoother" title="Smoothing"></div>
<div id="sensorType1Legend"></div>
</div>
<div id="chartSensorType1" class="custom_rickshaw_graph" data-backend-api-url = {{backendApiUri}}></div>
<div id="sensorType1xAxis" class="custom_x_axis"></div>
<div id="sensorType1Slider" class="custom_slider"></div>
</div>
</div>
<div id="chartDivSensorType2">
<div class="chartWrapper" id="chartWrapper">
<span id="sensorType2Title">smartFan</span>
<div id="sensorType2yAxis" class="custom_y_axis"></div>
<div class="legend_container">
<div id="smoother" title="Smoothing"></div>
<div id="sensorType2Legend"></div>
</div>
<div id="chartSensorType2" class="custom_rickshaw_graph" data-backend-api-url = {{backendApiUri}}></div>
<div id="sensorType2xAxis" class="custom_x_axis"></div>
<div id="sensorType2Slider" class="custom_slider"></div>
</div>
</div>
{{#zone "bottomJs"}}
{{js "js/d3.min.js"}}
{{js "js/rickshaw.min.js"}}
{{js "js/moment.min.js"}}
{{js "js/devicetype-graph.js"}}
{{/zone}}

@ -0,0 +1,42 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function onRequest(context) {
var devices = context.unit.params.devices;
var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("deviceId");
if (devices) {
return {
"devices": stringify(devices),
"backendApiUri": devicemgtProps["httpsURL"] + "/"+deviceType+"/device/stats/"
};
} else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") {
return {
"device": device,
"backendApiUri": devicemgtProps["httpsURL"] + "/"+deviceType+"/device/stats/" + deviceId
};
} else {
response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!");
exit();
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save