Add Uninstall feature to sample device types.

application-manager-new
NuwanSameera 9 years ago
parent f80523f409
commit c7c2222e4b

@ -21,13 +21,13 @@
<parent>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.agent</artifactId>
<packaging>war</packaging>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<name>WSO2 IoTS(Device Types) - Connected Cup Agent Web app</name>
<url>http://maven.apache.org</url>

@ -25,13 +25,13 @@
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.analytics</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<name>WSO2 IoTS(Device Types) - Connected Cup Analytics capp</name>
<packaging>pom</packaging>

@ -23,20 +23,18 @@
<parent>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.controller.service</artifactId>
<version>2.0.4-SNAPSHOT</version>
<artifactId>org.coffeeking.connectedcup.api</artifactId>
<version>2.1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 IoTS(Device Types) - Connected Cup Controller Service</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Controller Service</description>
<name>WSO2 IoTS(Device Types) - Connected Cup API</name>
<description>WSO2 IoTS(Device Types) - Connected Cup API</description>
<url>http://wso2.org</url>
<dependencies>
<!-- CDM -->
<dependency>
@ -56,7 +54,7 @@
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
@ -68,6 +66,12 @@
<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>
@ -95,7 +99,6 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
@ -193,7 +196,10 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
@ -206,17 +212,24 @@
<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.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.plugin</artifactId>
</dependency>
<dependency>
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
<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>
</dependencies>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<plugins>

@ -0,0 +1,57 @@
/*
* 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.coffeeking.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.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@API( name="connectedcup", version="1.0.0", context="/connectedcup" , tags = {"connectedcup"})
@DeviceType( value = "connectedcup")
public interface ConnectedCupControllerService {
@Path("device/coffeelevel")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "coffeelevel", name = "Coffee Level", type = "monitor",
description = "Request Coffee Level from Connected cup")
Response readCoffeeLevel(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId);
@Path("device/temperature")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "temperature", name = "Temperature", type = "monitor",
description = "Request Temperature reading from Connected cup")
Response readTemperature(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId);
@Path("device/ordercoffee")
@POST
Response orderCoffee(@QueryParam("deviceId") String deviceId, @QueryParam("deviceOwner") String deviceOwner);
}

@ -0,0 +1,118 @@
/*
* 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.coffeeking.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.coffeeking.api.transport.ConnectedCupMQTTConnector;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import javax.ws.rs.core.Response;
public class ConnectedCupControllerServiceImpl implements ConnectedCupControllerService {
private static Log log = LogFactory.getLog(ConnectedCupControllerServiceImpl.class);
private static ConnectedCupMQTTConnector connectedCupMQTTConnector;
public ConnectedCupMQTTConnector getConnectedCupMQTTConnector() {
return ConnectedCupControllerServiceImpl.connectedCupMQTTConnector;
}
public void setConnectedCupMQTTConnector(
final ConnectedCupMQTTConnector connectedCupMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
ConnectedCupControllerServiceImpl.connectedCupMQTTConnector = connectedCupMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
connectedCupMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. " +
"Hence, ConnectedCupMQTTConnector 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;
}
public Response readCoffeeLevel(String owner, String deviceId) {
if (log.isDebugEnabled()) {
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
}
try {
String mqttResource = ConnectedCupConstants.LEVEL_CONTEXT.replace("/", "");
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ConnectedCupConstants.SENSOR_LEVEL);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException | TransportHandlerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
public Response readTemperature(String owner, String deviceId) {
if (log.isDebugEnabled()) {
log.debug("Sending request to read connected cup temperature of device " + "[" + deviceId + "] via MQTT");
}
try {
String mqttResource = ConnectedCupConstants.TEMPERATURE_CONTEXT.replace("/", "");
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ConnectedCupConstants.SENSOR_TEMPERATURE);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException | TransportHandlerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
public Response orderCoffee(String deviceId, String deviceOwner) {
log.info("Coffee ordered....!");
if (log.isDebugEnabled()) {
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
}
return Response.ok().entity("Coffee ordered.").build();
}
}

@ -0,0 +1,54 @@
/*
* 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.coffeeking.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="connectedcup_mgt", version="1.0.0", context="/connectedcup_mgt", tags = {"connectedcup"})
@DeviceType("connectedcup")
public interface ConnectedCupManagerService {
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getDevice(@PathParam("device_id") String deviceId);
}

@ -0,0 +1,122 @@
/*
* 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.coffeeking.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.api.util.APIUtil;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
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 javax.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
public class ConnectedCupManagerServiceImpl implements ConnectedCupManagerService{
private static Log log = LogFactory.getLog(ConnectedCupManagerServiceImpl.class);
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(ConnectedCupConstants.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(ConnectedCupConstants.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) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(ConnectedCupConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.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();
}
}
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);
}
}

@ -16,7 +16,7 @@
* under the License.
*/
package org.coffeeking.controller.service.dto;
package org.coffeeking.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@ -16,7 +16,7 @@
* under the License.
*/
package org.coffeeking.controller.service.exception;
package org.coffeeking.api.exception;
public class ConnectedCupException extends Exception {
private static final long serialVersionUID = 118512086957330189L;

@ -16,19 +16,25 @@
* under the License.
*/
package org.coffeeking.controller.service.transport;
package org.coffeeking.api.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.api.util.ConnectedCupServiceUtils;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.coffeeking.controller.service.util.ConnectedCupServiceUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
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.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.iot.config.server.DeviceManagementConfigurationManager;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.io.File;
import java.nio.charset.StandardCharsets;
@ -37,14 +43,9 @@ import java.util.UUID;
@SuppressWarnings("no JAX-WS annotation")
public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(ConnectedCupMQTTConnector.class);
private static String serverName = DeviceManagementConfigurationManager.getInstance().
getDeviceManagementServerInfo().getName();
private static String subscribeTopic = "wso2/+/" + ConnectedCupConstants.DEVICE_TYPE + "/+/"
+ "connected_publisher";
private static Log log = LogFactory.getLog(ConnectedCupMQTTConnector.class);
private static final String subscribeTopic = "wso2/" + ConnectedCupConstants.DEVICE_TYPE + "/+/publisher";
private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
private ConnectedCupMQTTConnector() {
@ -78,7 +79,6 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
}
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
if (publishData.length != 4) {
@ -95,19 +95,15 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
MqttMessage pushMessage = new MqttMessage();
String publishTopic =
"wso2" + File.separator + deviceOwner + File.separator +
ConnectedCupConstants.DEVICE_TYPE + File.separator + deviceId;
"wso2" + File.separator + deviceOwner + File.separator + ConnectedCupConstants.DEVICE_TYPE +
File.separator + deviceId;
try {
String actualMessage = resource + ":" + state;
pushMessage.setPayload(actualMessage.getBytes(StandardCharsets.UTF_8));
pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);
pushMessage.setRetained(false);
publishToQueue(publishTopic, pushMessage);
} catch (Exception e) {
String errorMsg = "Preparing payload failed for device - [" + deviceId + "] of owner - " +
"[" + deviceOwner + "].";
@ -116,24 +112,33 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
}
}
@Override
public void processIncomingMessage(MqttMessage mqttMessage, String... strings) throws TransportHandlerException {
String topic = strings[0];
String ownerAndId = topic.replace("wso2" + File.separator, "");
ownerAndId = ownerAndId.replace(File.separator + ConnectedCupConstants.DEVICE_TYPE + File.separator, ":");
ownerAndId = ownerAndId.replace(File.separator + "connected_publisher", "");
public void processIncomingMessage(MqttMessage message, String... messageParams) throws TransportHandlerException {
if (messageParams.length != 0) {
String topic = messageParams[0];
String[] topicParams = topic.split("/");
String deviceId = topicParams[2];
String receivedMessage = message.toString();
String[] messageData = receivedMessage.split(":");
String owner = ownerAndId.split(":")[0];
String deviceId = ownerAndId.split(":")[1];
// String actualMessage = mqttMessage.toString();
String[] messageData = mqttMessage.toString().split(":");
Float value = Float.valueOf(messageData[1]);
if (log.isDebugEnabled()) {
log.debug("Received MQTT message for: [DEVICE.ID-" + deviceId + "]");
log.debug("Message [" + receivedMessage + "] topic: [" + topic + "]");
}
switch(messageData[0]) {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService != null) {
DeviceIdentifier identifier = new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE);
Device device = deviceManagementProviderService.getDevice(identifier);
if (device != null) {
String owner = device.getEnrolmentInfo().getOwner();
ctx.setTenantDomain(MultitenantUtils.getTenantDomain(owner), true);
ctx.setUsername(owner);
switch (messageData[0]) {
case "temperature":
SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_TEMPERATURE,
String.valueOf(messageData[1]),
@ -145,16 +150,18 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
Calendar.getInstance().getTimeInMillis());
break;
}
ConnectedCupServiceUtils.publishToDAS(owner, deviceId, messageData[0], value);
if (log.isDebugEnabled()) {
log.debug("Received MQTT message for OWNER: " + owner + " DEVICE.ID: " + deviceId + " | Command: " +
messageData[0] +" " + messageData[1] );
if (!ConnectedCupServiceUtils.publishToDAS(deviceId, messageData[0], Float.parseFloat
(messageData[1]))) {
log.error("MQTT Subscriber: Publishing data to DAS failed.");
}
}
}
} catch (DeviceManagementException e) {
log.error("Failed to retreive the device managment service for device type " +
ConnectedCupConstants.DEVICE_TYPE, e);
}
}
}
@Override
public void disconnect() {
@ -168,7 +175,6 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint
+ " for device-type - " + ConnectedCupConstants.DEVICE_TYPE, e);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
@ -179,7 +185,6 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
}
}
};
Thread terminatorThread = new Thread(stopConnection);
terminatorThread.setDaemon(true);
terminatorThread.start();
@ -190,7 +195,6 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
// nothing to do
}
@Override
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
// nothing to do
@ -205,4 +209,5 @@ public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
public void processIncomingMessage(MqttMessage message) throws TransportHandlerException {
// nothing to do
}
}

@ -0,0 +1,55 @@
package org.coffeeking.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;
}
}

