Add REST Api annotations to Api implementations.

revert-dabc3590
NuwanSameera 9 years ago
parent 20c88f1d30
commit 2d4f07fc55

@ -31,7 +31,18 @@ import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager; import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord; import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
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.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
@ -51,7 +62,10 @@ public class ArduinoControllerServiceImpl implements ArduinoControllerService {
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
@Override @Override
public Response registerDeviceIP(String deviceId, String deviceIP, String devicePort, HttpServletRequest request) { @Path("device/register/{deviceId}/{ip}/{port}")
@POST
public Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort, @Context HttpServletRequest request) {
String result; String result;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: "); log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: ");
@ -66,7 +80,10 @@ public class ArduinoControllerServiceImpl implements ArduinoControllerService {
} }
@Override @Override
public Response switchBulb(String deviceId, String protocol, String state) { @Path("device/{deviceId}/bulb")
@POST
public Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol,
@FormParam("state") String state) {
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId); LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
String operation = "BULB:" + state.toUpperCase(); String operation = "BULB:" + state.toUpperCase();
@ -82,7 +99,12 @@ public class ArduinoControllerServiceImpl implements ArduinoControllerService {
} }
@Override @Override
public Response requestTemperature(String deviceId, String protocol) { @Path("device/{deviceId}/temperature")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response requestTemperature(@PathParam("deviceId") String deviceId,
@QueryParam("protocol") String protocol) {
try { try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
@ -94,6 +116,9 @@ public class ArduinoControllerServiceImpl implements ArduinoControllerService {
} }
@Override @Override
@Path("device/sensor")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response pushData(DeviceData dataMsg) { public Response pushData(DeviceData dataMsg) {
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String deviceId = dataMsg.deviceId; String deviceId = dataMsg.deviceId;
@ -110,7 +135,9 @@ public class ArduinoControllerServiceImpl implements ArduinoControllerService {
} }
@Override @Override
public Response readControls(String deviceId, String protocol) { @Path("device/{deviceId}/controls")
@GET
public Response readControls(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol) {
String result; String result;
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId); LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
@ -138,7 +165,10 @@ public class ArduinoControllerServiceImpl implements ArduinoControllerService {
} }
@Override @Override
public Response pushTemperatureData(final DeviceData dataMsg, HttpServletRequest request) { @Path("device/temperature")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response pushTemperatureData(final DeviceData dataMsg, @Context HttpServletRequest request) {
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String deviceId = dataMsg.deviceId; String deviceId = dataMsg.deviceId;
float temperature = dataMsg.value; float temperature = dataMsg.value;
@ -154,7 +184,12 @@ public class ArduinoControllerServiceImpl implements ArduinoControllerService {
} }
@Override @Override
public Response getArduinoTemperatureStats(String deviceId, long from, long to) { @Path("device/stats/{deviceId}/sensors/temperature")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getArduinoTemperatureStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to) {
String fromDate = String.valueOf(from); String fromDate = String.valueOf(from);
String toDate = String.valueOf(to); String toDate = String.valueOf(to);
List<SensorData> sensorDatas = new ArrayList<>(); List<SensorData> sensorDatas = new ArrayList<>();

@ -32,6 +32,7 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@Path("enrollment")
@API(name = "arduino_mgt", version = "1.0.0", context = "/arduino_mgt", tags = {"arduino"}) @API(name = "arduino_mgt", version = "1.0.0", context = "/arduino_mgt", tags = {"arduino"})
@DeviceType(value = "arduino") @DeviceType(value = "arduino")
public interface ArduinoManagerService { public interface ArduinoManagerService {

@ -18,7 +18,6 @@
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.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;
@ -27,7 +26,6 @@ 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.extensions.feature.mgt.annotations.DeviceType;
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.exception.DeviceControllerException; import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
@ -38,6 +36,16 @@ import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException; 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 javax.ws.rs.core.Response;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -46,15 +54,16 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@API(name = "arduino_mgt", version = "1.0.0", context = "/arduino_mgt", tags = {"arduino"}) @Path("enrollment")
@DeviceType(value = "arduino")
public class ArduinoManagerServiceImpl implements ArduinoManagerService { public class ArduinoManagerServiceImpl implements ArduinoManagerService {
private static final String KEY_TYPE = "PRODUCTION"; private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey; private static ApiApplicationKey apiApplicationKey;
@Override @Override
public Response removeDevice(String deviceId) { @Path("devices/{device_id}")
@DELETE
public Response removeDevice(@PathParam("device_id") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE); deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
@ -71,7 +80,9 @@ public class ArduinoManagerServiceImpl implements ArduinoManagerService {
} }
@Override @Override
public Response updateDevice(String deviceId, String name) { @Path("devices/{device_id}")
@PUT
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE); deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
@ -93,7 +104,11 @@ public class ArduinoManagerServiceImpl implements ArduinoManagerService {
} }
@Override @Override
public Response getDevice(String deviceId) { @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 deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE); deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
@ -106,6 +121,10 @@ public class ArduinoManagerServiceImpl implements ArduinoManagerService {
} }
@Override @Override
@Path("devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getArduinoDevices() { public Response getArduinoDevices() {
try { try {
List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser( List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser(
@ -125,7 +144,10 @@ public class ArduinoManagerServiceImpl implements ArduinoManagerService {
} }
@Override @Override
public Response downloadSketch(String customDeviceName) { @Path("devices/download")
@GET
@Produces("application/octet-stream")
public Response downloadSketch(@QueryParam("deviceName") String customDeviceName) {
try { try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), customDeviceName); ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), customDeviceName);
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
@ -147,7 +169,9 @@ public class ArduinoManagerServiceImpl implements ArduinoManagerService {
} }
@Override @Override
public Response generateSketchLink(String deviceName) { @Path("devices/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName) {
try { try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName); ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());

@ -7,56 +7,40 @@
<display-name>Arduino</display-name> <display-name>Arduino</display-name>
<description>Arduino</description> <description>Arduino</description>
<servlet> <servlet>
<servlet-name>CXFServlet</servlet-name> <servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup> <load-on-startup>1</load-on-startup>
</servlet> </servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<servlet-mapping> <url-pattern>/*</url-pattern>
<servlet-name>CXFServlet</servlet-name> </servlet-mapping>
<url-pattern>/*</url-pattern> <context-param>
</servlet-mapping> <param-name>isAdminService</param-name>
<param-value>false</param-value>
<context-param> </context-param>
<param-name>isAdminService</param-name> <context-param>
<param-value>false</param-value> <param-name>doAuthentication</param-name>
</context-param> <param-value>true</param-value>
<context-param> </context-param>
<param-name>doAuthentication</param-name> <context-param>
<param-value>false</param-value> <param-name>isSharedWithAllTenants</param-name>
</context-param> <param-value>true</param-value>
<context-param> </context-param>
<param-name>isSharedWithAllTenants</param-name> <context-param>
<param-value>true</param-value> <param-name>providerTenantDomain</param-name>
</context-param> <param-value>carbon.super</param-value>
<context-param> </context-param>
<param-name>providerTenantDomain</param-name>
<param-value>carbon.super</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/arduino/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>arduino</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
</web-app> </web-app>

@ -21,11 +21,11 @@ package org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.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.websocket.server.PathParam;
import javax.ws.rs.FormParam; import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam; import javax.ws.rs.HeaderParam;
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.core.Response; import javax.ws.rs.core.Response;
@API(name = "digital_display", version = "1.0.0", context = "/digital_display", tags = {"digital_display"}) @API(name = "digital_display", version = "1.0.0", context = "/digital_display", tags = {"digital_display"})
@ -54,7 +54,7 @@ public interface DigitalDisplayControllerService {
@POST @POST
@Feature(code = "terminate-display", name = "Terminate Display", type = "operation", @Feature(code = "terminate-display", name = "Terminate Display", type = "operation",
description = "Terminate all running process in Digital Display") description = "Terminate all running process in Digital Display")
Response terminateDisplay(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId); Response terminateDisplay(@HeaderParam("sessionId") String sessionId, @PathParam("deviceId") String deviceId);
/** /**
* Reboot running digital display * Reboot running digital display

@ -20,10 +20,8 @@ package org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.exception.DigitalDisplayException; import org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.exception.DigitalDisplayException;
@ -32,13 +30,11 @@ import org.wso2.carbon.device.mgt.iot.digitaldisplay.plugin.constants.DigitalDis
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener; import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import javax.ws.rs.FormParam; import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam; import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.core.Context; import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
public class DigitalDisplayControllerServiceImpl implements DigitalDisplayControllerService { public class DigitalDisplayControllerServiceImpl implements DigitalDisplayControllerService {
@ -46,44 +42,9 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
private static Log log = LogFactory.getLog(DigitalDisplayControllerServiceImpl.class); private static Log log = LogFactory.getLog(DigitalDisplayControllerServiceImpl.class);
private static DigitalDisplayMQTTConnector digitalDisplayMQTTConnector; private static DigitalDisplayMQTTConnector digitalDisplayMQTTConnector;
private boolean waitForServerStartup() { @Path("device/{deviceId}/restart-browser")
while (!IoTServerStartupListener.isServerReady()) { @POST
try { public Response restartBrowser(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId) {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public DigitalDisplayMQTTConnector getDigitalDisplayMQTTConnector() {
return DigitalDisplayControllerServiceImpl.digitalDisplayMQTTConnector;
}
public void setDigitalDisplayMQTTConnector(final
DigitalDisplayMQTTConnector digitalDisplayMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
DigitalDisplayControllerServiceImpl.digitalDisplayMQTTConnector = digitalDisplayMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
digitalDisplayMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. " +
"Hence, DigitalDisplayMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
public Response restartBrowser(String deviceId, String sessionId) {
try { try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_BROWSER_CONSTANT + "::", ""); sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_BROWSER_CONSTANT + "::", "");
return Response.ok().build(); return Response.ok().build();
@ -94,7 +55,10 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
} }
} }
public Response terminateDisplay(String deviceId, String sessionId) { @Path("device/{deviceId}/terminate-display")
@POST
public Response terminateDisplay(@HeaderParam("sessionId") String sessionId,
@PathParam("deviceId") String deviceId) {
try { try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.TERMINATE_DISPLAY_CONSTANT + "::", ""); sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.TERMINATE_DISPLAY_CONSTANT + "::", "");
return Response.ok().build(); return Response.ok().build();
@ -103,10 +67,11 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
} catch (DigitalDisplayException e) { } catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} }
} }
public Response restartDisplay(String deviceId, String sessionId) { @Path("device/{deviceId}/restart-display")
@POST
public Response restartDisplay(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId) {
try { try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_DISPLAY_CONSTANT + "::", ""); sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_DISPLAY_CONSTANT + "::", "");
return Response.ok().build(); return Response.ok().build();
@ -117,7 +82,11 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
} }
} }
public Response editSequence(String deviceId, String name, String attribute, String newValue, String sessionId) { @Path("device/{deviceId}/edit-sequence")
@POST
public Response editSequence(@PathParam("deviceId") String deviceId, @FormParam("name") String name,
@FormParam("attribute") String attribute, @FormParam("new-value") String newValue,
@HeaderParam("sessionId") String sessionId) {
try { try {
String params = name + "|" + attribute + "|" + newValue; String params = name + "|" + attribute + "|" + newValue;
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.EDIT_SEQUENCE_CONSTANT + "::", params); sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.EDIT_SEQUENCE_CONSTANT + "::", params);
@ -129,7 +98,12 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
} }
} }
public Response uploadContent(String deviceId, String remotePath, String screenName, String sessionId) {
@Path("device/{deviceId}/upload-content")
@POST
public Response uploadContent(@PathParam("deviceId") String deviceId, @FormParam("remote-path") String remotePath,
@FormParam("screen-name") String screenName,
@HeaderParam("sessionId") String sessionId) {
try { try {
String params = remotePath + "|" + screenName; String params = remotePath + "|" + screenName;
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.UPLOAD_CONTENT_CONSTANT + "::", sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.UPLOAD_CONTENT_CONSTANT + "::",
@ -142,8 +116,12 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
} }
} }
public Response addNewResource(String deviceId, String type, String time, String path, String name, String position, @Path("device/{deviceId}/add-resource")
String sessionId) { @POST
public Response addNewResource(@PathParam("deviceId") String deviceId, @FormParam("type") String type,
@FormParam("time") String time, @FormParam("path") String path,
@FormParam("name") String name, @FormParam("position") String position,
@HeaderParam("sessionId") String sessionId) {
String params; String params;
try { try {
if (position.isEmpty()) { if (position.isEmpty()) {
@ -161,7 +139,10 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
} }
} }
public Response removeResource(String deviceId, String name, String sessionId) { @Path("device/{deviceId}/remove-resource")
@POST
public Response removeResource(@PathParam("deviceId") String deviceId, @FormParam("name") String name,
@HeaderParam("sessionId") String sessionId) {
try { try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.REMOVE_RESOURCE_CONSTANT + "::", name); sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.REMOVE_RESOURCE_CONSTANT + "::", name);
return Response.ok().build(); return Response.ok().build();
@ -172,7 +153,9 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
} }
} }
public Response restartServer(String deviceId, String sessionId) { @Path("device/{deviceId}/restart-server")
@POST
public Response restartServer(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId) {
try { try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_SERVER_CONSTANT + "::", ""); sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_SERVER_CONSTANT + "::", "");
return Response.ok().build(); return Response.ok().build();
@ -183,7 +166,10 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
} }
} }
public Response showScreenshot(String deviceId, String sessionId) {
@Path("device/{deviceId}/screenshot")
@POST
public Response showScreenshot(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId) {
try { try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.SCREENSHOT_CONSTANT + "::", ""); sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.SCREENSHOT_CONSTANT + "::", "");
return Response.ok().build(); return Response.ok().build();
@ -194,7 +180,10 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
} }
} }
public Response getDevicestatus(String deviceId, String sessionId) { @Path("device/{deviceId}/get-device-status")
@POST
public Response getDevicestatus(@PathParam("deviceId") String deviceId,
@HeaderParam("sessionId") String sessionId) {
try { try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.GET_DEVICE_STATUS_CONSTANT + "::", ""); sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.GET_DEVICE_STATUS_CONSTANT + "::", "");
return Response.ok().build(); return Response.ok().build();
@ -205,7 +194,9 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
} }
} }
public Response getResources(String deviceId, String sessionId) { @Path("device/{deviceId}/get-content-list")
@POST
public Response getResources(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId) {
try { try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.GET_CONTENTLIST_CONSTANT + "::", ""); sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.GET_CONTENTLIST_CONSTANT + "::", "");
return Response.ok().build(); return Response.ok().build();
@ -239,4 +230,41 @@ public class DigitalDisplayControllerServiceImpl implements DigitalDisplayContro
} }
} }
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public DigitalDisplayMQTTConnector getDigitalDisplayMQTTConnector() {
return DigitalDisplayControllerServiceImpl.digitalDisplayMQTTConnector;
}
public void setDigitalDisplayMQTTConnector(final
DigitalDisplayMQTTConnector digitalDisplayMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
DigitalDisplayControllerServiceImpl.digitalDisplayMQTTConnector = digitalDisplayMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
digitalDisplayMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. " +
"Hence, DigitalDisplayMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
} }

@ -24,7 +24,6 @@ import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT; import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
@ -33,6 +32,7 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@Path("enrollment")
@API(name = "digital_display_mgt", version = "1.0.0", context = "/digital_display_mgt", tags = {"digital_display"}) @API(name = "digital_display_mgt", version = "1.0.0", context = "/digital_display_mgt", tags = {"digital_display"})
@DeviceType(value = "digital_display") @DeviceType(value = "digital_display")
public interface DigitalDisplayManagerService { public interface DigitalDisplayManagerService {

@ -40,6 +40,15 @@ import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException; 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 javax.ws.rs.core.Response;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
@ -47,38 +56,16 @@ import java.nio.charset.StandardCharsets;
import java.util.Date; import java.util.Date;
import java.util.UUID; import java.util.UUID;
@Path("enrollment")
public class DigitalDisplayManagerServiceImpl implements DigitalDisplayManagerService { public class DigitalDisplayManagerServiceImpl implements DigitalDisplayManagerService {
private static Log log = LogFactory.getLog(DigitalDisplayManagerServiceImpl.class); private static Log log = LogFactory.getLog(DigitalDisplayManagerServiceImpl.class);
private static final String KEY_TYPE = "PRODUCTION"; private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey; private static ApiApplicationKey apiApplicationKey;
private boolean register(String deviceId, String name) { @Path("devices/{device_id}")
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); @DELETE
deviceIdentifier.setId(deviceId); public Response removeDevice(@PathParam("device_id") String deviceId) {
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(DigitalDisplayConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
}
}
public Response removeDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE); deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
@ -95,7 +82,9 @@ public class DigitalDisplayManagerServiceImpl implements DigitalDisplayManagerSe
} }
} }
public Response updateDevice(String deviceId, String name) { @Path("devices/{device_id}")
@PUT
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE); deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
@ -115,8 +104,11 @@ public class DigitalDisplayManagerServiceImpl implements DigitalDisplayManagerSe
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} }
} }
@Path("devices/{device_id}")
public Response getDevice(String deviceId) { @GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getDevice(@PathParam("device_id") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE); deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
@ -128,10 +120,12 @@ public class DigitalDisplayManagerServiceImpl implements DigitalDisplayManagerSe
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} }
} }
@Path("devices/download")
public Response downloadSketch(String deviceName) { @GET
@Produces("application/octet-stream")
public Response downloadSketch(@QueryParam("deviceName") String customDeviceName) {
try { try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName); ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), customDeviceName);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.type("application/zip"); response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
@ -153,6 +147,31 @@ public class DigitalDisplayManagerServiceImpl implements DigitalDisplayManagerSe
} }
} }
private boolean register(String deviceId, String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(DigitalDisplayConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
}
}
private ZipArchive createDownloadFile(String owner, String deviceName) private ZipArchive createDownloadFile(String owner, String deviceName)
throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException, throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException,
UserStoreException { UserStoreException {

@ -24,7 +24,7 @@
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="DigitalDisplayController" address="/controller"> <jaxrs:server id="DigitalDisplay" address="/">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<bean id="DigitalDisplayManagerControllerService" <bean id="DigitalDisplayManagerControllerService"
class="org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.DigitalDisplayControllerServiceImpl"> class="org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.DigitalDisplayControllerServiceImpl">

@ -21,28 +21,16 @@
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"> version="2.5">
<display-name>Digital-Display-Agent-Webapp</display-name> <display-name>Digital-Display-Agent-Webapp</display-name>
<servlet> <servlet>
<description>JAX-WS/JAX-RS MDM Android Endpoint</description>
<display-name>JAX-WS/JAX-RS Servlet</display-name>
<servlet-name>CXFServlet</servlet-name> <servlet-name>CXFServlet</servlet-name>
<servlet-class> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<load-on-startup>1</load-on-startup> <load-on-startup>1</load-on-startup>
</servlet> </servlet>
<servlet-mapping> <servlet-mapping>
<servlet-name>CXFServlet</servlet-name> <servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern> <url-pattern>/*</url-pattern>
</servlet-mapping> </servlet-mapping>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>providerTenantDomain</param-name>
<param-value>carbon.super</param-value>
</context-param>
<context-param> <context-param>
<param-name>isAdminService</param-name> <param-name>isAdminService</param-name>
<param-value>false</param-value> <param-value>false</param-value>
@ -51,6 +39,14 @@
<param-name>doAuthentication</param-name> <param-name>doAuthentication</param-name>
<param-value>true</param-value> <param-value>true</param-value>
</context-param> </context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>providerTenantDomain</param-name>
<param-value>carbon.super</param-value>
</context-param>
<!--publish to apim--> <!--publish to apim-->
<context-param> <context-param>
@ -61,17 +57,5 @@
<param-name>managed-api-owner</param-name> <param-name>managed-api-owner</param-name>
<param-value>admin</param-value> <param-value>admin</param-value>
</context-param> </context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/digital_display/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>digital_display</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
</web-app> </web-app>

@ -38,7 +38,10 @@ public class DroneControllerServiceImpl implements DroneControllerService {
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private DroneController droneController = new DroneControllerImpl(); private DroneController droneController = new DroneControllerImpl();
public Response registerDeviceIP(String deviceId, String deviceIP, String devicePort) { @Path("device/register/{deviceId}/{ip}/{port}")
@POST
public Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort) {
String result; String result;
String deviceHttpEndpoint = deviceIP + ":" + devicePort; String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint); deviceToIpMap.put(deviceId, deviceHttpEndpoint);
@ -49,7 +52,10 @@ public class DroneControllerServiceImpl implements DroneControllerService {
return Response.ok(Response.Status.OK.getStatusCode()).build(); return Response.ok(Response.Status.OK.getStatusCode()).build();
} }
public Response droneController(String deviceId, String action, String duration, String speed) { @Path("device/{deviceId}/send_command")
@POST
public Response droneController(@PathParam("deviceId") String deviceId, @FormParam("action") String action,
@FormParam("duration") String duration, @FormParam("speed") String speed) {
try { try {
DroneAnalyzerServiceUtils.sendControlCommand(droneController, deviceId, action, Double.valueOf(speed), DroneAnalyzerServiceUtils.sendControlCommand(droneController, deviceId, action, Double.valueOf(speed),
Double.valueOf(duration)); Double.valueOf(duration));

@ -31,6 +31,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;
@Path("enrollment")
@API(name = "drone_analyzer_mgt", version = "1.0.0", context = "/drone_analyzer_mgt", tags = {"drone_analyzer"}) @API(name = "drone_analyzer_mgt", version = "1.0.0", context = "/drone_analyzer_mgt", tags = {"drone_analyzer"})
@DeviceType(value = "drone_analyzer") @DeviceType(value = "drone_analyzer")
public interface DroneManagerService { public interface DroneManagerService {

@ -40,6 +40,15 @@ import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException; 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.Response; import javax.ws.rs.core.Response;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -48,39 +57,16 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@Path("enrollment")
public class DroneManagerServiceImpl implements DroneManagerService { public class DroneManagerServiceImpl implements DroneManagerService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneManagerServiceImpl.class); private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneManagerServiceImpl.class);
private static final String KEY_TYPE = "PRODUCTION"; private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey; private static ApiApplicationKey apiApplicationKey;
private boolean register(String deviceId, String name) { @Path("devices/{device_id}")
try { @DELETE
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); public Response removeDevice(@PathParam("device_id") String deviceId) {
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.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(DroneConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
}
}
public Response removeDevice(String deviceId) {
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
@ -96,7 +82,10 @@ public class DroneManagerServiceImpl implements DroneManagerService {
} }
} }
public Response updateDevice(String deviceId, String name) {
@Path("devices/{device_id}")
@PUT
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
@ -117,7 +106,11 @@ public class DroneManagerServiceImpl implements DroneManagerService {
} }
} }
public Response getDevice(String deviceId) { @Path("devices/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getDevice(@PathParam("device_id") String deviceId) {
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
@ -129,6 +122,10 @@ public class DroneManagerServiceImpl implements DroneManagerService {
} }
} }
@Path("devices")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getDroneDevices() { public Response getDroneDevices() {
try { try {
List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser()); List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser());
@ -147,7 +144,11 @@ public class DroneManagerServiceImpl implements DroneManagerService {
} }
} }
public Response downloadSketch(String deviceName, String sketchType) { @Path("devices/{sketch_type}/download")
@GET
@Produces("application/octet-stream")
public Response downloadSketch(@QueryParam("deviceName") String deviceName, @PathParam("sketch_type") String
sketchType) {
//create new device id //create new device id
String deviceId = shortUUID(); String deviceId = shortUUID();
@ -173,10 +174,12 @@ public class DroneManagerServiceImpl implements DroneManagerService {
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return rb.build(); return rb.build();
} }
public Response generateSketchLink(String deviceName, String sketchType) { @Path("devices/{sketch_type}/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType) {
try { try {
ZipArchive zipFile = createDownloadFile(deviceName, sketchType); ZipArchive zipFile = createDownloadFile(deviceName, sketchType);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
@ -196,6 +199,32 @@ public class DroneManagerServiceImpl implements DroneManagerService {
} }
} }
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.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(DroneConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
}
}
private ZipArchive createDownloadFile(String deviceName, String sketchType) private ZipArchive createDownloadFile(String deviceName, String sketchType)
throws DeviceManagementException, JWTClientException, APIManagerException, DeviceControllerException, throws DeviceManagementException, JWTClientException, APIManagerException, DeviceControllerException,
UserStoreException { UserStoreException {

@ -6,44 +6,41 @@
metadata-complete="true"> metadata-complete="true">
<display-name>WSO2 IoT Server</display-name> <display-name>WSO2 IoT Server</display-name>
<description>WSO2 IoT Server</description> <description>WSO2 IoT Server</description>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param> <servlet>
<param-name>isAdminService</param-name> <servlet-name>CXFServlet</servlet-name>
<param-value>false</param-value> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</context-param> <load-on-startup>1</load-on-startup>
<context-param> </servlet>
<param-name>doAuthentication</param-name> <servlet-mapping>
<param-value>false</param-value> <servlet-name>CXFServlet</servlet-name>
</context-param> <url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>providerTenantDomain</param-name>
<param-value>carbon.super</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/drone_analyzer/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>drone_analyzer</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
</web-app> </web-app>

@ -71,7 +71,7 @@ public interface RaspberryPiControllerService {
@GET @GET
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
Response getArduinoTemperatureStats(@PathParam("deviceId") String deviceId, @QueryParam("username") String user, Response getRaspberryPiTemperatureStats(@PathParam("deviceId") String deviceId, @QueryParam("username") String user,
@QueryParam("from") long from, @QueryParam("to") long to); @QueryParam("from") long from, @QueryParam("to") long to);
} }

@ -25,6 +25,7 @@ import org.wso2.carbon.device.mgt.analytics.data.publisher.AnalyticsDataRecord;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DeviceManagementAnalyticsException; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DeviceManagementAnalyticsException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService; import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.dto.DeviceData; import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.dto.DeviceData;
@ -37,7 +38,16 @@ import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener; import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
@ -52,42 +62,10 @@ public class RaspberryPiControllerServiceImpl implements RaspberryPiControllerSe
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private RaspberryPiMQTTConnector raspberryPiMQTTConnector; private RaspberryPiMQTTConnector raspberryPiMQTTConnector;
private boolean waitForServerStartup() { @Path("device/register/{deviceId}/{ip}/{port}")
while (!IoTServerStartupListener.isServerReady()) { @POST
try { public Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
Thread.sleep(1000); @PathParam("port") String devicePort, @Context HttpServletRequest request) {
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public RaspberryPiMQTTConnector getRaspberryPiMQTTConnector() {
return raspberryPiMQTTConnector;
}
public void setRaspberryPiMQTTConnector(
final RaspberryPiMQTTConnector raspberryPiMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
RaspberryPiControllerServiceImpl.this.raspberryPiMQTTConnector = raspberryPiMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
raspberryPiMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, RaspberryPiMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
public Response registerDeviceIP(String deviceId, String deviceIP, String devicePort, HttpServletRequest request) {
String result; String result;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId); log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId);
@ -101,7 +79,9 @@ public class RaspberryPiControllerServiceImpl implements RaspberryPiControllerSe
return Response.ok().entity(result).build(); return Response.ok().entity(result).build();
} }
public Response switchBulb(String deviceId, String state) { @Path("device/{deviceId}/bulb")
@POST
public Response switchBulb(@PathParam("deviceId") String deviceId, @FormParam("state") String state) {
String switchToState = state.toUpperCase(); String switchToState = state.toUpperCase();
if (!switchToState.equals(RaspberrypiConstants.STATE_ON) && !switchToState.equals( if (!switchToState.equals(RaspberrypiConstants.STATE_ON) && !switchToState.equals(
RaspberrypiConstants.STATE_OFF)) { RaspberrypiConstants.STATE_OFF)) {
@ -122,6 +102,10 @@ public class RaspberryPiControllerServiceImpl implements RaspberryPiControllerSe
return Response.ok().build(); return Response.ok().build();
} }
@Path("device/{deviceId}/readtemperature")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response requestTemperature(@PathParam("deviceId") String deviceId) { public Response requestTemperature(@PathParam("deviceId") String deviceId) {
SensorRecord sensorRecord = null; SensorRecord sensorRecord = null;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -147,7 +131,10 @@ public class RaspberryPiControllerServiceImpl implements RaspberryPiControllerSe
return Response.ok().entity(sensorRecord).build(); return Response.ok().entity(sensorRecord).build();
} }
public Response pushTemperatureData(final DeviceData dataMsg, HttpServletRequest request) { @Path("device/push_temperature")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response pushTemperatureData(final DeviceData dataMsg, @Context HttpServletRequest request) {
String owner = dataMsg.owner; String owner = dataMsg.owner;
String deviceId = dataMsg.deviceId; String deviceId = dataMsg.deviceId;
String deviceIp = dataMsg.reply; String deviceIp = dataMsg.reply;
@ -176,7 +163,13 @@ public class RaspberryPiControllerServiceImpl implements RaspberryPiControllerSe
return Response.ok().build(); return Response.ok().build();
} }
public Response getArduinoTemperatureStats(String deviceId, String user, long from, long to) { @Path("device/stats/{deviceId}/sensors/temperature")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getRaspberryPiTemperatureStats(@PathParam("deviceId") String deviceId,
@QueryParam("username") String user,
@QueryParam("from") long from, @QueryParam("to") long to) {
String fromDate = String.valueOf(from); String fromDate = String.valueOf(from);
String toDate = String.valueOf(to); String toDate = String.valueOf(to);
List<SensorData> sensorDatas = new ArrayList<>(); List<SensorData> sensorDatas = new ArrayList<>();
@ -208,7 +201,7 @@ public class RaspberryPiControllerServiceImpl implements RaspberryPiControllerSe
sensorData.setValue("" + (float) record.getValue(RaspberrypiConstants.SENSOR_TEMPERATURE)); sensorData.setValue("" + (float) record.getValue(RaspberrypiConstants.SENSOR_TEMPERATURE));
sensorDatas.add(sensorData); sensorDatas.add(sensorData);
} }
SensorData[] sensorDetails = sensorDatas.toArray(new SensorData[sensorDatas.size()]); SensorData[] sensorDetails = sensorDatas.toArray(new SensorData[sensorDatas.size()]);
return Response.ok().entity(sensorDetails).build(); return Response.ok().entity(sensorDetails).build();
} catch (DeviceManagementAnalyticsException e) { } catch (DeviceManagementAnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
@ -218,4 +211,39 @@ public class RaspberryPiControllerServiceImpl implements RaspberryPiControllerSe
} }
} }
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public RaspberryPiMQTTConnector getRaspberryPiMQTTConnector() {
return raspberryPiMQTTConnector;
}
public void setRaspberryPiMQTTConnector(
final RaspberryPiMQTTConnector raspberryPiMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
RaspberryPiControllerServiceImpl.this.raspberryPiMQTTConnector = raspberryPiMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
raspberryPiMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, RaspberryPiMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
} }

@ -32,6 +32,7 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@Path("enrollment")
@API(name = "raspberrypi_mgt", version = "1.0.0", context = "/raspberrypi_mgt", tags = {"raspberrypi"}) @API(name = "raspberrypi_mgt", version = "1.0.0", context = "/raspberrypi_mgt", tags = {"raspberrypi"})
@DeviceType(value = "raspberrypi") @DeviceType(value = "raspberrypi")
public interface RaspberryPiManagerService { public interface RaspberryPiManagerService {
@ -43,7 +44,7 @@ public interface RaspberryPiManagerService {
@Path("devices/{device_id}") @Path("devices/{device_id}")
@PUT @PUT
Response updateDevice(@PathParam("device_id") String deviceId, Response updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name); @QueryParam("name") String name);
@Path("devices/{device_id}") @Path("devices/{device_id}")
@GET @GET
@ -57,16 +58,15 @@ public interface RaspberryPiManagerService {
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
Response getRaspberrypiDevices(); Response getRaspberrypiDevices();
@Path("devices/{sketch_type}/download") @Path("devices/{sketch_type}/download")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
Response downloadSketch(@QueryParam("deviceName") String deviceName, @PathParam("sketch_type") String Response downloadSketch(@QueryParam("deviceName") String deviceName,
sketchType); @PathParam("sketch_type") String sketchType);
@Path("devices/{sketch_type}/generate_link") @Path("devices/{sketch_type}/generate_link")
@GET @GET
Response generateSketchLink(@QueryParam("deviceName") String deviceName, Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType); @PathParam("sketch_type") String sketchType);
} }

@ -43,6 +43,15 @@ import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException; 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 javax.ws.rs.core.Response;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
@ -52,39 +61,16 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@Path("enrollment")
public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService { public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService {
private static Log log = LogFactory.getLog(RaspberryPiManagerServiceImpl.class); private static Log log = LogFactory.getLog(RaspberryPiManagerServiceImpl.class);
private static final String KEY_TYPE = "PRODUCTION"; private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey; private static ApiApplicationKey apiApplicationKey;
private boolean register(String deviceId, String name) { @Path("devices/{device_id}")
try { @DELETE
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); public Response removeDevice(@PathParam("device_id") String deviceId) {
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE);
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(RaspberrypiConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
}
}
public Response removeDevice(String deviceId) {
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
@ -101,7 +87,9 @@ public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService
} }
} }
public Response updateDevice(String deviceId, String name) { @Path("devices/{device_id}")
@PUT
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE); deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE);
@ -123,7 +111,11 @@ public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService
} }
} }
public Response getDevice(String deviceId) { @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 deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE); deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE);
@ -136,6 +128,10 @@ public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService
} }
} }
@Path("devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getRaspberrypiDevices() { public Response getRaspberrypiDevices() {
try { try {
List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser( List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser(
@ -154,7 +150,12 @@ public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService
} }
} }
public Response downloadSketch(String deviceName, String sketchType) {
@Path("devices/{sketch_type}/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType) {
try { try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
@ -178,8 +179,10 @@ public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService
} }
} }
public Response generateSketchLink(String deviceName, String sketchType) { @Path("devices/{sketch_type}/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType) {
try { try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
@ -199,6 +202,30 @@ public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService
} }
} }
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE);
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(RaspberrypiConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
}
}
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
throws DeviceManagementException, JWTClientException, APIManagerException, DeviceControllerException, throws DeviceManagementException, JWTClientException, APIManagerException, DeviceControllerException,

@ -7,48 +7,40 @@
<display-name>RaspberryPi</display-name> <display-name>RaspberryPi</display-name>
<description>RaspberryPi</description> <description>RaspberryPi</description>
<servlet> <servlet>
<servlet-name>CXFServlet</servlet-name> <servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup> <load-on-startup>1</load-on-startup>
</servlet> </servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<servlet-mapping> <url-pattern>/*</url-pattern>
<servlet-name>CXFServlet</servlet-name> </servlet-mapping>
<url-pattern>/*</url-pattern> <context-param>
</servlet-mapping> <param-name>isAdminService</param-name>
<param-value>false</param-value>
<context-param> </context-param>
<param-name>isAdminService</param-name> <context-param>
<param-value>false</param-value> <param-name>doAuthentication</param-name>
</context-param> <param-value>true</param-value>
<context-param> </context-param>
<param-name>doAuthentication</param-name> <context-param>
<param-value>true</param-value> <param-name>isSharedWithAllTenants</param-name>
</context-param> <param-value>true</param-value>
</context-param>
<!--publish to apim--> <context-param>
<context-param> <param-name>providerTenantDomain</param-name>
<param-name>managed-api-enabled</param-name> <param-value>carbon.super</param-value>
<param-value>true</param-value> </context-param>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/raspberrypi/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>raspberrypi</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
</web-app> </web-app>

@ -56,7 +56,7 @@ public interface VirtualFireAlarmControllerService {
* @return a custom message indicating whether the DeviceID to IP mapping was successful. * @return a custom message indicating whether the DeviceID to IP mapping was successful.
*/ */
@POST @POST
@Path("register/{deviceId}/{ip}/{port}") @Path("device/register/{deviceId}/{ip}/{port}")
Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP, Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort, @Context HttpServletRequest request); @PathParam("port") String devicePort, @Context HttpServletRequest request);
@ -72,7 +72,7 @@ public interface VirtualFireAlarmControllerService {
* (Case-Insensitive String) * (Case-Insensitive String)
*/ */
@POST @POST
@Path("{deviceId}/buzz") @Path("device/{deviceId}/buzz")
@Feature(code = "buzz", name = "Buzzer On / Off", type = "operation", @Feature(code = "buzz", name = "Buzzer On / Off", type = "operation",
description = "Switch on/off Virtual Fire Alarm 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,
@ -89,7 +89,7 @@ public interface VirtualFireAlarmControllerService {
* whose temperature reading was requested. * whose temperature reading was requested.
*/ */
@GET @GET
@Path("{deviceId}/temperature") @Path("device/{deviceId}/temperature")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Feature(code = "temperature", name = "Temperature", type = "monitor", @Feature(code = "temperature", name = "Temperature", type = "monitor",
@ -105,7 +105,7 @@ public interface VirtualFireAlarmControllerService {
* @param dataMsg the temperature data received from the device in JSON format complying to type 'DeviceData'. * @param dataMsg the temperature data received from the device in JSON format complying to type 'DeviceData'.
*/ */
@POST @POST
@Path("temperature") @Path("device/temperature")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
Response pushTemperatureData(final DeviceData dataMsg); Response pushTemperatureData(final DeviceData dataMsg);
@ -123,7 +123,7 @@ public interface VirtualFireAlarmControllerService {
* @return an HTTP Response object with either the CA-Cert or the CA-Capabilities according to the operation. * @return an HTTP Response object with either the CA-Cert or the CA-Capabilities according to the operation.
*/ */
@GET @GET
@Path("scep") @Path("device/scep")
Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message); Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message);
@ -140,13 +140,13 @@ public interface VirtualFireAlarmControllerService {
* @return an HTTP Response object with the signed certificate for the device by the CA of the SCEP Server. * @return an HTTP Response object with the signed certificate for the device by the CA of the SCEP Server.
*/ */
@POST @POST
@Path("scep") @Path("device/scep")
Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream); Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream);
/** /**
* Retrieve Sensor data for the device type * Retrieve Sensor data for the device type
*/ */
@Path("stats/{deviceId}/sensors/{sensorName}") @Path("device/stats/{deviceId}/sensors/{sensorName}")
@GET @GET
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")

@ -28,6 +28,7 @@ import org.wso2.carbon.device.mgt.analytics.data.publisher.AnalyticsDataRecord;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DeviceManagementAnalyticsException; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DeviceManagementAnalyticsException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService; import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
@ -47,6 +48,15 @@ import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.scep.SC
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
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.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.InputStream; import java.io.InputStream;
@ -80,127 +90,10 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
// holds a mapping of the IP addresses to Device-IDs for HTTP communication // holds a mapping of the IP addresses to Device-IDs for HTTP communication
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private boolean waitForServerStartup() { @POST
while (!IoTServerStartupListener.isServerReady()) { @Path("device/register/{deviceId}/{ip}/{port}")
try { public Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
Thread.sleep(1000); @PathParam("port") String devicePort, @Context HttpServletRequest request) {
} catch (InterruptedException e) {
return true;
}
}
return false;
}
/**
* Fetches the `SecurityManager` specific to this VirtualFirealarm controller service.
*
* @return the 'SecurityManager' instance bound to the 'securityManager' variable of this service.
*/
@SuppressWarnings("Unused")
public SecurityManager getSecurityManager() {
return securityManager;
}
/**
* Sets the `securityManager` variable of this VirtualFirealarm controller service.
*
* @param securityManager a 'SecurityManager' object that handles the encryption, decryption, signing and validation
* of incoming messages from VirtualFirealarm device-types.
*/
@SuppressWarnings("Unused")
public void setSecurityManager(SecurityManager securityManager) {
this.securityManager = securityManager;
securityManager.initVerificationManager();
}
/**
* Fetches the `VirtualFireAlarmXMPPConnector` specific to this VirtualFirealarm controller service.
*
* @return the 'VirtualFireAlarmXMPPConnector' instance bound to the 'virtualFireAlarmXMPPConnector' variable of
* this service.
*/
@SuppressWarnings("Unused")
public VirtualFireAlarmXMPPConnector getVirtualFireAlarmXMPPConnector() {
return virtualFireAlarmXMPPConnector;
}
/**
* Sets the `virtualFireAlarmXMPPConnector` variable of this VirtualFirealarm controller service.
*
* @param virtualFireAlarmXMPPConnector a 'VirtualFireAlarmXMPPConnector' object that handles all XMPP related
* communications of any connected VirtualFirealarm device-type
*/
@SuppressWarnings("Unused")
public void setVirtualFireAlarmXMPPConnector(
final VirtualFireAlarmXMPPConnector virtualFireAlarmXMPPConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
VirtualFireAlarmControllerServiceImpl.this.virtualFireAlarmXMPPConnector = virtualFireAlarmXMPPConnector;
if (XmppConfig.getInstance().isEnabled()) {
Runnable xmppStarter = new Runnable() {
@Override
public void run() {
virtualFireAlarmXMPPConnector.initConnector();
virtualFireAlarmXMPPConnector.connect();
}
};
Thread xmppStarterThread = new Thread(xmppStarter);
xmppStarterThread.setDaemon(true);
xmppStarterThread.start();
} else {
log.warn("XMPP disabled in 'devicemgt-config.xml'. Hence, VirtualFireAlarmXMPPConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
/**
* Fetches the `VirtualFireAlarmMQTTConnector` specific to this VirtualFirealarm controller service.
*
* @return the 'VirtualFireAlarmMQTTConnector' instance bound to the 'virtualFireAlarmMQTTConnector' variable of
* this service.
*/
@SuppressWarnings("Unused")
public VirtualFireAlarmMQTTConnector getVirtualFireAlarmMQTTConnector() {
return virtualFireAlarmMQTTConnector;
}
/**
* Sets the `virtualFireAlarmMQTTConnector` variable of this VirtualFirealarm controller service.
*
* @param virtualFireAlarmMQTTConnector a 'VirtualFireAlarmMQTTConnector' object that handles all MQTT related
* communications of any connected VirtualFirealarm device-type
*/
@SuppressWarnings("Unused")
public void setVirtualFireAlarmMQTTConnector(
final VirtualFireAlarmMQTTConnector virtualFireAlarmMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
VirtualFireAlarmControllerServiceImpl.this.virtualFireAlarmMQTTConnector = virtualFireAlarmMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
virtualFireAlarmMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, VirtualFireAlarmMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
public Response registerDeviceIP(String deviceId, String deviceIP, String devicePort, HttpServletRequest request) {
String result; String result;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId); log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId);
@ -214,7 +107,10 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
return Response.ok().entity(result).build(); return Response.ok().entity(result).build();
} }
public Response switchBuzzer(String deviceId, String protocol, String state) { @POST
@Path("device/{deviceId}/buzz")
public Response switchBuzzer(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol,
@FormParam("state") String state) {
String switchToState = state.toUpperCase(); String switchToState = state.toUpperCase();
if (!switchToState.equals(VirtualFireAlarmConstants.STATE_ON) && !switchToState.equals( if (!switchToState.equals(VirtualFireAlarmConstants.STATE_ON) && !switchToState.equals(
VirtualFireAlarmConstants.STATE_OFF)) { VirtualFireAlarmConstants.STATE_OFF)) {
@ -252,7 +148,12 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
} }
} }
public Response requestTemperature(String deviceId, String protocol) { @GET
@Path("device/{deviceId}/temperature")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response requestTemperature(@PathParam("deviceId") String deviceId,
@QueryParam("protocol") String protocol) {
SensorRecord sensorRecord = null; SensorRecord sensorRecord = null;
String protocolString = protocol.toUpperCase(); String protocolString = protocol.toUpperCase();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -289,6 +190,9 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
} }
} }
@POST
@Path("device/temperature")
@Consumes(MediaType.APPLICATION_JSON)
public Response pushTemperatureData(final DeviceData dataMsg) { public Response pushTemperatureData(final DeviceData dataMsg) {
String deviceId = dataMsg.deviceId; String deviceId = dataMsg.deviceId;
String deviceIp = dataMsg.reply; String deviceIp = dataMsg.reply;
@ -312,7 +216,9 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
return Response.ok().build(); return Response.ok().build();
} }
public Response scepRequest(String operation, String message) { @GET
@Path("device/scep")
public Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Invoking SCEP operation " + operation); log.debug("Invoking SCEP operation " + operation);
} }
@ -362,7 +268,6 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Invoking GetCACaps"); log.debug("Invoking GetCACaps");
} }
try { try {
CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils. CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils.
getCertificateManagementService(); getCertificateManagementService();
@ -373,16 +278,15 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
} catch (VirtualFireAlarmException e) { } catch (VirtualFireAlarmException e) {
log.error("Error occurred while enrolling the device", e); log.error("Error occurred while enrolling the device", e);
} }
} else { } else {
log.error("Invalid SCEP operation " + operation); log.error("Invalid SCEP operation " + operation);
} }
return Response.serverError().build(); return Response.serverError().build();
} }
public Response scepRequestPost(String operation, InputStream inputStream) { @POST
@Path("device/scep")
public Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Invoking SCEP operation " + operation); log.debug("Invoking SCEP operation " + operation);
} }
@ -404,7 +308,14 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
return Response.serverError().build(); return Response.serverError().build();
} }
public Response getVirtualFirealarmStats(String deviceId, String sensor, String user, long from, long to) { @Path("device/stats/{deviceId}/sensors/{sensorName}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getVirtualFirealarmStats(@PathParam("deviceId") String deviceId,
@PathParam("sensorName") String sensor,
@QueryParam("username") String user, @QueryParam("from") long from,
@QueryParam("to") long to) {
try { try {
String fromDate = String.valueOf(from); String fromDate = String.valueOf(from);
String toDate = String.valueOf(to); String toDate = String.valueOf(to);
@ -448,6 +359,126 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
return Response.status(Response.Status.BAD_REQUEST).build(); return Response.status(Response.Status.BAD_REQUEST).build();
} }
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
/**
* Fetches the `SecurityManager` specific to this VirtualFirealarm controller service.
*
* @return the 'SecurityManager' instance bound to the 'securityManager' variable of this service.
*/
@SuppressWarnings("Unused")
public SecurityManager getSecurityManager() {
return securityManager;
}
/**
* Sets the `securityManager` variable of this VirtualFirealarm controller service.
*
* @param securityManager a 'SecurityManager' object that handles the encryption, decryption, signing and validation
* of incoming messages from VirtualFirealarm device-types.
*/
@SuppressWarnings("Unused")
public void setSecurityManager(SecurityManager securityManager) {
this.securityManager = securityManager;
securityManager.initVerificationManager();
}
/**
* Fetches the `VirtualFireAlarmXMPPConnector` specific to this VirtualFirealarm controller service.
*
* @return the 'VirtualFireAlarmXMPPConnector' instance bound to the 'virtualFireAlarmXMPPConnector' variable of
* this service.
*/
@SuppressWarnings("Unused")
public VirtualFireAlarmXMPPConnector getVirtualFireAlarmXMPPConnector() {
return virtualFireAlarmXMPPConnector;
}
/**
* Sets the `virtualFireAlarmXMPPConnector` variable of this VirtualFirealarm controller service.
*
* @param virtualFireAlarmXMPPConnector a 'VirtualFireAlarmXMPPConnector' object that handles all XMPP related
* communications of any connected VirtualFirealarm device-type
*/
@SuppressWarnings("Unused")
public void setVirtualFireAlarmXMPPConnector(
final VirtualFireAlarmXMPPConnector virtualFireAlarmXMPPConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
VirtualFireAlarmControllerServiceImpl.this.virtualFireAlarmXMPPConnector = virtualFireAlarmXMPPConnector;
if (XmppConfig.getInstance().isEnabled()) {
Runnable xmppStarter = new Runnable() {
@Override
public void run() {
virtualFireAlarmXMPPConnector.initConnector();
virtualFireAlarmXMPPConnector.connect();
}
};
Thread xmppStarterThread = new Thread(xmppStarter);
xmppStarterThread.setDaemon(true);
xmppStarterThread.start();
} else {
log.warn("XMPP disabled in 'devicemgt-config.xml'. Hence, VirtualFireAlarmXMPPConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
/**
* Fetches the `VirtualFireAlarmMQTTConnector` specific to this VirtualFirealarm controller service.
*
* @return the 'VirtualFireAlarmMQTTConnector' instance bound to the 'virtualFireAlarmMQTTConnector' variable of
* this service.
*/
@SuppressWarnings("Unused")
public VirtualFireAlarmMQTTConnector getVirtualFireAlarmMQTTConnector() {
return virtualFireAlarmMQTTConnector;
}
/**
* Sets the `virtualFireAlarmMQTTConnector` variable of this VirtualFirealarm controller service.
*
* @param virtualFireAlarmMQTTConnector a 'VirtualFireAlarmMQTTConnector' object that handles all MQTT related
* communications of any connected VirtualFirealarm device-type
*/
@SuppressWarnings("Unused")
public void setVirtualFireAlarmMQTTConnector(
final VirtualFireAlarmMQTTConnector virtualFireAlarmMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
VirtualFireAlarmControllerServiceImpl.this.virtualFireAlarmMQTTConnector = virtualFireAlarmMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
virtualFireAlarmMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, VirtualFireAlarmMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
/** /**
* get the event table from the sensor name. * get the event table from the sensor name.
*/ */

@ -32,20 +32,21 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@Path("enrollment")
@API(name = "virtual_firealarm_mgt", version = "1.0.0", context = "/virtual_firealarm_mgt", tags = "virtual_firealarm") @API(name = "virtual_firealarm_mgt", version = "1.0.0", context = "/virtual_firealarm_mgt", tags = "virtual_firealarm")
@DeviceType(value = "virtual_firealarm") @DeviceType(value = "virtual_firealarm")
public interface VirtualFireAlarmManagerService { public interface VirtualFireAlarmManagerService {
@Path("{device_id}") @Path("devices/{device_id}")
@DELETE @DELETE
Response removeDevice(@PathParam("device_id") String deviceId); Response removeDevice(@PathParam("device_id") String deviceId);
@Path("{device_id}") @Path("devices/{device_id}")
@PUT @PUT
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name); Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("{device_id}") @Path("devices/{device_id}")
@GET @GET
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ -57,13 +58,13 @@ public interface VirtualFireAlarmManagerService {
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
Response getFirealarmDevices(); Response getFirealarmDevices();
@Path("download") @Path("devices/download")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType); Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType);
@Path("generate_link") @Path("devices/generate_link")
@GET @GET
Response generateSketchLink(@QueryParam("deviceName") String deviceName, Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@QueryParam("sketchType") String sketchType); @QueryParam("sketchType") String sketchType);

@ -41,6 +41,15 @@ import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException; 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 javax.ws.rs.core.Response;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
@ -50,38 +59,15 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@Path("enrollment")
public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManagerService { public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManagerService {
private static final String KEY_TYPE = "PRODUCTION"; private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey; private static ApiApplicationKey apiApplicationKey;
private boolean register(String deviceId, String name) { @Path("devices/{device_id}")
try { @DELETE
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); public Response removeDevice(@PathParam("device_id") String deviceId) {
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);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
}
}
public Response removeDevice(String deviceId) {
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
@ -98,7 +84,9 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
} }
} }
public Response updateDevice(String deviceId, String name) { @Path("devices/{device_id}")
@PUT
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
@ -119,7 +107,11 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
} }
} }
public Response getDevice(String deviceId) { @Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getDevice(@PathParam("device_id") String deviceId) {
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
@ -131,6 +123,10 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
} }
} }
@Path("devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getFirealarmDevices() { public Response getFirealarmDevices() {
try { try {
List<Device> userDevices = List<Device> userDevices =
@ -149,7 +145,11 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
} }
} }
public Response downloadSketch(String deviceName, String sketchType) { @Path("devices/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
@QueryParam("sketchType") String sketchType) {
try { try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
@ -170,12 +170,13 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
return Response.status(500).entity(ex.getMessage()).build(); return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) { } catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build(); return Response.status(500).entity(ex.getMessage()).build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
} }
} }
public Response generateSketchLink(String deviceName, String sketchType) { @Path("devices/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@QueryParam("sketchType") String sketchType) {
try { try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
@ -192,8 +193,32 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
return Response.status(500).entity(ex.getMessage()).build(); return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) { } catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build(); return Response.status(500).entity(ex.getMessage()).build();
} finally { }
PrivilegedCarbonContext.endTenantFlow(); }
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);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
} }
} }

