Move digital display and drone analyzer to samples.

application-manager-new
NuwanSameera 9 years ago
parent 8b10e550ef
commit 2f2c23105a

@ -1126,24 +1126,6 @@
<destName>ArduinoDM_DB.h2.db</destName>
<fileMode>644</fileMode>
</file>
<!-- Copying DIGITAL DISPLAY H2 database -->
<file>
<source>
../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/database/DigitalDisplayDM_DB.h2.db
</source>
<outputDirectory>${pom.artifactId}-${pom.version}/repository/database</outputDirectory>
<destName>DigitalDisplayDM_DB.h2.db</destName>
<fileMode>644</fileMode>
</file>
<!-- Copying DRONE ANALYZER H2 database -->
<file>
<source>
../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/database/DroneAnalyzerDM_DB.h2.db
</source>
<outputDirectory>${pom.artifactId}-${pom.version}/repository/database</outputDirectory>
<destName>DroneAnalyzerDM_DB.h2.db</destName>
<fileMode>644</fileMode>
</file>
<!-- Copying RASPBERRY-PI H2 database -->
<file>
<source>

@ -163,18 +163,16 @@
<featureArtifactDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.arduino.feature:${carbon.device.mgt.plugin.version}
</featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.digitaldisplay.feature:${carbon.device.mgt.plugin.version}
</featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.droneanalyzer.feature:${carbon.device.mgt.plugin.version}
</featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.raspberrypi.feature:${carbon.device.mgt.plugin.version}
</featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature:${carbon.device.mgt.plugin.version}
</featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.devicetypes.feature:${carbon.device.mgt.plugin.version}
</featureArtifactDef>
<!-- IoT Device Management Features -->
<!-- Carbon Deployment Features -->
@ -864,19 +862,15 @@
<version>${carbon.device.mgt.plugin.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.iot.digitaldisplay.feature.group</id>
<version>${carbon.device.mgt.plugin.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.iot.droneanalyzer.feature.group</id>
<id>org.wso2.carbon.device.mgt.iot.raspberrypi.feature.group</id>
<version>${carbon.device.mgt.plugin.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.iot.raspberrypi.feature.group</id>
<id>org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature.group</id>
<version>${carbon.device.mgt.plugin.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature.group</id>
<id>org.wso2.carbon.device.mgt.iot.devicetypes.feature.group</id>
<version>${carbon.device.mgt.plugin.version}</version>
</feature>
<!-- Carbon Deployment Features -->

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

@ -0,0 +1,176 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.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.Feature;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@API(name = "digital_display", version = "1.0.0", context = "/digital_display", tags = {"digital_display"})
@DeviceType(value = "digital_display")
public interface DigitalDisplayControllerService {
/**
* Restart the running browser in the given digital display.
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/restart-browser")
@POST
@Feature(code = "restart-browser", name = "Restart Browser", type = "operation",
description = "Restart Browser in Digital Display")
Response restartBrowser(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Terminate all running processes. If this execute we have to reboot digital display manually.
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/terminate-display")
@POST
@Feature(code = "terminate-display", name = "Terminate Display", type = "operation",
description = "Terminate all running process in Digital Display")
Response terminateDisplay(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Reboot running digital display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/restart-display")
@POST
@Feature(code = "restart-display", name = "Restart Display", type = "operation",
description = "Restart Digital Display")
Response restartDisplay(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Search through the sequence and edit requested resource
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param name name of page need to change
* @param attribute this can be path,time or type
* @param newValue page is used to replace path
*/
@Path("device/{deviceId}/edit-sequence")
@POST
@Feature(code = "edit-sequence", name = "Edit Sequence", type = "operation",
description = "Search through the sequence and edit requested resource in Digital Display")
Response editSequence(@PathParam("deviceId") String deviceId, @FormParam("name") String name,
@FormParam("attribute") String attribute, @FormParam("new-value") String newValue,
@HeaderParam("sessionId") String sessionId);
@Path("device/{deviceId}/upload-content")
@POST
@Feature(code = "upload-content", name = "Upload Content", type = "operation",
description = "Search through the sequence and edit requested resource in Digital Display")
Response uploadContent(@PathParam("deviceId") String deviceId, @FormParam("remote-path") String remotePath,
@FormParam("screen-name") String screenName, @HeaderParam("sessionId") String sessionId);
/**
* Add new resource end to the existing sequence
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param type type of new resource
* @param time new resource visible time
* @param path URL of the new resource
*/
@Path("device/{deviceId}/add-resource")
@POST
@Feature(code = "add-resource", name = "Add Resource", type = "operation",
description = "Add new resource end to the existing sequence in Digital Display")
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);
/**
* Delete a resource in sequence
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param name name of the page no need to delete
*/
@Path("device/{deviceId}/remove-resource")
@POST
@Feature(code = "remove-resource", name = "Remove Resource", type = "operation",
description = "Delete a resource from sequence in Digital Display")
Response removeResource(@PathParam("deviceId") String deviceId, @FormParam("name") String name,
@HeaderParam("sessionId") String sessionId);
/**
* Restart HTTP in running display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/restart-server")
@POST
@Feature(code = "restart-server", name = "Restart Server", type = "operation",
description = "Stop HTTP Server running in Digital Display")
Response restartServer(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Get screenshot of running display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/screenshot")
@POST
@Feature(code = "screenshot", name = "Take Screenshot", type = "operation",
description = "Show current view in Digital Display")
Response showScreenshot(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Get statistics of running display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/get-device-status")
@POST
@Feature(code = "get-device-status", name = "Get Device Statistics", type = "operation",
description = "Current status in Digital Display")
Response getDevicestatus(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Stop specific display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/get-content-list")
@POST
@Feature(code = "get-content-list", name = "Get Content List", type = "operation",
description = "Content List in Digital Display")
Response getResources(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
}

@ -0,0 +1,233 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.digitaldisplay.api.exception.DigitalDisplayException;
import org.homeautomation.digitaldisplay.api.util.DigitalDisplayMQTTConnector;
import org.homeautomation.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import javax.ws.rs.core.Response;
public class DigitalDisplayControllerServiceImpl implements DigitalDisplayControllerService {
private static Log log = LogFactory.getLog(DigitalDisplayControllerServiceImpl.class);
private static DigitalDisplayMQTTConnector digitalDisplayMQTTConnector;
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();
}
public Response restartBrowser(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_BROWSER_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response terminateDisplay(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.TERMINATE_DISPLAY_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response restartDisplay(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_DISPLAY_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response editSequence(String deviceId, String name, String attribute, String newValue, String sessionId) {
try {
String params = name + "|" + attribute + "|" + newValue;
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.EDIT_SEQUENCE_CONSTANT + "::", params);
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response uploadContent(String deviceId, String remotePath, String screenName, String sessionId) {
try {
String params = remotePath + "|" + screenName;
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.UPLOAD_CONTENT_CONSTANT + "::",
params);
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response addNewResource(String deviceId, String type, String time, String path, String name, String position,
String sessionId) {
String params;
try {
if (position.isEmpty()) {
params = type + "|" + time + "|" + path + "|" + name;
} else {
params = type + "|" + time + "|" + path + "|" + name +
"|" + "after=" + position;
}
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.ADD_NEW_RESOURCE_CONSTANT + "::", params);
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response removeResource(String deviceId, String name, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.REMOVE_RESOURCE_CONSTANT + "::", name);
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response restartServer(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_SERVER_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response showScreenshot(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.SCREENSHOT_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getDevicestatus(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.GET_DEVICE_STATUS_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getResources(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.GET_CONTENTLIST_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* Send message via MQTT protocol
*
* @param deviceId id of the target digital display
* @param operation operation need to execute
* @param param parameters need to given operation
* @throws DeviceManagementException
* @throws DigitalDisplayException
*/
private void sendCommandViaMQTT(String deviceId, String operation, String param)
throws DeviceManagementException, DigitalDisplayException {
String topic = String.format(DigitalDisplayConstants.PUBLISH_TOPIC, deviceId);
String payload = operation + param;
try {
digitalDisplayMQTTConnector.publishToDigitalDisplay(topic, payload, 2, false);
} catch (TransportHandlerException e) {
String errorMessage = "Error publishing data to device with ID " + deviceId;
throw new DigitalDisplayException(errorMessage, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}

@ -0,0 +1,58 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.api;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@API(name = "digital_display_mgt", version = "1.0.0", context = "/digital_display_mgt", tags = {"digital_display"})
@DeviceType(value = "digital_display")
public interface DigitalDisplayManagerService {
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/download")
@GET
@Produces("application/octet-stream")
Response downloadSketch(@QueryParam("deviceName") String customDeviceName);
}

@ -0,0 +1,198 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.digitaldisplay.api.util.APIUtil;
import org.homeautomation.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
public class DigitalDisplayManagerServiceImpl implements DigitalDisplayManagerService {
private static Log log = LogFactory.getLog(DigitalDisplayManagerServiceImpl.class);
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
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;
}
}
public Response removeDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response updateDevice(String deviceId, String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DigitalDisplayConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException ex) {
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response downloadSketch(String deviceName) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
Response.ResponseBuilder response = Response.ok(zipFile.getZipFile());
response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return response.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String owner, String deviceName)
throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException,
UserStoreException {
if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
if (apiApplicationKey == null) {
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DigitalDisplayConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DigitalDisplayConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
String scopes = "device_type_" + DigitalDisplayConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
//adding registering data
boolean status;
//Register the device with CDMF
status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
DigitalDisplayConstants.DEVICE_TYPE, deviceId,
deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
}

@ -0,0 +1,33 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class DeviceJSON {
@XmlElement(required = true) public String owner;
@XmlElement(required = true) public String deviceId;
@XmlElement(required = true) public String reply;
}

@ -0,0 +1,59 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.api.exception;
public class DigitalDisplayException extends Exception {
private static final long serialVersionUID = 2736466230451105441L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public DigitalDisplayException(String msg, DigitalDisplayException nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DigitalDisplayException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public DigitalDisplayException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DigitalDisplayException() {
super();
}
public DigitalDisplayException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,51 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.api.model;
public class ScreenShotModel {
private String[] screenShotData;
private int length;
public ScreenShotModel(){
}
public ScreenShotModel(String[] screenShotData , int length){
this.screenShotData = screenShotData;
this.length = length;
}
public void setScreenShotData(String[] screrenShotData){
this.screenShotData = screenShotData;
}
public void setLength(int length){
this.length = length;
}
public String[] getScreenShotData(){
return this.screenShotData;
}
public int getLength(){
return this.length;
}
}

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

@ -0,0 +1,184 @@
package org.homeautomation.digitaldisplay.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.homeautomation.digitaldisplay.api.model.ScreenShotModel;
import org.homeautomation.digitaldisplay.api.websocket.DigitalDisplayWebSocketServerEndPoint;
import org.homeautomation.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.json.JSONObject;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;
@SuppressWarnings("no JAX-WS annotation")
public class DigitalDisplayMQTTConnector extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(DigitalDisplayMQTTConnector.class);
private static final String MQTT_TOPIC_APPENDER = "wso2/iot";
private static final String subscribeTopic =
MQTT_TOPIC_APPENDER + "/" + DigitalDisplayConstants.DEVICE_TYPE + "/+/digital_display_publisher";
private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
private ScheduledFuture<?> dataPushServiceHandler;
private Map<String, ScreenShotModel> screenshots = new HashMap<>();
private DigitalDisplayMQTTConnector() {
super(iotServerSubscriber, DigitalDisplayConstants.DEVICE_TYPE,
MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic);
}
@Override
public void connect() {
Runnable connector = new Runnable() {
public void run() {
while (!isConnected()) {
try {
String brokerUsername = MqttConfig.getInstance().getMqttQueueUsername();
String brokerPassword = MqttConfig.getInstance().getMqttQueuePassword();
setUsernameAndPassword(brokerUsername, brokerPassword);
connectToQueue();
} catch (TransportHandlerException e) {
log.error("Connection to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException ex) {
log.error("MQTT-Connector: Thread Sleep Interrupt Exception.", ex);
}
}
try {
subscribeToQueue();
} catch (TransportHandlerException e) {
log.warn("Subscription to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
}
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
@Override
public void processIncomingMessage(MqttMessage message, String... messageParams) {
String topic = messageParams[0];
String[] topicParams = topic.split("/");
String owner = topicParams[2];
String deviceId = topicParams[4];
String[] messageData = message.toString().split("::");
if (log.isDebugEnabled()) {
log.debug("Received MQTT message for: [OWNER-" + owner + "] & [DEVICE.ID-" + deviceId + "]");
}
String sessionId = messageData[0];
if (messageData.length == 2) {
String responseMessage = messageData[1];
DigitalDisplayWebSocketServerEndPoint.sendMessage(sessionId, new StringBuilder(responseMessage));
} else if (messageData.length == 3) {
String response = messageData[2];
JSONObject schreenShot = new JSONObject(response);
String picId = schreenShot.getString("pic_id");
String data = schreenShot.getString("data");
int pos = schreenShot.getInt("pos");
int length = schreenShot.getInt("size");
createScreenShot(sessionId, picId, pos, length, data);
}
}
private void createScreenShot(String sessionId, String picId, int pos, int length, String data) {
ScreenShotModel screenShotModel = screenshots.get(picId);
if (screenShotModel == null) {
screenShotModel = new ScreenShotModel();
screenShotModel.setScreenShotData(new String[length + 1]);
screenShotModel.setLength(0);
screenshots.put(picId, screenShotModel);
}
if (screenShotModel.getLength() <= length) {
screenShotModel.getScreenShotData()[pos] = data;
screenShotModel.setLength(screenShotModel.getLength() + 1);
if (screenShotModel.getLength() == (length + 1)) {
StringBuilder displayScreenShot = new StringBuilder("Screenshot||");
for (String screenshot : screenShotModel.getScreenShotData()) {
displayScreenShot.append(screenshot);
}
screenshots.remove(picId);
DigitalDisplayWebSocketServerEndPoint.sendMessage(sessionId, displayScreenShot);
}
}
}
public void publishToDigitalDisplay(String topic, String payLoad, int qos, boolean retained)
throws TransportHandlerException {
if (log.isDebugEnabled()) {
log.debug("Publishing message [" + payLoad + "to topic [" + topic + "].");
}
publishToQueue(topic, payLoad, qos, retained);
}
@Override
public void disconnect() {
Runnable stopConnection = new Runnable() {
public void run() {
while (isConnected()) {
try {
closeConnection();
} catch (MqttException e) {
if (log.isDebugEnabled()) {
log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
log.error("MQTT-Terminator: Thread Sleep Interrupt Exception");
}
}
}
}
};
Thread terminatorThread = new Thread(stopConnection);
terminatorThread.setDaemon(true);
terminatorThread.start();
}
@Override
public void publishDeviceData() throws TransportHandlerException {
}
@Override
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
}
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
}
@Override
public void processIncomingMessage() {
}
@Override
public void processIncomingMessage(MqttMessage message) throws TransportHandlerException {
}
}

@ -0,0 +1,67 @@
package org.homeautomation.digitaldisplay.api.websocket;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.inject.Singleton;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
@ServerEndpoint(value = "/{sessionId}")
@Singleton
public class DigitalDisplayWebSocketServerEndPoint {
private static Log log = LogFactory.getLog(DigitalDisplayWebSocketServerEndPoint.class);
private static Map<String, Session> clientSessions = new HashMap<>();
/**
* This method will be invoked when a client requests for a
* WebSocket connection.
*
* @param userSession the userSession which is opened.
*/
@OnOpen
public void onOpen(Session userSession, @PathParam("sessionId") String sessionId) {
clientSessions.put(sessionId, userSession);
}
/**
* This method will be invoked when a client closes a WebSocket
* connection.
*
* @param userSession the userSession which is opened.
*/
@OnClose
public void onClose(Session userSession) {
clientSessions.values().remove(userSession);
}
@OnError
public void onError(Throwable t) {
log.error("Error occurred " + t);
}
/**
* This method will be invoked when a message received from device
* to send client.
*
* @param sessionId the client of message to be sent.
* @param message the message sent by device to client
*/
public static void sendMessage(String sessionId, StringBuilder message) {
Session session = clientSessions.get(sessionId);
if (session != null) {
session.getAsyncRemote().sendText(message.toString());
} else {
log.error("Client already disconnected.");
}
}
}

@ -0,0 +1,138 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/devices/*</url>
<method>GET</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/devices/*</url>
<method>DELETE</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/*/download</url>
<method>GET</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/devices/*</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Restart Browser</name>
<path>/device-mgt/user/device</path>
<url>/device/*/restart-browser</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Terminate Display</name>
<path>/device-mgt/user/device/terminate-display</path>
<url>/device/*/terminate-display</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Restart Display</name>
<path>/device-mgt/user/device/restart-display</path>
<url>/device/*/restart-display</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Edit Sequence</name>
<path>/device-mgt/user/device/edit-sequence</path>
<url>/device/*/edit-sequence</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Upload Content</name>
<path>/device-mgt/user/device/upload-content</path>
<url>/device/*/upload-content</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Add Resource</name>
<path>/device-mgt/user/device/add-resource</path>
<url>/device/*/add-resource</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Remove Resource</name>
<path>/device-mgt/user/device/remove-resource</path>
<url>/device/*/remove-resource</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Restart Server</name>
<path>/device-mgt/user/device/restart-server</path>
<url>/device/*/restart-server</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Take Screenshot</name>
<path>/device-mgt/user/device/screenshot</path>
<url>/device/*/screenshot</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Get Device Stats</name>
<path>/device-mgt/user/device/get-device-status</path>
<url>/device/*/get-device-status</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
<Permission>
<name>Get Content List</name>
<path>/device-mgt/user/device/get-content-list</path>
<url>/device/*/get-content-list</url>
<method>POST</method>
<scope>digital_display_user</scope>
</Permission>
</PermissionConfiguration>

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright 2005-2013 WSO2, Inc. (http://wso2.com)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="DigitalDisplayController" address="/controller">
<jaxrs:serviceBeans>
<bean id="DigitalDisplayManagerControllerService"
class="org.homeautomation.digitaldisplay.api.DigitalDisplayControllerServiceImpl">
<property name="digitalDisplayMQTTConnector" ref="communicationHandler"/>
</bean>
<bean id="DigitalDisplayManagerService"
class="org.homeautomation.digitaldisplay.api.DigitalDisplayManagerServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
<bean id="communicationHandler"
class="org.homeautomation.digitaldisplay.api.util.DigitalDisplayMQTTConnector" >
</bean>
</beans>

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Digital-Display-Agent-Webapp</display-name>
<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-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>
<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>
<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>
<!--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>/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>

@ -0,0 +1,120 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>digitaldisplay-component</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.1.0-SNAPSHOT</version>
<artifactId>${groupId}.digitaldisplay.plugin</artifactId>
<packaging>bundle</packaging>
<name>${groupId}.digitaldisplay.plugin for CDMF </name>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>${org.apache.felix.version}</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${groupId}.digitaldisplay.plugin</Bundle-SymbolicName>
<Bundle-Name>${groupId}.digitaldisplay.plugin</Bundle-Name>
<Bundle-Version>2.1.0-SNAPSHOT</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.homeautomation.digitaldisplay.plugin.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.naming;resolution:=optional,
javax.sql;resolution:=optional,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.device.mgt.iot.*,
org.wso2.carbon.device.mgt.extensions.feature.mgt.*,
org.wso2.carbon.utils.*
</Import-Package>
<Export-Package>
!org.homeautomation.digitaldisplay.plugin.internal,
org.homeautomation.digitaldisplay.plugin.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,37 @@
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.homeautomation.digitaldisplay.plugin.constants;
public class DigitalDisplayConstants {
public final static String DEVICE_TYPE = "digital_display";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "DIGITAL_DISPLAY_DEVICE_ID";
public final static String RESTART_SERVER_CONSTANT = "restart_server";
public final static String RESTART_DISPLAY_CONSTANT = "restart_display";
public final static String RESTART_BROWSER_CONSTANT = "restart_browser";
public final static String TERMINATE_DISPLAY_CONSTANT = "terminate_display";
public final static String EDIT_SEQUENCE_CONSTANT = "edit_sequence";
public final static String UPLOAD_CONTENT_CONSTANT = "upload_content";
public final static String ADD_NEW_RESOURCE_CONSTANT = "add_new_resource";
public final static String REMOVE_RESOURCE_CONSTANT = "remove_resources";
public final static String SCREENSHOT_CONSTANT = "get_screenshot";
public final static String GET_CONTENTLIST_CONSTANT = "get_content_list";
public final static String GET_DEVICE_STATUS_CONSTANT = "get_device_status";
public final static String PUBLISH_TOPIC = "wso2/iot/digital_display/%s/digital_display_subscriber";
public static final String DATA_SOURCE_NAME = "jdbc/DigitalDisplayDM_DB";
}

@ -0,0 +1,56 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.plugin.exception;
public class DigitalDisplayDeviceMgtPluginException extends Exception{
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public DigitalDisplayDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DigitalDisplayDeviceMgtPluginException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public DigitalDisplayDeviceMgtPluginException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DigitalDisplayDeviceMgtPluginException() {
super();
}
public DigitalDisplayDeviceMgtPluginException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,256 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.digitaldisplay.plugin.exception.DigitalDisplayDeviceMgtPluginException;
import org.homeautomation.digitaldisplay.plugin.impl.dao.DigitalDisplayDAO;
import org.homeautomation.digitaldisplay.plugin.impl.feature.DigitalDisplayFeatureManager;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import java.util.List;
/**
* This represents the DigitalDisplay implementation of DeviceManagerService.
*/
public class DigitalDisplayManager implements DeviceManager {
private static final DigitalDisplayDAO digitalDisplayDAO = new DigitalDisplayDAO();
private static final Log log = LogFactory.getLog(DigitalDisplayManager.class);
private FeatureManager featureManager = new DigitalDisplayFeatureManager();
@Override
public FeatureManager getFeatureManager() {
return featureManager;
}
@Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration)
throws DeviceManagementException {
return false;
}
@Override
public TenantConfiguration getConfiguration() throws DeviceManagementException {
return null;
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new DigitalDisplay device : " + device.getDeviceIdentifier());
}
DigitalDisplayDAO.beginTransaction();
status = digitalDisplayDAO.getDeviceDAO().addDevice(device);
DigitalDisplayDAO.commitTransaction();
} catch (DigitalDisplayDeviceMgtPluginException e) {
try {
DigitalDisplayDAO.rollbackTransaction();
} catch (DigitalDisplayDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while enrolling the DigitalDisplay device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the DigitalDisplay device enrollment data");
}
DigitalDisplayDAO.beginTransaction();
status = digitalDisplayDAO.getDeviceDAO().updateDevice(device);
DigitalDisplayDAO.commitTransaction();
} catch (DigitalDisplayDeviceMgtPluginException e) {
try {
DigitalDisplayDAO.rollbackTransaction();
} catch (DigitalDisplayDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while updating the enrollment of the DigitalDisplay device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling DigitalDisplay device : " + deviceId);
}
DigitalDisplayDAO.beginTransaction();
status = digitalDisplayDAO.getDeviceDAO().deleteDevice(deviceId.getId());
DigitalDisplayDAO.commitTransaction();
} catch (DigitalDisplayDeviceMgtPluginException e) {
try {
DigitalDisplayDAO.rollbackTransaction();
} catch (DigitalDisplayDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while removing the DigitalDisplay device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of DigitalDisplay device : " + deviceId.getId());
}
Device iotDevice = digitalDisplayDAO.getDeviceDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (DigitalDisplayDeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of DigitalDisplay device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return isEnrolled;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return true;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of DigitalDisplay device : " + deviceId.getId());
}
device = digitalDisplayDAO.getDeviceDAO().getDevice(deviceId.getId());
} catch (DigitalDisplayDeviceMgtPluginException e) {
String msg = "Error while fetching the DigitalDisplay device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return device;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
}
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
}
@Override
public License getLicense(String s) throws LicenseManagementException {
return null;
}
@Override
public void addLicense(License license) throws LicenseManagementException {
}
@Override
public boolean requireDeviceAuthorization() {
return true;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug(
"updating the details of DigitalDisplay device : " + deviceIdentifier);
}
DigitalDisplayDAO.beginTransaction();
status = digitalDisplayDAO.getDeviceDAO().updateDevice(device);
DigitalDisplayDAO.commitTransaction();
} catch (DigitalDisplayDeviceMgtPluginException e) {
try {
DigitalDisplayDAO.rollbackTransaction();
} catch (DigitalDisplayDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg =
"Error while updating the DigitalDisplay device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all DigitalDisplay devices");
}
devices = digitalDisplayDAO.getDeviceDAO().getAllDevices();
} catch (DigitalDisplayDeviceMgtPluginException e) {
String msg = "Error while fetching all DigitalDisplay devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return devices;
}
}

@ -0,0 +1,106 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.homeautomation.digitaldisplay.plugin.impl;
import org.homeautomation.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List;
public class DigitalDisplayManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
private final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
@Override
public String getType() {
return DigitalDisplayConstants.DEVICE_TYPE;
}
@Override
public String getProviderTenantDomain() {
return DEVICE_TYPE_PROVIDER_DOMAIN;
}
@Override
public boolean isSharedWithAllTenants() {
return true;
}
@Override
public void init() throws DeviceManagementException {
deviceManager= new DigitalDisplayManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> list) throws
DeviceManagementException {
}
@Override
public Application[] getApplications(String domain, int pageNumber, int size)
throws ApplicationManagementException {
return new Application[0];
}
@Override
public void updateApplicationStatus(DeviceIdentifier deviceId, Application application,
String status) throws ApplicationManagementException {
}
@Override
public String getApplicationStatus(DeviceIdentifier deviceId, Application application)
throws ApplicationManagementException {
return null;
}
@Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> list) throws
ApplicationManagementException {
}
@Override
public void installApplicationForUsers(Operation operation, List<String> list) throws
ApplicationManagementException {
}
@Override
public void installApplicationForUserRoles(Operation operation, List<String> list) throws
ApplicationManagementException {
}
}

@ -0,0 +1,126 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.homeautomation.digitaldisplay.plugin.exception.DigitalDisplayDeviceMgtPluginException;
import org.homeautomation.digitaldisplay.plugin.impl.dao.impl.DigitalDisplayDeviceDAOImpl;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DigitalDisplayDAO {
private static final Log log = LogFactory.getLog(DigitalDisplayDAO.class);
static DataSource dataSource; // package local variable
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public DigitalDisplayDAO() {
initDigitalDisplayDAO();
}
public DigitalDisplayDeviceDAOImpl getDeviceDAO() {
return new DigitalDisplayDeviceDAOImpl();
}
public static void initDigitalDisplayDAO(){
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(DigitalDisplayConstants.DATA_SOURCE_NAME);
} catch (NamingException e) {
log.error("Error while looking up the data source: " + DigitalDisplayConstants.DATA_SOURCE_NAME);
}
}
public static void beginTransaction() throws DigitalDisplayDeviceMgtPluginException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new DigitalDisplayDeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws DigitalDisplayDeviceMgtPluginException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new DigitalDisplayDeviceMgtPluginException("Error occurred while retrieving data source connection",
e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws DigitalDisplayDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit " +
"has not been attempted");
}
}
} catch (SQLException e) {
throw new DigitalDisplayDeviceMgtPluginException("Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws DigitalDisplayDeviceMgtPluginException {
Connection con = currentConnection.get();
if(con != null){
try {
con.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
}
currentConnection.remove();
}
public static void rollbackTransaction() throws DigitalDisplayDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback " +
"has not been attempted");
}
}
} catch (SQLException e) {
throw new DigitalDisplayDeviceMgtPluginException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}
}
}

