Merge pull request #258 from ayyoob/transport

refactored apis and resolved xmpp issues
revert-dabc3590
Ruwan 9 years ago
commit 7f9b7c4914

@ -24,7 +24,7 @@ import javax.ws.rs.QueryParam;
*/ */
public interface AndroidSenseManagerService { public interface AndroidSenseManagerService {
@Path("/enrollment/devices/{device_id}") @Path("/device/{device_id}/register")
@POST @POST
AndroidConfiguration register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName); AndroidConfiguration register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName);
} }

@ -1,56 +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.wso2.carbon.device.mgt.iot.androidsense.service.impl;
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.POST;
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.Response;
@Path("enrollment")
@API(name = "android_sense_mgt", version = "1.0.0", context = "/android_sense_mgt", tags = {"android_sense"})
public interface AndroidSenseManagerService {
@Path("/devices/{device_id}")
@POST
Response register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName);
@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("application/json")
@Produces("application/json")
Response getDevice(@PathParam("device_id") String deviceId);
}

@ -1,181 +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.wso2.carbon.device.mgt.iot.androidsense.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.AndroidConfiguration;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.Constants;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
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.Response;
import java.util.Date;
@Path("enrollment")
public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerService {
private static Log log = LogFactory.getLog(AndroidSenseManagerServiceImpl.class);
@Path("/devices/{device_id}")
@POST
public Response register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
AndroidConfiguration androidConfiguration = new AndroidConfiguration();
androidConfiguration.setTenantDomain(APIUtil.getAuthenticatedUserTenantDomain());
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
if (mqttEndpoint.contains(Constants.LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, Utils.getHostName());
}
androidConfiguration.setMqttEndpoint(mqttEndpoint);
return Response.status(Response.Status.ACCEPTED.getStatusCode()).entity(androidConfiguration.toString())
.build();
}
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(deviceName);
device.setType(AndroidSenseConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
AndroidConfiguration androidConfiguration = new AndroidConfiguration();
androidConfiguration.setTenantDomain(APIUtil.getAuthenticatedUserTenantDomain());
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
if (mqttEndpoint.contains(Constants.LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, Utils.getHostName());
}
androidConfiguration.setMqttEndpoint(mqttEndpoint);
return Response.ok(androidConfiguration.toString()).build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).entity(false).build();
}
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(false).build();
}
}
@Path("/devices/{device_id}")
@DELETE
public Response removeDevice(@PathParam("device_id") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier, DeviceGroupConstants.
Permissions.DEFAULT_ADMIN_PERMISSIONS)) {
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();
}
}
@Path("/devices/{device_id}")
@PUT
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier, DeviceGroupConstants.
Permissions.DEFAULT_ADMIN_PERMISSIONS)) {
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(AndroidSenseConstants.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();
}
}
@Path("/devices/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getDevice(@PathParam("device_id") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try {
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();
}
}
}

@ -19,6 +19,7 @@
package org.wso2.carbon.device.mgt.iot.androidsense.service.impl; package org.wso2.carbon.device.mgt.iot.androidsense.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
@ -33,7 +34,7 @@ import javax.ws.rs.core.Response;
@DeviceType(value = "android_sense") @DeviceType(value = "android_sense")
@API(name = "android_sense", version = "1.0.0", context = "/android_sense", tags = {"android_sense"}) @API(name = "android_sense", version = "1.0.0", context = "/android_sense", tags = {"android_sense"})
public interface AndroidSenseControllerService { public interface AndroidSenseService {
/** /**
* End point to send the key words to the device * End point to send the key words to the device
@ -44,6 +45,7 @@ public interface AndroidSenseControllerService {
@Path("device/{deviceId}/words") @Path("device/{deviceId}/words")
@POST @POST
@Feature(code = "keywords", name = "Add Keywords", description = "Send keywords to the device") @Feature(code = "keywords", name = "Add Keywords", description = "Send keywords to the device")
@Permission(scope = "android_sense_user", permissions = {"/permission/admin/device-mgt/user/operations"})
Response sendKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("keywords") String keywords); Response sendKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("keywords") String keywords);
/** /**
@ -55,11 +57,13 @@ public interface AndroidSenseControllerService {
@Path("device/{deviceId}/words/threshold") @Path("device/{deviceId}/words/threshold")
@POST @POST
@Feature(code = "threshold", name = "Add a Threshold", description = "Set a threshold for word in the device") @Feature(code = "threshold", name = "Add a Threshold", description = "Set a threshold for word in the device")
@Permission(scope = "android_sense_user", permissions = {"/permission/admin/device-mgt/user/operations"})
Response sendThreshold(@PathParam("deviceId") String deviceId, @QueryParam("threshold") String threshold); Response sendThreshold(@PathParam("deviceId") String deviceId, @QueryParam("threshold") String threshold);
@Path("device/{deviceId}/words") @Path("device/{deviceId}/words")
@DELETE @DELETE
@Feature(code = "remove", name = "Remove Keywords", description = "Remove the keywords") @Feature(code = "remove", name = "Remove Keywords", description = "Remove the keywords")
@Permission(scope = "android_sense_user", permissions = {"/permission/admin/device-mgt/user/operations"})
Response removeKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("words") String words); Response removeKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("words") String words);
/** /**
@ -68,9 +72,18 @@ public interface AndroidSenseControllerService {
@Path("stats/{deviceId}/sensors/{sensorName}") @Path("stats/{deviceId}/sensors/{sensorName}")
@GET @GET
@Consumes("application/json") @Consumes("application/json")
@Permission(scope = "android_sense_user", permissions = {"/permission/admin/device-mgt/user/stats"})
@Produces("application/json") @Produces("application/json")
Response getAndroidSenseDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor, Response getAndroidSenseDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor,
@QueryParam("from") long from, @QueryParam("to") long to); @QueryParam("from") long from, @QueryParam("to") long to);
/**
* Enroll devices.
*/
@Path("device/{device_id}/register")
@POST
@Permission(scope = "android_sense_user", permissions = {"/permission/admin/device-mgt/user/devices"})
Response register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName);
} }

@ -23,12 +23,19 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.dataservice.commons.SORT; import org.wso2.carbon.analytics.dataservice.commons.SORT;
import org.wso2.carbon.analytics.dataservice.commons.SortByField; import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; 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.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.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.AndroidConfiguration;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.Constants;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.SensorRecord; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.SensorRecord;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants; import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
@ -40,6 +47,7 @@ import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -47,9 +55,9 @@ import java.util.Map;
/** /**
* The api for * The api for
*/ */
public class AndroidSenseControllerServiceImpl implements AndroidSenseControllerService { public class AndroidSenseServiceImpl implements AndroidSenseService {
private static Log log = LogFactory.getLog(AndroidSenseControllerServiceImpl.class); private static Log log = LogFactory.getLog(AndroidSenseServiceImpl.class);
@Path("device/{deviceId}/words") @Path("device/{deviceId}/words")
@POST @POST
@ -198,4 +206,52 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController
return sensorEventTableName; return sensorEventTableName;
} }
@Path("device/{device_id}/register")
@POST
public Response register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
AndroidConfiguration androidConfiguration = new AndroidConfiguration();
androidConfiguration.setTenantDomain(APIUtil.getAuthenticatedUserTenantDomain());
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
if (mqttEndpoint.contains(Constants.LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, Utils.getServerUrl());
}
androidConfiguration.setMqttEndpoint(mqttEndpoint);
return Response.status(Response.Status.ACCEPTED.getStatusCode()).entity(androidConfiguration.toString())
.build();
}
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(deviceName);
device.setType(AndroidSenseConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
AndroidConfiguration androidConfiguration = new AndroidConfiguration();
androidConfiguration.setTenantDomain(APIUtil.getAuthenticatedUserTenantDomain());
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
if (mqttEndpoint.contains(Constants.LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, Utils.getServerUrl());
}
androidConfiguration.setMqttEndpoint(mqttEndpoint);
return Response.ok(androidConfiguration.toString()).build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).entity(false).build();
}
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(false).build();
}
}
} }