@ -16,7 +16,7 @@
* under the License.
*/
package org.coffeeking.controller.service.util;
package org.coffeeking.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -27,9 +27,10 @@ import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import javax.ws.rs.HttpMethod;
import java.io.BufferedReader;
import java.io.IOException;
@ -44,8 +45,6 @@ import java.util.concurrent.Future;
public class ConnectedCupServiceUtils {
private static final Log log = LogFactory.getLog(ConnectedCupServiceUtils.class);
//TODO; replace this tenant domain
private static final String SUPER_TENANT = "carbon.super";
private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature";
private static final String COFFEE_LEVEL_STREAM_DEFINITION = "org.wso2.iot.devices.coffeelevel";
@ -194,18 +193,15 @@ public class ConnectedCupServiceUtils {
return completeResponse.toString();
}
public static boolean publishToDAS(String owner, String deviceId, String sensor, float values) {
PrivilegedCarbonContext.startTenantFlow();
public static boolean publishToDAS(String deviceId, String sensor, float values) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true);
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null);
Object metdaData[] = {owner, ConnectedCupConstants.DEVICE_TYPE, deviceId,
System.currentTimeMillis()};
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
Object metdaData[] = {owner, ConnectedCupConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payloadData[] = {values};
try {
switch (sensor){
switch (sensor) {
case "temperature":
deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData);
@ -214,11 +210,8 @@ public class ConnectedCupServiceUtils {
deviceAnalyticsService.publishEvent(COFFEE_LEVEL_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData);
}
} catch (DataPublisherConfigurationException e) {
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return true;
}

@ -26,48 +26,49 @@
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/manager/device/*</url>
<url>/devices/*</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
<scope>connectedcup_user</scope>
</Permission>
<Permission>
<name>Add device</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device/register</url>
<method>PUT</method>
<scope>emm_admin,emm_user</scope>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/devices/*</url>
<method>DELETE</method>
<scope>connectedcup_user</scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device/firealarm/download</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/devices/*</url>
<method>POST</method>
<scope>connectedcup_user</scope>
</Permission>
<Permission>
<name>Generate link to download</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device/firealarm/generate_link</url>
<name>Get coffee level</name>
<path>/device-mgt/user/device/coffeelevel</path>
<url>/device/coffeelevel</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
<scope>connectedcup_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/manager/device/update/*</url>
<method>POST</method>
<scope>emm_admin,emm_user</scope>
<name>Get temperature</name>
<path>/device-mgt/user/device/temperature</path>
<url>/device/temperature</url>
<method>GET</method>
<scope>connectedcup_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/manager/device/remove/*</url>
<method>DELETE</method>
<scope>emm_admin,emm_user</scope>
<name>Order coffee cup</name>
<path>/device-mgt/user/device/ordercoffee</path>
<url>/device/ordercoffee</url>
<method>POST</method>
<scope>connectedcup_user</scope>
</Permission>
</PermissionConfiguration>

@ -25,24 +25,23 @@
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="ConnectedCupController" address="/">
<jaxrs:server id="ConnectedCup" address="/">
<jaxrs:serviceBeans>
<bean id="ConnectedCupControllerService"
class="org.coffeeking.controller.service.ConnectedCupControllerService">
class="org.coffeeking.api.ConnectedCupControllerServiceImpl">
<property name="connectedCupMQTTConnector" ref="communicationHandler"/>
</bean>
<bean id="ConnectedCupManagerService"
class="org.coffeeking.api.ConnectedCupManagerServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
<bean
id="communicationHandler"
class="org.coffeeking.controller.service.transport.ConnectedCupMQTTConnector" >
id="communicationHandler" class="org.coffeeking.api.transport.ConnectedCupMQTTConnector">
</bean>
</beans>

@ -1,207 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.controller.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.coffeeking.controller.service.dto.DeviceJSON;
import org.coffeeking.controller.service.transport.ConnectedCupMQTTConnector;
import org.coffeeking.controller.service.util.ConnectedCupServiceUtils;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.annotations.device.feature.Feature;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.DeviceValidator;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Calendar;
@API( name="connectedcup", version="1.0.0", context="/connectedcup")
@DeviceType( value = "connectedcup")
public class ConnectedCupControllerService {
private static Log log = LogFactory.getLog(ConnectedCupControllerService.class);
private static final String SUPER_TENANT = "carbon.super";
private static ConnectedCupMQTTConnector connectedCupMQTTConnector;
public ConnectedCupMQTTConnector connectedCupMQTTConnector() {
return ConnectedCupControllerService.connectedCupMQTTConnector;
}
public void setconnectedCupMQTTConnector(
final ConnectedCupMQTTConnector connectedCupMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
ConnectedCupControllerService.connectedCupMQTTConnector = connectedCupMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
connectedCupMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. " +
"Hence, ConnectedCupMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
private boolean waitForServerStartup() {
while (!DeviceManagement.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
/**
* @param deviceId
* @param owner
*/
@Path("controller/coffeelevel")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Feature( code="coffeelevel", name="Coffee Level", type="monitor",
description="Request Coffee Level from Connected cup")
public SensorRecord readCoffeeLevel(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
DeviceValidator deviceValidator = new DeviceValidator();
try {
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(
deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
if (log.isDebugEnabled()) {
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
}
try {
String mqttResource = ConnectedCupConstants.LEVEL_CONTEXT.replace("/", "");
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ConnectedCupConstants.SENSOR_LEVEL);
} catch ( DeviceControllerException | TransportHandlerException e ) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord;
}
@Path("controller/temperature")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Feature( code="temperature", name="Temperature", type="monitor",
description="Request Temperature reading from Connected cup")
public SensorRecord readTemperature(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
DeviceValidator deviceValidator = new DeviceValidator();
try {
if (!deviceValidator.isExist(owner, SUPER_TENANT,
new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
if (log.isDebugEnabled()) {
log.debug("Sending request to read connected cup temperature of device " +
"[" + deviceId + "] via MQTT");
}
try {
String mqttResource = ConnectedCupConstants.TEMPERATURE_CONTEXT.replace("/", "");
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ConnectedCupConstants.SENSOR_TEMPERATURE);
} catch ( DeviceControllerException | TransportHandlerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord;
}
@Path("controller/ordercoffee")
@POST
public void orderCoffee(@QueryParam("deviceId") String deviceId, @QueryParam("deviceOwner") String
deviceOwner, @Context HttpServletResponse response){
DeviceValidator deviceValidator = new DeviceValidator();
try {
if (!deviceValidator.isExist(deviceOwner, SUPER_TENANT, new DeviceIdentifier(
deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.ACCEPTED.getStatusCode());
log.info("Coffee ordered....!");
if (log.isDebugEnabled()) {
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
}
// return response;
}
}

@ -1,261 +0,0 @@
<?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>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.0.4-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.manager.service</artifactId>
<version>2.0.4-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 IoTS(Device Types) - Connected Cup Manager Service</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Manager Service</description>
<url>http://wso2.org</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</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.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.plugin</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>connectedcup</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -1,242 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.manager.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
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.DeviceManagement;
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
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;
@API( name="connectedcup_mgt", version="1.0.0", context="/connectedcup_mgt")
public class ConnectedCupManagerService {
private static Log log = LogFactory.getLog(ConnectedCupManagerService.class);
private static final String SUPER_TENANT = "carbon.super";
@Context
private HttpServletResponse response;
/**
* @param name
* @param owner
* @return
*/
@Path("cup/register")
@POST
public boolean register(@QueryParam("name") String name, @QueryParam("owner") String owner) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
String deviceId = shortUUID();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(ConnectedCupConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(owner);
device.setEnrolmentInfo(enrolmentInfo);
KeyGenerationUtil.createApplicationKeys(ConnectedCupConstants.DEVICE_TYPE);
TokenClient accessTokenClient = new TokenClient(ConnectedCupConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
List<Device.Property> properties = new ArrayList<>();
Device.Property accessTokenProperty = new Device.Property();
accessTokenProperty.setName("accessToken");
accessTokenProperty.setValue(accessToken);
Device.Property refreshTokenProperty = new Device.Property();
refreshTokenProperty.setName("refreshToken");
refreshTokenProperty.setValue(refreshToken);
properties.add(accessTokenProperty);
properties.add(refreshTokenProperty);
device.setProperties(properties);
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device);
if (added) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return added;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} catch (AccessTokenException e) {
e.printStackTrace();
} finally {
deviceManagement.endTenantFlow();
}
return true;
}
@Path("/device/remove/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId,
@Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("/device/update/{device_id}")
@POST
public boolean updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name,
@Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
Device device = deviceManagement.getDeviceManagementService().getDevice(
deviceIdentifier);
device.setDeviceIdentifier(deviceId);
// device.setDeviceTypeId(deviceTypeId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(ConnectedCupConstants.DEVICE_TYPE);
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(
device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return updated;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("/device/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Device getDevice(@PathParam("device_id") String deviceId) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
Device device = deviceManagement.getDeviceManagementService().getDevice(
deviceIdentifier);
return device;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null;
} finally {
deviceManagement.endTenantFlow();
}
}
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);
}
}

@ -1,34 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ 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.
-->
<!--
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>

@ -1,42 +0,0 @@
<?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"
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="ConnectedCupmanager" address="/connectedcup">
<jaxrs:serviceBeans>
<bean id="ConnectedCupManagerService"
class="org.coffeeking.manager.service.ConnectedCupManagerService">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
</beans>

@ -1,69 +0,0 @@
<?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>ConnectedCup-Webapp</display-name>
<servlet>
<description>JAX-WS/JAX-RS 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>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>false</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>/connectedcup/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>connectedcup</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
</web-app>

@ -22,13 +22,13 @@
<parent>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.plugin</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 IoTS(Device Types) - Connected Cup CDMF Plugin</name>
<description>WSO2 IoTS(Device Types) - Connected Cup CDMF Plugin</description>
@ -119,5 +119,4 @@
</dependency>
</dependencies>
</project>

@ -22,7 +22,7 @@ package org.coffeeking.connectedcup.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.exception.ConnectedCupDeviceMgtPluginException;
import org.coffeeking.connectedcup.plugin.impl.dao.ConnectedCupDAO;
import org.coffeeking.connectedcup.plugin.impl.dao.ConnectedCupDAOUtil;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
@ -42,7 +42,7 @@ public class ConnectedCupManager implements DeviceManager {
private static final Log log = LogFactory.getLog(ConnectedCupManager.class);
private static final ConnectedCupDAO connectedCupDAO = new ConnectedCupDAO();
private static final ConnectedCupDAOUtil CONNECTED_CUP_DAO_UTIL = new ConnectedCupDAOUtil();
@Override
public FeatureManager getFeatureManager() {
@ -69,12 +69,12 @@ public class ConnectedCupManager implements DeviceManager {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new Connected Cup device : " + device.getDeviceIdentifier());
}
ConnectedCupDAO.beginTransaction();
status = connectedCupDAO.getConnectedCupDeviceDAO().addDevice(device);
ConnectedCupDAO.commitTransaction();
ConnectedCupDAOUtil.beginTransaction();
status = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().addDevice(device);
ConnectedCupDAOUtil.commitTransaction();
} catch (ConnectedCupDeviceMgtPluginException e) {
try {
ConnectedCupDAO.rollbackTransaction();
ConnectedCupDAOUtil.rollbackTransaction();
} catch (ConnectedCupDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, iotDAOEx);
@ -93,12 +93,12 @@ public class ConnectedCupManager implements DeviceManager {
if (log.isDebugEnabled()) {
log.debug("Modifying the Connected Cup device enrollment data");
}
ConnectedCupDAO.beginTransaction();
status = connectedCupDAO.getConnectedCupDeviceDAO().updateDevice(device);
ConnectedCupDAO.commitTransaction();
ConnectedCupDAOUtil.beginTransaction();
status = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().updateDevice(device);
ConnectedCupDAOUtil.commitTransaction();
} catch (ConnectedCupDeviceMgtPluginException e) {
try {
ConnectedCupDAO.rollbackTransaction();
ConnectedCupDAOUtil.rollbackTransaction();
} catch (ConnectedCupDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx);
@ -118,12 +118,12 @@ public class ConnectedCupManager implements DeviceManager {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling Connected Cup device : " + deviceId);
}
ConnectedCupDAO.beginTransaction();
status = connectedCupDAO.getConnectedCupDeviceDAO().deleteDevice(deviceId.getId());
ConnectedCupDAO.commitTransaction();
ConnectedCupDAOUtil.beginTransaction();
status = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().deleteDevice(deviceId.getId());
ConnectedCupDAOUtil.commitTransaction();
} catch (ConnectedCupDeviceMgtPluginException e) {
try {
ConnectedCupDAO.rollbackTransaction();
ConnectedCupDAOUtil.rollbackTransaction();
} catch (ConnectedCupDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx);
@ -142,7 +142,7 @@ public class ConnectedCupManager implements DeviceManager {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Connected Cup device : " + deviceId.getId());
}
Device iotDevice = connectedCupDAO.getConnectedCupDeviceDAO().getDevice(deviceId.getId());
Device iotDevice = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
@ -172,7 +172,7 @@ public class ConnectedCupManager implements DeviceManager {
try {if (log.isDebugEnabled()) {
log.debug("Getting the details of Connected Cup device : " + deviceId.getId());
}
device = connectedCupDAO.getConnectedCupDeviceDAO().getDevice(deviceId.getId());
device = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().getDevice(deviceId.getId());
} catch (ConnectedCupDeviceMgtPluginException e) {
String msg = "Error while fetching the Connected Cup device : " + deviceId.getId();
@ -221,12 +221,12 @@ public class ConnectedCupManager implements DeviceManager {
log.debug(
"updating the details of Connected Cup device : " + deviceIdentifier);
}
ConnectedCupDAO.beginTransaction();
status = connectedCupDAO.getConnectedCupDeviceDAO().updateDevice(device);
ConnectedCupDAO.commitTransaction();
ConnectedCupDAOUtil.beginTransaction();
status = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().updateDevice(device);
ConnectedCupDAOUtil.commitTransaction();
} catch (ConnectedCupDeviceMgtPluginException e) {
try {
ConnectedCupDAO.rollbackTransaction();
ConnectedCupDAOUtil.rollbackTransaction();
} catch (ConnectedCupDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
@ -246,7 +246,7 @@ public class ConnectedCupManager implements DeviceManager {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Connected Cup devices");
}
devices = connectedCupDAO.getConnectedCupDeviceDAO().getAllDevices();
devices = CONNECTED_CUP_DAO_UTIL.getConnectedCupDeviceDAO().getAllDevices();
} catch (ConnectedCupDeviceMgtPluginException e) {
String msg = "Error while fetching all Connected Cup devices.";
log.error(msg, e);

@ -49,11 +49,6 @@ public class ConnectedCupManagerService implements DeviceManagementService{
return true;
}
@Override
public String[] getSharedTenantsDomain() {
return new String[0];
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager=new ConnectedCupManager();

@ -22,7 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.coffeeking.connectedcup.plugin.exception.ConnectedCupDeviceMgtPluginException;
import org.coffeeking.connectedcup.plugin.impl.dao.impl.ConnectedCupDAOImpl;
import org.coffeeking.connectedcup.plugin.impl.dao.impl.ConnectedCupDAO;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
@ -30,13 +30,13 @@ import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectedCupDAO {
public class ConnectedCupDAOUtil {
private static final Log log = LogFactory.getLog(ConnectedCupDAO.class);
private static final Log log = LogFactory.getLog(ConnectedCupDAOUtil.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public ConnectedCupDAO() {
public ConnectedCupDAOUtil() {
initConnectedCupDAO();
}
@ -52,8 +52,8 @@ public class ConnectedCupDAO {
}
public ConnectedCupDAOImpl getConnectedCupDeviceDAO() {
return new ConnectedCupDAOImpl();
public ConnectedCupDAO getConnectedCupDeviceDAO() {
return new ConnectedCupDAO();
}
public static void beginTransaction() throws ConnectedCupDeviceMgtPluginException {

@ -22,7 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.coffeeking.connectedcup.plugin.exception.ConnectedCupDeviceMgtPluginException;
import org.coffeeking.connectedcup.plugin.impl.dao.ConnectedCupDAO;
import org.coffeeking.connectedcup.plugin.impl.dao.ConnectedCupDAOUtil;
import org.coffeeking.connectedcup.plugin.impl.dao.util.ConnectedCupUtils;
import org.wso2.carbon.device.mgt.common.Device;
import java.sql.Connection;
@ -35,10 +35,10 @@ import java.util.List;
/**
* Device Dao for connected cup Devices.
*/
public class ConnectedCupDAOImpl {
public class ConnectedCupDAO {
private static final Log log = LogFactory.getLog(ConnectedCupDAOImpl.class);
private static final Log log = LogFactory.getLog(ConnectedCupDAO.class);
public Device getDevice(String deviceId) throws ConnectedCupDeviceMgtPluginException {
Connection conn = null;
@ -46,7 +46,7 @@ public class ConnectedCupDAOImpl {
Device connectedCupDevice = null;
ResultSet resultSet = null;
try {
conn = ConnectedCupDAO.getConnection();
conn = ConnectedCupDAOUtil.getConnection();
String selectDBQuery =
"SELECT CONNECTED_CUP_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN" +
" FROM CONNECTED_CUP_DEVICE WHERE CONNECTED_CUP_DEVICE_ID = ?";
@ -78,7 +78,7 @@ public class ConnectedCupDAOImpl {
throw new ConnectedCupDeviceMgtPluginException(msg, e);
} finally {
ConnectedCupUtils.cleanupResources(stmt, resultSet);
ConnectedCupDAO.closeConnection();
ConnectedCupDAOUtil.closeConnection();
}
return connectedCupDevice;
}
@ -89,7 +89,7 @@ public class ConnectedCupDAOImpl {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ConnectedCupDAO.getConnection();
conn = ConnectedCupDAOUtil.getConnection();
String createDBQuery =
"INSERT INTO CONNECTED_CUP_DEVICE(CONNECTED_CUP_DEVICE_ID, DEVICE_NAME, " +
"ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?)";
@ -128,7 +128,7 @@ public class ConnectedCupDAOImpl {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ConnectedCupDAO.getConnection();
conn = ConnectedCupDAOUtil.getConnection();
String updateDBQuery =
"UPDATE CONNECTED_CUP_DEVICE SET DEVICE_NAME = ?, ACCESS_TOKEN=?, " +
"REFRESH_TOKEN=? WHERE CONNECTED_CUP_DEVICE_ID = ?";
@ -170,7 +170,7 @@ public class ConnectedCupDAOImpl {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ConnectedCupDAO.getConnection();
conn = ConnectedCupDAOUtil.getConnection();
String deleteDBQuery =
"DELETE FROM CONNECTED_CUP_DEVICE WHERE CONNECTED_CUP_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
@ -202,7 +202,7 @@ public class ConnectedCupDAOImpl {
List<Device> iotDevices = new ArrayList<>();
try {
conn = ConnectedCupDAO.getConnection();
conn = ConnectedCupDAOUtil.getConnection();
String selectDBQuery =
"SELECT CONNECTED_CUP_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN" +
"FROM CONNECTED_CUP_DEVICE";
@ -235,7 +235,7 @@ public class ConnectedCupDAOImpl {
throw new ConnectedCupDeviceMgtPluginException(msg, e);
} finally {
ConnectedCupUtils.cleanupResources(stmt, resultSet);
ConnectedCupDAO.closeConnection();
ConnectedCupDAOUtil.closeConnection();
}
}

@ -24,13 +24,13 @@
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device.mgt.iot.connectedcup-parent</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 IoTS(Device Types) - Connected Cup Component</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Component</description>
@ -39,8 +39,7 @@
<modules>
<module>analytics</module>
<module>plugin</module>
<module>controller</module>
<module>manager</module>
<module>api</module>
<module>agent</module>
<module>ui</module>
</modules>
@ -65,201 +64,4 @@
</pluginManagement>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.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</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.analytics_${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>
</dependencies>
</dependencyManagement>
</project>

@ -25,13 +25,13 @@
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.ui</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<name>WSO2 IoTS(Device Types) - Connected Cup UI</name>
<packaging>pom</packaging>

@ -25,14 +25,14 @@
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>connected-cup-feature-parent</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.feature</artifactId>
<packaging>pom</packaging>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<name>WSO2 IoTS(Device Types) - Connected Cup Feature</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Feature</description>
<url>http://wso2.org</url>
@ -43,28 +43,18 @@
<artifactId>org.coffeeking.connectedcup.plugin</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.manager.service</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.controller.service</artifactId>
<artifactId>org.coffeeking.connectedcup.api</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.agent</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
@ -148,15 +138,7 @@
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.manager.service</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>connectedcup_mgt.war</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.controller.service</artifactId>
<artifactId>org.coffeeking.connectedcup.api</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
@ -232,7 +214,7 @@
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:true</propertyDef>
</properties>
</adviceFile>
<bundles>

@ -5,12 +5,22 @@ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../depl
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/carbonapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/carbonapps/,target:${installFolder}/../../deployment/server/carbonapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/connectedcup/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/connectedcup/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/connectedcup,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${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.coffeeking.connectedcup_${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.coffeeking.connectedcup_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\
instructions.unconfigure = \
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/device-types/connectedcup.json);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/device-types/connectedcup.xml);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/connectedcup.war);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/connected-cup-agent.war);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/connectedcup);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/connected-cup-agent);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../dbscripts/cdm/plugins/connectedcup);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/datasources/connectedcup-datasources.xml);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../database/ConnectedCupDM_DB.h2.db);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.device-view);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.connectedcup.type-view);\

@ -23,14 +23,14 @@
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device.mgt.iot.connectedcup-parent</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>connected-cup-feature-parent</artifactId>
<packaging>pom</packaging>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<name>WSO2 IoTS(Device Types) - Connected Cup Feature Parent</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Feature Parent</description>
<url>http://wso2.org</url>

@ -31,7 +31,7 @@
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device.mgt.iot.connectedcup-parent</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 IoTS(Device Types) - Connected Cup Component</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Component</description>
@ -155,6 +155,218 @@
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.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>
</dependencies>
</dependencyManagement>
@ -230,8 +442,8 @@
<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.0.4-SNAPSHOT</carbon.device.mgt.plugin.version>
<carbon.iot.device.mgt.jar.version>2.0.4.SNAPSHOT</carbon.iot.device.mgt.jar.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-->

@ -1,64 +0,0 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<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>${project-base-package}-component</artifactId>
<version>2.0.4-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${groupId}.currentsensor.agent</artifactId>
<version>2.0.4-SNAPSHOT</version>
<name>${groupId}.currentsensor.agent</name>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warName>${groupId}.currentsensor.agent</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -1,23 +0,0 @@
<!--/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/-->
<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>Sample-Agent-Webapp</display-name>
</web-app>

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

@ -25,13 +25,13 @@
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}-component</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${groupId}.currentsensor.analytics</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<name>${groupId}.currentsensor.analytics</name>
<packaging>pom</packaging>

@ -23,19 +23,18 @@
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}-component</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${groupId}.currentsensor.manager</artifactId>
<artifactId>${groupId}.currentsensor.api</artifactId>
<version>2.1.0-SNAPSHOT</version>
<packaging>war</packaging>
<version>2.0.4-SNAPSHOT</version>
<name>${groupId}.currentsensor.manager</name>
<url>http://wso2.org</url>
<name>${groupId}.currentsensor API</name>
<url>http://wso2.com</url>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@ -51,17 +50,14 @@
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warName>${groupId}.currentsensor.manager</warName>
<warName>${groupId}.currentsensor.controller</warName>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId>
</dependency>
<dependencies>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
@ -79,7 +75,7 @@
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
@ -99,6 +95,7 @@
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
@ -113,6 +110,12 @@
<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>
@ -122,6 +125,13 @@
<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>
@ -207,17 +217,10 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
@ -230,11 +233,30 @@
<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.currentsensor.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>
</dependencies>
</project>

@ -0,0 +1,92 @@
/*
* 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.currentsensor.api;
import org.homeautomation.currentsensor.api.dto.DeviceJSON;
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.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@API(name = "currentsensor", version = "1.0.0", context = "/currentsensor", tags = {"currentsensor"})
@DeviceType(value = "currentsensor")
public interface CurrentSensorControllerService {
@Path("device/register/{owner}/{deviceId}/{ip}/{port}")
@POST
Response registerDeviceIP(@PathParam("owner") String owner, @PathParam("deviceId") String deviceId,
@PathParam("ip") String deviceIP, @PathParam("port") String devicePort);
/**
* @param deviceId
* @return
*/
@Path("device/read-current")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "read-current", name = "Current", type = "monitor",
description = "Request current reading from Arduino agent")
Response requestCurrent(@HeaderParam("deviceId") String deviceId);
/**
* @param deviceId
* @return
*/
@Path("device/read-power")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "read-power", name = "Power", type = "monitor",
description = "Request power reading from Arduino agent")
Response requestPower(@HeaderParam("deviceId") String deviceId);
/**
* @param deviceId
* @return
*/
@Path("device/read-flowrate")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "read-flowrate", name = "Flow Rate", type = "monitor",
description = "Request flow rate reading from Arduino agent")
Response requestFlowRate(@HeaderParam("deviceId") String deviceId);
/**
* @param dataMsg
*/
@Path("device/push-data")
@POST
@Consumes(MediaType.APPLICATION_JSON)
Response pushData(final DeviceJSON dataMsg);
}

@ -0,0 +1,153 @@
/*
* 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.currentsensor.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.currentsensor.api.dto.DeviceJSON;
import org.homeautomation.currentsensor.api.util.CurrentSensorServiceUtils;
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import javax.ws.rs.core.Response;
import java.util.Calendar;
import java.util.concurrent.ConcurrentHashMap;
public class CurrentSensorControllerServiceImpl implements CurrentSensorControllerService{
private static Log log = LogFactory.getLog(CurrentSensorControllerServiceImpl.class);
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public Response registerDeviceIP(String owner, String deviceId, String deviceIP, String devicePort) {
//TODO:: Need to get IP from the request itself
String result;
if (log.isDebugEnabled()) {
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: " + owner);
}
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.ok().entity(result).build();
}
public Response requestCurrent(String deviceId) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
CurrentSensorConstants.SENSOR_CURRENT);
} catch (DeviceControllerException e) {
Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
return Response.ok().entity(sensorRecord).build();
}
public Response requestPower(String deviceId) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
CurrentSensorConstants.SENSOR_POWER);
} catch (DeviceControllerException e) {
Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
return Response.ok().entity(sensorRecord).build();
}
public Response requestFlowRate(String deviceId) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
CurrentSensorConstants.SENSOR_FLOWRATE);
} catch (DeviceControllerException e) {
Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
return Response.ok().entity(sensorRecord).build();
}
public Response pushData(final DeviceJSON dataMsg) {
String owner = dataMsg.owner;
String deviceId = dataMsg.deviceId;
String deviceIp = dataMsg.reply;
float current = dataMsg.current;
float flow_rate = dataMsg.flow_rate;
String registeredIp = deviceToIpMap.get(deviceId);
if (registeredIp == null) {
log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp +
" for device ID - " + deviceId);
return Response.status(Response.Status.PRECONDITION_FAILED.getStatusCode()).build();
} else if (!registeredIp.equals(deviceIp)) {
log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId +
" is already registered under some other IP. Re-registration required");
return Response.status(Response.Status.CONFLICT.getStatusCode()).build();
}
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_CURRENT,
String.valueOf(current),
Calendar.getInstance().getTimeInMillis());
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_POWER,
String.valueOf(current * 230),
Calendar.getInstance().getTimeInMillis());
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_FLOWRATE,
String.valueOf(flow_rate),
Calendar.getInstance().getTimeInMillis());
if (!CurrentSensorServiceUtils.publishToDASCurrent(dataMsg.deviceId, current)) {
log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId +
"] of owner [" + owner + "]");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.deviceId, current * 230)) {
log.warn("An error occured whilst trying to publish pin data of Power Sensor Data with ID [" + deviceId +
"] of owner [" + owner + "]");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
if (!CurrentSensorServiceUtils.publishToDASFlowRate(dataMsg.deviceId, flow_rate)) {
log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId +
"] of owner [" + owner + "]");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.ok().build();
}
}

@ -0,0 +1,60 @@
/*
* 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.currentsensor.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 = "currentsensor_mgt", version = "1.0.0", context = "/currentsensor_mgt", tags = {"currentsensor"})
@DeviceType(value = "currentsensor")
public interface CurrentSensorManagerService {
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices/{sketch_type}/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
Response downloadSketch(@QueryParam("deviceName") String deviceName, @PathParam("sketch_type") String
sketchType);
}

@ -0,0 +1,197 @@
/*
* 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.currentsensor.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
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.homeautomation.currentsensor.api.util.APIUtil;
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
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.user.api.UserStoreException;
import javax.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
class CurrentSensorManagerServiceImpl implements CurrentSensorManagerService {
private static Log log = LogFactory.getLog(CurrentSensorManagerServiceImpl.class);
private static ApiApplicationKey apiApplicationKey;
private static final String KEY_TYPE = "PRODUCTION";
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(CurrentSensorConstants.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(CurrentSensorConstants.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) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(CurrentSensorConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(CurrentSensorConstants.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, String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String owner, String deviceName)
throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException,
UserStoreException {
if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
if (apiApplicationKey == null) {
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {CurrentSensorConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
CurrentSensorConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
String scopes = "device_type_" + CurrentSensorConstants.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();
//Register the device with CDMF
boolean status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
CurrentSensorConstants.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);
}
}

@ -16,7 +16,7 @@
* under the License.
*/
package org.homeautomation.currentsensor.manager.api.dto;
package org.homeautomation.currentsensor.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@ -0,0 +1,55 @@
package org.homeautomation.currentsensor.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;
}
}

@ -16,77 +16,66 @@
* under the License.
*/
package org.homeautomation.currentsensor.manager.api.util;
package org.homeautomation.currentsensor.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService;
public class CurrentSensorServiceUtils {
private static final Log log = LogFactory.getLog(CurrentSensorServiceUtils.class);
//TODO; replace this tenant domain
private static final String SUPER_TENANT = "carbon.super";
private static final Log log = LogFactory.getLog(CurrentSensorServiceUtils.class);
private static final String CURRENT_STREAM_DEFINITION = "org.wso2.iot.devices.current";
private static final String POWER_STREAM_DEFINITION = "org.wso2.iot.devices.power";
private static final String FLOWRATE_STREAM_DEFINITION = "org.wso2.iot.devices.flowrate";
public static boolean publishToDASCurrent(String owner, String deviceId, float current) {
PrivilegedCarbonContext.startTenantFlow();
public static boolean publishToDASCurrent(String deviceId, float current) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true);
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null);
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payloadCurrent[] = {current};
Object payloadData[] = {current};
try {
deviceAnalyticsService.publishEvent(CURRENT_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadCurrent);
deviceAnalyticsService.publishEvent(CURRENT_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return true;
}
public static boolean publishToDASPower(String owner, String deviceId, float power) {
PrivilegedCarbonContext.startTenantFlow();
public static boolean publishToDASPower(String deviceId, float power) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true);
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null);
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payloadPower[] = {power};
Object payloadData[] = {power};
try {
deviceAnalyticsService.publishEvent(POWER_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadPower);
deviceAnalyticsService.publishEvent(POWER_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return true;
}
public static boolean publishToDASFlowRate(String owner, String deviceId, float flowRate) {
PrivilegedCarbonContext.startTenantFlow();
public static boolean publishToDASFlowRate(String deviceId, float flowRate) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true);
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null);
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
Object metdaData[] = {owner, CurrentSensorConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payload[] = {flowRate};
Object payloadData[] = {flowRate};
try {
deviceAnalyticsService.publishEvent(FLOWRATE_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payload);
deviceAnalyticsService.publishEvent(FLOWRATE_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return true;
}

@ -0,0 +1,108 @@
<?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>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Add device</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/register</url>
<method>PUT</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/doormanager/download</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Generate link to download</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/doormanager/generate_link</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/devices/update/*</url>
<method>POST</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/devices/remove/*</url>
<method>DELETE</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Register Device</name>
<path>/device-mgt/user/device/register</path>
<url>/device/register/*/*/*/*</url>
<method>POST</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Read Current</name>
<path>/device-mgt/user/device/read-current</path>
<url>/device/read-current</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Read Power</name>
<path>/device-mgt/user/device/read-power</path>
<url>/device/read-power</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Read Flow rate</name>
<path>/device-mgt/user/device/read-flowrate</path>
<url>/device/read-flowrate</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Push data</name>
<path>/device-mgt/user/device/push-data</path>
<url>/device/push-data</url>
<method>POST</method>
<scope>emm_admin,emm_user</scope>
</Permission>
</PermissionConfiguration>

@ -25,10 +25,13 @@
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="CurrentSensorManager" address="/">
<jaxrs:server id="CurrentSensor" address="/">
<jaxrs:serviceBeans>
<bean id="CurrentSensorControllerService"
class="org.homeautomation.currentsensor.api.CurrentSensorControllerServiceImpl">
</bean>
<bean id="CurrentSensorManagerService"
class="org.homeautomation.currentsensor.manager.api.CurrentSensorManagerService">
class="org.homeautomation.currentsensor.api.CurrentSensorManagerServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>

@ -1,225 +0,0 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<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>${project-base-package}-component</artifactId>
<version>2.0.4-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${groupId}.currentsensor.controller</artifactId>
<version>2.0.4-SNAPSHOT</version>
<packaging>war</packaging>
<name>${groupId}.currentsensor.controller API</name>
<url>http://wso2.com</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warName>${groupId}.currentsensor.controller</warName>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId>
</dependency>
<!-- 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</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>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</dependency>
<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>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.json.wso2</groupId>
<artifactId>json</artifactId>
</dependency>
</dependencies>
</project>

@ -1,260 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.currentsensor.manager.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.currentsensor.manager.api.dto.DeviceJSON;
import org.homeautomation.currentsensor.manager.api.util.CurrentSensorServiceUtils;
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.annotations.device.feature.Feature;
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.DeviceValidator;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Calendar;
import java.util.concurrent.ConcurrentHashMap;
@API(name = "currentsensor", version = "1.0.0", context = "/currentsensor")
@DeviceType(value = "currentsensor")
public class CurrentSensorControllerService {
private static Log log = LogFactory.getLog(CurrentSensorControllerService.class);
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private static final String SUPER_TENANT = "carbon.super";
private boolean waitForServerStartup() {
while (!DeviceManagement.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
@Path("controller/register/{owner}/{deviceId}/{ip}/{port}")
@POST
public String registerDeviceIP(@PathParam("owner") String owner,
@PathParam("deviceId") String deviceId,
@PathParam("ip") String deviceIP,
@PathParam("port") String devicePort,
@Context HttpServletResponse response,
@Context HttpServletRequest request) {
System.out.println("Register Call..");
//TODO:: Need to get IP from the request itself
String result;
if (log.isDebugEnabled()) {
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: " + owner);
}
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
response.setStatus(Response.Status.OK.getStatusCode());
if (log.isDebugEnabled()) {
log.debug(result);
}
return result;
}
/**
* @param owner
* @param deviceId
* @param protocol
* @param response
* @return
*/
@Path("controller/read-current")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "read-current", name = "Current", type = "monitor",
description = "Request current reading from Arduino agent")
public SensorRecord requestCurrent(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
CurrentSensorConstants.SENSOR_CURRENT);
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord;
}
/**
* @param owner
* @param deviceId
* @param protocol
* @param response
* @return
*/
@Path("controller/read-power")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "read-power", name = "Power x100", type = "monitor",
description = "Request power reading from Arduino agent")
public SensorRecord requestPower(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
CurrentSensorConstants.SENSOR_POWER);
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord;
}
/**
* @param owner
* @param deviceId
* @param protocol
* @param response
* @return
*/
@Path("controller/read-flowrate")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "read-flowrate", name = "Flow Rate x100", type = "monitor",
description = "Request flow rate reading from Arduino agent")
public SensorRecord requestFlowRate(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
CurrentSensorConstants.SENSOR_FLOWRATE);
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord;
}
/**
* @param dataMsg
* @param response
*/
@Path("controller/push-data")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void pushData(final DeviceJSON dataMsg, @Context HttpServletResponse response) {
String owner = dataMsg.owner;
String deviceId = dataMsg.deviceId;
String deviceIp = dataMsg.reply;
float current = dataMsg.current;
float flow_rate = dataMsg.flow_rate;
try {
DeviceValidator deviceValidator = new DeviceValidator();
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId,
CurrentSensorConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
log.warn("Temperature data Received from unregistered raspberrypi device [" + deviceId +
"] for owner [" + owner + "]");
return;
}
String registeredIp = deviceToIpMap.get(deviceId);
if (registeredIp == null) {
log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp +
" for device ID - " + deviceId);
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
} else if (!registeredIp.equals(deviceIp)) {
log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId +
" is already registered under some other IP. Re-registration required");
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return;
}
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_CURRENT,
String.valueOf(current),
Calendar.getInstance().getTimeInMillis());
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_POWER,
String.valueOf(current * 230 / 100),
Calendar.getInstance().getTimeInMillis());
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_FLOWRATE,
String.valueOf(flow_rate/100),
Calendar.getInstance().getTimeInMillis());
if (!CurrentSensorServiceUtils.publishToDASCurrent(dataMsg.owner, dataMsg.deviceId, current)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId +
"] of owner [" + owner + "]");
}
if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.owner, dataMsg.deviceId, current * 230 / 100)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.warn("An error occured whilst trying to publish pin data of Power Sensor Data with ID [" + deviceId +
"] of owner [" + owner + "]");
}
if (!CurrentSensorServiceUtils.publishToDASFlowRate(dataMsg.owner, dataMsg.deviceId, flow_rate/100)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId +
"] of owner [" + owner + "]");
}
} catch (DeviceManagementException e) {
String errorMsg = "Validation attempt for deviceId [" + deviceId + "] of owner [" + owner + "] failed.\n";
log.error(errorMsg + Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase() + "\n" + e.getErrorMessage());
}
}
}