@ -0,0 +1,194 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.plugin.impl.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.homeautomation.digitaldisplay.plugin.exception.DigitalDisplayDeviceMgtPluginException;
import org.homeautomation.digitaldisplay.plugin.impl.dao.DigitalDisplayDAO;
import org.homeautomation.digitaldisplay.plugin.impl.util.DigitalDisplayUtils;
import org.wso2.carbon.device.mgt.common.Device;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Implements CRUD for digital display Devices.
*/
public class DigitalDisplayDeviceDAOImpl {
private static final Log log = LogFactory.getLog(DigitalDisplayDeviceDAOImpl.class);
public Device getDevice(String iotDeviceId) throws DigitalDisplayDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
Device device = null;
ResultSet resultSet = null;
try {
conn = DigitalDisplayDAO.getConnection();
String selectDBQuery =
"SELECT DIGITAL_DISPLAY_DEVICE_ID, DEVICE_NAME" +
" FROM DIGITAL_DISPLAY_DEVICE WHERE DIGITAL_DISPLAY_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, iotDeviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
device = new Device();
device.setName(resultSet.getString(
DigitalDisplayConstants.DEVICE_PLUGIN_DEVICE_NAME));
if (log.isDebugEnabled()) {
log.debug("Digital Display device " + iotDeviceId + " data has been fetched from " +
"Digital Display database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching Digital Display device : '" + iotDeviceId + "'";
log.error(msg, e);
throw new DigitalDisplayDeviceMgtPluginException(msg, e);
} finally {
DigitalDisplayUtils.cleanupResources(stmt, resultSet);
DigitalDisplayDAO.closeConnection();
}
return device;
}
public boolean addDevice(Device device) throws DigitalDisplayDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DigitalDisplayDAO.getConnection();
String createDBQuery =
"INSERT INTO DIGITAL_DISPLAY_DEVICE(DIGITAL_DISPLAY_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, device.getDeviceIdentifier());
stmt.setString(2, device.getName());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Digital Display device " + device.getDeviceIdentifier() + " data has been" +
" added to the Digital Display database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the Digital Display device '" +
device.getDeviceIdentifier() + "' to the Digital Display db.";
log.error(msg, e);
throw new DigitalDisplayDeviceMgtPluginException(msg, e);
} finally {
DigitalDisplayUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean updateDevice(Device device) throws DigitalDisplayDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DigitalDisplayDAO.getConnection();
String updateDBQuery =
"UPDATE DIGITAL_DISPLAY_DEVICE SET DEVICE_NAME = ? WHERE DIGITAL_DISPLAY_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
stmt.setString(1, device.getName());
stmt.setString(2, device.getDeviceIdentifier());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Digital Display device " + device.getDeviceIdentifier() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Digital Display device '" +
device.getDeviceIdentifier() + "' data.";
log.error(msg, e);
throw new DigitalDisplayDeviceMgtPluginException(msg, e);
} finally {
DigitalDisplayUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean deleteDevice(String iotDeviceId) throws DigitalDisplayDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DigitalDisplayDAO.getConnection();
String deleteDBQuery =
"DELETE FROM DIGITAL_DISPLAY_DEVICE WHERE DIGITAL_DISPLAY_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, iotDeviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Digital Display device " + iotDeviceId + " data has deleted" +
" from the Digital Display database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting Digital Display device " + iotDeviceId;
log.error(msg, e);
throw new DigitalDisplayDeviceMgtPluginException(msg, e);
} finally {
DigitalDisplayUtils.cleanupResources(stmt, null);
}
return status;
}
public List<Device> getAllDevices() throws DigitalDisplayDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device iotDevice;
List<Device> iotDevices = new ArrayList<Device>();
try {
conn = DigitalDisplayDAO.getConnection();
String selectDBQuery =
"SELECT DIGITAL_DISPLAY_DEVICE_ID, DEVICE_NAME FROM DIGITAL_DISPLAY_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
iotDevice = new Device();
iotDevice.setDeviceIdentifier(resultSet.getString(DigitalDisplayConstants.DEVICE_PLUGIN_DEVICE_ID));
iotDevice.setName(resultSet.getString(DigitalDisplayConstants.DEVICE_PLUGIN_DEVICE_NAME));
iotDevices.add(iotDevice);
}
if (log.isDebugEnabled()) {
log.debug("All Digital Display device details have fetched from Digital Display database.");
}
return iotDevices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all Digital Display device data'";
log.error(msg, e);
throw new DigitalDisplayDeviceMgtPluginException(msg, e);
} finally {
DigitalDisplayUtils.cleanupResources(stmt, resultSet);
DigitalDisplayDAO.closeConnection();
}
}
}