@ -56,33 +56,12 @@
<method>GET</method> <method>GET</method>
<scope>android_sense_device</scope> <scope>android_sense_device</scope>
</Permission> </Permission>
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/enrollment/devices/*</url>
<method>GET</method>
<scope>android_sense_user</scope>
</Permission>
<Permission> <Permission>
<name>Add device</name> <name>Add device</name>
<path>/device-mgt/user/devices</path> <path>/device-mgt/user/devices</path>
<url>/enrollment/devices/*</url> <url>/device/*/register</url>
<method>POST</method> <method>POST</method>
<scope>android_sense_user</scope> <scope>android_sense_user</scope>
</Permission> </Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/enrollment/devices/*</url>
<method>DELETE</method>
<scope>android_sense_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/enrollment/devices/*</url>
<method>PUT</method>
<scope>android_sense_user</scope>
</Permission>
</PermissionConfiguration> </PermissionConfiguration>

@ -24,11 +24,9 @@
<jaxrs:server id="AndroidSense" address="/"> <jaxrs:server id="AndroidSense" address="/">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<bean id="AndroidSenseControllerService" <bean id="AndroidSenseService"
class="org.wso2.carbon.device.mgt.iot.androidsense.service.impl.AndroidSenseControllerServiceImpl"> class="org.wso2.carbon.device.mgt.iot.androidsense.service.impl.AndroidSenseServiceImpl">
</bean> </bean>
<bean id="AndroidSenseManagerService"
class="org.wso2.carbon.device.mgt.iot.androidsense.service.impl.AndroidSenseManagerServiceImpl"/>
</jaxrs:serviceBeans> </jaxrs:serviceBeans>
<jaxrs:providers> <jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" /> <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />

@ -1,150 +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.wso2.carbon.device.mgt.iot.arduino.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
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.Response;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
public class ArduinoControllerServiceImpl implements ArduinoControllerService {
private static Log log = LogFactory.getLog(ArduinoControllerServiceImpl.class);
private static Map<String, LinkedList<String>> internalControlsQueue = new HashMap<>();
@Override
@Path("device/{deviceId}/bulb")
@POST
public Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state) {
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
ArduinoConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
String operation = "BULB:" + state.toUpperCase();
if (deviceControlList == null) {
deviceControlList = new LinkedList<>();
deviceControlList.add(operation);
internalControlsQueue.put(deviceId, deviceControlList);
} else {
deviceControlList.add(operation);
}
return Response.status(Response.Status.OK.getStatusCode()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@Override
@Path("device/{deviceId}/controls")
@GET
public Response readControls(@PathParam("deviceId") String deviceId) {
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
ArduinoConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
String result;
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (deviceControlList == null) {
result = "No controls have been set for device " + deviceId + " of owner " + owner;
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.status(Response.Status.CONFLICT.getStatusCode()).entity(result).build();
} else {
try {
result = deviceControlList.remove();
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.status(Response.Status.ACCEPTED.getStatusCode()).entity(result).build();
} catch (NoSuchElementException ex) {
result = "There are no more controls for device " + deviceId + " of owner " + owner;
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.status(Response.Status.NO_CONTENT.getStatusCode()).entity(result).build();
}
}
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@Override
@Path("device/stats/{deviceId}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getArduinoTemperatureStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to) {
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
ArduinoConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String query = "deviceId:" + deviceId + " AND deviceType:" +
ArduinoConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = ArduinoConstants.TEMPERATURE_EVENT_TABLE;
try {
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("time", SORT.ASC, false);
sortByFields.add(sortByField);
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
} catch (AnalyticsException e) {
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();
}
}
}

@ -1,63 +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.wso2.carbon.device.mgt.iot.arduino.service.impl;
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")
@API(name = "arduino_mgt", version = "1.0.0", context = "/arduino_mgt", tags = {"arduino"})
public interface ArduinoManagerService {
@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/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getArduinoDevices();
@Path("devices/download")
@GET
@Produces("application/octet-stream")
Response downloadSketch(@QueryParam("deviceName") String customDeviceName);
}

@ -19,6 +19,7 @@
package org.wso2.carbon.device.mgt.iot.arduino.service.impl; package org.wso2.carbon.device.mgt.iot.arduino.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
@ -32,15 +33,17 @@ import javax.ws.rs.core.Response;
@API(name = "arduino", version = "1.0.0", context = "/arduino", tags = {"arduino"}) @API(name = "arduino", version = "1.0.0", context = "/arduino", tags = {"arduino"})
@DeviceType(value = "arduino") @DeviceType(value = "arduino")
public interface ArduinoControllerService { public interface ArduinoService {
@Path("device/{deviceId}/bulb") @Path("device/{deviceId}/bulb")
@POST @POST
@Feature(code = "bulb", name = "Control Bulb", description = "Control Bulb on Arduino Uno") @Feature(code = "bulb", name = "Control Bulb", description = "Control Bulb on Arduino Uno")
@Permission(scope = "arduino_user", permissions = {"/permission/admin/device-mgt/user/operations"})
Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state); Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state);
@Path("device/{deviceId}/controls") @Path("device/{deviceId}/controls")
@GET @GET
@Permission(scope = "arduino_device", permissions = {"/permission/admin/device-mgt/user/operations"})
Response readControls(@PathParam("deviceId") String deviceId); Response readControls(@PathParam("deviceId") String deviceId);
/** /**
@ -50,7 +53,17 @@ public interface ArduinoControllerService {
@GET @GET
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
@Permission(scope = "arduino_user", permissions = {"/permission/admin/device-mgt/user/stats"})
Response getArduinoTemperatureStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, Response getArduinoTemperatureStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to); @QueryParam("to") long to);
/**
* download device agent
*/
@Path("device/download")
@GET
@Produces("application/octet-stream")
@Permission(scope = "arduino_user", permissions = {"/permission/admin/device-mgt/user/devices"})
Response downloadSketch(@QueryParam("deviceName") String customDeviceName);
} }