@ -1,40 +0,0 @@
<?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.
-->
<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="CurrentSensorController" address="/">
<jaxrs:serviceBeans>
<bean id="CurrentSensorManagerControllerService"
class="org.homeautomation.currentsensor.manager.api.CurrentSensorControllerService">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
</beans>

@ -1,254 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.currentsensor.manager.api;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
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.DeviceManagement;
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
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 javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
@DeviceType(value = "currentsensor")
public class CurrentSensorManagerService {
private static Log log = LogFactory.getLog(CurrentSensorManagerService.class);
//TODO; replace this tenant domain
private final String SUPER_TENANT = "carbon.super";
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
@Path("manager/device/register")
@PUT
public boolean register(@QueryParam("deviceId") String deviceId,
@QueryParam("name") String name, @QueryParam("owner") String owner) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
try {
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(CurrentSensorConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(owner);
device.setEnrolmentInfo(enrolmentInfo);
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device);
if (added) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return added;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("manager/device/remove/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId,
@Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
try {
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("manager/device/update/{device_id}")
@POST
public boolean updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name,
@Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
try {
Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
// device.setDeviceTypeId(deviceTypeId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(CurrentSensorConstants.DEVICE_TYPE);
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return updated;
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage());
return false;
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("manager/device/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Device getDevice(@PathParam("device_id") String deviceId) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
try {
return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
} catch (DeviceManagementException ex) {
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
return null;
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("manager/device/{sketch_type}/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response downloadSketch(@QueryParam("owner") String owner,
@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String
sketchType) {
try {
ZipArchive zipFile = createDownloadFile(owner, deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return response.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (AccessTokenException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
throws DeviceManagementException, AccessTokenException, DeviceControllerException {
if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
KeyGenerationUtil.createApplicationKeys("currentsensor");
TokenClient accessTokenClient = new TokenClient(CurrentSensorConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
//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, owner);
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, SUPER_TENANT, 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);
}
}

@ -1,33 +0,0 @@
<?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>

@ -1,58 +0,0 @@
<?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>Current-Sensor-Agent-Webapp</display-name>
<servlet>
<description>JAX-WS/JAX-RS IOT Current Sensor 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>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>false</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>/currentsensor/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>currentsensor</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
</web-app>

@ -22,12 +22,12 @@
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}-component</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<artifactId>${groupId}.currentsensor.plugin</artifactId>
<packaging>bundle</packaging>
<name>${groupId}.currentsensor.plugin for CDMF </name>
@ -58,7 +58,7 @@
<instructions>
<Bundle-SymbolicName>${groupId}.currentsensor.plugin</Bundle-SymbolicName>
<Bundle-Name>${groupId}.currentsensor.plugin</Bundle-Name>
<Bundle-Version>2.0.4-SNAPSHOT</Bundle-Version>
<Bundle-Version>2.1.0-SNAPSHOT</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.homeautomation.currentsensor.plugin.internal</Private-Package>
<Import-Package>

@ -27,4 +27,7 @@ public class CurrentSensorConstants {
public final static String SENSOR_POWER = "power";
public final static String SENSOR_FLOWRATE = "flowrate";
public static final String DATA_SOURCE_NAME = "jdbc/currentsensorDM_DB";
public final static String DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN = "accessToken";
public final static String DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN = "refreshToken";
}

@ -0,0 +1,56 @@
/*
* 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.currentsensor.plugin.exception;
public class CurrentSensorDeviceMgtPluginException extends Exception{
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public CurrentSensorDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public CurrentSensorDeviceMgtPluginException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public CurrentSensorDeviceMgtPluginException(String msg) {
super(msg);
setErrorMessage(msg);
}
public CurrentSensorDeviceMgtPluginException() {
super();
}
public CurrentSensorDeviceMgtPluginException(Throwable cause) {
super(cause);
}
}

@ -18,32 +18,23 @@
package org.homeautomation.currentsensor.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.currentsensor.plugin.impl.dao.CurrentSensorDAO;
import org.homeautomation.currentsensor.plugin.exception.CurrentSensorDeviceMgtPluginException;
import org.homeautomation.currentsensor.plugin.impl.dao.CurrentSensorDAOUtil;
import org.wso2.carbon.device.mgt.common.*;
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 org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOFactoryInterface;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dto.IotDevice;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.util.IotDeviceManagementUtil;
import java.util.ArrayList;
import java.util.List;
/**
* This represents the Current Sensor implementation of DeviceManagerService.
*/
public class CurrentSensorManager implements DeviceManager {
private static final IotDeviceManagementDAOFactoryInterface iotDeviceManagementDAOFactory = new CurrentSensorDAO();
private static final Log log = LogFactory.getLog(CurrentSensorManager.class);
private static final CurrentSensorDAOUtil CURRENT_SENSOR_DAO_UTIL = new CurrentSensorDAOUtil();
@Override
public FeatureManager getFeatureManager() {
@ -66,23 +57,21 @@ public class CurrentSensorManager implements DeviceManager {
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status;
IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device);
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new Current Sensor device : " + device.getDeviceIdentifier());
log.debug("Enrolling a new Connected Cup device : " + device.getDeviceIdentifier());
}
CurrentSensorDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice(
iotDevice);
CurrentSensorDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
CurrentSensorDAOUtil.beginTransaction();
status = CURRENT_SENSOR_DAO_UTIL.getCurrentSensorDeviceDAO().addDevice(device);
CurrentSensorDAOUtil.commitTransaction();
} catch (CurrentSensorDeviceMgtPluginException e) {
try {
CurrentSensorDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
CurrentSensorDAOUtil.rollbackTransaction();
} catch (CurrentSensorDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while enrolling the Current Sensor device : " + device.getDeviceIdentifier();
String msg = "Error while enrolling the Connected Cup device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -92,23 +81,21 @@ public class CurrentSensorManager implements DeviceManager {
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status;
IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device);
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Current Sensor device enrollment data");
log.debug("Modifying the Connected Cup device enrollment data");
}
CurrentSensorDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO()
.updateIotDevice(iotDevice);
CurrentSensorDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
CurrentSensorDAOUtil.beginTransaction();
status = CURRENT_SENSOR_DAO_UTIL.getCurrentSensorDeviceDAO().updateDevice(device);
CurrentSensorDAOUtil.commitTransaction();
} catch (CurrentSensorDeviceMgtPluginException e) {
try {
CurrentSensorDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
CurrentSensorDAOUtil.rollbackTransaction();
} catch (CurrentSensorDeviceMgtPluginException 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 Current Sensor device : " +
String msg = "Error while updating the enrollment of the Connected Cup device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
@ -121,20 +108,19 @@ public class CurrentSensorManager implements DeviceManager {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling Current Sensor device : " + deviceId);
log.debug("Dis-enrolling Connected Cup device : " + deviceId);
}
CurrentSensorDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO()
.deleteIotDevice(deviceId.getId());
CurrentSensorDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
CurrentSensorDAOUtil.beginTransaction();
status = CURRENT_SENSOR_DAO_UTIL.getCurrentSensorDeviceDAO().deleteDevice(deviceId.getId());
CurrentSensorDAOUtil.commitTransaction();
} catch (CurrentSensorDeviceMgtPluginException e) {
try {
CurrentSensorDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
CurrentSensorDAOUtil.rollbackTransaction();
} catch (CurrentSensorDeviceMgtPluginException 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 Current Sensor device : " + deviceId.getId();
String msg = "Error while removing the Connected Cup device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -146,16 +132,14 @@ public class CurrentSensorManager implements DeviceManager {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Current Sensor device : " + deviceId.getId());
log.debug("Checking the enrollment of Connected Cup device : " + deviceId.getId());
}
IotDevice iotDevice =
iotDeviceManagementDAOFactory.getIotDeviceDAO().getIotDevice(
deviceId.getId());
Device iotDevice = CURRENT_SENSOR_DAO_UTIL.getCurrentSensorDeviceDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (IotDeviceManagementDAOException e) {
String msg = "Error while checking the enrollment status of Current Sensor device : " +
} catch (CurrentSensorDeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of Connected Cup device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
@ -177,15 +161,13 @@ public class CurrentSensorManager implements DeviceManager {
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Current Sensor device : " + deviceId.getId());
try {if (log.isDebugEnabled()) {
log.debug("Getting the details of Connected Cup device : " + deviceId.getId());
}
IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO().
getIotDevice(deviceId.getId());
device = IotDeviceManagementUtil.convertToDevice(iotDevice);
} catch (IotDeviceManagementDAOException e) {
String msg = "Error while fetching the Current Sensor device : " + deviceId.getId();
device = CURRENT_SENSOR_DAO_UTIL.getCurrentSensorDeviceDAO().getDevice(deviceId.getId());
} catch (CurrentSensorDeviceMgtPluginException e) {
String msg = "Error while fetching the Connected Cup device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -220,31 +202,29 @@ public class CurrentSensorManager implements DeviceManager {
@Override
public boolean requireDeviceAuthorization() {
return true;
return false;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
boolean status;
IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device);
try {
if (log.isDebugEnabled()) {
log.debug(
"updating the details of Current Sensor device : " + deviceIdentifier);
"updating the details of Connected Cup device : " + deviceIdentifier);
}
CurrentSensorDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO()
.updateIotDevice(iotDevice);
CurrentSensorDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
CurrentSensorDAOUtil.beginTransaction();
status = CURRENT_SENSOR_DAO_UTIL.getCurrentSensorDeviceDAO().updateDevice(device);
CurrentSensorDAOUtil.commitTransaction();
} catch (CurrentSensorDeviceMgtPluginException e) {
try {
CurrentSensorDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
CurrentSensorDAOUtil.rollbackTransaction();
} catch (CurrentSensorDeviceMgtPluginException 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 Current Sensor device : " + deviceIdentifier;
"Error while updating the Connected Cup device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -256,18 +236,11 @@ public class CurrentSensorManager implements DeviceManager {
List<Device> devices = null;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Current Sensor devices");
}
List<IotDevice> iotDevices =
iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices();
if (iotDevices != null) {
devices = new ArrayList<Device>();
for (IotDevice iotDevice : iotDevices) {
devices.add(IotDeviceManagementUtil.convertToDevice(iotDevice));
}
log.debug("Fetching the details of all Connected Cup devices");
}
} catch (IotDeviceManagementDAOException e) {
String msg = "Error while fetching all Current Sensor devices.";
devices = CURRENT_SENSOR_DAO_UTIL.getCurrentSensorDeviceDAO().getAllDevices();
} catch (CurrentSensorDeviceMgtPluginException e) {
String msg = "Error while fetching all Connected Cup devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}

@ -47,11 +47,6 @@ public class CurrentSensorManagerService implements DeviceManagementService{
return true;
}
@Override
public String[] getSharedTenantsDomain() {
return new String[0];
}
@Override
public void init() throws DeviceManagementException {
deviceManager= new CurrentSensorManager();

@ -21,12 +21,8 @@ package org.homeautomation.currentsensor.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
import org.homeautomation.currentsensor.plugin.impl.dao.impl.CurrentSensorDeviceDAOImpl;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceDAO;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOFactoryInterface;
import org.homeautomation.currentsensor.plugin.exception.CurrentSensorDeviceMgtPluginException;
import org.homeautomation.currentsensor.plugin.impl.dao.impl.CurrentSensorDAO;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
@ -34,23 +30,17 @@ import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class CurrentSensorDAO extends IotDeviceManagementDAOFactory
implements IotDeviceManagementDAOFactoryInterface {
public class CurrentSensorDAOUtil{
private static final Log log = LogFactory.getLog(CurrentSensorDAO.class);
static DataSource dataSource; // package local variable
private static final Log log = LogFactory.getLog(CurrentSensorDAOUtil.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public CurrentSensorDAO() {
public CurrentSensorDAOUtil() {
initCurrentSensorDAO();
}
@Override
public IotDeviceDAO getIotDeviceDAO() {
return new CurrentSensorDeviceDAOImpl();
}
public static void initCurrentSensorDAO(){
public static void initCurrentSensorDAO() {
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(CurrentSensorConstants.DATA_SOURCE_NAME);
@ -58,52 +48,60 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory
log.error("Error while looking up the data source: " +
CurrentSensorConstants.DATA_SOURCE_NAME);
}
}
public CurrentSensorDAO getCurrentSensorDeviceDAO() {
return new CurrentSensorDAO();
}
public static void beginTransaction() throws IotDeviceManagementDAOException {
public static void beginTransaction() throws CurrentSensorDeviceMgtPluginException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while retrieving datasource connection", e);
throw new CurrentSensorDeviceMgtPluginException(
"Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws IotDeviceManagementDAOException {
public static Connection getConnection() throws CurrentSensorDeviceMgtPluginException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection",
e);
throw new CurrentSensorDeviceMgtPluginException(
"Error occurred while retrieving data source connection", e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws IotDeviceManagementDAOException {
public static void commitTransaction() throws CurrentSensorDeviceMgtPluginException {
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");
log.debug("Datasource connection associated with the current thread is null, " +
"hence commit has not been attempted");
}
}
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while committing the transaction", e);
throw new CurrentSensorDeviceMgtPluginException(
"Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws IotDeviceManagementDAOException {
public static void closeConnection() throws CurrentSensorDeviceMgtPluginException {
Connection con = currentConnection.get();
if(con != null){
if (con != null) {
try {
con.close();
} catch (SQLException e) {
@ -113,19 +111,20 @@ public class CurrentSensorDAO extends IotDeviceManagementDAOFactory
currentConnection.remove();
}
public static void rollbackTransaction() throws IotDeviceManagementDAOException {
public static void rollbackTransaction() throws CurrentSensorDeviceMgtPluginException {
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");
log.debug(
"Datasource connection associated with the current thread is null, " +
"hence rollback has not been attempted");
}
}
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while rollback the transaction", e);
throw new CurrentSensorDeviceMgtPluginException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}

@ -0,0 +1,242 @@
/*
* 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.currentsensor.plugin.impl.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
import org.homeautomation.currentsensor.plugin.exception.CurrentSensorDeviceMgtPluginException;
import org.homeautomation.currentsensor.plugin.impl.dao.CurrentSensorDAOUtil;
import org.homeautomation.currentsensor.plugin.impl.util.CurrentSensorUtils;
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 IotDeviceDAO for current sensor Devices.
*/
public class CurrentSensorDAO {
private static final Log log = LogFactory.getLog(CurrentSensorDAO.class);
public Device getDevice(String deviceId) throws CurrentSensorDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
Device CurrentSensorDevice = null;
ResultSet resultSet = null;
try {
conn = CurrentSensorDAOUtil.getConnection();
String selectDBQuery =
"SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN" +
" FROM CURRENT_SENSOR_DEVICE WHERE CURRENT_SENSOR_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, deviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
CurrentSensorDevice = new Device();
CurrentSensorDevice.setName(resultSet.getString(
CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME));
List<Device.Property> propertyList = new ArrayList<Device.Property>();
propertyList.add(CurrentSensorUtils.getProperty(
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN,
resultSet.getString("ACCESS_TOKEN")));
propertyList.add(CurrentSensorUtils.getProperty(
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN,
resultSet.getString("REFRESH_TOKEN")));
CurrentSensorDevice.setProperties(propertyList);
if (log.isDebugEnabled()) {
log.debug("Connected Cup service " + deviceId + " data has been fetched from" +
"Connected Cup database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching Connected Cup device : '" + deviceId + "'";
log.error(msg, e);
throw new CurrentSensorDeviceMgtPluginException(msg, e);
} finally {
CurrentSensorUtils.cleanupResources(stmt, resultSet);
CurrentSensorDAOUtil.closeConnection();
}
return CurrentSensorDevice;
}
public boolean addDevice(Device CurrentSensorDevice) throws CurrentSensorDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = CurrentSensorDAOUtil.getConnection();
String createDBQuery =
"INSERT INTO CURRENT_SENSOR_DEVICE(CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME, " +
"ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, CurrentSensorDevice.getDeviceIdentifier());
stmt.setString(2, CurrentSensorDevice.getName());
stmt.setString(3, CurrentSensorUtils.getDeviceProperty(
CurrentSensorDevice.getProperties(),
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN));
stmt.setString(4, CurrentSensorUtils.getDeviceProperty(
CurrentSensorDevice.getProperties(),
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN));
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Connected Cup device " + CurrentSensorDevice.getDeviceIdentifier() +
" data has been added to the Connected Cup database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the Connected Cup device '" +
CurrentSensorDevice.getDeviceIdentifier() + "' to the Connected Cup db.";
log.error(msg, e);
throw new CurrentSensorDeviceMgtPluginException(msg, e);
} finally {
CurrentSensorUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean updateDevice(Device CurrentSensorDevice) throws CurrentSensorDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = CurrentSensorDAOUtil.getConnection();
String updateDBQuery =
"UPDATE CURRENT_SENSOR_DEVICE SET DEVICE_NAME = ?, ACCESS_TOKEN=?, " +
"REFRESH_TOKEN=? WHERE CURRENT_SENSOR_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
if (CurrentSensorDevice.getProperties() == null) {
CurrentSensorDevice.setProperties(new ArrayList<Device.Property>());
}
stmt.setString(1, CurrentSensorDevice.getName());
stmt.setString(2, CurrentSensorUtils.getDeviceProperty(
CurrentSensorDevice.getProperties(),
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN));
stmt.setString(3, CurrentSensorUtils.getDeviceProperty(
CurrentSensorDevice.getProperties(),
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN));
stmt.setString(4, CurrentSensorDevice.getDeviceIdentifier());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Connected Cup device " + CurrentSensorDevice.getDeviceIdentifier() +
" data has been modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Connected Cup device '" +
CurrentSensorDevice.getDeviceIdentifier() + "' data.";
log.error(msg, e);
throw new CurrentSensorDeviceMgtPluginException(msg, e);
} finally {
CurrentSensorUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean deleteDevice(String deviceId) throws CurrentSensorDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = CurrentSensorDAOUtil.getConnection();
String deleteDBQuery =
"DELETE FROM CURRENT_SENSOR_DEVICE WHERE CURRENT_SENSOR_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, deviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Connected Cup device " + deviceId + " data has deleted" +
" from the Connected Cup database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting Connected Cup device " + deviceId;
log.error(msg, e);
throw new CurrentSensorDeviceMgtPluginException(msg, e);
} finally {
CurrentSensorUtils.cleanupResources(stmt, null);
}
return status;
}
public List<Device> getAllDevices() throws CurrentSensorDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device CurrentSensorDevice;
List<Device> iotDevices = new ArrayList<>();
try {
conn = CurrentSensorDAOUtil.getConnection();
String selectDBQuery =
"SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN" +
"FROM CURRENT_SENSOR_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
CurrentSensorDevice = new Device();
CurrentSensorDevice.setDeviceIdentifier(resultSet.getString(
CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_ID));
CurrentSensorDevice.setName(resultSet.getString(
CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME));
List<Device.Property> propertyList = new ArrayList<Device.Property>();
propertyList.add(CurrentSensorUtils.getProperty(
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN,
resultSet.getString("ACCESS_TOKEN")));
propertyList.add(CurrentSensorUtils.getProperty(
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN,
resultSet.getString("REFRESH_TOKEN")));
CurrentSensorDevice.setProperties(propertyList);
}
if (log.isDebugEnabled()) {
log.debug("All Connected Cup device details have fetched from Connected Cup database" +
".");
}
return iotDevices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all Connected Cup device data'";
log.error(msg, e);
throw new CurrentSensorDeviceMgtPluginException(msg, e);
} finally {
CurrentSensorUtils.cleanupResources(stmt, resultSet);
CurrentSensorDAOUtil.closeConnection();
}
}
}

@ -1,237 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.currentsensor.plugin.impl.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
import org.homeautomation.currentsensor.plugin.impl.dao.CurrentSensorDAO;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceDAO;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.util.IotDeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dto.IotDevice;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implements IotDeviceDAO for current sensor Devices.
*/
public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
private static final Log log = LogFactory.getLog(CurrentSensorDeviceDAOImpl.class);
@Override
public IotDevice getIotDevice(String iotDeviceId)
throws IotDeviceManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
IotDevice iotDevice = null;
ResultSet resultSet = null;
try {
conn = CurrentSensorDAO.getConnection();
String selectDBQuery =
"SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME" +
" FROM CURRENT_SENSOR_DEVICE WHERE CURRENT_SENSOR_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, iotDeviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
iotDevice = new IotDevice();
iotDevice.setIotDeviceName(resultSet.getString(
CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME));
Map<String, String> propertyMap = new HashMap<String, String>();
iotDevice.setDeviceProperties(propertyMap);
if (log.isDebugEnabled()) {
log.debug("Current Sensor device " + iotDeviceId + " data has been fetched from " +
"Current Sensor database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching Current Sensor device : '" + iotDeviceId + "'";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet);
CurrentSensorDAO.closeConnection();
}
return iotDevice;
}
@Override
public boolean addIotDevice(IotDevice iotDevice)
throws IotDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = CurrentSensorDAO.getConnection();
String createDBQuery =
"INSERT INTO CURRENT_SENSOR_DEVICE(CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, iotDevice.getIotDeviceId());
stmt.setString(2, iotDevice.getIotDeviceName());
if (iotDevice.getDeviceProperties() == null) {
iotDevice.setDeviceProperties(new HashMap<String, String>());
}
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Current Sensor device " + iotDevice.getIotDeviceId() + " data has been" +
" added to the Current Sensor database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the Current Sensor device '" +
iotDevice.getIotDeviceId() + "' to the Current Sensor db.";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean updateIotDevice(IotDevice iotDevice)
throws IotDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = CurrentSensorDAO.getConnection();
String updateDBQuery =
"UPDATE CURRENT_SENSOR_DEVICE SET DEVICE_NAME = ? WHERE CURRENT_SENSOR_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
if (iotDevice.getDeviceProperties() == null) {
iotDevice.setDeviceProperties(new HashMap<String, String>());
}
stmt.setString(1, iotDevice.getIotDeviceName());
stmt.setString(2, iotDevice.getIotDeviceId());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Current Sensor device " + iotDevice.getIotDeviceId() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Current Sensor device '" +
iotDevice.getIotDeviceId() + "' data.";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean deleteIotDevice(String iotDeviceId)
throws IotDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = CurrentSensorDAO.getConnection();
String deleteDBQuery =
"DELETE FROM CURRENT_SENSOR_DEVICE WHERE CURRENT_SENSOR_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, iotDeviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Current Sensor device " + iotDeviceId + " data has deleted" +
" from the Current Sensor database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting Current Sensor device " + iotDeviceId;
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public List<IotDevice> getAllIotDevices()
throws IotDeviceManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
IotDevice iotDevice;
List<IotDevice> iotDevices = new ArrayList<IotDevice>();
try {
conn = CurrentSensorDAO.getConnection();
String selectDBQuery =
"SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME " +
"FROM CURRENT_SENSOR_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
iotDevice = new IotDevice();
iotDevice.setIotDeviceId(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_ID));
iotDevice.setIotDeviceName(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME));
Map<String, String> propertyMap = new HashMap<String, String>();
iotDevice.setDeviceProperties(propertyMap);
iotDevices.add(iotDevice);
}
if (log.isDebugEnabled()) {
log.debug("All Current Sensor device details have fetched from Current Sensor database.");
}
return iotDevices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all Current Sensor device data'";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet);
CurrentSensorDAO.closeConnection();
}
}
}

@ -20,7 +20,13 @@ package org.homeautomation.currentsensor.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
@ -30,15 +36,52 @@ public class CurrentSensorUtils {
private static Log log = LogFactory.getLog(CurrentSensorUtils.class);
public static String getDeviceProperty(Map<String, String> deviceProperties, String property) {
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;
}
String deviceProperty = deviceProperties.get(property);
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;
}
if (deviceProperty == null) {
return "";
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);
}
}
}
return deviceProperty;
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}

@ -25,26 +25,15 @@ import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.service.DeviceTypeService;
/**
* @scr.component name="org.wso2.carbon.device.mgt.iot.currentsensor.plugin.internal.CurrentSensorManagementServiceComponent"
* @scr.component name="org.homeautomation.currentsensor.plugin.internal.ServiceComponent"
* immediate="true"
* @scr.reference name="org.wso2.carbon.device.mgt.iot.service.DeviceTypeService"
* interface="org.wso2.carbon.device.mgt.iot.service.DeviceTypeService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDeviceTypeService"
* unbind="unsetDeviceTypeService"
*/
public class ServiceComponent {
private ServiceRegistration currentSensorServiceRegRef;
private static final Log log = LogFactory.getLog(ServiceComponent.class);
protected void activate(ComponentContext ctx) {
@ -53,15 +42,10 @@ public class ServiceComponent {
}
try {
BundleContext bundleContext = ctx.getBundleContext();
currentSensorServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(), new
CurrentSensorManagerService(),
null);
if (log.isDebugEnabled()) {
log.debug("Current Sensor Management Service Component has been successfully activated");
}
@ -70,7 +54,6 @@ public class ServiceComponent {
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating Current Sensor Management Service Component");
@ -89,20 +72,4 @@ public class ServiceComponent {
}
}
protected void setDeviceTypeService(DeviceTypeService deviceTypeService) {
/* This is to avoid this component getting initialized before the
common registered */
if (log.isDebugEnabled()) {
log.debug("Data source service set to mobile service component");
}
}
protected void unsetDeviceTypeService(DeviceTypeService deviceTypeService) {
//do nothing
}
}

@ -22,11 +22,11 @@
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>currentsensor</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<artifactId>${project-base-package}-component</artifactId>
<name>WSO2 IoTS(Device Types) - Current Sensor Component</name>
<packaging>pom</packaging>
@ -53,211 +53,8 @@
<modules>
<module>analytics</module>
<module>plugin</module>
<module>controller</module>
<module>manager</module>
<module>agent</module>
<module>api</module>
<module>ui</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId>
<version>2.0.4-SNAPSHOT</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</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.analytics_${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>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>

@ -25,12 +25,12 @@
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}-component</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<artifactId>${groupId}.currentsensor.ui</artifactId>
<name>${groupId}.currentsensor.ui</name>
<packaging>pom</packaging>

@ -23,12 +23,12 @@
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>feature</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<artifactId>${groupId}.currentsensor.feature</artifactId>
<packaging>pom</packaging>
<name>${project.artifactId}</name>
@ -42,19 +42,7 @@
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.manager</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.controller</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.agent</artifactId>
<artifactId>${project-base-package}.api</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
<type>war</type>
</dependency>
@ -138,17 +126,7 @@
<artifactItems>
<artifactItem>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.manager</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps/
</outputDirectory>
<destFileName>currentsensor_mgt.war</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.controller</artifactId>
<artifactId>${project-base-package}.api</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
@ -156,16 +134,6 @@
</outputDirectory>
<destFileName>currentsensor.war</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.agent</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps/
</outputDirectory>
<destFileName>currentsensor_agent.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
@ -220,7 +188,7 @@
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:true</propertyDef>
</properties>
</adviceFile>
<bundles>

@ -14,3 +14,15 @@ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../data
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.currentsensor_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/carbonapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.currentsensor_${feature.version}/carbonapps/,target:${installFolder}/../../deployment/server/carbonapps/,overwrite:true);\
instructions.unconfigure = \
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/device-types/currentsensor.json);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/device-types/currentsensor.xml);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/currentsensor.war);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/currentsensor);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../dbscripts/cdm/plugins/currentsensor);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../resources/sketches/currentsensor);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/datasources/currentsensor-datasources.xml);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../database/currentsensorDM_DB.h2.db);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.currentsensor.device-view);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.currentsensor.type-view);\