@ -23,7 +23,7 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="VirtualFireAlarmController" address="/device"> <jaxrs:server id="VirtualFireAlarm" address="/">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<bean id="VirtualFireAlarmControllerService" <bean id="VirtualFireAlarmControllerService"
class="org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.VirtualFireAlarmControllerServiceImpl"> class="org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.VirtualFireAlarmControllerServiceImpl">
@ -31,14 +31,6 @@
<property name="virtualFireAlarmMQTTConnector" ref="mqttConnectorBean"/> <property name="virtualFireAlarmMQTTConnector" ref="mqttConnectorBean"/>
<property name="virtualFireAlarmXMPPConnector" ref="xmppConnectorBean"/> <property name="virtualFireAlarmXMPPConnector" ref="xmppConnectorBean"/>
</bean> </bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
<jaxrs:server id="VirtualFireAlarmManager" address="/devices">
<jaxrs:serviceBeans>
<bean id="VirtualFireAlarmManagerService" <bean id="VirtualFireAlarmManagerService"
class="org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.VirtualFireAlarmManagerServiceImpl"> class="org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.VirtualFireAlarmManagerServiceImpl">
</bean> </bean>

@ -7,59 +7,40 @@
<display-name>WSO2 IoT Server</display-name> <display-name>WSO2 IoT Server</display-name>
<description>WSO2 IoT Server</description> <description>WSO2 IoT Server</description>
<servlet> <servlet>
<servlet-name>CXFServlet</servlet-name> <servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup> <load-on-startup>1</load-on-startup>
</servlet> </servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<servlet-mapping> <url-pattern>/*</url-pattern>
<servlet-name>CXFServlet</servlet-name> </servlet-mapping>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>false</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param> <context-param>
<param-name>managed-api-context-template</param-name> <param-name>isAdminService</param-name>
<param-value>/virtual_firealarm/{version}</param-value> <param-value>false</param-value>
</context-param> </context-param>
<context-param> <context-param>
<param-name>managed-api-application</param-name> <param-name>doAuthentication</param-name>
<param-value>virtual_firealarm</param-value> <param-value>true</param-value>
</context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>providerTenantDomain</param-name>
<param-value>carbon.super</param-value>
</context-param> </context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
<!-- Below configuration is used to redirect http requests to https -->
<!--<security-constraint>-->
<!--<web-resource-collection>-->
<!--<web-resource-name>IoT</web-resource-name>-->
<!--<url-pattern>/*</url-pattern>-->
<!--</web-resource-collection>-->
<!--<user-data-constraint>-->
<!--<transport-guarantee>CONFIDENTIAL</transport-guarantee>-->
<!--</user-data-constraint>-->
<!--</security-constraint>-->
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
</web-app> </web-app>
Loading…
Cancel
Save