@ -21,6 +21,9 @@ package org.wso2.carbon.device.mgt.iot.arduino.service.impl;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.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.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
@ -29,6 +32,9 @@ import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.APIUtil; import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants; import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ZipUtil;
@ -39,115 +45,132 @@ import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientExceptio
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.PUT; import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.UUID; import java.util.UUID;
@Path("enrollment") public class ArduinoServiceImpl implements ArduinoService {
public class ArduinoManagerServiceImpl implements ArduinoManagerService {
private static Log log = LogFactory.getLog(ArduinoServiceImpl.class);
private static Map<String, LinkedList<String>> internalControlsQueue = new HashMap<>();
private static final String KEY_TYPE = "PRODUCTION"; private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey; private static ApiApplicationKey apiApplicationKey;
private static Log log = LogFactory.getLog(ArduinoManagerServiceImpl.class);
@Override @Override
@Path("devices/{device_id}") @Path("device/{deviceId}/bulb")
@DELETE @POST
public Response removeDevice(@PathParam("device_id") String deviceId) { public Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
try { try {
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier); if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
if (removed) { ArduinoConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.OK.getStatusCode()).entity(true).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
String operation = "BULB:" + state.toUpperCase();
if (deviceControlList == null) {
deviceControlList = new LinkedList<>();
deviceControlList.add(operation);
internalControlsQueue.put(deviceId, deviceControlList);
} else { } else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build(); deviceControlList.add(operation);
} }
} catch (DeviceManagementException e) { return Response.status(Response.Status.OK.getStatusCode()).build();
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).build();
} }
} }
@Override @Override
@Path("devices/{device_id}") @Path("device/{deviceId}/controls")
@PUT @GET
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) { public Response readControls(@PathParam("deviceId") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
try { try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier); if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
device.setDeviceIdentifier(deviceId); ArduinoConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
device.setName(name); }
device.setType(ArduinoConstants.DEVICE_TYPE); String result;
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device); LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
if (updated) { String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
return Response.status(Response.Status.OK.getStatusCode()).entity(true).build(); if (deviceControlList == null) {
result = "No controls have been set for device " + deviceId + " of owner " + owner;
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.status(Response.Status.CONFLICT.getStatusCode()).entity(result).build();
} else { } else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build(); try {
result = deviceControlList.remove();
if (log.isDebugEnabled()) {
log.debug(result);
} }
} catch (DeviceManagementException e) { return Response.status(Response.Status.ACCEPTED.getStatusCode()).entity(result).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); } catch (NoSuchElementException ex) {
result = "There are no more controls for device " + deviceId + " of owner " + owner;
if (log.isDebugEnabled()) {
log.debug(result);
} }
return Response.status(Response.Status.NO_CONTENT.getStatusCode()).entity(result).build();
} }
}
@Override } catch (DeviceAccessAuthorizationException e) {
@Path("devices/{device_id}") log.error(e.getErrorMessage(), e);
@GET return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getDevice(@PathParam("device_id") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.status(Response.Status.OK.getStatusCode()).entity(device).build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} }
} }
@Override @Override
@Path("devices") @Path("device/stats/{deviceId}")
@GET @GET
@Consumes(MediaType.APPLICATION_JSON) @Consumes("application/json")
@Produces(MediaType.APPLICATION_JSON) @Produces("application/json")
public Response getArduinoDevices() { public Response getArduinoTemperatureStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to) {
try { try {
List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser( if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
APIUtil.getAuthenticatedUser()); ArduinoConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
ArrayList<Device> userDevicesforArduino = new ArrayList<>(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
for (Device device : userDevices) {
if (device.getType().equals(ArduinoConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
userDevicesforArduino.add(device);
} }
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String query = "deviceId:" + deviceId + " AND deviceType:" +
ArduinoConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = ArduinoConstants.TEMPERATURE_EVENT_TABLE;
try {
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("time", SORT.ASC, false);
sortByFields.add(sortByField);
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
} catch (AnalyticsException e) {
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();
} }
Device[] devices = userDevicesforArduino.toArray(new Device[]{}); } catch (DeviceAccessAuthorizationException e) {
return Response.status(Response.Status.OK.getStatusCode()).entity(devices).build(); log.error(e.getErrorMessage(), e);
} catch (DeviceManagementException e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(true).build();
} }
} }
@Override @Override
@Path("/devices/download") @Path("/device/download")
@GET @GET
@Produces("application/zip") @Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName) { public Response downloadSketch(@QueryParam("deviceName") String deviceName) {
@ -197,7 +220,7 @@ public class ArduinoManagerServiceImpl implements ArduinoManagerService {
ArduinoConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true); ArduinoConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
} }
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient(); JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + ArduinoConstants.DEVICE_TYPE + " device_" + deviceId; String scopes = "arduino_device device_type_" + ArduinoConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes); apiApplicationKey.getConsumerSecret(), owner, scopes);
//create token //create token
@ -210,9 +233,8 @@ public class ArduinoManagerServiceImpl implements ArduinoManagerService {
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
ZipUtil ziputil = new ZipUtil(); ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), return ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
ArduinoConstants.DEVICE_TYPE, deviceId, deviceName, accessToken, refreshToken); ArduinoConstants.DEVICE_TYPE, deviceId, deviceName, accessToken, refreshToken);
return zipFile;
} }
private static String shortUUID() { private static String shortUUID() {
@ -245,5 +267,4 @@ public class ArduinoManagerServiceImpl implements ArduinoManagerService {
return false; return false;
} }
} }
} }