@ -0,0 +1,58 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.homeautomation.digitaldisplay.plugin.impl.feature;
import org.homeautomation.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
import java.util.List;
public class DigitalDisplayFeatureManager implements FeatureManager {
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
return false;
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
return false;
}
@Override
public Feature getFeature(String name) throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeature(DigitalDisplayConstants.DEVICE_TYPE, name);
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeatures(DigitalDisplayConstants.DEVICE_TYPE);
}
@Override
public boolean removeFeature(String name) throws DeviceManagementException {
return false;
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
return false;
}
}

@ -0,0 +1,50 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource;
import java.io.File;
/**
* Provides methods for initializing the database script.
*/
public class DeviceSchemaInitializer extends DatabaseCreator{
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
+ File.separator + "cdm" + File.separator + "plugins" + File.separator;
public DeviceSchemaInitializer(DataSource dataSource) {
super(dataSource);
}
@Override
protected String getDbScriptLocation(String databaseType) {
String scriptName = databaseType + ".sql";
if (log.isDebugEnabled()) {
log.debug("Loading database script from :" + scriptName);
}
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
}
}

@ -0,0 +1,110 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.homeautomation.digitaldisplay.plugin.exception.DigitalDisplayDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.common.Device;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Contains utility methods used by Digital Display plugin.
*/
public class DigitalDisplayUtils {
private static Log log = LogFactory.getLog(DigitalDisplayUtils.class);
public static String getDeviceProperty(List<Device.Property> deviceProperties, String propertyKey) {
String deviceProperty = "";
for(Device.Property property :deviceProperties){
if(propertyKey.equals(property.getName())){
deviceProperty = property.getValue();
}
}
return deviceProperty;
}
public static Device.Property getProperty(String property, String value) {
if (property != null) {
Device.Property prop = new Device.Property();
prop.setName(property);
prop.setValue(value);
return prop;
}
return null;
}
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}
/**
* Creates the device management schema.
*/
public static void setupDeviceManagementSchema() throws DigitalDisplayDeviceMgtPluginException {
try {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(DigitalDisplayConstants.DATA_SOURCE_NAME);
DeviceSchemaInitializer initializer =
new DeviceSchemaInitializer(dataSource);
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} catch (NamingException e) {
log.error("Error while looking up the data source: " + DigitalDisplayConstants.DATA_SOURCE_NAME);
} catch (Exception e) {
throw new DigitalDisplayDeviceMgtPluginException("Error occurred while initializing Iot Device " +
"Management database schema", e);
}
}
}

@ -0,0 +1,84 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.digitaldisplay.plugin.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.digitaldisplay.plugin.exception.DigitalDisplayDeviceMgtPluginException;
import org.homeautomation.digitaldisplay.plugin.impl.DigitalDisplayManagerService;
import org.homeautomation.digitaldisplay.plugin.impl.util.DigitalDisplayUtils;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
/**
* @scr.component name="org.homeautomation.digitaldisplay.plugin.internal.DigitalDisplayManagementServiceComponent"
* immediate="true"
*/
public class DigitalDisplayManagementServiceComponent {
private ServiceRegistration digitalDisplayServiceRegRef;
private static final Log log = LogFactory.getLog(DigitalDisplayManagementServiceComponent.class);
protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("Activating Digital Display Management Service Component");
}
try {
BundleContext bundleContext = ctx.getBundleContext();
digitalDisplayServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(), new
DigitalDisplayManagerService(), null);
String setupOption = System.getProperty("setup");
if (setupOption != null) {
if (log.isDebugEnabled()) {
log.debug("-Dsetup is enabled. Iot Device management repository schema initialization is about " +
"to begin");
}
try {
DigitalDisplayUtils.setupDeviceManagementSchema();
} catch (DigitalDisplayDeviceMgtPluginException e) {
log.error("Exception occurred while initializing device management database schema", e);
}
}
if (log.isDebugEnabled()) {
log.debug("Digital Display Management Service Component has been successfully activated");
}
} catch (Throwable e) {
log.error("Error occurred while activating Digital Display Management Service Component", e);
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating DigitalDisplay Management Service Component");
}
try {
if (digitalDisplayServiceRegRef != null) {
digitalDisplayServiceRegRef.unregister();
}
if (log.isDebugEnabled()) {
log.debug("DigitalDisplay Management Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error("Error occurred while de-activating Iot Device Management bundle", e);
}
}
}

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>digitaldisplay</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.1.0-SNAPSHOT</version>
<artifactId>digitaldisplay-component</artifactId>
<name>WSO2 IoTS(Device Types) - Digital Display Component</name>
<packaging>pom</packaging>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<version>${maven-scr-plugin.version}</version>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>plugin</module>
<module>api</module>
<module>ui</module>
</modules>
</project>

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>digitaldisplay-component</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.1.0-SNAPSHOT</version>
<artifactId>${groupId}.digitaldisplay.ui</artifactId>
<name>${groupId}.digitaldisplay.ui</name>
<packaging>pom</packaging>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<finalName>${project.artifactId}-${carbon.device.mgt.version}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/src.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>create-archive</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,36 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>src</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<baseDirectory>${basedir}/src</baseDirectory>
<fileSets>
<fileSet>
<directory>${basedir}/src/main/resources/jaggeryapps/devicemgt</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>
</assembly>