@ -24,14 +24,14 @@
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>currentsensor</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>feature</artifactId>
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<modules>
<module>feature</module>

@ -28,7 +28,7 @@
<groupId>org.homeautomation</groupId>
<artifactId>currentsensor</artifactId>
<version>2.0.4-SNAPSHOT</version>
<version>2.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modelVersion>4.0.0</modelVersion>
<url>http://wso2.com</url>
@ -38,6 +38,7 @@
<module>feature</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
@ -151,9 +152,238 @@
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>org.homeautomation.currentsensor.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>
</dependencyManagement>
<properties>
<carbon.kernel.version>4.4.3</carbon.kernel.version>
<carbon.device.mgt.version>1.1.0-SNAPSHOT</carbon.device.mgt.version>
@ -161,8 +391,8 @@
<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.0.4-SNAPSHOT</carbon.device.mgt.plugin.version>
<carbon.iot.device.mgt.jar.version>2.0.4.SNAPSHOT</carbon.iot.device.mgt.jar.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>
<commons-io.version>2.4</commons-io.version>

@ -24,10 +24,10 @@
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.homeautomation.doormanager.manager</artifactId>
<artifactId>org.homeautomation.doormanager.api</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>org.homeautomation.doormanager.manager </name>
<name>org.homeautomation.doormanager.api </name>
<url>http://wso2.org</url>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
@ -52,6 +52,10 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>org.homeautomation.doormanager.plugin</artifactId>
@ -73,7 +77,7 @@
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
@ -233,5 +237,21 @@
<artifactId>gson</artifactId>
<version>2.2.4</version>
</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>
</dependencies>
</project>