@ -47,7 +47,7 @@ public class ZipUtil {
String iotServerIP; String iotServerIP;
try { try {
iotServerIP = Utils.getHostName(); iotServerIP = Utils.getServerUrl();
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY); String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
Map<String, String> contextParams = new HashMap<>(); Map<String, String> contextParams = new HashMap<>();

@ -50,33 +50,12 @@
<method>GET</method> <method>GET</method>
<scope>arduino_device</scope> <scope>arduino_device</scope>
</Permission> </Permission>
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/enrollment/devices/*</url>
<method>GET</method>
<scope>arduino_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/enrollment/devices/*</url>
<method>DELETE</method>
<scope>arduino_user</scope>
</Permission>
<Permission> <Permission>
<name>Download device</name> <name>Download device</name>
<path>/device-mgt/user/devices</path> <path>/device-mgt/user/devices</path>
<url>/enrollment/devices/download</url> <url>/device/download</url>
<method>GET</method> <method>GET</method>
<scope>arduino_user</scope> <scope>arduino_user</scope>
</Permission> </Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/enrollment/devices/*</url>
<method>PUT</method>
<scope>arduino_user</scope>
</Permission>
</PermissionConfiguration> </PermissionConfiguration>

@ -25,11 +25,8 @@
<jaxrs:server id="Arduino" address="/"> <jaxrs:server id="Arduino" address="/">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<bean id="ArduinoManagerService" <bean id="ArduinoService"
class="org.wso2.carbon.device.mgt.iot.arduino.service.impl.ArduinoManagerServiceImpl"> class="org.wso2.carbon.device.mgt.iot.arduino.service.impl.ArduinoServiceImpl">
</bean>
<bean id="ArduinoControllerService"
class="org.wso2.carbon.device.mgt.iot.arduino.service.impl.ArduinoControllerServiceImpl">
</bean> </bean>
</jaxrs:serviceBeans> </jaxrs:serviceBeans>
<jaxrs:providers> <jaxrs:providers>

@ -2,6 +2,6 @@
"deviceType": { "deviceType": {
"label": "Arduino", "label": "Arduino",
"category": "iot", "category": "iot",
"downloadAgentUri": "arduino/enrollment/devices/download" "downloadAgentUri": "arduino/device/download"
} }
} }

@ -55,7 +55,7 @@ public class Utils {
public static final String HOST_NAME = "HostName"; public static final String HOST_NAME = "HostName";
private static final Log log = LogFactory.getLog(Utils.class); private static final Log log = LogFactory.getLog(Utils.class);
public static String getHostName() { public static String getServerUrl() {
String hostName = ServerConfiguration.getInstance().getFirstProperty(HOST_NAME); String hostName = ServerConfiguration.getInstance().getFirstProperty(HOST_NAME);
try { try {
if (hostName == null) { if (hostName == null) {

@ -1,109 +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.wso2.carbon.device.mgt.iot.raspberrypi.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
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.Response;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RaspberryPiControllerServiceImpl implements RaspberryPiControllerService {
private static Log log = LogFactory.getLog(RaspberryPiControllerServiceImpl.class);
@Path("device/{deviceId}/bulb")
@POST
public Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state) {
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
RaspberrypiConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
String switchToState = state.toUpperCase();
if (!switchToState.equals(RaspberrypiConstants.STATE_ON) && !switchToState.equals(
RaspberrypiConstants.STATE_OFF)) {
log.error("The requested state change shoud be either - 'ON' or 'OFF'");
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
String actualMessage = RaspberrypiConstants.BULB_CONTEXT + ":" + state;
Map<String, String> dynamicProperties = new HashMap<>();
String publishTopic = APIUtil.getTenantDomainOftheUser() + "/"
+ RaspberrypiConstants.DEVICE_TYPE + "/" + deviceId;
dynamicProperties.put(RaspberrypiConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
APIUtil.getOutputEventAdapterService().publish(RaspberrypiConstants.MQTT_ADAPTER_NAME,
dynamicProperties, actualMessage);
return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@Path("device/stats/{deviceId}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getRaspberryPiTemperatureStats(@PathParam("deviceId") String deviceId,
@QueryParam("from") long from, @QueryParam("to") long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String query = "deviceId:" + deviceId + " AND deviceType:" +
RaspberrypiConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = RaspberrypiConstants.TEMPERATURE_EVENT_TABLE;
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
RaspberrypiConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("time", SORT.ASC, false);
sortByFields.add(sortByField);
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
} catch (AnalyticsException e) {
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();
}
}
}

@ -1,66 +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.wso2.carbon.device.mgt.iot.raspberrypi.service.impl;
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")
@API(name = "raspberrypi_mgt", version = "1.0.0", context = "/raspberrypi_mgt", tags = {"raspberrypi"})
@DeviceType(value = "raspberrypi")
public interface RaspberryPiManagerService {
@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")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getRaspberrypiDevices();
@Path("devicesg/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketch_type") String sketchType);
}

@ -19,25 +19,27 @@
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl; package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@API(name = "raspberrypi", version = "1.0.0", context = "/raspberrypi", tags = {"raspberrypi"}) @API(name = "raspberrypi", version = "1.0.0", context = "/raspberrypi", tags = {"raspberrypi"})
@DeviceType(value = "raspberrypi") @DeviceType(value = "raspberrypi")
public interface RaspberryPiControllerService { public interface RaspberryPiService {
@Path("device/{deviceId}/bulb") @Path("device/{deviceId}/bulb")
@POST @POST
@Feature(code = "bulb", name = "Bulb On / Off", description = "Switch on/off Raspberry Pi agent's bulb. (On / Off)") @Feature(code = "bulb", name = "Bulb On / Off", description = "Switch on/off Raspberry Pi agent's bulb. (On / Off)")
@Permission(scope = "raspberrypi_user", permissions = {"/permission/admin/device-mgt/user/operations"})
Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state); Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state);
/** /**
@ -47,7 +49,17 @@ public interface RaspberryPiControllerService {
@GET @GET
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
@Permission(scope = "raspberrypi_user", permissions = {"/permission/admin/device-mgt/user/stats"})
Response getRaspberryPiTemperatureStats(@PathParam("deviceId") String deviceId, Response getRaspberryPiTemperatureStats(@PathParam("deviceId") String deviceId,
@QueryParam("from") long from, @QueryParam("to") long to); @QueryParam("from") long from, @QueryParam("to") long to);
/**
* download the agent.
*/
@Path("device/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Permission(scope = "raspberrypi_user", permissions = {"/permission/admin/device-mgt/user/devices"})
Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketch_type") String sketchType);
} }

@ -21,6 +21,9 @@ package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.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.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
@ -29,8 +32,11 @@ import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.APIUtil; import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.ZipUtil;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive; 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.JWTClient;
@ -39,118 +45,90 @@ import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientExceptio
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.PUT; import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.UUID; import java.util.UUID;
@Path("enrollment") public class RaspberryPiServiceImpl implements RaspberryPiService {
public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService {
private static Log log = LogFactory.getLog(RaspberryPiManagerServiceImpl.class); private static Log log = LogFactory.getLog(RaspberryPiServiceImpl.class);
private static final String KEY_TYPE = "PRODUCTION"; private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey; private static ApiApplicationKey apiApplicationKey;
@Override @Path("device/{deviceId}/bulb")
@Path("devices/{device_id}") @POST
@DELETE public Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state) {
public Response removeDevice(@PathParam("device_id") String deviceId) {
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
deviceIdentifier.setId(deviceId); RaspberrypiConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice( }
deviceIdentifier); String switchToState = state.toUpperCase();
if (removed) { if (!switchToState.equals(RaspberrypiConstants.STATE_ON) && !switchToState.equals(
RaspberrypiConstants.STATE_OFF)) {
log.error("The requested state change shoud be either - 'ON' or 'OFF'");
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
String actualMessage = RaspberrypiConstants.BULB_CONTEXT + ":" + state;
Map<String, String> dynamicProperties = new HashMap<>();
String publishTopic = APIUtil.getTenantDomainOftheUser() + "/"
+ RaspberrypiConstants.DEVICE_TYPE + "/" + deviceId;
dynamicProperties.put(RaspberrypiConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
APIUtil.getOutputEventAdapterService().publish(RaspberrypiConstants.MQTT_ADAPTER_NAME,
dynamicProperties, actualMessage);
return Response.ok().build(); return Response.ok().build();
} else { } catch (DeviceAccessAuthorizationException e) {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build(); log.error(e.getErrorMessage(), e);
} return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} }
} }
@Override @Path("device/stats/{deviceId}")
@Path("devices/{device_id}")
@PUT
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(RaspberrypiConstants.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());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Override
@Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getDevice(@PathParam("device_id") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException ex) {
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Override
@Path("devices")
@GET @GET
@Consumes(MediaType.APPLICATION_JSON) @Consumes("application/json")
@Produces(MediaType.APPLICATION_JSON) @Produces("application/json")
public Response getRaspberrypiDevices() { public Response getRaspberryPiTemperatureStats(@PathParam("deviceId") String deviceId,
@QueryParam("from") long from, @QueryParam("to") long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String query = "deviceId:" + deviceId + " AND deviceType:" +
RaspberrypiConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = RaspberrypiConstants.TEMPERATURE_EVENT_TABLE;
try { try {
List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser( if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
APIUtil.getAuthenticatedUser()); RaspberrypiConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
ArrayList<Device> usersRaspberrypiDevices = new ArrayList<>(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
for (Device device : userDevices) { }
if (device.getType().equals(RaspberrypiConstants.DEVICE_TYPE) && List<SortByField> sortByFields = new ArrayList<>();
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) { SortByField sortByField = new SortByField("time", SORT.ASC, false);
usersRaspberrypiDevices.add(device); sortByFields.add(sortByField);
} List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
} return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
Device[] devices = usersRaspberrypiDevices.toArray(new Device[]{}); } catch (AnalyticsException e) {
return Response.ok().entity(devices).build(); String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
} catch (DeviceManagementException e) { log.error(errorMsg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); 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();
} }
} }
@Override @Override
@Path("devices/download") @Path("device/download")
@GET @GET
@Produces("application/zip") @Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType) { public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType) {
@ -234,9 +212,8 @@ public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
ZipUtil ziputil = new ZipUtil(); ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, return ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
deviceId, deviceName, accessToken, refreshToken); deviceId, deviceName, accessToken, refreshToken);
return zipFile;
} }
private static String shortUUID() { private static String shortUUID() {
@ -244,5 +221,4 @@ public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong(); long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX); return Long.toString(l, Character.MAX_RADIX);
} }
} }