@ -0,0 +1,98 @@
{{#zone "topCss"}}
<style>
.thumbnail.icon:before {
padding-top: 0;
}
</style>
{{/zone}}
{{#zone "device-thumbnail"}}
<img src="{{@unit.publicUri}}/images/display-icon.png"/>
{{/zone}}
{{#zone "operation-status"}}
<div id="div-operation-status" class="hidden" align="center" style="padding: 10px; margin-bottom: 5px">
</div>
{{/zone}}
{{#zone "device-opetations"}}
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">
Operations
</div>
<div class="add-margin-top-4x">
{{unit "iot.unit.device.operation-bar" device=device}}
</div>
{{/zone}}
{{#zone "device-detail-properties"}}
<div class="media">
<div class="media-left col-xs-12 col-sm-2 col-md-2 col-lg-2">
<ul class="list-group" role="tablist">
<li><a class="list-group-item" href="#event_log" role="tab" data-toggle="tab"
aria-controls="event_log">Operations Log</a></li>
</ul>
</div>
<div class="media-body add-padding-left-5x remove-padding-xs tab-content">
<div class="panel panel-default tab-pane active"
id="device_statistics" role="tabpanel" aria-labelledby="device_statistics">
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">
Display Status
</div>
<div class="col-md-12">
<div id="screeshot" class="col-md-4">
<div>Display View</div>
<a id="zoom-image" href="{{@unit.publicUri}}/images/default-screen.png" target="_blank">
<img id="img" src="{{@unit.publicUri}}/images/default-screen.png"
style="width: 40% ; height: 40% ; float: left" class="img-responsive"/>
</a>
</div>
<div id="content-list-pane" class="col-md-4">
<div>Content List</div>
<ul id="content-list"></ul>
</div>
<div id="device-statics-pane" class="col-md-4">
<div>Device Statistics</div>
<ul id="device-statics"></ul>
</div>
</div>
</div>
<div class="panel-group tab-content">
<div class="panel panel-default tab-pane" id="event_log" role="tabpanel"
aria-labelledby="event_log">
<div class="panel-heading">Operations Log <span><a href="#"
id="refresh-operations"><i
class="fw fw-refresh"></i></a></span></div>
<div class="panel-body">
<div id="operations-spinner" class="wr-advance-operations-init hidden">
<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<i class="fw fw-settings fw-spin fw-2x"></i>
&nbsp;&nbsp;&nbsp;
Loading Operations Log . . .
<br>
<br>
</div>
<div id="operations-log-container">
<div class="panel-body">
Not available yet
</div>
<br class="c-both"/>
</div>
</div>
</div>
</div>
</div>
</div>
{{/zone}}
{{#zone "bottomJs"}}
<script type="text/javascript">
var port = "{{port}}";
var host = "{{host}}";
var sessionId = "{{sessionId}}";
</script>
{{js "js/websocket.js"}}
{{/zone}}

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

@ -0,0 +1,81 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var displayClient = null;
window.onload = function () {
connect();
};
window.onbeforeunload = function () {
disconnect();
}
function connect() {
displayClient = new WebSocket("wss://" + host + ":" + port + "/digital_display/" + sessionId);
displayClient.onmessage = function (event) {
var message = event.data;
var operationDiv = document.getElementById("div-operation-status");
var type = message.split('||')[0];
var reply = message.split('||')[1];
if (type.valueOf() == new String("Screenshot").valueOf()) {
document.getElementById('img').setAttribute('src', 'data:image/png;base64,' + reply);
document.getElementById('zoom-image').setAttribute('href', 'data:image/png;base64,' + reply);
} else if (type.valueOf() == new String("Success").valueOf()) {
$('#div-operation-status').removeClass('hidden');
$('#div-operation-status').text(reply);
operationDiv.style.backgroundColor = '#DFF2BF';
operationDiv.style.color = '#4F8A10';
} else if (type.valueOf() == new String("Failed").valueOf()) {
$('#div-operation-status').removeClass('hidden');
$('#div-operation-status').text(reply);
operationDiv.style.backgroundColor = '#FFBABA';
operationDiv.style.color = '#D8000C';
} else if (type.valueOf() == new String("ContentList").valueOf()) {
var resources = reply.split("-");
var ul = document.getElementById("content-list");
ul.innerHTML = "";
for (i = 0; i < resources.length; i++) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(resources[i]));
ul.appendChild(li);
}
} else if (type.valueOf() == new String("DeviceStatus").valueOf()) {
var resources = reply.split("-");
var ul = document.getElementById("device-statics");
ul.innerHTML = "";
for (i = 0; i < resources.length; i++) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(resources[i]));
ul.appendChild(li);
}
}
setTimeout(function () {
$('#div-operation-status').addClass('hidden');
}, 10000);
};
}
function disconnect() {
displayClient.close();
}

@ -0,0 +1,191 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var modalPopup = ".wr-modalpopup";
var modalPopupContainer = modalPopup + " .modalpopup-container";
var modalPopupContent = modalPopup + " .modalpopup-content";
var body = "body";
/*
* set popup maximum height function.
*/
function setPopupMaxHeight() {
$(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30)));
$(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2)));
}
/*
* show popup function.
*/
function showPopup() {
$(modalPopup).show();
setPopupMaxHeight();
$('#downloadForm').validate({
rules: {
deviceName: {
minlength: 4,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
$(element).closest('.control-group').removeClass('error').addClass('success');
$('label[for=deviceName]').remove();
}
});
var deviceType = "";
$('.deviceType').each(function () {
if (this.value != "") {
deviceType = this.value;
}
});
if (deviceType == 'digitaldisplay'){
$('.sketchType').remove();
$('input[name="sketchType"][value="digitaldisplay"]').prop('checked', true);
$("label[for='digitaldisplay']").text("Simple Agent");
}else{
$('.sketchTypes').remove();
}
}
/*
* hide popup function.
*/
function hidePopup() {
$('label[for=deviceName]').remove();
$('.control-group').removeClass('success').removeClass('error');
$(modalPopupContent).html('');
$(modalPopup).hide();
}
/*
* DOM ready functions.
*/
$(document).ready(function () {
attachEvents();
});
function attachEvents() {
/**
* Following click function would execute
* when a user clicks on "Download" link
* on Device Management page in WSO2 DC Console.
*/
$("a.download-link").click(function () {
var sketchType = $(this).data("sketchtype");
var deviceType = $(this).data("devicetype");
var downloadDeviceAPI = "/devicemgt/api/devices/sketch/generate_link";
var payload = {"sketchType": sketchType, "deviceType": deviceType};
$(modalPopupContent).html($('#download-device-modal-content').html());
showPopup();
var deviceName;
$("a#download-device-download-link").click(function () {
$('.new-device-name').each(function () {
if (this.value != "") {
deviceName = this.value;
}
});
$('label[for=deviceName]').remove();
if (deviceName && deviceName.length >= 4) {
payload.deviceName = deviceName;
invokerUtil.post(
downloadDeviceAPI,
payload,
function (data, textStatus, jqxhr) {
doAction(data);
},
function (data) {
doAction(data);
}
);
}else if(deviceName){
$('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">Please enter at least 4 ' +
'characters.</label>');
$('.control-group').removeClass('success').addClass('error');
} else {
$('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">This field is required.' +
'</label>');
$('.control-group').removeClass('success').addClass('error');
}
});
$("a#download-device-cancel-link").click(function () {
hidePopup();
});
});
}
function downloadAgent() {
var deviceName;
$('.new-device-name').each(function () {
if (this.value != "") {
deviceName = this.value;
}
});
var deviceNameFormat = /^[^~?!#$:;%^*`+={}\[\]\\()|<>,'"]{1,30}$/;
if (deviceName && deviceNameFormat.test(deviceName)) {
$('#downloadForm').submit();
hidePopup();
$(modalPopupContent).html($('#device-agent-downloading-content').html());
showPopup();
setTimeout(function () {
hidePopup();
}, 1000);
}else {
$("#invalid-username-error-msg span").text("Invalid device name");
$("#invalid-username-error-msg").removeClass("hidden");
}
}
function doAction(data) {
//if it is saml redirection response
if (data.status == null) {
document.write(data);
}
if (data.status == "200") {
$(modalPopupContent).html($('#download-device-modal-content-links').html());
$("input#download-device-url").val(data.responseText);
$("input#download-device-url").focus(function () {
$(this).select();
});
showPopup();
} else if (data.status == "401") {
$(modalPopupContent).html($('#device-401-content').html());
$("#device-401-link").click(function () {
window.location = "/devicemgt/login";
});
showPopup();
} else if (data == "403") {
$(modalPopupContent).html($('#device-403-content').html());
$("#device-403-link").click(function () {
window.location = "/devicemgt/login";
});
showPopup();
} else {
$(modalPopupContent).html($('#device-unexpected-error-content').html());
$("a#device-unexpected-error-link").click(function () {
hidePopup();
});
}
}

@ -0,0 +1,292 @@
<div class="col-lg-12 margin-top-double">
<h1 class="grey ">Digital Display</h1>
<hr>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 padding-top">
<img src="{{@unit.publicUri}}/images/display-icon.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 padding-top">
<h4 class="doc-link">Click <a href="https://docs.wso2.com/display/IoTS100/Digital+Display"
target="_blank">[ here ]</a> for latest instructions and
troubleshooting.</h4>
</div>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 padding-top">
<h3 class="uppercase">What it Does</h3>
<hr>
<p class="grey margin-top">Connect a Digital Message Display to WSO2 IoT Server and manage
it.</p>
<br>
<h3 class="uppercase">What You Need</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double">
<span class="circle">ITEM 01</span>
&nbsp;&nbsp;&nbsp;Raspberry Pi with SD Card(Internet Enabled [Wifi or Ethernet]).
</li>
<li class="padding-top-double">
<span class="circle">ITEM 02</span>
&nbsp;&nbsp;&nbsp;A Digital Display with HDMI Cable.
</li>
<li class="padding-top-double">
<span class="circle">STEP 03</span>
&nbsp;&nbsp;&nbsp;Proceed to [Prepare] section.
</ul>
<br>
<a href="/api-store/apis/info?name={{@uriParams.deviceType}}&version=1.0.0&provider=admin"
class="btn-operations" target="_blank">
<i class="fw fw-api"></i> View API</i> &nbsp;
</a>
<a href="#" class="download-link btn-operations">
<i class="fw fw-download"></i>Download Agent
</a>
<div id="download-device-modal-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 center-container">
<h3>Name your device and download the agent from following link.</h3>
<br/>
<form id="downloadForm" method="GET"
action="{{@app.context}}/api/devices/sketch/download">
<div id="invalid-username-error-msg" class="alert alert-danger hidden"
role="alert">
<i class="icon fw fw-error"></i><span></span>
</div>
<div class="control-group">
<div class="controls">
<input class="new-device-name" style="color:#3f3f3f;padding:5px"
type="text" placeholder="Ex. Lobby_DigitalDisplay"
name="deviceName" size="60" required>
<br/>
<br/>
<input type="hidden" class="deviceType" name="deviceType"
value="digital_display"/>
<input type="hidden" class="sketchType" name="sketchType"
value="digital_display"/>
</div>
</div>
<div class="buttons" style="padding-bottom: 0px">
<a class="btn btn-operations" onclick="downloadAgent()">Download Now</a>
&nbsp;&nbsp;
<a href="#" id="download-device-download-link"
class="btn btn-operations"> Copy Link </a>
&nbsp;&nbsp;
</div>
</form>
</div>
</div>
</div>
</div>
<div id="device-agent-downloading-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Agent will downloading shortly.</h3>
</div>
</div>
</div>
</div>
<div id="download-device-modal-content-links" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Please download the file from following link(Press CTRL+C).</h3>
<br/>
<div>
<input id="download-device-url" style="color:#3f3f3f;padding:5px"
type="text" value="" placeholder="Type here" size="60">
</div>
</div>
</div>
</div>
</div>
<div id="device-400-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Exception at backend. Try Later.</h3>
<div class="buttons">
<a href="#" id="device-400-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-401-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>You have to log in first.</h3><br/>
<div class="buttons">
<a href="#" id="device-401-link" class="blue-button">
Goto Login Page
</a>&nbsp;&nbsp;
<a href="#" onclick="hidePopup();" class="btn-operations">
Cancel
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-403-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Action not permitted.</h3><br/>
<div class="buttons">
<a href="#" id="device-403-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-409-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Sketch does not exist.</h3><br/>
<div class="buttons">
<a href="#" id="device-409-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-unexpected-error-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Unexpected error.</h3><br/>
<div class="buttons">
<a href="#" id="device-unexpected-error-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<br/><br/>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 padding-double grey-bg">
<h3 class="uppercase">Prepare</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double">
<span class="circle">01</span>
&nbsp;&nbsp;&nbsp;Connect a monitor to your RaspberryPi via HDMI cable.
</li>
<li class="padding-top-double">
<span class="circle">02</span>
&nbsp;&nbsp;&nbsp;Configure RaspberryPi to connect to the Internet.
</li>
<li class="padding-top-double">
<span class="circle">03</span>
&nbsp;&nbsp;&nbsp;Go ahead and [Download Agent] the Digital Display Agent.
</li>
<li class="padding-top-double">
<span class="circle">04</span>
&nbsp;&nbsp;&nbsp;Unzip downloaded agent.
</li>
<li class="padding-top-double">
<span class="circle">05</span>
&nbsp;&nbsp;&nbsp;Start Agent by running installpackages.sh followed by wso2Agent.sh
</li>
</ul>
<br>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
<h3 class="uppercase">Digital-Display Setup</h3>
<hr>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@unit.publicUri}}/images/schematicsGuide.png" target="_blank">
<img src="{{@unit.publicUri}}/images/schematicsGuide.png" class="img-responsive">
</a>
</center>
<br/>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
<h3 class="uppercase">Try Out</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double">
<span class="circle">01</span>
&nbsp;&nbsp;&nbsp;You can view all your connected devices at
<a href="{{@app.context}}/devices">[Device Management]</a> page.
</li>
<li class="padding-top-double">
<span class="circle">02</span>
&nbsp;&nbsp;&nbsp;Select one of connected devices and check for available control
operations.
</ul>
<br/>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@unit.publicUri}}/images/myDevices_analytics.png" target="_blank">
<img src="{{@unit.publicUri}}/images/myDevices_analytics.png" class="img-responsive">
</a>
</center>
</div>
<style type="text/css">
.circle {
background: none repeat scroll 0 0 #191919;
border-radius: 50px;
height: 50px;
padding: 10px;
width: 50px;
color: #fff;
}
.padding-top-double {
padding-top: 20px;
}
.padding-double {
padding: 20px;
}
.grey {
color: #333;
}
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #7f7f7f;
margin: 1em 0;
padding: 0;
opacity: 0.2;
}
.light-grey {
color: #7c7c7c;
}
.uppercase {
text-transform: uppercase;
}
.grey-bg {
background-color: #f6f4f4;
}
.doc-link {
background: #11375B;
padding: 20px;
color: white;
margin-top: 0;
}
.doc-link a {
color: white;
}
</style>
{{#zone "bottomJs"}}
{{js "/js/download.js"}}
{{js "/js/jquery.validate.js"}}
{{/zone}}

@ -0,0 +1,208 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>digitaldisplay-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.1.0-SNAPSHOT</version>
<artifactId>${groupId}.digitaldisplay.feature</artifactId>
<packaging>pom</packaging>
<name>${project.artifactId}</name>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.api</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
<version>1.2.140.wso2v3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.ui</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/jaggeryapps/devicemgt
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.api</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps/
</outputDirectory>
<destFileName>digital_display.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<!-- Creating Digital Display Plugin Management schema -->
<id>create-digital-display-plugin-mgt-schema</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo message="########### Create Digital Display plugin Management H2 Schema ###########"/>
<property name="db.dir"
value="target/maven-shared-archive-resources/database"/>
<property name="userid" value="wso2carbon"/>
<property name="password" value="wso2carbon"/>
<property name="dbURL"
value="jdbc:h2:file:${basedir}/${db.dir}/DigitalDisplayDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
<mkdir dir="${basedir}/${db.dir}"/>
<sql driver="org.h2.Driver" url="${dbURL}" userid="${userid}"
password="${password}"
autocommit="true" onerror="continue">
<classpath refid="maven.dependency.classpath"/>
<classpath refid="maven.compile.classpath"/>
<classpath refid="maven.runtime.classpath"/>
<fileset file="${basedir}/src/main/resources/dbscripts/h2.sql"/>
</sql>
<echo message="##################### END ####################"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>${project-base-package}</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:true</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.homeautomation:${project-base-package}.plugin:${carbon.device.mgt.plugin.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,29 @@
#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
#[Device-Configurations]
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/digital_display/controller
mqtt-ep=${MQTT_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15

@ -0,0 +1,16 @@
#!/bin/bash
# installing dependencies
echo ===Installing Dependencies
sudo apt-get install python-pip
sudo pip install paho-mqtt
sudo apt-get install python-lxml
sudo apt-get install gtk2
sudo apt-get install xdotool
# unzipping the archive
echo ===Unzipping DigitalDisplay.zip
unzip DigitalDisplay
# copying the property file
echo ===Moving deviceConfig.properties
cp ./deviceConfig.properties ./DigitalDisplay

@ -0,0 +1,2 @@
templates=deviceConfig.properties
zipfilename=DigitalDisplayAgent.zip

@ -0,0 +1,12 @@
#!/bin/bash
ps aux|grep wso2server.py|awk '{print $2}'|xargs kill -9
ps aux|grep httpserver.py|awk '{print $2}'|xargs kill -9
#xdotool mousemove 0 0
#xdotool search -name LXTerminal windowunmap
#cd ~/
cd ./DigitalDisplay/
mkdir -p tmp/dd-kernel-test
python displayagent.py
while true; do
sleep 100
done

@ -0,0 +1,7 @@
{
"deviceType": {
"label": "Digital Display",
"category": "iot"
}
}

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

@ -0,0 +1,46 @@
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>
<datasources>
<datasource>
<name>DigitalDisplayDM_DB</name>
<description>The datasource used for the Digital Display database</description>
<jndiConfig>
<name>jdbc/DigitalDisplayDM_DB</name>
</jndiConfig>
<definition type="RDBMS">
<configuration>
<url>jdbc:h2:repository/database/DigitalDisplayDM_DB;DB_CLOSE_ON_EXIT=FALSE
</url>
<username>wso2carbon</username>
<password>wso2carbon</password>
<driverClassName>org.h2.Driver</driverClassName>
<maxActive>50</maxActive>
<maxWait>60000</maxWait>
<testOnBorrow>true</testOnBorrow>
<validationQuery>SELECT 1</validationQuery>
<validationInterval>30000</validationInterval>
</configuration>
</definition>
</datasource>
</datasources>
</datasources-configuration>

@ -0,0 +1,11 @@
-- -----------------------------------------------------
-- Table `DIGITAL_DISPLAY_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DIGITAL_DISPLAY_DEVICE` (
`DIGITAL_DISPLAY_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`DIGITAL_DISPLAY_DEVICE_ID`) );

@ -0,0 +1,12 @@
-- -----------------------------------------------------
-- Table `DIGITAL_DISPLAY_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DIGITAL_DISPLAY_DEVICE` (
`DIGITAL_DISPLAY_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`DIGITAL_DISPLAY_DEVICE_ID`) )
ENGINE = InnoDB;

@ -0,0 +1,26 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../conf/device-types/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.digitaldisplay_${feature.version}/configs/,target:${installFolder}/../../conf/device-types/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.digitaldisplay_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/digital_display/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.digitaldisplay_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/digital_display/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.digitaldisplay_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/digital_display,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.digitaldisplay_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.digitaldisplay_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.digitaldisplay_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\
instructions.unconfigure = \
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/device-types/digital_display.json);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/device-types/digital_display.xml);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/digital_display.war);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/digital_display);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../dbscripts/cdm/plugins/digital_display);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../resources/sketches/digital_display);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/datasources/digitaldisplay-datasources.xml);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../database/DigitalDisplayDM_DB.h2.db);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.digital_display.device-view);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.digital_display.type-view);\

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>digitaldisplay</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>digitaldisplay-feature</artifactId>
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<version>2.1.0-SNAPSHOT</version>
<modules>
<module>feature</module>
</modules>
</project>