@ -0,0 +1,109 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.api;
import org.homeautomation.doormanager.api.dto.UserInfo;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "doormanager", version = "1.0.0", context = "/doormanager", tags = {"doormanager"})
@DeviceType(value = "doormanager")
public interface DoorManagerControllerService {
/**
* Assign new user to lock
*
* @param owner owner of the device
* @param deviceId unique identifier for given device
* @param protocol transport protocol which is being using here MQTT
* @param cardNumber RFID card number
* @param userName user name of RFID card owner
* @param emailAddress email address of RFID card owner
*/
@Path("device/assign-user")
@POST
@Feature(code = "assign_user", name = "Assign new user to lock", type = "operation",
description = "Add new access card to user to control the lock ")
Response assignUserToLock(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("cardNumber") String cardNumber,
@FormParam("userName") String userName,
@FormParam("emailAddress") String emailAddress);
/**
* Change status of door lock safe: LOCK/UNLOCK
*
* @param owner owner of the device
* @param deviceId unique identifier for given device
* @param protocol transport protocol which is being using here MQTT
* @param state status of lock safe: lock/unlock
*/
@Path("device/change-status")
@POST
@Feature(code = "change-status", name = "Change status of door lock safe: LOCK/UNLOCK", type = "operation",
description = "Change status of door lock safe: LOCK/UNLOCK")
Response changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("state") String state);
/**
* Request current status of door lock safe
*
* @param owner owner of the device
* @param deviceId unique identifier for given device
* @param protocol transport protocol which is being using here MQTT
*/
@GET
@Path("device/current-status")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "current-status", name = "Door Locker Status", type = "monitor",
description = "Request current status of door safe")
Response requestStatusOfDoorLockSafe(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol);
/**
* @param userInfo user information which are required to test given user is authorized to open requested door
* @return if user is authorized open the the door allow to open it
*/
@GET
@Path("device/get-user-info")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@SuppressWarnings("unchecked")
//This is to avoid unchecked call to put(k, v) into jsonObject. org.json.simple
// library uses raw type collections internally.
Response get_user_info(final UserInfo userInfo);
}