@ -52,7 +52,7 @@ public class ZipUtil {
String iotServerIP; String iotServerIP;
try { try {
iotServerIP = Utils.getHostName(); iotServerIP = Utils.getServerUrl();
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY); String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY); String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort; String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;

@ -36,31 +36,10 @@
<method>GET</method> <method>GET</method>
<scope>raspberrypi_user</scope> <scope>raspberrypi_user</scope>
</Permission> </Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/enrollment/devices/*</url>
<method>DELETE</method>
<scope>raspberrypi_user</scope>
</Permission>
<Permission> <Permission>
<name>Download device</name> <name>Download device</name>
<path>/device-mgt/user/devices</path> <path>/device-mgt/user/devices</path>
<url>/enrollment/devices/download</url> <url>/device/download</url>
<method>GET</method>
<scope>raspberrypi_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/enrollment/devices/*</url>
<method>POST</method>
<scope>raspberrypi_user</scope>
</Permission>
<Permission>
<name>Get Devices</name>
<path>/device-mgt/user/devices/list</path>
<url>/enrollment/devices</url>
<method>GET</method> <method>GET</method>
<scope>raspberrypi_user</scope> <scope>raspberrypi_user</scope>
</Permission> </Permission>

@ -27,11 +27,8 @@
<jaxrs:server id="RaspberryPi" address="/"> <jaxrs:server id="RaspberryPi" address="/">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<bean id="RaspberryPiControllerService" <bean id="RaspberryPiService"
class="org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.RaspberryPiControllerServiceImpl"> class="org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.RaspberryPiServiceImpl">
</bean>
<bean id="RaspberryPiManagerService"
class="org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.RaspberryPiManagerServiceImpl">
</bean> </bean>
</jaxrs:serviceBeans> </jaxrs:serviceBeans>
<jaxrs:providers> <jaxrs:providers>

@ -2,6 +2,6 @@
"deviceType": { "deviceType": {
"label": "Raspberry Pi", "label": "Raspberry Pi",
"category": "iot", "category": "iot",
"downloadAgentUri": "raspberrypi/enrollment/devices/download" "downloadAgentUri": "raspberrypi/device/download"
} }
} }

@ -68,11 +68,8 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
final AgentManager agentManager = AgentManager.getInstance(); final AgentManager agentManager = AgentManager.getInstance();
username = agentManager.getAgentConfigs().getDeviceId(); username = agentManager.getAgentConfigs().getDeviceId();
password = agentManager.getAgentConfigs().getAuthToken(); password = agentManager.getAgentConfigs().getAuthToken();
resource = agentManager.getAgentConfigs().getDeviceOwner(); xmppDeviceJID = username + "@" + agentManager.getAgentConfigs().getXmppServerName();
xmppAdminJID = "wso2admin_" + AgentConstants.DEVICE_TYPE + "@" + agentManager.getAgentConfigs().getXmppServerName();
xmppDeviceJID = username + "@" + server;
xmppAdminJID = "wso2_" + AgentConstants.DEVICE_TYPE + "@" + server;
Runnable connect = new Runnable() { Runnable connect = new Runnable() {
public void run() { public void run() {

@ -39,6 +39,7 @@ public class AgentConfiguration {
private String authToken; private String authToken;
private String refreshToken; private String refreshToken;
private int dataPushInterval; private int dataPushInterval;
private String xmppServerName;
public String getTenantDomain() { public String getTenantDomain() {
return tenantDomain; return tenantDomain;
@ -159,6 +160,14 @@ public class AgentConfiguration {
public void setScepContext(String scepContext) { public void setScepContext(String scepContext) {
this.scepContext = scepContext; this.scepContext = scepContext;
} }
public String getXmppServerName() {
return xmppServerName;
}
public void setXmppServerName(String xmppServerName) {
this.xmppServerName = xmppServerName;
}
} }

@ -134,4 +134,6 @@ public class AgentConstants {
"select deviceID, temp\n" + "select deviceID, temp\n" +
"insert into bulbOffStream;"; "insert into bulbOffStream;";
public static final String XMPP_SERVER_NAME_PROPERTY = "xmpp-server-name";
} }

@ -102,6 +102,8 @@ public class AgentUtilOperations {
AgentConstants.MQTT_BROKER_EP_PROPERTY)); AgentConstants.MQTT_BROKER_EP_PROPERTY));
iotServerConfigs.setXmppServerEndpoint(properties.getProperty( iotServerConfigs.setXmppServerEndpoint(properties.getProperty(
AgentConstants.XMPP_SERVER_EP_PROPERTY)); AgentConstants.XMPP_SERVER_EP_PROPERTY));
iotServerConfigs.setXmppServerName(properties.getProperty(
AgentConstants.XMPP_SERVER_NAME_PROPERTY));
iotServerConfigs.setAuthMethod(properties.getProperty( iotServerConfigs.setAuthMethod(properties.getProperty(
AgentConstants.AUTH_METHOD_PROPERTY)); AgentConstants.AUTH_METHOD_PROPERTY));
iotServerConfigs.setAuthToken(properties.getProperty( iotServerConfigs.setAuthToken(properties.getProperty(
@ -138,6 +140,8 @@ public class AgentUtilOperations {
iotServerConfigs.getRefreshToken()); iotServerConfigs.getRefreshToken());
log.info(AgentConstants.LOG_APPENDER + "Data Push Interval: " + log.info(AgentConstants.LOG_APPENDER + "Data Push Interval: " +
iotServerConfigs.getDataPushInterval()); iotServerConfigs.getDataPushInterval());
log.info(AgentConstants.LOG_APPENDER + "XMPP Server Name: " +
iotServerConfigs.getXmppServerName());
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
log.error(AgentConstants.LOG_APPENDER + "Unable to find " + propertiesFileName + log.error(AgentConstants.LOG_APPENDER + "Unable to find " + propertiesFileName +

@ -32,3 +32,4 @@ auth-token=79d68b50ae5f5a06e812889979b3453
refresh-token=8bdda6359dddad218cff3354d5a8cb3b refresh-token=8bdda6359dddad218cff3354d5a8cb3b
network-interface=en0 network-interface=en0
push-interval=14 push-interval=14
xmpp-server-name=localhost

@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.communication.xmpp
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Message;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentConfiguration;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentConstants; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentUtilOperations; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentUtilOperations;
@ -68,11 +69,8 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
final AgentManager agentManager = AgentManager.getInstance(); final AgentManager agentManager = AgentManager.getInstance();
username = agentManager.getAgentConfigs().getDeviceId(); username = agentManager.getAgentConfigs().getDeviceId();
password = agentManager.getAgentConfigs().getAuthToken(); password = agentManager.getAgentConfigs().getAuthToken();
resource = agentManager.getAgentConfigs().getDeviceOwner(); xmppDeviceJID = username + "@" + agentManager.getAgentConfigs().getXmppServerName();
xmppAdminJID = "wso2admin_" + AgentConstants.DEVICE_TYPE + "@" + agentManager.getAgentConfigs().getXmppServerName();
xmppDeviceJID = username + "@" + server;
xmppAdminJID = "wso2_" + AgentConstants.DEVICE_TYPE + "@" + server;
Runnable connect = new Runnable() { Runnable connect = new Runnable() {
public void run() { public void run() {

@ -39,6 +39,7 @@ public class AgentConfiguration {
private String authToken; private String authToken;
private String refreshToken; private String refreshToken;
private int dataPushInterval; private int dataPushInterval;
private String xmppServerName;
public String getTenantDomain() { public String getTenantDomain() {
return tenantDomain; return tenantDomain;
@ -159,6 +160,14 @@ public class AgentConfiguration {
public void setScepContext(String scepContext) { public void setScepContext(String scepContext) {
this.scepContext = scepContext; this.scepContext = scepContext;
} }
public String getXmppServerName() {
return xmppServerName;
}
public void setXmppServerName(String xmppServerName) {
this.xmppServerName = xmppServerName;
}
} }

@ -77,6 +77,7 @@ public class AgentConstants {
public static final String APIM_GATEWAY_EP_PROPERTY = "apim-ep"; public static final String APIM_GATEWAY_EP_PROPERTY = "apim-ep";
public static final String MQTT_BROKER_EP_PROPERTY = "mqtt-ep"; public static final String MQTT_BROKER_EP_PROPERTY = "mqtt-ep";
public static final String XMPP_SERVER_EP_PROPERTY = "xmpp-ep"; public static final String XMPP_SERVER_EP_PROPERTY = "xmpp-ep";
public static final String XMPP_SERVER_NAME_PROPERTY = "xmpp-server-name";
public static final String AUTH_METHOD_PROPERTY = "auth-method"; public static final String AUTH_METHOD_PROPERTY = "auth-method";
public static final String AUTH_TOKEN_PROPERTY = "auth-token"; public static final String AUTH_TOKEN_PROPERTY = "auth-token";
public static final String REFRESH_TOKEN_PROPERTY = "refresh-token"; public static final String REFRESH_TOKEN_PROPERTY = "refresh-token";

@ -106,6 +106,8 @@ public class AgentUtilOperations {
AgentConstants.MQTT_BROKER_EP_PROPERTY)); AgentConstants.MQTT_BROKER_EP_PROPERTY));
iotServerConfigs.setXmppServerEndpoint(properties.getProperty( iotServerConfigs.setXmppServerEndpoint(properties.getProperty(
AgentConstants.XMPP_SERVER_EP_PROPERTY)); AgentConstants.XMPP_SERVER_EP_PROPERTY));
iotServerConfigs.setXmppServerName(properties.getProperty(
AgentConstants.XMPP_SERVER_NAME_PROPERTY));
iotServerConfigs.setAuthMethod(properties.getProperty( iotServerConfigs.setAuthMethod(properties.getProperty(
AgentConstants.AUTH_METHOD_PROPERTY)); AgentConstants.AUTH_METHOD_PROPERTY));
iotServerConfigs.setAuthToken(properties.getProperty( iotServerConfigs.setAuthToken(properties.getProperty(
@ -142,6 +144,8 @@ public class AgentUtilOperations {
iotServerConfigs.getRefreshToken()); iotServerConfigs.getRefreshToken());
log.info(AgentConstants.LOG_APPENDER + "Data Push Interval: " + log.info(AgentConstants.LOG_APPENDER + "Data Push Interval: " +
iotServerConfigs.getDataPushInterval()); iotServerConfigs.getDataPushInterval());
log.info(AgentConstants.LOG_APPENDER + "XMPP Server Name: " +
iotServerConfigs.getXmppServerName());
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
String errorMsg = "[" + propertiesFileName + "] file not found at: " + AgentConstants.PROPERTIES_FILE_PATH; String errorMsg = "[" + propertiesFileName + "] file not found at: " + AgentConstants.PROPERTIES_FILE_PATH;

@ -32,3 +32,4 @@ auth-token=79d68b50ae5f5a06e812889979b3453
refresh-token=8bdda6359dddad218cff3354d5a8cb3b refresh-token=8bdda6359dddad218cff3354d5a8cb3b
network-interface=en0 network-interface=en0
push-interval=14 push-interval=14
xmpp-server-name=localhost

@ -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.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl;
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")
@API(name = "virtual_firealarm_mgt", version = "1.0.0", context = "/virtual_firealarm_mgt", tags = {"virtual_firealarm"})
public interface VirtualFireAlarmManagerService {
@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")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getFirealarmDevices();
@Path("/devices/download")
@GET
@Produces("application/zip")
Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType);
}

@ -1,294 +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.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppAccount;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.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.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;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Path("enrollment")
public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManagerService {
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
private static Log log = LogFactory.getLog(VirtualFireAlarmManagerServiceImpl.class);
@Path("/devices/{device_id}")
@DELETE
public Response removeDevice(@PathParam("device_id") String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier, DeviceGroupConstants.
Permissions.DEFAULT_ADMIN_PERMISSIONS)) {
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();
}
}
@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(VirtualFireAlarmConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier, DeviceGroupConstants.
Permissions.DEFAULT_ADMIN_PERMISSIONS)) {
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(VirtualFireAlarmConstants.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();
}
}
@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(VirtualFireAlarmConstants.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();
}
}
@Path("/devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getFirealarmDevices() {
try {
List<Device> userDevices =
APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser());
ArrayList<Device> userDevicesforFirealarm = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(VirtualFireAlarmConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
userDevicesforFirealarm.add(device);
}
}
Device[] devices = userDevicesforFirealarm.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();
}
}
@Path("/devices/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 resp = response.build();
zipFile.getZipFile().delete();
return resp;
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (VirtualFirealarmDeviceMgtPluginException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
}
}
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(VirtualFireAlarmConstants.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(VirtualFireAlarmConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
return APIUtil.getDeviceManagementService().enrollDevice(device);
} catch (DeviceManagementException e) {
log.error(e.getMessage(), e);
return false;
}
}
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
throws DeviceManagementException, APIManagerException, JWTClientException,
UserStoreException, VirtualFirealarmDeviceMgtPluginException {
//create new device id
String deviceId = shortUUID();
if (apiApplicationKey == null) {
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {VirtualFireAlarmConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
VirtualFireAlarmConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + VirtualFireAlarmConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner,
scopes);
String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken();
//adding registering data
XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(deviceId);
newXmppAccount.setUsername(deviceId);
newXmppAccount.setPassword(accessToken);
newXmppAccount.setEmail(deviceId + "@" + APIUtil.getTenantDomainOftheUser());
XmppServerClient xmppServerClient = new XmppServerClient();
boolean status;
if (XmppConfig.getInstance().isEnabled()) {
status = xmppServerClient.createAccount(newXmppAccount);
if (!status) {
String msg = "XMPP Account was not created for device - " + deviceId + " of owner - " + owner +
".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot" +
".common.config.server.configs";
throw new DeviceManagementException(msg);
}
}
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(), sketchType, deviceId,
deviceName, accessToken, refreshToken);
return zipFile;
}
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
}

@ -35,7 +35,7 @@ import javax.ws.rs.core.Response;
*/ */
@API(name = "virtual_firealarm", version = "1.0.0", context = "/virtual_firealarm", tags = {"virtual_firealarm"}) @API(name = "virtual_firealarm", version = "1.0.0", context = "/virtual_firealarm", tags = {"virtual_firealarm"})
@DeviceType(value = "virtual_firealarm") @DeviceType(value = "virtual_firealarm")
public interface VirtualFireAlarmControllerService { public interface VirtualFireAlarmService {
/** /**
* This is an API called/used from within the Server(Front-End) or by a device Owner. It sends a control command to * This is an API called/used from within the Server(Front-End) or by a device Owner. It sends a control command to
@ -49,7 +49,7 @@ public interface VirtualFireAlarmControllerService {
*/ */
@POST @POST
@Path("device/{deviceId}/buzz") @Path("device/{deviceId}/buzz")
@Permission(scope = "virtual_firealarm_user", permissions = {"device-mgt/virtual_firealarm/user"}) @Permission(scope = "virtual_firealarm_user", permissions = {"/permission/admin/device-mgt/user/operations"})
@Feature(code = "buzz", name = "Buzzer On / Off", description = "Switch on/off Virtual Fire Alarm Buzzer. (On / Off)") @Feature(code = "buzz", name = "Buzzer On / Off", description = "Switch on/off Virtual Fire Alarm Buzzer. (On / Off)")
Response switchBuzzer(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol, Response switchBuzzer(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol,
@FormParam("state") String state); @FormParam("state") String state);
@ -60,10 +60,16 @@ public interface VirtualFireAlarmControllerService {
*/ */
@Path("device/stats/{deviceId}") @Path("device/stats/{deviceId}")
@GET @GET
@Permission(scope = "virtual_firealarm_user", permissions = {"device-mgt/virtual_firealarm/user"}) @Permission(scope = "virtual_firealarm_user", permissions = {"/permission/admin/device-mgt/user/stats"})
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
Response getVirtualFirealarmStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, Response getVirtualFirealarmStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to); @QueryParam("to") long to);
@Path("device/download")
@GET
@Produces("application/zip")
@Permission(scope = "virtual_firealarm_user", permissions = {"/permission/admin/device-mgt/user/devices"})
Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType);
} }