@ -0,0 +1,496 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2</groupId>
<artifactId>wso2</artifactId>
<version>1</version>
</parent>
<groupId>org.homeautomation</groupId>
<artifactId>digitaldisplay</artifactId>
<version>2.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modelVersion>4.0.0</modelVersion>
<url>http://wso2.com</url>
<modules>
<module>component</module>
<module>feature</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
<version>${eclipse.osgi.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.equinox</groupId>
<artifactId>org.eclipse.equinox.common</artifactId>
<version>${eclipse.equinox.common.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
<exclusion>
<groupId>org.beanshell</groupId>
<artifactId>bsh</artifactId>
</exclusion>
<exclusion>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</exclusion>
</exclusions>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
<version>3.3.100.v20120522-1822</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
<version>${carbon.kernel.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.log4j.wso2</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.bootstrap</artifactId>
</exclusion>
</exclusions>
<scope>provided</scope>
</dependency>
<!-- CXF dependencies -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>${cxf.version}</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf.version}</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>${paho.mqtt.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>${javax.ws.rs.version}</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>org.homeautomation.digitaldisplay.plugin</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.apimgt.webapp.publisher_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
<version>${carbon.kernel.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.ndatasource.core_${carbon.kernel.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.iot_${carbon.iot.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.core_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.common_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.certificate.mgt.core_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.apimgt.annotations_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.analytics.data.publisher_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
<version>${commons-httpclient.orbit.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/commons-httpclient_3.1.0.wso2v2.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<version>${carbon.kernel.version}</version>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.utils_${carbon.kernel.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
<version>${smack.wso2.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/smack_3.0.4.wso2v1.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
<version>${smackx.wso2.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/smackx_3.0.4.wso2v1.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
<version>${commons-json.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/json_3.0.0.wso2v1.jar
</systemPath>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4.0.wso2v1</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/commons-codec_1.4.0.wso2v1.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.extensions_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.apimgt.application.extension_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
<version>${carbon.device.mgt.jar.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.identity.jwt.client.extension_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
<version>${carbon.kernel.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.user.api_${carbon.kernel.version}.jar
</systemPath>
</dependency>
</dependencies>
</dependencyManagement>
<pluginRepositories>
<pluginRepository>
<id>wso2.releases</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</pluginRepository>
<pluginRepository>
<id>wso2.snapshots</id>
<name>Apache Snapshot Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
<pluginRepository>
<id>wso2-nexus</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</pluginRepository>
</pluginRepositories>
<repositories>
<!-- Before adding ANYTHING in here, please start a discussion on the dev list.
Ideally the Axis2 build should only use Maven central (which is available
by default) and nothing else. We had troubles with other repositories in
the past. Therefore configuring additional repositories here should be
considered very carefully. -->
<repository>
<id>wso2-nexus</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</repository>
<repository>
<id>wso2.releases</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</repository>
</repositories>
<properties>
<carbon.kernel.version>4.4.3</carbon.kernel.version>
<carbon.device.mgt.version>1.1.0-SNAPSHOT</carbon.device.mgt.version>
<carbon.device.mgt.jar.version>1.1.0.SNAPSHOT</carbon.device.mgt.jar.version>
<paho.mqtt.version>1.0.2</paho.mqtt.version>
<commons-json.version>3.0.0.wso2v1</commons-json.version>
<eclipse.osgi.version>3.8.1.v20120830-144521</eclipse.osgi.version>
<carbon.device.mgt.plugin.version>2.1.0-SNAPSHOT</carbon.device.mgt.plugin.version>
<carbon.iot.device.mgt.jar.version>2.1.0.SNAPSHOT</carbon.iot.device.mgt.jar.version>
<javax.ws.rs.version>1.1.1</javax.ws.rs.version>
<!--XMPP/MQTT Version-->
<smack.wso2.version>3.0.4.wso2v1</smack.wso2.version>
<smackx.wso2.version>3.0.4.wso2v1</smackx.wso2.version>
<cxf.version>2.6.1</cxf.version>
<jackson.version>1.9.0</jackson.version>
<commons-httpclient.orbit.version>3.1.0.wso2v2</commons-httpclient.orbit.version>
<commons-json.version>3.0.0.wso2v1</commons-json.version>
<eclipse.equinox.common.version>3.6.100.v20120522-1841</eclipse.equinox.common.version>
<wso2.maven.compiler.source>1.7</wso2.maven.compiler.source>
<wso2.maven.compiler.target>1.7</wso2.maven.compiler.target>
<project-base-package>org.homeautomation.digitaldisplay</project-base-package>
<junit.version>3.8.1</junit.version>
<org.apache.felix.version>1.4.0</org.apache.felix.version>
<maven-clean-plugin.version>2.4.1</maven-clean-plugin.version>
<maven-compiler-plugin.version>2.3.2</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-antrun-plugin.version>1.8</maven-antrun-plugin.version>
<maven-scr-plugin.version>1.7.2</maven-scr-plugin.version>
</properties>
</project>

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

@ -0,0 +1,46 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@API(name = "drone_analyzer", version = "1.0.0", context = "/drone_analyzer", tags = {"drone_analyzer"})
@DeviceType(value = "drone_analyzer")
public interface DroneControllerService {
@Path("device/register/{deviceId}/{ip}/{port}")
@POST
Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort);
@Path("device/{deviceId}/send_command")
@POST
/*@Feature( code="send_command", name="Send Command", type="operation",
description="Send Commands to Drone")*/
Response droneController(@PathParam("deviceId") String deviceId, @FormParam("action") String action,
@FormParam("duration") String duration, @FormParam("speed") String speed);
}

@ -0,0 +1,55 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.util.DroneAnalyzerServiceUtils;
import org.homeautomation.droneanalyzer.plugin.controller.DroneController;
import org.homeautomation.droneanalyzer.plugin.controller.impl.DroneControllerImpl;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import javax.ws.rs.core.Response;
import java.util.concurrent.ConcurrentHashMap;
public class DroneControllerServiceImpl implements DroneControllerService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneControllerServiceImpl.class);
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private DroneController droneController = new DroneControllerImpl();
public Response registerDeviceIP(String deviceId, String deviceIP, String devicePort) {
String result;
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.ok(Response.Status.OK.getStatusCode()).build();
}
public Response droneController(String deviceId, String action, String duration, String speed) {
try {
DroneAnalyzerServiceUtils.sendControlCommand(droneController, deviceId, action, Double.valueOf(speed),
Double.valueOf(duration));
return Response.status(Response.Status.ACCEPTED).build();
} catch (DeviceManagementException e) {
log.error("Drone command didn't success. Try again, \n" + e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
}

@ -0,0 +1,69 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@API(name = "drone_analyzer_mgt", version = "1.0.0", context = "/drone_analyzer_mgt", tags = {"drone_analyzer"})
@DeviceType(value = "drone_analyzer")
public interface DroneManagerService {
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getDroneDevices();
@Path("devices/{sketch_type}/download")
@GET
@Produces("application/octet-stream")
Response downloadSketch(@QueryParam("deviceName") String deviceName, @PathParam("sketch_type") String sketchType);
@Path("devices/{sketch_type}/generate_link")
@GET
Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType);
}

@ -0,0 +1,259 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.util.APIUtil;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppAccount;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class DroneManagerServiceImpl implements DroneManagerService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneManagerServiceImpl.class);
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
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;
}
}
public Response removeDevice(String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier);
if (removed) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response updateDevice(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DroneConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getDevice(String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getDroneDevices() {
try {
List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser());
ArrayList<Device> userDevicesforDrone = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(DroneConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(
EnrolmentInfo.Status.ACTIVE)) {
userDevicesforDrone.add(device);
}
}
Device[] devices = userDevicesforDrone.toArray(new Device[]{});
return Response.ok().entity(devices).build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response downloadSketch(String deviceName, String sketchType) {
//create new device id
String deviceId = shortUUID();
//create token
String token = UUID.randomUUID().toString();
String refreshToken = UUID.randomUUID().toString();
//adding registering data
boolean status = register(deviceId, deviceName);
if (!status) {
return Response.status(500).entity(
"Error occurred while registering the device with " + "id: " + deviceId + " owner:" +
APIUtil.getAuthenticatedUser()).build();
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile;
try {
zipFile = ziputil.createZipFile(APIUtil.getAuthenticatedUser(), APIUtil.getTenantDomainOftheUser(),
sketchType, deviceId, deviceName, token, refreshToken);
} catch (DeviceManagementException ex) {
return Response.status(500).entity("Error occurred while creating zip file").build();
}
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return rb.build();
}
public Response generateSketchLink(String deviceName, String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(deviceName, sketchType);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String deviceName, String sketchType)
throws DeviceManagementException, JWTClientException, APIManagerException, DeviceControllerException,
UserStoreException {
//create new device id
String deviceId = shortUUID();
if (apiApplicationKey == null) {
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DroneConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DroneConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String scopes = "device_type_" + DroneConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
//adding registering data
XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(APIUtil.getAuthenticatedUser() + "_" + deviceId);
newXmppAccount.setUsername(deviceId);
newXmppAccount.setPassword(accessToken);
newXmppAccount.setEmail(deviceId + "@wso2.com");
XmppServerClient xmppServerClient = new XmppServerClient();
xmppServerClient.initControlQueue();
boolean status;
if (XmppConfig.getInstance().isEnabled()) {
status = xmppServerClient.createXMPPAccount(newXmppAccount);
if (!status) {
String msg = "XMPP Account was not created for device - " + deviceId + " of owner - " +
APIUtil.getAuthenticatedUser() + ".XMPP might have been disabled in " +
"org.wso2.carbon.device.mgt.iot.common.config.server.configs";
log.warn(msg);
throw new DeviceManagementException(msg);
}
}
//Register the device with CDMF
status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId
+ " owner:" + APIUtil.getAuthenticatedUser();
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(APIUtil.getAuthenticatedUser(), APIUtil.getTenantDomainOftheUser(),
sketchType, deviceId, deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
}

@ -0,0 +1,125 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.transport.DroneAnalyzerXMPPConnector;
import org.homeautomation.droneanalyzer.api.trasformer.MessageTransformer;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@ServerEndpoint("/datastream/drone_status")
public class DroneRealTimeService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneRealTimeService.class);
private MessageTransformer messageController;
private DroneAnalyzerXMPPConnector xmppConnector;
public DroneRealTimeService() {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
messageController = new MessageTransformer();
xmppConnector = new DroneAnalyzerXMPPConnector(messageController);
if (XmppConfig.getInstance().isEnabled()){
xmppConnector.connect();
} else {
log.warn("XMPP disabled in 'devicemgt-config.xml'. Hence, DroneAnalyzerXMPPConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
@OnOpen
public void onOpen(Session session){
log.info(session.getId() + " has opened a connection");
try {
session.getBasicRemote().sendText("Connection Established");
} catch (IOException e) {
log.error( e.getMessage()+"\n"+ e);
}
}
@OnMessage
public void onMessage(String message, Session session){
while (true) {
try {
if (messageController != null && !messageController.isEmptyQueue()) {
String messageControllerMessage = messageController.getMessage();
session.getBasicRemote().sendText(messageControllerMessage);
break;
}
Thread.sleep(DroneConstants.MINIMUM_TIME_DURATION);
} catch (IOException | InterruptedException ex) {
log.error(ex.getMessage(), ex);
break;
}
}
}
@OnClose
public void onClose(Session session){
try {
xmppConnector.disconnect();
log.info("XMPP connection is disconnected");
}
catch (Exception e) {
log.error(e.getMessage() + "\n" + e);
}
log.info("Session " + session.getId() + " has ended");
}
@OnError
public void onError(Session session, Throwable t) {
try {
session.getBasicRemote().sendText("Connection closed");
xmppConnector.disconnect();
log.info("XMPP connection is disconnected");
} catch (Exception e) {
log.error(e.getMessage()+"\n"+ e);
}
log.info("Session " + session.getId() + " has ended");
}
}

@ -0,0 +1,32 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api.exception;
public class DroneAnalyzerException extends Exception {
private static final long serialVersionUID = 118512086958330189L;
public DroneAnalyzerException(String errorMessage) {
super(errorMessage);
}
public DroneAnalyzerException(String errorMessage, Throwable throwable) {
super(errorMessage, throwable);
}
}

@ -0,0 +1,160 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.trasformer.MessageTransformer;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.jivesoftware.smack.packet.Message;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.xmpp.XMPPTransportHandler;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class DroneAnalyzerXMPPConnector extends XMPPTransportHandler {
private static Log log = LogFactory.getLog(DroneAnalyzerXMPPConnector.class);
private static String xmppServerIP;
private static String xmppAdminUsername;
private static String xmppAdminPassword;
private static String xmppAdminAccountJID;
private MessageTransformer messageTransformer;
private ScheduledFuture<?> connectorServiceHandler;
private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
public DroneAnalyzerXMPPConnector(MessageTransformer messageTransformer) {
super(XmppConfig.getInstance().getXmppServerIP(), XmppConfig.getInstance().getSERVER_CONNECTION_PORT());
this.messageTransformer = messageTransformer;
}
@Override
public void connect() {
Runnable connector = new Runnable() {
@Override
public void run() {
if (!isConnected()) {
try {
initConnector();
connectToServer();
loginToServer(xmppAdminUsername, xmppAdminPassword, null);
setFilterOnReceiver(xmppAdminAccountJID);
} catch (TransportHandlerException e) {
if (log.isDebugEnabled()) {
log.warn("Connection/Login to XMPP server at: " + server + " as " +
xmppAdminUsername + " failed for device-type [" +
DroneConstants.DEVICE_TYPE + "].", e);
}
}
}
}
};
connectorServiceHandler = service.scheduleAtFixedRate(connector, 0, timeoutInterval, TimeUnit.MILLISECONDS);
}
public void initConnector() {
xmppServerIP = XmppConfig.getInstance().getXmppServerIP();
xmppAdminUsername = XmppConfig.getInstance().getXmppUsername();
xmppAdminPassword = XmppConfig.getInstance().getXmppPassword();
xmppAdminAccountJID = xmppAdminUsername + "@" + xmppServerIP;
}
@Override
public void processIncomingMessage(Message message) throws TransportHandlerException {
try {
String from = message.getFrom();
String inboundMessage = message.getBody();
int indexOfSlash = from.indexOf("/");
if (indexOfSlash == 0) {
if (log.isDebugEnabled()) {
log.debug("Required resource not available.");
}
} else {
String resource = from.substring(indexOfSlash + 1, from.length());
if ((inboundMessage != null) && (resource.equals(DroneConstants.MESSAGE_RESOURCE))) {
messageTransformer.messageTranslater(inboundMessage);
} else {
if (log.isDebugEnabled()) {
log.debug("Message is empty or it is not belongs to " + xmppAdminUsername);
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {
log.error("Wrong message format: input message", e);
} catch (RuntimeException e) {
log.error("Unexpected error has been occurred, ", e);
}
}
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
String xmppJID = publishData[0];
String xmppMessage = publishData[1];
String xmppSubject = publishData[2];
sendXMPPMessage(xmppJID, xmppMessage, xmppSubject);
}
public void disconnect() {
Runnable stopConnection = new Runnable() {
public void run() {
while (isConnected()) {
connectorServiceHandler.cancel(true);
closeConnection();
if (log.isDebugEnabled()) {
log.warn("Unable to 'STOP' connection to XMPP server at: " + server +
" for user - " + xmppAdminUsername);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
log.error("XMPP-Terminator: Thread Sleep Interrupt Exception for "
+ DroneConstants.DEVICE_TYPE + " type.", e1);
}
}
}
};
Thread terminatorThread = new Thread(stopConnection);
terminatorThread.setDaemon(true);
terminatorThread.start();
}
@Override
public void processIncomingMessage() throws TransportHandlerException {
}
@Override
public void processIncomingMessage(Message message, String... messageParams) throws TransportHandlerException {
}
@Override
public void publishDeviceData() throws TransportHandlerException {
}
@Override
public void publishDeviceData(Message publishData) throws TransportHandlerException {
}
}

@ -0,0 +1,134 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api.trasformer;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.constants.MessageConfig;
import java.io.IOException;
public class MessageTransformer {
private Log log = LogFactory.getLog(MessageTransformer.class);
private CircularFifoQueue<String> sharedQueue;
private String outboundMessageFormatForSimulator = "{\"quatanium_val\":[%f, %f, %f, %f]," +
"\"basicParam\":{\"velocity\":[%f, %f, %f], \"global_location\":[%f, %f, %f]},\"battery_level\":%f, \"device_type\":\"SIMULATOR\"}";
private String outboundMessageFormatForIrisDrone = "{\"quatanium_val\":[%f, %f, %f]," +
"\"basicParam\":{\"velocity\":[%f, %f, %f], \"global_location\":[%f, %f, %f]},\"battery_level\":%f," +
"\"device_type\":\"IRIS_DRONE\"}";
public MessageTransformer(){
sharedQueue = new CircularFifoQueue<String>(DroneConstants.MAXIMUM_BUFFERE_SIZE_OF_SHARED_QUEUE);
}
private void messageTranslaterForSimulator(JsonNode inbound_message){
JsonNode node = inbound_message;
String outboundMessage;
try {
JsonNode velocity = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(MessageConfig.OUT_BASIC_PARAM_VELOCITY);
JsonNode globalLocation = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(
MessageConfig.OUT_BASIC_PARAM_GLOBAL_LOCATION);
JsonNode quataniumVals = node.get(MessageConfig.OUT_QUATANNIM_VAL);
JsonNode batteryLevel = node.get(MessageConfig.OUT_BATTERY_LEVEL);
outboundMessage = String.format(outboundMessageFormatForSimulator, sTd(quataniumVals.get(0)),
sTd(quataniumVals.get(1)), sTd(quataniumVals.get(2)), sTd(quataniumVals.get(0)),
sTd(velocity.get(0)), sTd(velocity.get(1)), sTd(velocity.get(2)), sTd(globalLocation.get(0)),
sTd(globalLocation.get(1)), sTd(globalLocation.get(2)), sTd(batteryLevel));
sharedQueue.add(outboundMessage);
} catch (Exception e) {
log.error(e.getMessage()+",\n"+ e);
}
}
private void messageTranslaterForIRISDrone(JsonNode inbound_message){
JsonNode node = inbound_message;
String outboundMessage;
try {
JsonNode velocity = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(MessageConfig.OUT_BASIC_PARAM_VELOCITY);
JsonNode globalLocation = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(
MessageConfig.OUT_BASIC_PARAM_GLOBAL_LOCATION);
JsonNode quataniumVals = node.get(MessageConfig.OUT_QUATANNIM_VAL);
JsonNode batteryLevel = node.get(MessageConfig.OUT_BATTERY_LEVEL);
outboundMessage = String.format(outboundMessageFormatForIrisDrone, sTd(quataniumVals.get(0)),
sTd(quataniumVals.get(1)), sTd(quataniumVals.get(2)), sTd(velocity.get(0)),
sTd(velocity.get(1)), sTd(velocity.get(2)), sTd(globalLocation.get(0)),
sTd(globalLocation.get(1)), sTd(globalLocation.get(2)), sTd(batteryLevel));
sharedQueue.add(outboundMessage);
}catch (Exception e) {
log.error(e.getMessage()+",\n"+ e);
}
}
public void messageTranslater(String inbound_message){
JsonNode actualMessage;
ObjectMapper objectMapper = new ObjectMapper();
try {
actualMessage = objectMapper.readValue(inbound_message, JsonNode.class);
JsonNode deviceType = actualMessage.get(MessageConfig.IN_DEVICE_TYPE);
switch (deviceType.getTextValue()) {
case MessageConfig.IN_IRIS_DRONE:
messageTranslaterForIRISDrone(actualMessage);
break;
case MessageConfig.IN_SIMULATOR:
messageTranslaterForSimulator(actualMessage);
break;
default:
if(log.isDebugEnabled()){
log.debug("Wrong message format");
}
}
} catch (JsonProcessingException e) {
log.error("Incoming message might be corrupted, "+ e);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
private double sTd(JsonNode s)
{
return Double.parseDouble(s.toString());
}
public String getMessage() {
try{
if(sharedQueue.isEmpty() || sharedQueue == null){
return "";
}
return sharedQueue.remove();
}catch(Exception e) {
log.error("There is no more messages to send or internal server error has been occurred, \n"+ e );
return "";
}
}
public boolean isEmptyQueue(){
return sharedQueue != null? sharedQueue.isEmpty():false;
}
}

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

@ -0,0 +1,95 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api.util;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.transport.DroneAnalyzerXMPPConnector;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.controller.DroneController;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import java.io.File;
public class DroneAnalyzerServiceUtils {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneAnalyzerServiceUtils.class);
public static void sendCommandViaXMPP(String deviceOwner, String deviceId, String resource,
String state, DroneAnalyzerXMPPConnector droneXMPPConnector)
throws DeviceManagementException, TransportHandlerException {
String xmppServerDomain = XmppConfig.getInstance().getXmppEndpoint();
int indexOfChar = xmppServerDomain.lastIndexOf(File.separator);
if (indexOfChar != -1) {
xmppServerDomain = xmppServerDomain.substring((indexOfChar + 1), xmppServerDomain.length());
}
indexOfChar = xmppServerDomain.indexOf(":");
if (indexOfChar != -1) {
xmppServerDomain = xmppServerDomain.substring(0, indexOfChar);
}
String clientToConnect = deviceId + "@" + xmppServerDomain + File.separator + deviceOwner;
String message = resource.replace("/", "") + ":" + state;
droneXMPPConnector.publishDeviceData(clientToConnect, message, "CONTROL-REQUEST");
}
public static boolean sendControlCommand(DroneController controller, String deviceId, String action,
double speed, double duration)
throws DeviceManagementException {
boolean controlState = false;
try{
switch (action){
case DroneConstants.TAKE_OFF:
controlState = controller.takeoff();
break;
case DroneConstants.LAND:
controlState = controller.land();
break;
case DroneConstants.BACK:
controlState = controller.back(speed, duration);
break;
case DroneConstants.CLOCK_WISE:
controlState = controller.clockwise(speed, duration);
break;
case DroneConstants.COUNTER_CLOCKWISE:
controlState = controller.conterClockwise(speed, duration);
break;
case DroneConstants.DOWN:
controlState = controller.down(speed, duration);
break;
case DroneConstants.FRONT:
controlState = controller.back(speed, duration);
break;
case DroneConstants.FORWARD:
controlState = controller.clockwise(speed, duration);
break;
case DroneConstants.UP:
controlState = controller.up(speed, duration);
break;
default:
log.error("Invalid command");
break;
}
}catch(Exception e){
log.error(e.getMessage()+ "\n"+ e);
}
return controlState;
}
}

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/devices/*</url>
<method>GET</method>
<scope>drone_analyzer_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/devices/*</url>
<method>DELETE</method>
<scope>drone_analyzer_user</scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/*/download</url>
<method>GET</method>
<scope>drone_analyzer_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/devices/*</url>
<method>POST</method>
<scope>drone_analyzer_user</scope>
</Permission>
<Permission>
<name>Get Devices</name>
<path>/device-mgt/user/devices</path>
<url>/devices</url>
<method>GET</method>
<scope>drone_analyzer_user</scope>
</Permission>
<Permission>
<name>Generate Link</name>
<path>/device-mgt/user/devices/generate_link</path>
<url>/devices/*/generate_link</url>
<method>GET</method>
<scope>drone_analyzer_user</scope>
</Permission>
<Permission>
<name>Register Device</name>
<path>/device-mgt/user/device/register</path>
<url>/device/register/*/*/*</url>
<method>POST</method>
<scope>drone_analyzer_device</scope>
</Permission>
<Permission>
<name>Send Command</name>
<path>/device-mgt/user/device/send_command</path>
<url>/device/*/send_command</url>
<method>POST</method>
<scope>drone_analyzer_user</scope>
</Permission>
</PermissionConfiguration>

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright 2005-2013 WSO2, Inc. (http://wso2.com)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
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/core http://cxf.apache.org/schemas/core.xsd">
<jaxrs:server id="DroneAnalyzer" address="/">
<jaxrs:features>
<cxf:logging/>
</jaxrs:features>
<jaxrs:serviceBeans>
<bean id="DroneControllerService"
class="org.homeautomation.droneanalyzer.api.DroneControllerServiceImpl">
<!--<property name="DroneXMPPConnector" ref="xmppConnectorBean"/>-->
</bean>
<bean id="DroneManagerService"
class="org.homeautomation.droneanalyzer.api.DroneManagerServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
</beans>

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="utf-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
metadata-complete="true">
<display-name>WSO2 IoT Server</display-name>
<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>
<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>
<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>

@ -0,0 +1,120 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>droneanalyzer-component</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.1.0-SNAPSHOT</version>
<artifactId>${groupId}.droneanalyzer.plugin</artifactId>
<packaging>bundle</packaging>
<name>${groupId}.droneanalyzer.plugin for CDMF </name>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>${org.apache.felix.version}</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${groupId}.droneanalyzer.plugin</Bundle-SymbolicName>
<Bundle-Name>${groupId}.droneanalyzer.plugin</Bundle-Name>
<Bundle-Version>2.1.0-SNAPSHOT</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.homeautomation.droneanalyzer.plugin.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.naming;resolution:=optional,
javax.sql;resolution:=optional,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.device.mgt.iot.*,
org.wso2.carbon.device.mgt.extensions.feature.mgt.*,
org.wso2.carbon.utils.*
</Import-Package>
<Export-Package>
!org.homeautomation.droneanalyzer.plugin.internal,
org.homeautomation.droneanalyzer.plugin.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,41 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.constants;
public class DroneConstants {
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "DRONE_DEVICE_ID";
public final static String MESSAGE_RESOURCE = "drone_current_status";
public static final String DEVICE_TYPE = "drone_analyzer";
public static final int MINIMUM_TIME_DURATION = 150;
public static final int MAXIMUM_BUFFERE_SIZE_OF_SHARED_QUEUE = 10;
public static final String DEVICE_ID = "drone_type1";
public final static String TAKE_OFF = "takeoff";
public final static String LAND = "land";
public final static String UP = "up";
public final static String DOWN = "down";
public final static String BACK = "back";
public final static String FORWARD = "forward";
public final static String FRONT = "front";
public final static String CLOCK_WISE = "clockwise";
public final static String COUNTER_CLOCKWISE = "counterClockwise";
public static final String DATA_SOURCE_NAME = "jdbc/DroneAnalyzerDM_DB";
}

@ -0,0 +1,40 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.constants;
public class MessageConfig {
public static final String IN_QUATANNIM_VAL = "quatanium_val";
public static final String IN_DEVICE_TYPE = "device_type";
public static final String IN_IRIS_DRONE = "IRIS_DRONE";
public static final String IN_SIMULATOR = "SIMULATOR";
public static final String OUT_QUATANNIM_VAL = "quatanium_val";
public static final String IN_ACCELETOMETER_VAL = "accelerometer";
public static final String OUT_ACCELETOMETER_VAL = "accelerometer";
public static final String IN_GYROSCOPE_VAL = "gyroscope";
public static final String OUT_GYROSCOPE_VAL = "gyroscope";
public static final String IN_MAGNETOMETER_VAL = "magnetometer";
public static final String OUT_MAGNETOMETER_VAL = "magnetometer";
public static final String IN_BASIC_PARAM_VAL = "basicParam";
public static final String OUT_BASIC_PARAM_VAL = "basicParam";
public static final String OUT_BASIC_PARAM_VELOCITY = "velocity";
public static final String OUT_BASIC_PARAM_GLOBAL_LOCATION = "global_location";
public static final String OUT_BATTERY_LEVEL = "battery_level";
}

@ -0,0 +1,34 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.controller;
public interface DroneController {
boolean takeoff();
boolean land();
boolean up(double speed, double duration);
boolean down(double speed, double duration);
boolean left(double speed, double duration);
boolean right(double speed, double duration);
boolean front(double speed, double duration);
boolean back(double speed, double duration);
boolean clockwise(double speed, double duration);
boolean conterClockwise(double speed, double duration);
}

@ -0,0 +1,74 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.controller.impl;
import org.homeautomation.droneanalyzer.plugin.controller.DroneController;
public class DroneControllerImpl implements DroneController {
@Override
public boolean takeoff() {
return false;
}
@Override
public boolean land() {
return false;
}
@Override
public boolean up(double speed, double duration) {
return false;
}
@Override
public boolean down(double speed, double duration) {
return false;
}
@Override
public boolean left(double speed, double duration) {
return false;
}
@Override
public boolean right(double speed, double duration) {
return false;
}
@Override
public boolean front(double speed, double duration) {
return false;
}
@Override
public boolean back(double speed, double duration) {
return false;
}
@Override
public boolean clockwise(double speed, double duration) {
return false;
}
@Override
public boolean conterClockwise(double speed, double duration) {
return false;
}
}

@ -0,0 +1,56 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.exception;
public class DroneAnalyzerDeviceMgtPluginException extends Exception{
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public DroneAnalyzerDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DroneAnalyzerDeviceMgtPluginException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public DroneAnalyzerDeviceMgtPluginException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DroneAnalyzerDeviceMgtPluginException() {
super();
}
public DroneAnalyzerDeviceMgtPluginException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,256 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.exception.DroneAnalyzerDeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.dao.DroneAnalyzerDAO;
import org.homeautomation.droneanalyzer.plugin.impl.feature.DroneAnalyzerFeatureManager;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import java.util.List;
/**
* This represents the Drone Analyzer service implementation of DeviceManagerService.
*/
public class DroneAnalyzerManager implements DeviceManager {
private static final DroneAnalyzerDAO droneAnalyzerDAO = new DroneAnalyzerDAO();
private static final Log log = LogFactory.getLog(DroneAnalyzerManager.class);
private FeatureManager droneFeatureManager = new DroneAnalyzerFeatureManager();
@Override
public FeatureManager getFeatureManager() {
return droneFeatureManager;
}
@Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration)
throws DeviceManagementException {
//TODO implement this
return false;
}
@Override
public TenantConfiguration getConfiguration() throws DeviceManagementException {
//TODO implement this
return null;
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new drone device : " + device.getDeviceIdentifier());
}
DroneAnalyzerDAO.beginTransaction();
status = droneAnalyzerDAO.getDeviceDAO().addDevice(device);
DroneAnalyzerDAO.commitTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while enrolling the drone device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Virtual Firealarm device enrollment data");
}
DroneAnalyzerDAO.beginTransaction();
status = droneAnalyzerDAO.getDeviceDAO().updateDevice(device);
DroneAnalyzerDAO.commitTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while updating the enrollment of the drone device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling drone device : " + deviceId);
}
DroneAnalyzerDAO.beginTransaction();
status = droneAnalyzerDAO.getDeviceDAO().deleteIotDevice(deviceId.getId());
DroneAnalyzerDAO.commitTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while removing the drone device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Drone device : " + deviceId.getId());
}
Device iotDevice = droneAnalyzerDAO.getDeviceDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (DroneAnalyzerDeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of Drone device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return isEnrolled;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return true;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Drone device : " + deviceId.getId());
}
device = droneAnalyzerDAO.getDeviceDAO().getDevice(deviceId.getId());
} catch (DroneAnalyzerDeviceMgtPluginException e) {
String msg = "Error while fetching the Drone device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return device;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
}
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
}
@Override
public License getLicense(String s) throws LicenseManagementException {
return null;
}
@Override
public void addLicense(License license) throws LicenseManagementException {
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug(
"updating the details of Drone device : " + deviceIdentifier);
}
DroneAnalyzerDAO.beginTransaction();
status = droneAnalyzerDAO.getDeviceDAO().updateDevice(device);
DroneAnalyzerDAO.commitTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg =
"Error while updating the Drone device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices = null;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Drone devices");
}
devices = droneAnalyzerDAO.getDeviceDAO().getAllDevices();
} catch (DroneAnalyzerDeviceMgtPluginException e) {
String msg = "Error while fetching all Drone devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return devices;
}
@Override
public boolean requireDeviceAuthorization() {
return true;
}
}

@ -0,0 +1,106 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.impl;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List;
public class DroneAnalyzerManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
private final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
@Override
public String getType() {
return DroneConstants.DEVICE_TYPE;
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager = new DroneAnalyzerManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> list)
throws DeviceManagementException {
}
@Override
public Application[] getApplications(String s, int i, int i1) throws ApplicationManagementException {
return new Application[0];
}
@Override
public void updateApplicationStatus(DeviceIdentifier deviceIdentifier, Application application, String s)
throws ApplicationManagementException {
}
@Override
public String getApplicationStatus(DeviceIdentifier deviceIdentifier, Application application)
throws ApplicationManagementException {
return null;
}
@Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> list)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUsers(Operation operation, List<String> list)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUserRoles(Operation operation, List<String> list)
throws ApplicationManagementException {
}
@Override
public String getProviderTenantDomain() {
return DEVICE_TYPE_PROVIDER_DOMAIN;
}
@Override
public boolean isSharedWithAllTenants() {
return true;
}
}

@ -0,0 +1,127 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.exception.DroneAnalyzerDeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.dao.impl.DroneAnalyzerDeviceDAOImpl;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DroneAnalyzerDAO {
private static final Log log = LogFactory.getLog(DroneAnalyzerDAO.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public DroneAnalyzerDAO() {
initDroneAnalyzerDAO();
}
public static void initDroneAnalyzerDAO() {
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(DroneConstants.DATA_SOURCE_NAME);
} catch (NamingException e) {
log.error("Error while looking up the data source: " + DroneConstants.DATA_SOURCE_NAME);
}
}
public DroneAnalyzerDeviceDAOImpl getDeviceDAO() {
return new DroneAnalyzerDeviceDAOImpl();
}
public static void beginTransaction() throws DroneAnalyzerDeviceMgtPluginException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new DroneAnalyzerDeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws DroneAnalyzerDeviceMgtPluginException {
if (currentConnection != null && currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new DroneAnalyzerDeviceMgtPluginException("Error occurred while retrieving data source connection", e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws DroneAnalyzerDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new DroneAnalyzerDeviceMgtPluginException("Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws DroneAnalyzerDeviceMgtPluginException {
Connection con = currentConnection.get();
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
}
currentConnection.remove();
}
public static void rollbackTransaction() throws DroneAnalyzerDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new DroneAnalyzerDeviceMgtPluginException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}
}
}

@ -0,0 +1,195 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.impl.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.exception.DroneAnalyzerDeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.dao.DroneAnalyzerDAO;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerUtils;
import org.wso2.carbon.device.mgt.common.Device;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Implements CRUD for drone analyzer.
*/
public class DroneAnalyzerDeviceDAOImpl {
private static final Log log = LogFactory.getLog(DroneAnalyzerDeviceDAOImpl.class);
public Device getDevice(String deviceId) throws DroneAnalyzerDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
Device device = null;
ResultSet resultSet = null;
try {
conn = DroneAnalyzerDAO.getConnection();
if(conn == null){
log.error("Database connection hasn't been created");
}
String selectDBQuery =
"SELECT DRONE_DEVICE_ID, DEVICE_NAME FROM DRONE_DEVICE WHERE DRONE_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, deviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
device = new Device();
if (log.isDebugEnabled()) {
log.debug("Drone device " + deviceId + " data has been fetched from " +
"Drone database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching drone device : '" + deviceId + "'";
log.error(msg, e);
throw new DroneAnalyzerDeviceMgtPluginException(msg, e);
} finally {
DroneAnalyzerUtils.cleanupResources(stmt, resultSet);
DroneAnalyzerDAO.closeConnection();
}
return device;
}
public boolean addDevice(Device device) throws DroneAnalyzerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DroneAnalyzerDAO.getConnection();
String createDBQuery =
"INSERT INTO DRONE_DEVICE(DRONE_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, device.getDeviceIdentifier());
stmt.setString(2, device.getName());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("drone device " + device.getDeviceIdentifier() + " data has been" +
" added to the drone database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the drone device '" +
device.getDeviceIdentifier() + "' to the drone db.";
log.error(msg, e);
throw new DroneAnalyzerDeviceMgtPluginException(msg, e);
} finally {
DroneAnalyzerUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean updateDevice(Device device) throws DroneAnalyzerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DroneAnalyzerDAO.getConnection();
String updateDBQuery =
"UPDATE DRONE_DEVICE SET DEVICE_NAME = ? WHERE DRONE_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
stmt.setString(1, device.getName());
stmt.setString(2, device.getDeviceIdentifier());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Drone device " + device.getDeviceIdentifier() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Drone device '" + device.getDeviceIdentifier() + "' data.";
log.error(msg, e);
throw new DroneAnalyzerDeviceMgtPluginException(msg, e);
} finally {
DroneAnalyzerUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean deleteIotDevice(String iotDeviceId) throws DroneAnalyzerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DroneAnalyzerDAO.getConnection();
System.out.println("delete device ");
String deleteDBQuery =
"DELETE FROM DRONE_DEVICE WHERE DRONE_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, iotDeviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Drone device " + iotDeviceId + " data has deleted" +
" from the drone database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting drone device " + iotDeviceId;
log.error(msg, e);
throw new DroneAnalyzerDeviceMgtPluginException(msg, e);
} finally {
DroneAnalyzerUtils.cleanupResources(stmt, null);
}
return status;
}
public List<Device> getAllDevices() throws DroneAnalyzerDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device iotDevice;
List<Device> iotDevices = new ArrayList<Device>();
try {
conn = DroneAnalyzerDAO.getConnection();
String selectDBQuery =
"SELECT DRONE_DEVICE_ID, DEVICE_NAME " +
"FROM DRONE_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
iotDevice = new Device();
iotDevice.setDeviceIdentifier(resultSet.getString(DroneConstants.DEVICE_PLUGIN_DEVICE_ID));
iotDevice.setName(resultSet.getString(DroneConstants.DEVICE_PLUGIN_DEVICE_NAME));
}
if (log.isDebugEnabled()) {
log.debug("All drone device details have fetched from drone database.");
}
return iotDevices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all drone device data'";
log.error(msg, e);
throw new DroneAnalyzerDeviceMgtPluginException(msg, e);
} finally {
DroneAnalyzerUtils.cleanupResources(stmt, resultSet);
DroneAnalyzerDAO.closeConnection();
}
}
}

@ -0,0 +1,58 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.homeautomation.droneanalyzer.plugin.impl.feature;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
import java.util.List;
public class DroneAnalyzerFeatureManager implements FeatureManager {
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
return false;
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
return false;
}
@Override
public Feature getFeature(String name) throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeature(DroneConstants.DEVICE_TYPE, name);
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeatures(DroneConstants.DEVICE_TYPE);
}
@Override
public boolean removeFeature(String name) throws DeviceManagementException {
return false;
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
return false;
}
}

@ -0,0 +1,50 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource;
import java.io.File;
/**
* Provides methods for initializing the database script.
*/
public class DeviceSchemaInitializer extends DatabaseCreator {
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
+ File.separator + "cdm" + File.separator + "plugins" + File.separator;
public DeviceSchemaInitializer(DataSource dataSource) {
super(dataSource);
}
@Override
protected String getDbScriptLocation(String databaseType) {
String scriptName = databaseType + ".sql";
if (log.isDebugEnabled()) {
log.debug("Loading database script from :" + scriptName);
}
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
}
}

@ -0,0 +1,109 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.exception.DroneAnalyzerDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.common.Device;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Contains utility methods used by Drone Analyzer plugin.
*/
public class DroneAnalyzerUtils {
private static Log log = LogFactory.getLog(DroneAnalyzerUtils.class);
public static String getDeviceProperty(List<Device.Property> deviceProperties, String propertyKey) {
String deviceProperty = "";
for(Device.Property property :deviceProperties){
if(propertyKey.equals(property.getName())){
deviceProperty = property.getValue();
}
}
return deviceProperty;
}
public static Device.Property getProperty(String property, String value) {
if (property != null) {
Device.Property prop = new Device.Property();
prop.setName(property);
prop.setValue(value);
return prop;
}
return null;
}
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}
/**
* Creates the device management schema.
*/
public static void setupDeviceManagementSchema() throws DroneAnalyzerDeviceMgtPluginException {
try {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(DroneConstants.DATA_SOURCE_NAME);
DeviceSchemaInitializer initializer =
new DeviceSchemaInitializer(dataSource);
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} catch (NamingException e) {
log.error("Error while looking up the data source: " + DroneConstants.DATA_SOURCE_NAME);
} catch (Exception e) {
throw new DroneAnalyzerDeviceMgtPluginException("Error occurred while initializing Iot Device " +
"Management database schema", e);
}
}
}

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

Loading…
Cancel
Save