@ -0,0 +1,226 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.api.exception.DoorManagerException;
import org.homeautomation.doormanager.api.transport.DoorManagerMQTTConnector;
import org.homeautomation.doormanager.api.dto.UserInfo;
import org.homeautomation.doormanager.api.util.APIUtil;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.DoorManager;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.json.simple.JSONObject;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.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 org.wso2.carbon.user.api.UserStoreManager;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class DoorManagerControllerServiceImpl implements DoorManagerControllerService{
private static Log log = LogFactory.getLog(DoorManagerControllerServiceImpl.class);
private static String CURRENT_STATUS = "doorLockerCurrentStatus";
private DoorManager doorManager;
private DoorManagerMQTTConnector doorManagerMQTTConnector;
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
DoorManagerControllerServiceImpl() {
doorManager = new DoorManager();
}
@Context //injected response proxy supporting multiple thread
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public DoorManagerMQTTConnector getDoorManagerMQTTConnector() {
return doorManagerMQTTConnector;
}
public void setDoorManagerMQTTConnector(final DoorManagerMQTTConnector MQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
DoorManagerControllerServiceImpl.this.doorManagerMQTTConnector = MQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
doorManagerMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, DoorManagerMQTTConnector" +
" not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
public Response assignUserToLock(String owner, String deviceId, String protocol, String cardNumber, String userName,
String emailAddress) {
if (userName != null && cardNumber != null && deviceId != null) {
try {
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
DoorLockSafe doorLockSafe = new DoorLockSafe();
if (userStoreManager.isExistingUser(userName)) {
if (apiApplicationKey == null) {
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DoorManagerConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DoorManagerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
String scopes = "device_type_" + DoorManagerConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes);
String accessToken = accessTokenInfo.getAccess_token();
if (accessToken == null) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
Map<String, String> claims = new HashMap<>();
claims.put(DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, accessToken);
claims.put(DoorManagerConstants.DEVICE_CLAIMS_REFRESH_TOKEN,
accessTokenInfo.getRefresh_token());
claims.put(DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, cardNumber);
userStoreManager.setUserClaimValues(userName, claims, null);
doorLockSafe.setAccessToken(accessTokenInfo.getAccess_token());
doorLockSafe.setRefreshToken(accessTokenInfo.getRefresh_token());
doorLockSafe.setDeviceId(deviceId);
doorLockSafe.setOwner(owner);
doorLockSafe.setEmailAddress(emailAddress);
doorLockSafe.setUIDofUser(cardNumber);
doorLockSafe.setSerialNumber(deviceId);
if (doorManager.assignUserToLock(doorLockSafe)) {
return Response.ok().build();
} else {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
} else {
return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
}
} catch (UserStoreException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (JWTClientException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (APIManagerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DoorManagerDeviceMgtPluginException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
} else {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
}
public Response changeStatusOfDoorLockSafe(String owner, String deviceId, String protocol, String state) {
try {
int lockerCurrentState;
if (state.toUpperCase().equals("LOCK")) {
lockerCurrentState = 0;
} else {
lockerCurrentState = 1;
}
SensorDataManager.getInstance().setSensorRecord(deviceId, CURRENT_STATUS,
String.valueOf(lockerCurrentState), Calendar.getInstance().getTimeInMillis());
doorManagerMQTTConnector.sendCommandViaMQTT(owner, deviceId, "DoorManager:", state.toUpperCase());
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DoorManagerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response requestStatusOfDoorLockSafe(String owner, String deviceId, String protocol) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, CURRENT_STATUS);
return Response.ok(sensorRecord).entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response get_user_info(final UserInfo userInfo) {
if (userInfo.userName != null && userInfo.cardNumber != null && userInfo.deviceId != null) {
try {
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
if (userStoreManager.isExistingUser(userInfo.userName)) {
String accessToken = userStoreManager.getUserClaimValue(userInfo.userName,
DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, null);
String cardNumber = userStoreManager.getUserClaimValue(userInfo.userName,
DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, null);
if (cardNumber != null) {
if (cardNumber.equals(userInfo.cardNumber)) {
if (accessToken != null) {
JSONObject credentials = new JSONObject();
credentials.put(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN, accessToken);
//return Response.ok(credentials, MediaType.APPLICATION_JSON_TYPE).build();
return Response.status(Response.Status.OK).build();
}
}
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} else {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} catch (UserStoreException e) {
log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
return Response.status(Response.Status.BAD_REQUEST).build();
}
}

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

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

@ -16,7 +16,7 @@
* under the License.
*/
package org.homeautomation.doormanager.controller.api.dto;
package org.homeautomation.doormanager.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@ -16,7 +16,7 @@
* under the License.
*/
package org.homeautomation.doormanager.controller.api.dto;
package org.homeautomation.doormanager.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@ -16,7 +16,7 @@
* under the License.
*/
package org.homeautomation.doormanager.controller.api.exception;
package org.homeautomation.doormanager.api.exception;
public class DoorManagerException extends Exception {

@ -16,16 +16,16 @@
* under the License.
*/
package org.homeautomation.doormanager.controller.api.transport;
package org.homeautomation.doormanager.api.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.homeautomation.doormanager.controller.api.exception.DoorManagerException;
import org.homeautomation.doormanager.controller.api.util.DoorManagerServiceUtils;
import org.homeautomation.doormanager.api.exception.DoorManagerException;
import org.homeautomation.doormanager.api.util.DoorManagerServiceUtils;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
@ -45,11 +45,8 @@ public class DoorManagerMQTTConnector extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(DoorManagerMQTTConnector.class);
private static String PUBLISHER_CONTEXT = "publisher";
private static String SUBSCRIBER_CONTEXT = "subscriber";
private static String SUBCRIBER_TOPIC = "wso2" + File.separator + "iot" + File.separator + "+" + File.separator +
DoorManagerConstants.DEVICE_TYPE + File.separator + "+" + File.separator + PUBLISHER_CONTEXT;
private static String PUBLISHER_TOPIC = "wso2/iot/%s/" + DoorManagerConstants.DEVICE_TYPE + "/%s/"
+ SUBSCRIBER_CONTEXT;
private static String SUBCRIBER_TOPIC = "wso2/" + DoorManagerConstants.DEVICE_TYPE + "/+/publisher";
private static String PUBLISHER_TOPIC = "wso2/"+ DoorManagerConstants.DEVICE_TYPE + "/%s/subscriber";
private static String SUBSCRIBER = UUID.randomUUID().toString().substring(0, 5);
private DoorManagerMQTTConnector() {
@ -165,12 +162,12 @@ public class DoorManagerMQTTConnector extends MQTTTransportHandler {
String payload = operation + param;
try {
publishToAutomaticDoorLocker(topic, payload, 2, false);
if (param.equals("LOCK")) {
if (param.toUpperCase().equals("LOCK")) {
if (!DoorManagerServiceUtils.publishToDASLockerStatus(deviceOwner, deviceId, 0)) {
log.warn("An error occurred whilst trying to publish with ID [" + deviceId + "] of owner [" +
deviceOwner + "]");
}
} else {
} else if (param.toUpperCase().equals("UNLOCK")) {
if (!DoorManagerServiceUtils.publishToDASLockerStatus(deviceOwner, deviceId, 1)) {
log.warn("An error occurred whilst trying to publish with ID [" + deviceId + "] of owner [" +
deviceOwner + "]");

@ -16,8 +16,9 @@
* under the License.
*/
package org.homeautomation.doormanager.manager.api.util;
package org.homeautomation.doormanager.api.util;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
@ -26,6 +27,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
*/
public class APIUtil {
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
@ -36,9 +38,10 @@ public class APIUtil {
return username;
}
public static String getTenantDomainOfUser() {
public static String getTenantDomainOftheUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
return threadLocalCarbonContext.getTenantDomain();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
return tenantDomain;
}
public static DeviceManagementProviderService getDeviceManagementService() {
@ -51,4 +54,15 @@ public class APIUtil {
}
return deviceManagementProviderService;
}
public static APIManagementProviderService getAPIManagementProviderService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
APIManagementProviderService apiManagementProviderService =
(APIManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (apiManagementProviderService == null) {
String msg = "API management provider service has not initialized.";
throw new IllegalStateException(msg);
}
return apiManagementProviderService;
}
}

@ -16,16 +16,17 @@
* under the License.
*/
package org.homeautomation.doormanager.controller.api.util;
package org.homeautomation.doormanager.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService;
public class DoorManagerServiceUtils {
private static final Log log = LogFactory.getLog(DoorManagerServiceUtils.class);
private static final String STREAM_DEFINITION = "org.wso2.iot.devices.smartLock";
private static final String STREAM_DEFINITION_VERSION = "1.0.0";
@ -38,8 +39,8 @@ public class DoorManagerServiceUtils {
* @param status current status of lock:- 1: open, 0: close
* @return status
*/
public static boolean publishToDASLockerStatus(String owner, String deviceId, float status) throws
DataPublisherConfigurationException {
public static boolean publishToDASLockerStatus(String owner, String deviceId, float status)
throws DataPublisherConfigurationException {
Object payloadCurrent[] = {status};
return publishToDAS(owner, deviceId, payloadCurrent, STREAM_DEFINITION);
}
@ -61,8 +62,6 @@ public class DoorManagerServiceUtils {
} catch (DataPublisherConfigurationException e) {
log.error(e);
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return true;
}

@ -16,7 +16,7 @@
* under the License.
*/
package org.homeautomation.firealarm.manager.api.util;
package org.homeautomation.doormanager.api.util;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@ -31,43 +31,71 @@
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/manager/device/*</url>
<url>/devices/*</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Add device</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device/register</url>
<url>/devices/register</url>
<method>PUT</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device/doormanager/download</url>
<url>/devices/doormanager/download</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Generate link to download</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device/doormanager/generate_link</url>
<url>/devices/doormanager/generate_link</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/manager/device/update/*</url>
<url>/devices/update/*</url>
<method>POST</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/manager/device/remove/*</url>
<url>/devices/remove/*</url>
<method>DELETE</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Assign user</name>
<path>/device-mgt/user/device/assign-user</path>
<url>/device/assign-user</url>
<method>POST</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Change status</name>
<path>/device-mgt/user/device/change-status</path>
<url>/device/change-status</url>
<method>POST</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Get current status</name>
<path>/device-mgt/user/device/</path>
<url>/device/current-status</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Get user Info</name>
<path>/device-mgt/user/device/</path>
<url>/device/get-user-info</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
</PermissionConfiguration>

@ -25,9 +25,12 @@
<jaxrs:server id="DoorManagerController" address="/">
<jaxrs:serviceBeans>
<bean id="DoorManagerControllerService"
class="org.homeautomation.doormanager.controller.api.DoorManagerControllerService">
class="org.homeautomation.doormanager.api.DoorManagerControllerServiceImpl">
<property name="DoorManagerMQTTConnector" ref="communicationHandler"/>
</bean>
<bean id="DoorManagerManagerService"
class="org.homeautomation.doormanager.api.DoorManagerManagerServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
@ -35,7 +38,7 @@
</jaxrs:server>
<bean id="communicationHandler"
class="org.homeautomation.doormanager.controller.api.transport.DoorManagerMQTTConnector">
class="org.homeautomation.doormanager.api.transport.DoorManagerMQTTConnector">
</bean>
</beans>

@ -1,228 +0,0 @@
<!--/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager-component</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.homeautomation.doormanager.controller</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>org.homeautomation.doormanager.controller</name>
<url>http://wso2.com</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warName>org.homeautomation.doormanager.controller</warName>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>org.homeautomation.doormanager.plugin</artifactId>
</dependency>
<!-- 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</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>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</dependency>
<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>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.json.wso2</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.core</artifactId>
<version>4.4.3</version>
</dependency>
</dependencies>
</project>

@ -1,326 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.controller.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.controller.api.dto.UserInfo;
import org.homeautomation.doormanager.controller.api.exception.DoorManagerException;
import org.homeautomation.doormanager.controller.api.transport.DoorManagerMQTTConnector;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.DoorManager;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.json.JSONException;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.annotations.device.feature.Feature;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
import org.wso2.carbon.device.mgt.iot.DeviceValidator;
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "doormanager", version = "1.0.0", context = "/doormanager")
@DeviceType(value = "doormanager")
public class DoorManagerControllerService {
private static Log log = LogFactory.getLog(DoorManagerControllerService.class);
private static String CURRENT_STATUS = "doorLockerCurrentStatus";
private DoorManager doorManager;
private DoorManagerMQTTConnector doorManagerMQTTConnector;
DoorManagerControllerService() {
doorManager = new DoorManager();
}
@Context //injected response proxy supporting multiple thread
private boolean waitForServerStartup() {
while (!DeviceManagement.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public DoorManagerMQTTConnector getDoorManagerMQTTConnector() {
return doorManagerMQTTConnector;
}
public void setDoorManagerMQTTConnector(final DoorManagerMQTTConnector MQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
DoorManagerControllerService.this.doorManagerMQTTConnector = MQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
doorManagerMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, DoorManagerMQTTConnector" +
" not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
/**
* Assign new user to lock
*
* @param owner owner of the device
* @param deviceId unique identifier for given device
* @param protocol transport protocol which is being using here MQTT
* @param cardNumber RFID card number
* @param userName user name of RFID card owner
* @param emailAddress email address of RFID card owner
*/
@Path("controller/assign_user")
@POST
@Feature(code = "assign_user", name = "Assign new user to lock", type = "operation",
description = "Add new access card to user to control the lock ")
public void assignUserToLock(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("cardNumber") String cardNumber,
@FormParam("userName") String userName,
@FormParam("emailAddress") String emailAddress,
@Context HttpServletResponse response) {
if (userName != null && cardNumber != null && deviceId != null) {
try {
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
DoorLockSafe doorLockSafe = new DoorLockSafe();
if (userStoreManager.isExistingUser(userName)) {
TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(deviceId, userName);
String accessToken = accessTokenInfo.getAccess_token();
if (accessToken == null) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
Map<String, String> claims = new HashMap<>();
claims.put(DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, accessToken);
claims.put(DoorManagerConstants.DEVICE_CLAIMS_REFRESH_TOKEN,
accessTokenInfo.getRefresh_token());
claims.put(DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, cardNumber);
userStoreManager.setUserClaimValues(userName, claims, null);
doorLockSafe.setAccessToken(accessTokenInfo.getAccess_token());
doorLockSafe.setRefreshToken(accessTokenInfo.getRefresh_token());
doorLockSafe.setDeviceId(deviceId);
doorLockSafe.setOwner(owner);
doorLockSafe.setEmailAddress(emailAddress);
doorLockSafe.setUIDofUser(cardNumber);
doorLockSafe.setSerialNumber(deviceId);
if (doorManager.assignUserToLock(doorLockSafe)) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
}
} else {
response.setStatus(Response.Status.NOT_FOUND.getStatusCode());
}
} catch (UserStoreException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e);
} catch (DoorManagerDeviceMgtPluginException | AccessTokenException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
} else {
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
}
}
/**
* Change status of door lock safe: LOCK/UNLOCK
*
* @param owner owner of the device
* @param deviceId unique identifier for given device
* @param protocol transport protocol which is being using here MQTT
* @param state status of lock safe: lock/unlock
*/
@Path("controller/change-status")
@POST
@Feature(code = "change-status", name = "Change status of door lock safe: LOCK/UNLOCK", type = "operation",
description = "Change status of door lock safe: LOCK/UNLOCK")
public void changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("state") String state,
@Context HttpServletResponse response) {
try {
int lockerCurrentState;
if (state.toUpperCase().equals("LOCK")) {
lockerCurrentState = 0;
} else {
lockerCurrentState = 1;
}
SensorDataManager.getInstance().setSensorRecord(deviceId, CURRENT_STATUS,
String.valueOf(lockerCurrentState), Calendar.getInstance().getTimeInMillis());
doorManagerMQTTConnector.sendCommandViaMQTT(owner, deviceId, "DoorManager:", state.toUpperCase());
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DoorManagerException e) {
log.error(e);
}
}
/**
* Request current status of door lock safe
*
* @param owner owner of the device
* @param deviceId unique identifier for given device
* @param protocol transport protocol which is being using here MQTT
* @param response http servlet response object
*/
@GET
@Path("controller/current-status")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "current-status", name = "Door Locker Status", type = "monitor",
description = "Request current status of door safe")
public SensorRecord requestStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
DeviceValidator deviceValidator = new DeviceValidator();
try {
if (!deviceValidator.isExist(owner, CarbonContext.getThreadLocalCarbonContext().getTenantDomain(),
new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, CURRENT_STATUS);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException | DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
/**
* @param userInfo user information which are required to test given user is authorized to open requested door
* @return if user is authorized open the the door allow to open it
*/
@POST
@Path("controller/get_user_info")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@SuppressWarnings("unchecked") //This is to avoid unchecked call to put(k, v) into jsonObject. org.json.simple
// library uses raw type collections internally.
public Response get_user_info(final UserInfo userInfo) {
if (userInfo.userName != null && userInfo.cardNumber != null && userInfo.deviceId != null) {
try {
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
if (userStoreManager.isExistingUser(userInfo.userName)) {
String accessToken = userStoreManager.getUserClaimValue(userInfo.userName,
DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, null);
String cardNumber = userStoreManager.getUserClaimValue(userInfo.userName,
DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, null);
if (cardNumber != null) {
if (cardNumber.equals(userInfo.cardNumber)) {
if (accessToken != null) {
JSONObject credentials = new JSONObject();
credentials.put(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN, accessToken);
//return Response.ok(credentials, MediaType.APPLICATION_JSON_TYPE).build();
return Response.status(Response.Status.OK).build();
}
}
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} else {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} catch (UserStoreException e) {
log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (JSONException e) {
log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
return Response.status(Response.Status.BAD_REQUEST).build();
}
/*
private void sendCEPEvent(String deviceId, String cardId, boolean accessStatus){
String cepEventReciever = "http://localhost:9768/endpoints/LockEventReciever";
HttpClient httpClient = new SystemDefaultHttpClient();
HttpPost method = new HttpPost(cepEventReciever);
JsonObject event = new JsonObject();
JsonObject metaData = new JsonObject();
metaData.addProperty("deviceID", deviceId);
metaData.addProperty("cardID", cardId);
event.add("metaData", metaData);
String eventString = "{\"event\": " + event + "}";
try {
StringEntity entity = new StringEntity(eventString);
method.setEntity(entity);
if (cepEventReciever.startsWith("https")) {
method.setHeader("Authorization", "Basic " + Base64.encode(("admin" + ":" + "admin").getBytes()));
}
httpClient.execute(method).getEntity().getContent().close();
} catch (UnsupportedEncodingException e) {
log.error("Error while constituting CEP event"+ e.getMessage());
} catch (ClientProtocolException e) {
log.error("Error while sending message to CEP "+ e.getMessage());
} catch (IOException e) {
log.error("Error while sending message to CEP "+ e.getMessage());
}
}*/
}

@ -1,336 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.manager.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.manager.api.util.APIUtil;
import org.homeautomation.doormanager.manager.api.util.ResponsePayload;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
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.apimgt.AccessTokenInfo;
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
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 javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@SuppressWarnings("NonJaxWsWebServices")
@DeviceType(value = "doormanager")
@API(name = "doormanager_mgt", version = "1.0.0", context = "/doormanager_mgt")
public class DoorManagerManagerService {
private static Log log = LogFactory.getLog(DoorManagerManagerService.class);
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
/**
* Generate UUID
*
* @return generated UUID
*/
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
/**
* Register new device into IoT Server
*
* @param name name of new device
* @return registration status
*/
@Path("manager/device/register")
@POST
public boolean register(@QueryParam("deviceId") String deviceId,
@QueryParam("name") String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false;
}
String owner = APIUtil.getAuthenticatedUser();
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name);
device.setType(DoorManagerConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(owner);
device.setEnrolmentInfo(enrolmentInfo);
KeyGenerationUtil.createApplicationKeys(DoorManagerConstants.DEVICE_TYPE);
TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
List<Device.Property> properties = new ArrayList<>();
Device.Property accessTokenProperty = new Device.Property();
accessTokenProperty.setName(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN);
log.warn("locker access Token :" + accessToken);
accessTokenProperty.setValue(accessToken);
Device.Property refreshTokenProperty = new Device.Property();
refreshTokenProperty.setName(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN);
refreshTokenProperty.setValue(refreshToken);
properties.add(accessTokenProperty);
properties.add(refreshTokenProperty);
device.setProperties(properties);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return added;
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} catch (AccessTokenException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
}
}
/**
* Remove installed device
*
* @param deviceId unique identifier for device
* @param response to request
*/
@Path("manager/device/remove/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId,
@Context HttpServletResponse response) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
try {
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
}
/**
* Update device name
*
* @param deviceId unique identifier for device
* @param name new name of the device
* @param response to request
* @return update status
*/
@Path("manager/device/update/{device_id}")
@POST
public boolean updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name,
@Context HttpServletResponse response) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DoorManagerConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return updated;
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage());
return false;
}
}
/**
* Get device information
*
* @param deviceId unique identifier for device
* @return device
*/
@Path("manager/device/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Device getDevice(@PathParam("device_id") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
try {
return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
} catch (DeviceManagementException ex) {
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
return null;
}
}
/**
* This will download the agent for given device type
*
* @param deviceName name of the device which is to be created
* @param sketchType name of sketch type
* @return agent archive
*/
@Path("manager/device/{sketch_type}/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return response.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (AccessTokenException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
/**
* This will give link to generated agent
*
* @param deviceName name of the device which is to be created
* @param sketchType name of sketch type
* @return link to generated agent
*/
@Path("manager/device/{sketch_type}/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
ResponsePayload responsePayload = new ResponsePayload();
responsePayload.setStatusCode(HttpStatus.SC_OK);
responsePayload.setMessageFromServer("Sending Requested sketch by type: " + sketchType +
" and id: " + zipFile.getDeviceId() + ".");
responsePayload.setResponseContent(zipFile.getDeviceId());
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
} catch (IllegalArgumentException ex) {
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(ex.getMessage()).build();
} catch (DeviceManagementException ex) {
log.error("Error occurred while creating device with name " + deviceName + "\n", ex);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
} catch (AccessTokenException ex) {
log.error(ex.getMessage(), ex);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
log.error(ex.getMessage(), ex);
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
}
}
/**
* This will give link to generated agent
*
* @param deviceName name of the device which is to be created
* @param sketchType name of sketch type
* @return link to generated agent
*/
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
throws DeviceManagementException, AccessTokenException, DeviceControllerException {
if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
KeyGenerationUtil.createApplicationKeys(DoorManagerConstants.DEVICE_TYPE);
TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
//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.getTenantDomainOfUser(), sketchType,
deviceId, deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
}

@ -1,34 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ 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 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>

@ -1,38 +0,0 @@
<?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="DoorManager" address="/">
<jaxrs:serviceBeans>
<bean id="DoorManagerService"
class="org.homeautomation.doormanager.manager.api.DoorManagerManagerService">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
</beans>

@ -1,66 +0,0 @@
<?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.
-->
<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>Sample-Webapp-Manager</display-name>
<servlet>
<description>JAX-WS/JAX-RS 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>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>false</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>/doormanager/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>doormanager</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
</web-app>

@ -23,7 +23,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAO;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAOUtil;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.*;
@ -39,7 +39,7 @@ import java.util.List;
public class DoorManager implements DeviceManager {
private static final Log log = LogFactory.getLog(DoorManager.class);
private static final DoorManagerDAO DOOR_MANAGER_DAO = new DoorManagerDAO();
private static final DoorManagerDAOUtil DOOR_MANAGER_DAO = new DoorManagerDAOUtil();
private PrivilegedCarbonContext ctx;
@Override
@ -65,12 +65,12 @@ public class DoorManager implements DeviceManager {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new Automatic Door Locker device : " + device.getDeviceIdentifier());
}
DoorManagerDAO.beginTransaction();
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().addDevice(device);
DoorManagerDAO.commitTransaction();
DoorManagerDAOUtil.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAO.rollbackTransaction();
DoorManagerDAOUtil.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
e1.printStackTrace();
}
@ -88,12 +88,12 @@ public class DoorManager implements DeviceManager {
if (log.isDebugEnabled()) {
log.debug("Modifying the Automatic Door Locker device enrollment data");
}
DoorManagerDAO.beginTransaction();
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().updateDevice(device);
DoorManagerDAO.commitTransaction();
DoorManagerDAOUtil.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAO.rollbackTransaction();
DoorManagerDAOUtil.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
e1.printStackTrace();
}
@ -112,12 +112,12 @@ public class DoorManager implements DeviceManager {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling Automatic Door Locker device : " + deviceId);
}
DoorManagerDAO.beginTransaction();
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().deleteDevice(deviceId.getId());
DoorManagerDAO.commitTransaction();
DoorManagerDAOUtil.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAO.rollbackTransaction();
DoorManagerDAOUtil.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
e1.printStackTrace();
}
@ -215,12 +215,12 @@ public class DoorManager implements DeviceManager {
log.debug(
"updating the details of Automatic Door Locker device : " + deviceIdentifier);
}
DoorManagerDAO.beginTransaction();
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().updateDevice(device);
DoorManagerDAO.commitTransaction();
DoorManagerDAOUtil.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAO.rollbackTransaction();
DoorManagerDAOUtil.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
@ -267,27 +267,16 @@ public class DoorManager implements DeviceManager {
return realmService.getTenantUserRealm(ctx.getTenantId()).getUserStoreManager();
}
/**
* Ends tenant flow.
*/
private void endTenantFlow() {
PrivilegedCarbonContext.endTenantFlow();
ctx = null;
if (log.isDebugEnabled()) {
log.debug("Tenant flow ended");
}
}
public boolean assignUserToLock(DoorLockSafe doorLockSafe) throws DoorManagerDeviceMgtPluginException {
boolean status;
try {
DoorManagerDAO.beginTransaction();
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().registerDoorLockSafe(doorLockSafe);
DoorManagerDAO.commitTransaction();
DoorManagerDAOUtil.commitTransaction();
return status;
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAO.rollbackTransaction();
DoorManagerDAOUtil.rollbackTransaction();
throw new DoorManagerDeviceMgtPluginException(e);
} catch (DoorManagerDeviceMgtPluginException e1) {
String msg = "Error while adding new access card to user to control the lock "
@ -301,9 +290,9 @@ public class DoorManager implements DeviceManager {
public boolean checkCardDoorAssociation(String cardNumber, String deviceId)
throws DoorManagerDeviceMgtPluginException {
boolean status;
DoorManagerDAO.beginTransaction();
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().checkCardDoorAssociation(cardNumber, deviceId);
DoorManagerDAO.commitTransaction();
DoorManagerDAOUtil.commitTransaction();
return status;
}

@ -49,11 +49,6 @@ public class DoorManagerService implements DeviceManagementService {
return true;
}
@Override
public String[] getSharedTenantsDomain() {
return new String[0];
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager = new DoorManager();

@ -22,7 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.dao.impl.DoorManagerDAOImpl;
import org.homeautomation.doormanager.plugin.impl.dao.impl.DoorManagerDAO;
import javax.naming.Context;
import javax.naming.InitialContext;
@ -31,13 +31,13 @@ import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DoorManagerDAO {
public class DoorManagerDAOUtil {
private static final Log log = LogFactory.getLog(DoorManagerDAO.class);
private static final Log log = LogFactory.getLog(DoorManagerDAOUtil.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public DoorManagerDAO() {
public DoorManagerDAOUtil() {
initAutomaticDoorLOckerDAO();
}
@ -126,7 +126,7 @@ public class DoorManagerDAO {
}
}
public DoorManagerDAOImpl getAutomaticDoorLockerDeviceDAO() {
return new DoorManagerDAOImpl();
public DoorManagerDAO getAutomaticDoorLockerDeviceDAO() {
return new DoorManagerDAO();
}
}

@ -23,7 +23,7 @@ import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAO;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAOUtil;
import org.homeautomation.doormanager.plugin.impl.dao.util.DoorManagerUtils;
import org.wso2.carbon.device.mgt.common.Device;
@ -37,10 +37,10 @@ import java.util.List;
/**
* Device Dao for automatic door locker Devices.
*/
public class DoorManagerDAOImpl {
public class DoorManagerDAO {
private static final Log log = LogFactory.getLog(DoorManagerDAOImpl.class);
private static final Log log = LogFactory.getLog(DoorManagerDAO.class);
public Device getDevice(String deviceId) throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
@ -48,7 +48,7 @@ public class DoorManagerDAOImpl {
Device automaticDoorLockerDevice = null;
ResultSet resultSet = null;
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String selectDBQuery =
"SELECT doormanager_DEVICE_ID, DEVICE_NAME" +
" FROM doormanager_DEVICE WHERE doormanager_DEVICE_ID = ?";
@ -72,7 +72,7 @@ public class DoorManagerDAOImpl {
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAO.closeConnection();
DoorManagerDAOUtil.closeConnection();
}
return automaticDoorLockerDevice;
}
@ -83,7 +83,7 @@ public class DoorManagerDAOImpl {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String createDBQuery =
"INSERT INTO doormanager_DEVICE(doormanager_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?)";
@ -120,7 +120,7 @@ public class DoorManagerDAOImpl {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String createDBQuery =
"INSERT INTO REGISTERED_DOORLOCK_SAFE(doormanager_DEVICE_ID, SERIAL_NUMBER, UID_of_USER, POLICY, " +
"EMAIL_ADDRESS, ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?, ?, ?, ?)";
@ -157,7 +157,7 @@ public class DoorManagerDAOImpl {
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String selectDBQuery =
"SELECT SERIAL_NUMBER FROM REGISTERED_DOORLOCK_SAFE WHERE SERIAL_NUMBER = ? AND doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
@ -178,7 +178,7 @@ public class DoorManagerDAOImpl {
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAO.closeConnection();
DoorManagerDAOUtil.closeConnection();
}
}
@ -188,7 +188,7 @@ public class DoorManagerDAOImpl {
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String selectDBQuery =
"SELECT UID_OF_USER FROM REGISTERED_DOORLOCK_SAFE WHERE SERIAL_NUMBER = ? AND DOORMANAGER_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
@ -221,7 +221,7 @@ public class DoorManagerDAOImpl {
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAO.closeConnection();
DoorManagerDAOUtil.closeConnection();
}
}
@ -232,7 +232,7 @@ public class DoorManagerDAOImpl {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String createDBQuery =
"INSERT INTO SHARED_DOORLOCK_SAFE(doormanager_DEVICE_ID, SERIAL_NUMBER, UID_of_USER, POLICY) VALUES (?, ?, ?, ?)";
stmt = conn.prepareStatement(createDBQuery);
@ -264,7 +264,7 @@ public class DoorManagerDAOImpl {
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String selectDBQuery = "SELECT * FROM REGISTERED_DOORLOCK_SAFE WHERE UID_of_USER = ? AND doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, cardNum);
@ -291,7 +291,7 @@ public class DoorManagerDAOImpl {
ResultSet resultSet = null;
String email;
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String selectDBQuery = "SELECT EMAIL_ADDRESS FROM REGISTERED_DOORLOCK_SAFE WHERE UID_of_USER = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, cardNum);
@ -317,7 +317,7 @@ public class DoorManagerDAOImpl {
ResultSet resultSet = null;
List<String> userCredentials = new ArrayList<>();
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String selectDBQuery =
"SELECT ACCESS_TOKEN, REFRESH_TOKEN FROM REGISTERED_DOORLOCK_SAFE WHERE DOORMANAGER_DEVICE_ID = ? AND UID_OF_USER = ?";
stmt = conn.prepareStatement(selectDBQuery);
@ -342,7 +342,7 @@ public class DoorManagerDAOImpl {
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAO.closeConnection();
DoorManagerDAOUtil.closeConnection();
}
}
@ -354,7 +354,7 @@ public class DoorManagerDAOImpl {
ResultSet resultSet = null;
List<String> doorLockSafes = new ArrayList<>();
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String selectDBQuery =
"SELECT SERIAL_NUMBER FROM REGISTERED_DOORLOCK_SAFE WHERE doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
@ -373,7 +373,7 @@ public class DoorManagerDAOImpl {
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAO.closeConnection();
DoorManagerDAOUtil.closeConnection();
}
}
@ -382,7 +382,7 @@ public class DoorManagerDAOImpl {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String updateDBQuery =
"UPDATE doormanager_DEVICE SET DEVICE_NAME = ? WHERE doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
@ -415,7 +415,7 @@ public class DoorManagerDAOImpl {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String deleteDBQuery =
"DELETE FROM doormanager_DEVICE WHERE doormanager_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
@ -446,7 +446,7 @@ public class DoorManagerDAOImpl {
Device connectedCupDevice;
List<Device> iotDevices = new ArrayList<>();
try {
conn = DoorManagerDAO.getConnection();
conn = DoorManagerDAOUtil.getConnection();
String selectDBQuery =
"SELECT doormanager_DEVICE_ID, DEVICE_NAME FROM doormanager_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
@ -468,7 +468,7 @@ public class DoorManagerDAOImpl {
throw new DoorManagerDeviceMgtPluginException(msg, e);
} finally {
DoorManagerUtils.cleanupResources(stmt, resultSet);
DoorManagerDAO.closeConnection();
DoorManagerDAOUtil.closeConnection();
}
}
}

@ -47,236 +47,9 @@
</plugins>
</pluginManagement>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId>
<version>1.0.0-SNAPSHOT</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.iot.device.mgt.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</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.analytics_${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>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</groupId>
<artifactId>org.wso2.carbon.user.core</artifactId>
<version>${carbon.kernel.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.user.core_${carbon.kernel.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>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>plugin</module>
<module>controller</module>
<module>manager</module>
<module>api</module>
<module>analytics</module>
<module>ui</module>
</modules>

@ -38,13 +38,7 @@
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.manager</artifactId>
<version>1.0.0-SNAPSHOT</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.controller</artifactId>
<artifactId>${project-base-package}.api</artifactId>
<version>1.0.0-SNAPSHOT</version>
<type>war</type>
</dependency>
@ -120,28 +114,7 @@
</configuration>
</execution>
<execution>
<id>copy-jaxrs-manager-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.manager</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps/
</outputDirectory>
<destFileName>doormanager_mgt.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-controller-war</id>
<id>copy-jaxrs-api-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
@ -150,7 +123,7 @@
<artifactItems>
<artifactItem>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.controller</artifactId>
<artifactId>${project-base-package}.api</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
@ -213,7 +186,7 @@
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:true</propertyDef>
</properties>
</adviceFile>
<bundles>

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

Loading…
Cancel
Save