@ -18,20 +18,38 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.dataservice.commons.SORT; import org.wso2.carbon.analytics.dataservice.commons.SORT;
import org.wso2.carbon.analytics.dataservice.commons.SortByField; import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
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.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.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFirealarmSecurityManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFirealarmSecurityManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppAccount;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.APIUtil; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.VirtualFireAlarmServiceUtils; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.VirtualFireAlarmServiceUtils;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.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.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam; import javax.ws.rs.FormParam;
@ -43,16 +61,23 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID;
public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmControllerService { public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
private static final String XMPP_PROTOCOL = "XMPP"; private static final String XMPP_PROTOCOL = "XMPP";
private static Log log = LogFactory.getLog(VirtualFireAlarmControllerServiceImpl.class); private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
private static Log log = LogFactory.getLog(VirtualFireAlarmServiceImpl.class);
@POST @POST
@Path("device/{deviceId}/buzz") @Path("device/{deviceId}/buzz")
@ -83,7 +108,8 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
Map<String, String> dynamicProperties = new HashMap<>(); Map<String, String> dynamicProperties = new HashMap<>();
switch (protocolString) { switch (protocolString) {
case XMPP_PROTOCOL: case XMPP_PROTOCOL:
dynamicProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY, deviceId); dynamicProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY,
deviceId + "@" + XmppConfig.getInstance().getXmppServerName());
dynamicProperties.put(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "CONTROL-REQUEST"); dynamicProperties.put(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "CONTROL-REQUEST");
dynamicProperties.put(VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY, dynamicProperties.put(VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY,
VirtualFireAlarmConstants.CHAT_PROPERTY_KEY); VirtualFireAlarmConstants.CHAT_PROPERTY_KEY);
@ -91,7 +117,6 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
dynamicProperties, encryptedMsg); dynamicProperties, encryptedMsg);
break; break;
default: default:
String publishTopic = APIUtil.getTenantDomainOftheUser() + "/" String publishTopic = APIUtil.getTenantDomainOftheUser() + "/"
+ VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId; + VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId;
dynamicProperties.put(VirtualFireAlarmConstants.ADAPTER_TOPIC_PROPERTY, publishTopic); dynamicProperties.put(VirtualFireAlarmConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
@ -131,7 +156,8 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
Map<String, String> dynamicProperties = new HashMap<>(); Map<String, String> dynamicProperties = new HashMap<>();
switch (protocolString) { switch (protocolString) {
case XMPP_PROTOCOL: case XMPP_PROTOCOL:
dynamicProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY, deviceId); dynamicProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY,
deviceId + "@" + XmppConfig.getInstance().getXmppServerName());
dynamicProperties.put(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "POLICTY-REQUEST"); dynamicProperties.put(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "POLICTY-REQUEST");
dynamicProperties.put(VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY, dynamicProperties.put(VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY,
VirtualFireAlarmConstants.CHAT_PROPERTY_KEY); VirtualFireAlarmConstants.CHAT_PROPERTY_KEY);
@ -190,4 +216,120 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
} }
} }
@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 resp = response.build();
zipFile.getZipFile().delete();
return resp;
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (VirtualFirealarmDeviceMgtPluginException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
}
}
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(VirtualFireAlarmConstants.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(VirtualFireAlarmConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
return APIUtil.getDeviceManagementService().enrollDevice(device);
} catch (DeviceManagementException e) {
log.error(e.getMessage(), e);
return false;
}
}
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
throws DeviceManagementException, APIManagerException, JWTClientException,
UserStoreException, VirtualFirealarmDeviceMgtPluginException {
//create new device id
String deviceId = shortUUID();
if (apiApplicationKey == null) {
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {VirtualFireAlarmConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
VirtualFireAlarmConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + VirtualFireAlarmConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner,
scopes);
String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken();
//adding registering data
XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(deviceId);
newXmppAccount.setUsername(deviceId);
newXmppAccount.setPassword(accessToken);
newXmppAccount.setEmail(deviceId + "@" + APIUtil.getTenantDomainOftheUser());
boolean status;
if (XmppConfig.getInstance().isEnabled()) {
status = XmppServerClient.createAccount(newXmppAccount);
if (!status) {
String msg = "XMPP Account was not created for device - " + deviceId + " of owner - " + owner +
".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot" +
".common.config.server.configs";
throw new DeviceManagementException(msg);
}
}
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);
}
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);
}
} }

@ -53,7 +53,7 @@ public class ZipUtil {
String iotServerIP; String iotServerIP;
try { try {
iotServerIP = Utils.getHostName(); iotServerIP = Utils.getServerUrl();
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY); String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY); String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort; String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
@ -80,7 +80,7 @@ public class ZipUtil {
contextParams.put("XMPP_EP", "XMPP:" + xmppEndpoint); contextParams.put("XMPP_EP", "XMPP:" + xmppEndpoint);
contextParams.put("DEVICE_TOKEN", token); contextParams.put("DEVICE_TOKEN", token);
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken); contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
contextParams.put("SERVER_NAME", XmppConfig.getInstance().getXmppServerName());
ZipArchive zipFile; ZipArchive zipFile;
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
return zipFile; return zipFile;

@ -28,48 +28,13 @@
<PermissionConfiguration> <PermissionConfiguration>
<APIVersion></APIVersion> <APIVersion></APIVersion>
<!-- Device related APIs --> <!-- Device related APIs -->
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/enrollment/devices/*</url>
<method>GET</method>
<scope>virtual_firealarm_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/enrollment/devices/*</url>
<method>DELETE</method>
<scope>virtual_firealarm_user</scope>
</Permission>
<Permission> <Permission>
<name>Download device</name> <name>Download device</name>
<path>/device-mgt/virtual_firealarm/user</path> <path>/device-mgt/user/devices</path>
<url>/enrollment/devices/download</url> <url>/device/download</url>
<method>GET</method> <method>GET</method>
<scope>virtual_firealarm_user</scope> <scope>virtual_firealarm_user</scope>
</Permission> </Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/enrollment/devices/*</url>
<method>POST</method>
<scope>virtual_firealarm_user</scope>
</Permission>
<Permission>
<name>Get Devices</name>
<path>/device-mgt/user/devices/list</path>
<url>/enrollment/devices</url>
<method>GET</method>
<scope>virtual_firealarm_user</scope>
</Permission>
<Permission>
<name>Register Device</name>
<path>/device-mgt/user/operations</path>
<url>/device/register/*/*/*</url>
<method>POST</method>
<scope>virtual_firealarm_device</scope>
</Permission>
<Permission> <Permission>
<name>Control Buzz</name> <name>Control Buzz</name>
<path>/device-mgt/user/operations</path> <path>/device-mgt/user/operations</path>
@ -77,13 +42,6 @@
<method>POST</method> <method>POST</method>
<scope>virtual_firealarm_user</scope> <scope>virtual_firealarm_user</scope>
</Permission> </Permission>
<Permission>
<name>Push Temperature</name>
<path>/device-mgt/user/stats</path>
<url>/device/temperature</url>
<method>POST</method>
<scope>virtual_firealarm_device</scope>
</Permission>
<Permission> <Permission>
<name>Get Stats</name> <name>Get Stats</name>
<path>/device-mgt/user/stats</path> <path>/device-mgt/user/stats</path>

@ -25,11 +25,8 @@
<jaxrs:server id="VirtualFireAlarm" address="/"> <jaxrs:server id="VirtualFireAlarm" address="/">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<bean id="VirtualFireAlarmControllerService" <bean id="VirtualFireAlarmService"
class="org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.VirtualFireAlarmControllerServiceImpl"> class="org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.VirtualFireAlarmServiceImpl">
</bean>
<bean id="VirtualFireAlarmManagerService"
class="org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.VirtualFireAlarmManagerServiceImpl">
</bean> </bean>
</jaxrs:serviceBeans> </jaxrs:serviceBeans>
<jaxrs:providers> <jaxrs:providers>

@ -80,11 +80,12 @@ public class VirtualFireAlarmConstants {
public static final String IS_ENABLED_KEY = "enabled"; public static final String IS_ENABLED_KEY = "enabled";
public static final String HOST_KEY = "host"; public static final String HOST_KEY = "host";
public static final String PORT_KEY = "port"; public static final String PORT_KEY = "port";
public static final String CONNECTION_PORT = "connection.port";
public static final String ADMIN_USERNAME = "admin.username"; public static final String ADMIN_USERNAME = "admin.username";
public static final String ADMIN_PASSWORD = "admin.password"; public static final String ADMIN_PASSWORD = "admin.password";
public static final String XMPP_SERVER_PASSWORD = "admin@123456789"; public static final String XMPP_SERVER_PASSWORD = "admin@123456789";
public static final String SERVER_NAME = "serverName";
public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator
+ "mqtt.properties"; + "mqtt.properties";
public static final String XMPP_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator public static final String XMPP_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator

@ -38,6 +38,8 @@ 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.OutputEventAdapterConfiguration;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.utils.NetworkUtils;
import javax.naming.Context; import javax.naming.Context;
import javax.naming.InitialContext; import javax.naming.InitialContext;
import javax.naming.NamingException; import javax.naming.NamingException;
@ -45,6 +47,7 @@ import javax.sql.DataSource;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.SocketException;
import java.security.PublicKey; import java.security.PublicKey;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.sql.Connection; import java.sql.Connection;
@ -359,7 +362,8 @@ public class VirtualFireAlarmUtils {
xmppAdapterProperties.put(VirtualFireAlarmConstants.PORT_KEY, String.valueOf(xmppConfig.getXmppServerPort())); xmppAdapterProperties.put(VirtualFireAlarmConstants.PORT_KEY, String.valueOf(xmppConfig.getXmppServerPort()));
xmppAdapterProperties.put(VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminUsername()); xmppAdapterProperties.put(VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminUsername());
xmppAdapterProperties.put(VirtualFireAlarmConstants.PASSWORD_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminPassword()); xmppAdapterProperties.put(VirtualFireAlarmConstants.PASSWORD_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminPassword());
xmppAdapterProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminJID()); xmppAdapterProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminJID()
+ "/input-adapter");
xmppAdapterProperties.put(VirtualFireAlarmConstants.CONTENT_TRANSFORMATION, xmppAdapterProperties.put(VirtualFireAlarmConstants.CONTENT_TRANSFORMATION,
VirtualFirealarmXmppContentTransformer.class.getName()); VirtualFirealarmXmppContentTransformer.class.getName());
xmppAdapterProperties.put(VirtualFireAlarmConstants.CONTENT_VALIDATION, "default"); xmppAdapterProperties.put(VirtualFireAlarmConstants.CONTENT_VALIDATION, "default");
@ -397,7 +401,8 @@ public class VirtualFireAlarmUtils {
xmppAdapterProperties.put(VirtualFireAlarmConstants.PORT_KEY, String.valueOf(xmppConfig.getXmppServerPort())); xmppAdapterProperties.put(VirtualFireAlarmConstants.PORT_KEY, String.valueOf(xmppConfig.getXmppServerPort()));
xmppAdapterProperties.put(VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminUsername()); xmppAdapterProperties.put(VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminUsername());
xmppAdapterProperties.put(VirtualFireAlarmConstants.PASSWORD_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminPassword()); xmppAdapterProperties.put(VirtualFireAlarmConstants.PASSWORD_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminPassword());
xmppAdapterProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminJID()); xmppAdapterProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminJID()
+ "/output-adapter");
outputEventAdapterConfiguration.setStaticProperties(xmppAdapterProperties); outputEventAdapterConfiguration.setStaticProperties(xmppAdapterProperties);
return outputEventAdapterConfiguration; return outputEventAdapterConfiguration;
} }

@ -14,6 +14,9 @@ public class VirtualFirealarmEventAdapterSubscription implements InputEventAdapt
if (actualMessage.contains("PUBLISHER")) { if (actualMessage.contains("PUBLISHER")) {
float temperature = Float.parseFloat(actualMessage.split(":")[2]); float temperature = Float.parseFloat(actualMessage.split(":")[2]);
VirtualFireAlarmUtils.publishToDAS(deviceId, temperature); VirtualFireAlarmUtils.publishToDAS(deviceId, temperature);
} else {
float temperature = Float.parseFloat(actualMessage.split(":")[1]);
VirtualFireAlarmUtils.publishToDAS(deviceId, temperature);
} }
} }
} }

@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFireAlarmUtils;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -37,6 +38,7 @@ public class XmppConfig {
private String virtualFirealarmAdminUsername; private String virtualFirealarmAdminUsername;
private String virtualFirealarmAdminPassword; private String virtualFirealarmAdminPassword;
private String virtualFirealarmAdminJID; private String virtualFirealarmAdminJID;
private String xmppServerName;
private static XmppConfig xmppConfig = new XmppConfig(); private static XmppConfig xmppConfig = new XmppConfig();
private static final Log log = LogFactory.getLog(XmppConfig.class); private static final Log log = LogFactory.getLog(XmppConfig.class);
@ -48,12 +50,13 @@ public class XmppConfig {
Properties properties = new Properties(); Properties properties = new Properties();
properties.load(propertyStream); properties.load(propertyStream);
xmppServerIP = properties.getProperty(VirtualFireAlarmConstants.HOST_KEY); xmppServerIP = properties.getProperty(VirtualFireAlarmConstants.HOST_KEY);
xmppServerName = properties.getProperty(VirtualFireAlarmConstants.SERVER_NAME);
xmppServerPort = Integer.parseInt(properties.getProperty(VirtualFireAlarmConstants.PORT_KEY)); xmppServerPort = Integer.parseInt(properties.getProperty(VirtualFireAlarmConstants.PORT_KEY));
isEnabled = Boolean.parseBoolean(properties.getProperty(VirtualFireAlarmConstants.IS_ENABLED_KEY)); isEnabled = Boolean.parseBoolean(properties.getProperty(VirtualFireAlarmConstants.IS_ENABLED_KEY));
xmppUsername = properties.getProperty(VirtualFireAlarmConstants.ADMIN_USERNAME); xmppUsername = properties.getProperty(VirtualFireAlarmConstants.ADMIN_USERNAME);
xmppPassword = properties.getProperty(VirtualFireAlarmConstants.ADMIN_PASSWORD); xmppPassword = properties.getProperty(VirtualFireAlarmConstants.ADMIN_PASSWORD);
virtualFirealarmAdminUsername = "wso2admin_" + VirtualFireAlarmConstants.DEVICE_TYPE; virtualFirealarmAdminUsername = "wso2admin_" + VirtualFireAlarmConstants.DEVICE_TYPE;
virtualFirealarmAdminJID = virtualFirealarmAdminUsername + "@" + xmppServerIP; virtualFirealarmAdminJID = virtualFirealarmAdminUsername + "@" + xmppServerName;
virtualFirealarmAdminPassword = VirtualFireAlarmConstants.XMPP_SERVER_PASSWORD; virtualFirealarmAdminPassword = VirtualFireAlarmConstants.XMPP_SERVER_PASSWORD;
} catch (IOException e) { } catch (IOException e) {
log.error(e); log.error(e);
@ -97,4 +100,7 @@ public class XmppConfig {
return virtualFirealarmAdminJID; return virtualFirealarmAdminJID;
} }
public String getXmppServerName() {
return xmppServerName;
}
} }

@ -18,8 +18,6 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.AccountManager; import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPConnection;
@ -36,7 +34,8 @@ public class XmppServerClient {
if (xmppAccount != null) { if (xmppAccount != null) {
try { try {
ConnectionConfiguration config = new ConnectionConfiguration(XmppConfig.getInstance().getXmppServerIP(), ConnectionConfiguration config = new ConnectionConfiguration(XmppConfig.getInstance().getXmppServerIP(),
XmppConfig.getInstance().getXmppServerPort()); XmppConfig.getInstance().getXmppServerPort(),
"Accounts");
XMPPConnection xmppConnection = new XMPPConnection(config); XMPPConnection xmppConnection = new XMPPConnection(config);
xmppConnection.connect(); xmppConnection.connect();
xmppConnection.login(XmppConfig.getInstance().getXmppUsername(), XmppConfig.getInstance().getXmppPassword()); xmppConnection.login(XmppConfig.getInstance().getXmppUsername(), XmppConfig.getInstance().getXmppPassword());

@ -32,10 +32,10 @@ public class XmppUtil {
XmppServerClient xmppServerClient = new XmppServerClient(); XmppServerClient xmppServerClient = new XmppServerClient();
try { try {
XmppAccount xmppAccount = new XmppAccount(); XmppAccount xmppAccount = new XmppAccount();
xmppAccount.setAccountName(XmppConfig.getInstance().getVirtualFirealarmAdminJID()); xmppAccount.setAccountName(XmppConfig.getInstance().getVirtualFirealarmAdminUsername());
xmppAccount.setUsername(XmppConfig.getInstance().getVirtualFirealarmAdminUsername()); xmppAccount.setUsername(XmppConfig.getInstance().getVirtualFirealarmAdminUsername());
xmppAccount.setPassword(XmppConfig.getInstance().getVirtualFirealarmAdminPassword()); xmppAccount.setPassword(XmppConfig.getInstance().getVirtualFirealarmAdminPassword());
xmppAccount.setEmail(""); xmppAccount.setEmail(XmppConfig.getInstance().getVirtualFirealarmAdminJID());
xmppServerClient.createAccount(xmppAccount); xmppServerClient.createAccount(xmppAccount);
} catch (VirtualFirealarmDeviceMgtPluginException e) { } catch (VirtualFirealarmDeviceMgtPluginException e) {
String errorMsg = "An error was encountered whilst trying to create Server XMPP account for device-type - " String errorMsg = "An error was encountered whilst trying to create Server XMPP account for device-type - "

@ -21,8 +21,7 @@ function onRequest(context) {
var deviceType = context.uriParams.deviceType; var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("id"); var deviceId = request.getParameter("id");
var autoCompleteParams = [ var autoCompleteParams = [
{"name" : "deviceId", "value" : deviceId}, {"name" : "deviceId", "value" : deviceId}
{"name" : "protocol", "value" : "MQTT"}
]; ];
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {

@ -2,6 +2,6 @@
"deviceType": { "deviceType": {
"label": "Virtual Firealarm", "label": "Virtual Firealarm",
"category": "virtual", "category": "virtual",
"downloadAgentUri": "virtual_firealarm/enrollment/devices/download" "downloadAgentUri": "virtual_firealarm/device/download"
} }
} }

@ -3,3 +3,4 @@ host=localhost
port=5222 port=5222
admin.username=admin admin.username=admin
admin.password=admin admin.password=admin
serverName=localhost

@ -31,5 +31,5 @@ auth-method=token
auth-token=${DEVICE_TOKEN} auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN} refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15 push-interval=15
xmpp-server-name=${SERVER_NAME}

@ -31,5 +31,5 @@ auth-method=token
auth-token=${DEVICE_TOKEN} auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN} refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15 push-interval=15
xmpp-server-name=${SERVER_NAME}

Loading…
Cancel
Save