changed source code according to new API changes

application-manager-new
GPrathap 9 years ago
parent 4f6ab8f6f6
commit 70fcea507d

@ -1,3 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~ ~

@ -1,3 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--/* <!--/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
@ -24,10 +25,10 @@
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>${artifactId}</artifactId> <artifactId>${project-base-package}.analytics</artifactId>
<version>${version}</version> <version>${version}</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name> ${artifactId} </name> <name> ${project-base-package}.analytics</name>
<url>http://wso2.org</url> <url>http://wso2.org</url>
<build> <build>
<plugins> <plugins>

@ -1,21 +1,24 @@
<!--/* <?xml version="1.0" encoding="UTF-8"?>
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. <!--
* ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License, ~
* Version 2.0 (the "License"); you may not use this file except ~ WSO2 Inc. licenses this file to you under the Apache License,
* in compliance with the License. ~ Version 2.0 (the "License"); you may not use this file except
* You may obtain a copy of the License at ~ in compliance with the License.
* ~ You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 ~
* ~ 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 ~ Unless required by applicable law or agreed to in writing,
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ software distributed under the License is distributed on an
* KIND, either express or implied. See the License for the ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* specific language governing permissions and limitations ~ KIND, either express or implied. See the License for the
* under the License. ~ 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" -->
<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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<groupId>${groupId}</groupId> <groupId>${groupId}</groupId>
@ -24,10 +27,10 @@
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>${artifactId}</artifactId> <artifactId>${project-base-package}.controller</artifactId>
<version>${version}</version> <version>${version}</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>${artifactId}</name> <name>${project-base-package}.controller</name>
<url>http://wso2.com</url> <url>http://wso2.com</url>
<build> <build>
<plugins> <plugins>
@ -37,15 +40,15 @@
<version>${maven-compiler-plugin.version}</version> <version>${maven-compiler-plugin.version}</version>
<configuration> <configuration>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source> <source>${maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target> <target>${maven.compiler.target}</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version> <version>${maven-war-plugin.version}</version>
<configuration> <configuration>
<warName>${artifactId}</warName> <warName>${project-base-package}.controller</warName>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

@ -1,4 +1,3 @@
package ${groupId}.${rootArtifactId}.controller.api.util;
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
@ -16,6 +15,9 @@ package ${groupId}.${rootArtifactId}.controller.api.util;
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package ${groupId}.${rootArtifactId}.controller.api.util;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants;
@ -25,14 +27,11 @@ import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
public class ServiceUtils { public class ServiceUtils {
private static final Log log = LogFactory.getLog(ServiceUtils.class); private static final Log log = LogFactory.getLog(ServiceUtils.class);
//TODO; replace this tenant domain
private static final String SUPER_TENANT = "carbon.super";
private static final String SENSOR_STREAM_DEFINITION = "org.wso2.iot.devices.${nameOfTheSensor}"; private static final String SENSOR_STREAM_DEFINITION = "org.wso2.iot.devices.${nameOfTheSensor}";
private static final String SENSOR_STREAM_VERSION = "1.0.0"; private static final String SENSOR_STREAM_VERSION = "1.0.0";
/** /**
* sensor data are published to DAS * Sensor data are published to DAS
* @param owner name of device owner * @param owner name of device owner
* @param deviceId unique identifier of the device * @param deviceId unique identifier of the device
* @param sensorValue current value of sensor which is set at agent side * @param sensorValue current value of sensor which is set at agent side
@ -41,7 +40,10 @@ public class ServiceUtils {
public static boolean publishToDASSensorValue(String owner, String deviceId, float sensorValue) { public static boolean publishToDASSensorValue(String owner, String deviceId, float sensorValue) {
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true); ctx.setUsername(owner);
if (ctx.getTenantDomain(true) == null) {
ctx.setTenantDomain("carbon.super", true);
}
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null); DeviceAnalyticsService.class, null);
Object metdaData[] = {owner, DeviceTypeConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object metdaData[] = {owner, DeviceTypeConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};

@ -1,5 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~ ~
@ -18,9 +17,9 @@
~ under the License. ~ under the License.
--> -->
<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation=" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~ ~
@ -16,6 +17,7 @@
~ specific language governing permissions and limitations ~ specific language governing permissions and limitations
~ under the License. ~ under the License.
--> -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

@ -1,4 +1,4 @@
package ${groupId}.${rootArtifactId}.manager.api;
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
@ -16,17 +16,25 @@ package ${groupId}.${rootArtifactId}.manager.api;
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package ${groupId}.${rootArtifactId}.manager.api;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants;
import ${groupId}.${rootArtifactId}.manager.api.util.APIUtil;
import ${groupId}.${rootArtifactId}.manager.api.util.ResponsePayload;
import org.wso2.carbon.apimgt.annotations.device.DeviceType; import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil; import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo; 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.apimgt.TokenClient;
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException; import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
@ -35,45 +43,49 @@ import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*; 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.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
@SuppressWarnings("NonJaxWsWebServices")
@DeviceType(value = "${deviceType}") @DeviceType(value = "${deviceType}")
public class ManagerService { public class ManagerService {
private static Log log = LogFactory.getLog(ManagerService.class); private static Log log = LogFactory.getLog(ManagerService.class);
//TODO; replace this tenant domain
private final String SUPER_TENANT = "carbon.super";
@Context //injected response proxy supporting multiple thread @Context //injected response proxy supporting multiple thread
private HttpServletResponse response; private HttpServletResponse response;
/** /**
* Register new devcie into IoTS * Register new device into IoT Server
*
* @param deviceId unique identifier for device * @param deviceId unique identifier for device
* @param name name of new device * @param name name of new device
* @param owner owner of the device * @return registration status
* @return
*/ */
@Path("manager/device/register") @Path("manager/device/register")
@PUT @PUT
public boolean register(@QueryParam("deviceId") String deviceId, public boolean register(@QueryParam("deviceId") String deviceId,
@QueryParam("name") String name, @QueryParam("owner") String owner) { @QueryParam("name") String name) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
try { try {
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode()); response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false; return false;
} }
String owner = APIUtil.getAuthenticatedUser();
Device device = new Device(); Device device = new Device();
device.setDeviceIdentifier(deviceId); device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
@ -84,7 +96,25 @@ public class ManagerService {
device.setType(DeviceTypeConstants.DEVICE_TYPE); device.setType(DeviceTypeConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(owner); enrolmentInfo.setOwner(owner);
device.setEnrolmentInfo(enrolmentInfo); device.setEnrolmentInfo(enrolmentInfo);
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); KeyGenerationUtil.createApplicationKeys(DeviceTypeConstants.DEVICE_TYPE);
TokenClient accessTokenClient = new TokenClient(DeviceTypeConstants.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 = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) { if (added) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
} else { } else {
@ -93,27 +123,30 @@ public class ManagerService {
return added; return added;
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getErrorMessage(), e);
return false;
} catch (AccessTokenException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error("Unable to obtain access token", e);
return false; return false;
} finally {
deviceManagement.endTenantFlow();
} }
} }
/** /**
* Remove installed device * Remove installed device
*
* @param deviceId unique identifier for device * @param deviceId unique identifier for device
* @param response * @param response to request
*/ */
@Path("manager/device/remove/{device_id}") @Path("manager/device/remove/{device_id}")
@DELETE @DELETE
public void removeDevice(@PathParam("device_id") String deviceId, public void removeDevice(@PathParam("device_id") String deviceId,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
try { try {
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier); deviceIdentifier);
if (removed) { if (removed) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
@ -122,33 +155,32 @@ public class ManagerService {
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
deviceManagement.endTenantFlow();
} }
} }
/** /**
* Update device name * Update device name
*
* @param deviceId unique identifier for device * @param deviceId unique identifier for device
* @param name new name of the device * @param name new name of the device
* @param response * @param response to request
* @return * @return update status
*/ */
@Path("manager/device/update/{device_id}") @Path("manager/device/update/{device_id}")
@POST @POST
public boolean updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name, public boolean updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
try { try {
Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId); device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name); device.setName(name);
device.setType(DeviceTypeConstants.DEVICE_TYPE); device.setType(DeviceTypeConstants.DEVICE_TYPE);
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device); boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) { if (updated) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
} else { } else {
@ -158,49 +190,45 @@ public class ManagerService {
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
log.error(e.getErrorMessage()); log.error(e.getErrorMessage());
return false; return false;
} finally {
deviceManagement.endTenantFlow();
} }
} }
/** /**
* Get device information * Get device information
*
* @param deviceId unique identifier for device * @param deviceId unique identifier for device
* @return * @return device
*/ */
@Path("manager/device/{device_id}") @Path("manager/device/{device_id}")
@GET @GET
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Device getDevice(@PathParam("device_id") String deviceId) { public Device getDevice(@PathParam("device_id") String deviceId) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE); deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
try { try {
return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
} catch (DeviceManagementException ex) { } catch (DeviceManagementException ex) {
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex); log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
return null; return null;
} finally {
deviceManagement.endTenantFlow();
} }
} }
/** /**
* This will download the agent for given device type * This will download the agent for given device type
* @param owner owner of the device *
* @param deviceName name of the device which is to be created * @param deviceName name of the device which is to be created
* @param sketchType name of sketch type * @param sketchType name of sketch type
* @return * @return agent archive
*/ */
@Path("manager/device/{sketch_type}/download") @Path("manager/device/{sketch_type}/download")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response downloadSketch(@QueryParam("owner") String owner, @QueryParam("deviceName") String deviceName, public Response downloadSketch(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType) { @PathParam("sketch_type") String sketchType) {
try { try {
ZipArchive zipFile = createDownloadFile(owner, deviceName, sketchType); ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.type("application/zip"); response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
@ -218,12 +246,47 @@ public class ManagerService {
} }
} }
/**
* 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();
}
}
/** /**
* Make zip file which include all the agent source codes and configuration file * Make zip file which include all the agent source codes and configuration file
* @param owner owner of the device *
* @param owner owner of the device
* @param deviceName name of device * @param deviceName name of device
* @param sketchType name of sketch type * @param sketchType name of sketch type
* @return * @return zip archive file
* @throws DeviceManagementException * @throws DeviceManagementException
* @throws AccessTokenException * @throws AccessTokenException
* @throws DeviceControllerException * @throws DeviceControllerException
@ -234,7 +297,7 @@ public class ManagerService {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!"); throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
} }
//create new device id //create new device id
String deviceId = shortUUID(); String deviceId = APIUtil.shortUUID();
KeyGenerationUtil.createApplicationKeys(DeviceTypeConstants.DEVICE_TYPE); KeyGenerationUtil.createApplicationKeys(DeviceTypeConstants.DEVICE_TYPE);
TokenClient accessTokenClient = new TokenClient(DeviceTypeConstants.DEVICE_TYPE); TokenClient accessTokenClient = new TokenClient(DeviceTypeConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
@ -244,26 +307,15 @@ public class ManagerService {
//adding registering data //adding registering data
boolean status; boolean status;
//Register the device with CDMF //Register the device with CDMF
status = register(deviceId, deviceName, owner); status = register(deviceId, deviceName);
if (!status) { if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner; String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
ZipUtil ziputil = new ZipUtil(); ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, SUPER_TENANT, sketchType, deviceId, deviceName, accessToken, ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOfUser(), sketchType, deviceId,
refreshToken); deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId); zipFile.setDeviceId(deviceId);
return zipFile; return zipFile;
} }
/**
* Generate UUID
* @return
*/
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
} }

@ -0,0 +1,67 @@
/*
* 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 ${groupId}.${rootArtifactId}.manager.api.util;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
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 {
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 getTenantDomainOfUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
return threadLocalCarbonContext.getTenantDomain();
}
public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management service has not initialized.";
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
/**
* Generate UUID
* @return
*/
public static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
}

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

@ -0,0 +1,73 @@
<?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>/manager/device/*</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>
<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/${deviceType}/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/${deviceType}/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>
<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>
<method>DELETE</method>
<scope>emm_admin,emm_user</scope>
</Permission>
</PermissionConfiguration>

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~ ~
@ -16,11 +17,12 @@
~ specific language governing permissions and limitations ~ specific language governing permissions and limitations
~ under the License. ~ under the License.
--> -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"> version="2.5">
<display-name>Sample-Webapp-Manager</display-name> <display-name>${deviceType}-Webapp-Manager</display-name>
<servlet> <servlet>
<description>JAX-WS/JAX-RS Endpoint</description> <description>JAX-WS/JAX-RS Endpoint</description>
<display-name>JAX-WS/JAX-RS Servlet</display-name> <display-name>JAX-WS/JAX-RS Servlet</display-name>
@ -40,7 +42,7 @@
</context-param> </context-param>
<context-param> <context-param>
<param-name>doAuthentication</param-name> <param-name>doAuthentication</param-name>
<param-value>false</param-value> <param-value>true</param-value>
</context-param> </context-param>
<!--publish to apim--> <!--publish to apim-->
<context-param> <context-param>

@ -1,21 +1,24 @@
<!--/* <?xml version="1.0" encoding="UTF-8"?>
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. <!--
* ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License, ~
* Version 2.0 (the "License"); you may not use this file except ~ WSO2 Inc. licenses this file to you under the Apache License,
* in compliance with the License. ~ Version 2.0 (the "License"); you may not use this file except
* You may obtain a copy of the License at ~ in compliance with the License.
* ~ You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 ~
* ~ 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 ~ Unless required by applicable law or agreed to in writing,
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ software distributed under the License is distributed on an
* KIND, either express or implied. See the License for the ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* specific language governing permissions and limitations ~ KIND, either express or implied. See the License for the
* under the License. ~ 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" -->
<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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<groupId>${groupId}</groupId> <groupId>${groupId}</groupId>
@ -25,9 +28,9 @@
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<version>${version}</version> <version>${version}</version>
<artifactId>${artifactId}</artifactId> <artifactId>${project-base-package}.plugin</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>${artifactId}</name> <name>${project-base-package}.plugin</name>
<url>http://wso2.org</url> <url>http://wso2.org</url>
<build> <build>
<plugins> <plugins>
@ -41,8 +44,8 @@
<version>${maven-compiler-plugin.version}</version> <version>${maven-compiler-plugin.version}</version>
<configuration> <configuration>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source> <source>${maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target> <target>${maven.compiler.target}</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
@ -52,8 +55,8 @@
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<instructions> <instructions>
<Bundle-SymbolicName>${artifactId}</Bundle-SymbolicName> <Bundle-SymbolicName>${project-base-package}.plugin</Bundle-SymbolicName>
<Bundle-Name>${artifactId}</Bundle-Name> <Bundle-Name>${project-base-package}.plugin</Bundle-Name>
<Bundle-Version>${version}</Bundle-Version> <Bundle-Version>${version}</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description> <Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>${project-base-package}.plugin.internal</Private-Package> <Private-Package>${project-base-package}.plugin.internal</Private-Package>
@ -70,7 +73,7 @@
org.wso2.carbon.device.mgt.common.*, org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.context.*, org.wso2.carbon.context.*,
org.wso2.carbon.ndatasource.core, org.wso2.carbon.ndatasource.core,
org.wso2.carbon.device.mgt.iot.*, org.wso2.carbon.device.mgt.iot.*
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
!${project-base-package}.plugin.internal, !${project-base-package}.plugin.internal,

@ -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 ${groupId}.${rootArtifactId}.plugin.exception;
public class DeviceTypePluginException extends Exception {
private String errorMessage;
public DeviceTypePluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DeviceTypePluginException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public DeviceTypePluginException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DeviceTypePluginException() {
super();
}
public DeviceTypePluginException(Throwable cause) {
super(cause);
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -18,18 +18,20 @@
package ${groupId}.${rootArtifactId}.plugin.impl; package ${groupId}.${rootArtifactId}.plugin.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import ${groupId}.${rootArtifactId}.plugin.impl.dao.DeviceTypeDAO; import ${groupId}.${rootArtifactId}.plugin.impl.dao.DeviceTypeDAO;
import ${groupId}.${rootArtifactId}.plugin.exception.DeviceTypePluginException;
import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License; 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.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.ArrayList;
import java.util.List; import java.util.List;
@ -40,9 +42,10 @@ import java.util.List;
*/ */
public class DeviceTypeManager implements DeviceManager { public class DeviceTypeManager implements DeviceManager {
private static final IotDeviceManagementDAOFactoryInterface iotDeviceManagementDAOFactory = new DeviceTypeDAO();
private static final Log log = LogFactory.getLog(DeviceTypeManager.class); private static final Log log = LogFactory.getLog(DeviceTypeManager.class);
private static final DeviceTypeDAO deviceTypeDAO = new DeviceTypeDAO();
@Override @Override
public FeatureManager getFeatureManager() { public FeatureManager getFeatureManager() {
return null; return null;
@ -64,18 +67,17 @@ public class DeviceTypeManager implements DeviceManager {
@Override @Override
public boolean enrollDevice(Device device) throws DeviceManagementException { public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status; boolean status;
IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device);
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Enrolling a new ${rootArtifactId} device : " + device.getDeviceIdentifier()); log.debug("Enrolling a new ${rootArtifactId} device : " + device.getDeviceIdentifier());
} }
DeviceTypeDAO.beginTransaction(); DeviceTypeDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice(iotDevice); status = deviceTypeDAO.getDeviceTypeDAO().addDevice(device);
DeviceTypeDAO.commitTransaction(); DeviceTypeDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) { } catch (DeviceTypePluginException e) {
try { try {
DeviceTypeDAO.rollbackTransaction(); DeviceTypeDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) { } catch (DeviceTypePluginException iotDAOEx) {
log.warn("Error occurred while roll back the device enrol transaction :" + device.toString(), iotDAOEx); log.warn("Error occurred while roll back the device enrol transaction :" + device.toString(), iotDAOEx);
} }
String msg = "Error while enrolling the ${rootArtifactId} device : " + device.getDeviceIdentifier(); String msg = "Error while enrolling the ${rootArtifactId} device : " + device.getDeviceIdentifier();
@ -88,19 +90,17 @@ public class DeviceTypeManager implements DeviceManager {
@Override @Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException { public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status; boolean status;
IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device);
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Modifying the ${rootArtifactId} device enrollment data"); log.debug("Modifying the ${rootArtifactId} device enrollment data");
} }
DeviceTypeDAO.beginTransaction(); DeviceTypeDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO() status = deviceTypeDAO.getDeviceTypeDAO().updateDevice(device);
.updateIotDevice(iotDevice);
DeviceTypeDAO.commitTransaction(); DeviceTypeDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) { } catch (DeviceTypePluginException e) {
try { try {
DeviceTypeDAO.rollbackTransaction(); DeviceTypeDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) { } catch (DeviceTypePluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString(); String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx); log.warn(msg, iotDAOEx);
} }
@ -120,13 +120,12 @@ public class DeviceTypeManager implements DeviceManager {
log.debug("Dis-enrolling ${rootArtifactId} device : " + deviceId); log.debug("Dis-enrolling ${rootArtifactId} device : " + deviceId);
} }
DeviceTypeDAO.beginTransaction(); DeviceTypeDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO() status = deviceTypeDAO.getDeviceTypeDAO().deleteDevice(deviceId.getId());
.deleteIotDevice(deviceId.getId());
DeviceTypeDAO.commitTransaction(); DeviceTypeDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) { } catch (DeviceTypePluginException e) {
try { try {
DeviceTypeDAO.rollbackTransaction(); DeviceTypeDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) { } catch (DeviceTypePluginException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString(); String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx); log.warn(msg, iotDAOEx);
} }
@ -144,13 +143,12 @@ public class DeviceTypeManager implements DeviceManager {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of ${rootArtifactId} device : " + deviceId.getId()); log.debug("Checking the enrollment of ${rootArtifactId} device : " + deviceId.getId());
} }
IotDevice iotDevice = Device iotDevice =
iotDeviceManagementDAOFactory.getIotDeviceDAO().getIotDevice( deviceTypeDAO.getDeviceTypeDAO().getDevice(deviceId.getId());
deviceId.getId());
if (iotDevice != null) { if (iotDevice != null) {
isEnrolled = true; isEnrolled = true;
} }
} catch (IotDeviceManagementDAOException e) { } catch (DeviceTypePluginException e) {
String msg = "Error while checking the enrollment status of ${rootArtifactId} device : " + String msg = "Error while checking the enrollment status of ${rootArtifactId} device : " +
deviceId.getId(); deviceId.getId();
log.error(msg, e); log.error(msg, e);
@ -177,10 +175,8 @@ public class DeviceTypeManager implements DeviceManager {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting the details of ${rootArtifactId} device : " + deviceId.getId()); log.debug("Getting the details of ${rootArtifactId} device : " + deviceId.getId());
} }
IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO(). device = deviceTypeDAO.getDeviceTypeDAO().getDevice(deviceId.getId());
getIotDevice(deviceId.getId()); } catch (DeviceTypePluginException e) {
device = IotDeviceManagementUtil.convertToDevice(iotDevice);
} catch (IotDeviceManagementDAOException e) {
String msg = "Error while fetching the ${rootArtifactId} device : " + deviceId.getId(); String msg = "Error while fetching the ${rootArtifactId} device : " + deviceId.getId();
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
@ -222,19 +218,17 @@ public class DeviceTypeManager implements DeviceManager {
@Override @Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException { public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
boolean status; boolean status;
IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device);
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("updating the details of ${rootArtifactId} device : " + deviceIdentifier); log.debug("updating the details of ${rootArtifactId} device : " + deviceIdentifier);
} }
DeviceTypeDAO.beginTransaction(); DeviceTypeDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO() status = deviceTypeDAO.getDeviceTypeDAO().updateDevice(device);
.updateIotDevice(iotDevice);
DeviceTypeDAO.commitTransaction(); DeviceTypeDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) { } catch (DeviceTypePluginException e) {
try { try {
DeviceTypeDAO.rollbackTransaction(); DeviceTypeDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) { } catch (DeviceTypePluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString(); String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx); log.warn(msg, iotDAOEx);
} }
@ -248,20 +242,13 @@ public class DeviceTypeManager implements DeviceManager {
@Override @Override
public List<Device> getAllDevices() throws DeviceManagementException { public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices = null; List<Device> devices;
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Fetching the details of all ${rootArtifactId} devices"); log.debug("Fetching the details of all ${rootArtifactId} devices");
} }
List<IotDevice> iotDevices = devices = deviceTypeDAO.getDeviceTypeDAO().getAllDevices();
iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices(); } catch (DeviceTypePluginException e) {
if (iotDevices != null) {
devices = new ArrayList<Device>();
for (IotDevice iotDevice : iotDevices) {
devices.add(IotDeviceManagementUtil.convertToDevice(iotDevice));
}
}
} catch (IotDeviceManagementDAOException e) {
String msg = "Error while fetching all ${rootArtifactId} devices."; String msg = "Error while fetching all ${rootArtifactId} devices.";
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);

@ -1,4 +1,3 @@
package ${groupId}.${rootArtifactId}.plugin.impl;
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
@ -16,6 +15,9 @@ package ${groupId}.${rootArtifactId}.plugin.impl;
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package ${groupId}.${rootArtifactId}.plugin.impl;
import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
@ -53,7 +55,7 @@ public class DeviceTypeManagerService implements DeviceManagementService{
@Override @Override
public void init() throws DeviceManagementException { public void init() throws DeviceManagementException {
deviceManager= new DeviceTypeManager(); this.deviceManager = new DeviceTypeManager();
} }
@Override @Override
@ -67,7 +69,7 @@ public class DeviceTypeManagerService implements DeviceManagementService{
} }
@Override @Override
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> list) throws public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> deviceIds) throws
DeviceManagementException { DeviceManagementException {
} }
@ -90,17 +92,19 @@ public class DeviceTypeManagerService implements DeviceManagementService{
} }
@Override @Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> list) public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> deviceIdentifiers)
throws ApplicationManagementException { throws ApplicationManagementException {
} }
@Override @Override
public void installApplicationForUsers(Operation operation, List<String> list) public void installApplicationForUsers(Operation operation, List<String> userNameList)
throws ApplicationManagementException { throws ApplicationManagementException {
} }
@Override @Override
public void installApplicationForUserRoles(Operation operation, List<String> list) public void installApplicationForUserRoles(Operation operation, List<String> userRoleList)
throws ApplicationManagementException { throws ApplicationManagementException {
} }
} }

@ -1,4 +1,3 @@
package ${groupId}.${rootArtifactId}.plugin.impl.dao;
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
@ -17,14 +16,13 @@ package ${groupId}.${rootArtifactId}.plugin.impl.dao;
* under the License. * under the License.
*/ */
package ${groupId}.${rootArtifactId}.plugin.impl.dao;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants;
import ${groupId}.${rootArtifactId}.plugin.impl.dao.impl.DeviceTypeDAOImpl; import ${groupId}.${rootArtifactId}.plugin.impl.dao.impl.DeviceTypeDAOImpl;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceDAO; import ${groupId}.${rootArtifactId}.plugin.exception.DeviceTypePluginException;
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 javax.naming.Context; import javax.naming.Context;
@ -34,19 +32,17 @@ import javax.sql.DataSource;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
public class DeviceTypeDAO extends IotDeviceManagementDAOFactory public class DeviceTypeDAO{
implements IotDeviceManagementDAOFactoryInterface {
private static final Log log = LogFactory.getLog(DeviceTypeDAO.class); private static final Log log = LogFactory.getLog(DeviceTypeDAO.class);
static DataSource dataSource; // package local variable static DataSource dataSource; // package local variable
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>(); private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
public DeviceTypeDAO() { public DeviceTypeDAO() {
initDeviceTypeDAO(); initDeviceTypeDAO();
} }
@Override public DeviceTypeDAOImpl getDeviceTypeDAO() {
public IotDeviceDAO getIotDeviceDAO() {
return new DeviceTypeDAOImpl(); return new DeviceTypeDAOImpl();
} }
@ -60,29 +56,29 @@ public class DeviceTypeDAO extends IotDeviceManagementDAOFactory
} }
} }
public static void beginTransaction() throws IotDeviceManagementDAOException { public static void beginTransaction() throws DeviceTypePluginException {
try { try {
Connection conn = dataSource.getConnection(); Connection conn = dataSource.getConnection();
conn.setAutoCommit(false); conn.setAutoCommit(false);
currentConnection.set(conn); currentConnection.set(conn);
} catch (SQLException e) { } catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while retrieving datasource connection", e); throw new DeviceTypePluginException("Error occurred while retrieving datasource connection", e);
} }
} }
public static Connection getConnection() throws IotDeviceManagementDAOException { public static Connection getConnection() throws DeviceTypePluginException {
if (currentConnection.get() == null) { if (currentConnection.get() == null) {
try { try {
currentConnection.set(dataSource.getConnection()); currentConnection.set(dataSource.getConnection());
} catch (SQLException e) { } catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", throw new DeviceTypePluginException("Error occurred while retrieving data source connection",
e); e);
} }
} }
return currentConnection.get(); return currentConnection.get();
} }
public static void commitTransaction() throws IotDeviceManagementDAOException { public static void commitTransaction() throws DeviceTypePluginException {
try { try {
Connection conn = currentConnection.get(); Connection conn = currentConnection.get();
if (conn != null) { if (conn != null) {
@ -94,13 +90,13 @@ public class DeviceTypeDAO extends IotDeviceManagementDAOFactory
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while committing the transaction", e); throw new DeviceTypePluginException("Error occurred while committing the transaction", e);
} finally { } finally {
closeConnection(); closeConnection();
} }
} }
public static void closeConnection() throws IotDeviceManagementDAOException { public static void closeConnection() throws DeviceTypePluginException {
Connection con = currentConnection.get(); Connection con = currentConnection.get();
if(con != null){ if(con != null){
@ -113,7 +109,7 @@ public class DeviceTypeDAO extends IotDeviceManagementDAOFactory
currentConnection.remove(); currentConnection.remove();
} }
public static void rollbackTransaction() throws IotDeviceManagementDAOException { public static void rollbackTransaction() throws DeviceTypePluginException {
try { try {
Connection conn = currentConnection.get(); Connection conn = currentConnection.get();
if (conn != null) { if (conn != null) {
@ -125,7 +121,7 @@ public class DeviceTypeDAO extends IotDeviceManagementDAOFactory
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while rollback the transaction", e); throw new DeviceTypePluginException("Error occurred while rollback the transaction", e);
} finally { } finally {
closeConnection(); closeConnection();
} }

@ -21,11 +21,11 @@ package ${groupId}.${rootArtifactId}.plugin.impl.dao.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants;
import ${groupId}.${rootArtifactId}.plugin.exception.DeviceTypePluginException;
import ${groupId}.${rootArtifactId}.plugin.impl.dao.DeviceTypeDAO; import ${groupId}.${rootArtifactId}.plugin.impl.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceDAO; import ${groupId}.${rootArtifactId}.plugin.impl.dao.util.DeviceTypeUtils;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException; import org.wso2.carbon.device.mgt.common.Device;
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.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -38,175 +38,157 @@ import java.util.Map;
/** /**
* Implements IotDeviceDAO for ${deviceType} Devices. * Implements IotDeviceDAO for ${deviceType} Devices.
*/ */
public class DeviceTypeDAOImpl implements IotDeviceDAO { public class DeviceTypeDAOImpl {
private static final Log log = LogFactory.getLog(DeviceTypeDAOImpl.class); private static final Log log = LogFactory.getLog(DeviceTypeDAOImpl.class);
@Override public Device getDevice(String deviceId) throws DeviceTypePluginException {
public IotDevice getIotDevice(String iotDeviceId) throws IotDeviceManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
IotDevice iotDevice = null; Device iotDevice = null;
ResultSet resultSet = null; ResultSet resultSet = null;
try { try {
conn = ${groupId}.${rootArtifactId}.plugin.impl.dao.DeviceTypeDAO.getConnection(); conn = DeviceTypeDAO.getConnection();
String selectDBQuery = String selectDBQuery =
"SELECT ${deviceType}_DEVICE_ID, DEVICE_NAME" + "SELECT ${deviceType}_DEVICE_ID, DEVICE_NAME" +
" FROM ${deviceType}_DEVICE WHERE ${deviceType}_DEVICE_ID = ?"; " FROM ${deviceType}_DEVICE WHERE ${deviceType}_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery); stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, iotDeviceId); stmt.setString(1, deviceId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
iotDevice = new IotDevice(); iotDevice = new Device();
iotDevice.setIotDeviceName(resultSet.getString( iotDevice.setName(resultSet.getString(
DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_NAME)); DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_NAME));
Map<String, String> propertyMap = new HashMap<String, String>(); List<Device.Property> propertyList = new ArrayList<>();
iotDevice.setProperties(propertyList);
iotDevice.setDeviceProperties(propertyMap);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("${deviceType} device " + iotDeviceId + " data has been fetched from " + log.debug("${deviceType} device " + deviceId + " data has been fetched from " +
"${deviceType} database."); "${deviceType} database.");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while fetching ${deviceType} device : '" + iotDeviceId + "'"; String msg = "Error occurred while fetching ${deviceType} device : '" + deviceId + "'";
log.error(msg, e); log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e); throw new DeviceTypePluginException(msg, e);
} finally { } finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); DeviceTypeUtils.cleanupResources(stmt, resultSet);
DeviceTypeDAO.closeConnection(); DeviceTypeDAO.closeConnection();
} }
return iotDevice; return iotDevice;
} }
@Override public boolean addDevice(Device device) throws DeviceTypePluginException {
public boolean addIotDevice(IotDevice iotDevice) throws IotDeviceManagementDAOException {
boolean status = false; boolean status = false;
Connection conn = null; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = ${groupId}.${rootArtifactId}.plugin.impl.dao.DeviceTypeDAO.getConnection(); conn = DeviceTypeDAO.getConnection();
String createDBQuery = String createDBQuery =
"INSERT INTO ${deviceType}_DEVICE(${deviceType}_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)"; "INSERT INTO ${deviceType}_DEVICE(${deviceType}_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery); stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, iotDevice.getIotDeviceId()); stmt.setString(1, device.getDeviceIdentifier());
stmt.setString(2, iotDevice.getIotDeviceName()); stmt.setString(2, device.getName());
if (iotDevice.getDeviceProperties() == null) {
iotDevice.setDeviceProperties(new HashMap<String, String>());
}
int rows = stmt.executeUpdate(); int rows = stmt.executeUpdate();
if (rows > 0) { if (rows > 0) {
status = true; status = true;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("${deviceType} device " + iotDevice.getIotDeviceId() + " data has been" + log.debug("${deviceType} device " + device.getDeviceIdentifier() + " data has been" +
" added to the ${deviceType} database."); " added to the ${deviceType} database.");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while adding the ${deviceType} device '" + String msg = "Error occurred while adding the ${deviceType} device '" +
iotDevice.getIotDeviceId() + "' to the ${deviceType} db."; device.getDeviceIdentifier() + "' to the ${deviceType} db.";
log.error(msg, e); log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e); throw new DeviceTypePluginException(msg, e);
} finally { } finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null); DeviceTypeUtils.cleanupResources(stmt, null);
} }
return status; return status;
} }
@Override public boolean updateDevice(Device device) throws DeviceTypePluginException {
public boolean updateIotDevice(IotDevice iotDevice) throws IotDeviceManagementDAOException {
boolean status = false; boolean status = false;
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = ${groupId}.${rootArtifactId}.plugin.impl.dao.DeviceTypeDAO.getConnection(); conn = DeviceTypeDAO.getConnection();
String updateDBQuery = String updateDBQuery =
"UPDATE ${deviceType}_DEVICE SET DEVICE_NAME = ? WHERE ${deviceType}_DEVICE_ID = ?"; "UPDATE ${deviceType}_DEVICE SET DEVICE_NAME = ? WHERE ${deviceType}_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery); stmt = conn.prepareStatement(updateDBQuery);
if (iotDevice.getDeviceProperties() == null) { if (device.getProperties() == null) {
iotDevice.setDeviceProperties(new HashMap<String, String>()); device.setProperties(new ArrayList<Device.Property>());
} }
stmt.setString(1, iotDevice.getIotDeviceName()); stmt.setString(1, device.getName());
stmt.setString(2, iotDevice.getIotDeviceId()); stmt.setString(2, device.getDeviceIdentifier());
int rows = stmt.executeUpdate(); int rows = stmt.executeUpdate();
if (rows > 0) { if (rows > 0) {
status = true; status = true;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("${deviceType} device " + iotDevice.getIotDeviceId() + " data has been" + log.debug("${deviceType} device " + device.getDeviceIdentifier() + " data has been" +
" modified."); " modified.");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while modifying the ${deviceType} device '" + String msg = "Error occurred while modifying the ${deviceType} device '" +
iotDevice.getIotDeviceId() + "' data."; device.getDeviceIdentifier() + "' data.";
log.error(msg, e); log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e); throw new DeviceTypePluginException(msg, e);
} finally { } finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null); DeviceTypeUtils.cleanupResources(stmt, null);
} }
return status; return status;
} }
@Override public boolean deleteDevice(String deviceId) throws DeviceTypePluginException {
public boolean deleteIotDevice(String iotDeviceId) throws IotDeviceManagementDAOException {
boolean status = false; boolean status = false;
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = ${groupId}.${rootArtifactId}.plugin.impl.dao.DeviceTypeDAO.getConnection(); conn = DeviceTypeDAO.getConnection();
String deleteDBQuery = String deleteDBQuery =
"DELETE FROM ${deviceType}_DEVICE WHERE ${deviceType}_DEVICE_ID = ?"; "DELETE FROM ${deviceType}_DEVICE WHERE ${deviceType}_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery); stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, iotDeviceId); stmt.setString(1, deviceId);
int rows = stmt.executeUpdate(); int rows = stmt.executeUpdate();
if (rows > 0) { if (rows > 0) {
status = true; status = true;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("${deviceType} device " + iotDeviceId + " data has deleted" + log.debug("${deviceType} device " + deviceId + " data has deleted" +
" from the ${deviceType} database."); " from the ${deviceType} database.");
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while deleting ${deviceType} device " + iotDeviceId; String msg = "Error occurred while deleting ${deviceType} device " + deviceId;
log.error(msg, e); log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e); throw new DeviceTypePluginException(msg, e);
} finally { } finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null); DeviceTypeUtils.cleanupResources(stmt, null);
} }
return status; return status;
} }
@Override public List<Device> getAllDevices() throws DeviceTypePluginException {
public List<IotDevice> getAllIotDevices() throws IotDeviceManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
IotDevice iotDevice; Device device;
List<IotDevice> iotDevices = new ArrayList<IotDevice>(); List<Device> iotDevices = new ArrayList<>();
try { try {
conn = ${groupId}.${rootArtifactId}.plugin.impl.dao.DeviceTypeDAO.getConnection(); conn = DeviceTypeDAO.getConnection();
String selectDBQuery = String selectDBQuery =
"SELECT ${deviceType}_DEVICE_ID, DEVICE_NAME " + "SELECT ${deviceType}_DEVICE_ID, DEVICE_NAME " +
"FROM ${deviceType}_DEVICE"; "FROM ${deviceType}_DEVICE";
stmt = conn.prepareStatement(selectDBQuery); stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
iotDevice = new IotDevice(); device = new Device();
iotDevice.setIotDeviceId(resultSet.getString(DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_ID)); device.setDeviceIdentifier(resultSet.getString(DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_ID));
iotDevice.setIotDeviceName(resultSet.getString(DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_NAME)); device.setName(resultSet.getString(DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_NAME));
List<Device.Property> propertyList = new ArrayList<>();
Map<String, String> propertyMap = new HashMap<String, String>(); device.setProperties(propertyList);
iotDevice.setDeviceProperties(propertyMap);
iotDevices.add(iotDevice);
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("All ${deviceType} device details have fetched from ${deviceType} database."); log.debug("All ${deviceType} device details have fetched from ${deviceType} database.");
@ -215,12 +197,10 @@ public class DeviceTypeDAOImpl implements IotDeviceDAO {
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while fetching all ${deviceType} device data'"; String msg = "Error occurred while fetching all ${deviceType} device data'";
log.error(msg, e); log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e); throw new DeviceTypePluginException(msg, e);
} finally { } finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); DeviceTypeUtils.cleanupResources(stmt, resultSet);
DeviceTypeDAO.closeConnection(); DeviceTypeDAO.closeConnection();
} }
} }
} }

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

@ -1,38 +0,0 @@
package ${groupId}.${rootArtifactId}.plugin.impl.util;
/*
* 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.
*/
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Map;
/**
* Contains utility methods used by ${rootArtifactId} plugin.
*/
public class DevicetypeUtils {
private static Log log = LogFactory.getLog(DevicetypeUtils.class);
public static String getDeviceProperty(Map<String, String> deviceProperties, String property) {
String deviceProperty = deviceProperties.get(property);
if (deviceProperty == null) {
return "";
}
return deviceProperty;
}
}

@ -25,22 +25,13 @@ import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration; import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.service.DeviceTypeService;
/** /**
* @scr.component name="${groupId}.${rootArtifactId}.plugin.internal.ServiceComponent" * @scr.component name="${groupId}.${rootArtifactId}.plugin.internal.ServiceComponent"
* immediate="true" * 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 { public class ServiceComponent {
private ServiceRegistration serviceRegistration; private ServiceRegistration serviceRegistration;
private static final Log log = LogFactory.getLog(ServiceComponent.class); private static final Log log = LogFactory.getLog(ServiceComponent.class);
@ -76,14 +67,4 @@ public class ServiceComponent {
log.error("Error occurred while de-activating Iot Device Management bundle", e); log.error("Error occurred while de-activating Iot Device Management bundle", e);
} }
} }
}
protected void setDeviceTypeService(DeviceTypeService deviceTypeService) {
if (log.isDebugEnabled()) {
log.debug("Data source service set to mobile service component");
}
}
protected void unsetDeviceTypeService(DeviceTypeService deviceTypeService) {
//do nothing
}
}

@ -1,3 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~ ~

@ -25,11 +25,12 @@
{{/zone}} {{/zone}}
{{#zone "device-thumbnail"}} {{#zone "device-thumbnail"}}
<img src="{{@unit.publicUri}}/images/current-sensor.png"/> <img src="{{@unit.publicUri}}/images/deviceType.png"/>
{{/zone}} {{/zone}}
{{#zone "operation-status"}} {{#zone "operation-status"}}
<div id="div-operation-status" class="hidden" align="center" style="padding: 10px; margin-bottom: 5px"> <div id="div-operation-status" class="hidden" align="center"
style="padding: 10px; margin-bottom: 5px">
</div> </div>
{{/zone}} {{/zone}}
@ -46,7 +47,8 @@
<div class="media"> <div class="media">
<div class="media-left col-xs-12 col-sm-2 col-md-2 col-lg-2"> <div class="media-left col-xs-12 col-sm-2 col-md-2 col-lg-2">
<li class="active"><a class="list-group-item" href="#device_statistics" role="tab" <li class="active"><a class="list-group-item" href="#device_statistics" role="tab"
data-toggle="tab" aria-controls="device_statistics">Device Statistics</a> data-toggle="tab" aria-controls="device_statistics">Device
Statistics</a>
</li> </li>
<ul class="list-group" role="tablist"> <ul class="list-group" role="tablist">
<li><a class="list-group-item" href="#policies" role="tab" <li><a class="list-group-item" href="#policies" role="tab"
@ -65,7 +67,8 @@
</div> </div>
<div class="panel panel-default tab-pane" id="policy_compliance" role="tabpanel" <div class="panel panel-default tab-pane" id="policy_compliance" role="tabpanel"
aria-labelledby="policy_compliance"> aria-labelledby="policy_compliance">
<div class="panel-heading">Policy Compliance <span><a href="#" id="refresh-policy"> <div class="panel-heading">Policy Compliance <span><a href="#"
id="refresh-policy">
<i class="fw fw-refresh"></i></a></span></div> <i class="fw fw-refresh"></i></a></span></div>
<div class="panel panel-default tab-pane" id="policies" role="tabpanel" <div class="panel panel-default tab-pane" id="policies" role="tabpanel"
aria-labelledby="policies"> aria-labelledby="policies">

@ -56,13 +56,6 @@ function showPopup() {
deviceType = this.value; deviceType = this.value;
} }
}); });
if (deviceType == 'currentsensor'){
$('.sketchType').remove();
$('input[name="sketchType"][value="currentsensor"]').prop('checked', true);
$("label[for='currentsensor']").text("Simple Agent");
}else{
$('.sketchTypes').remove();
}
} }
/* /*
@ -115,11 +108,15 @@ function attachEvents() {
doAction(data); doAction(data);
} }
); );
}else if(deviceName){ } else if (deviceName) {
$('.controls').append('<label for="deviceName" generated="true" class="error" style="display: inline-block;">Please enter at least 4 characters.</label>'); $('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">Please enter at least 4 ' +
'characters.</label>');
$('.control-group').removeClass('success').addClass('error'); $('.control-group').removeClass('success').addClass('error');
} else { } else {
$('.controls').append('<label for="deviceName" generated="true" class="error" style="display: inline-block;">This field is required.</label>'); $('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">This field is required.' +
'</label>');
$('.control-group').removeClass('success').addClass('error'); $('.control-group').removeClass('success').addClass('error');
} }
}); });
@ -127,23 +124,46 @@ function attachEvents() {
$("a#download-device-cancel-link").click(function () { $("a#download-device-cancel-link").click(function () {
hidePopup(); hidePopup();
}); });
}); });
} }
function downloadAgent() { function downloadAgent() {
$('#downloadForm').submit(); var deviceName = "";
var deviceName;
$('.new-device-name').each(function () { $('.new-device-name').each(function () {
if (this.value != "") { if (this.value != "") {
deviceName = this.value; deviceName = this.value;
} }
}); });
if (deviceName && deviceName.length >= 4) { var deviceType = "";
setTimeout(function () { $('.deviceType').each(function () {
if (this.value != "") {
deviceType = this.value;
}
});
var sketchType = "";
$('.sketchType').each(function () {
if (this.value != "") {
sketchType = this.value;
}
});
var deviceNameFormat = /^[^~?!#$:;%^*`+={}\[\]\\()|<>,'"]{1,30}$/;
if (deviceName && deviceNameFormat.test(deviceName)) {
$(modalPopupContent).html($('#device-agent-downloading-content').html());
var successCallback = function (data) {
data = JSON.parse(data);
hidePopup();
window.location = "/devicemgt/api/devices/sketch/download/" + data.responseContent;
};
var generateLink = "/" + deviceType + "_mgt/manager/device/" + sketchType
+ "/generate_link?deviceName=" + deviceName;
invokerUtil.get(generateLink, successCallback, function (message) {
console.log(message.content);
hidePopup(); hidePopup();
}, 1000); doAction(data);
});
} else {
$("#invalid-username-error-msg span").text("Invalid device name");
$("#invalid-username-error-msg").removeClass("hidden");
} }
} }
@ -153,14 +173,7 @@ function doAction(data) {
document.write(data); document.write(data);
} }
if (data.status == "200") { if (data.status == "401") {
$(modalPopupContent).html($('#download-device-modal-content-links').html());
$("input#download-device-url").val(data.responseText);
$("input#download-device-url").focus(function () {
$(this).select();
});
showPopup();
} else if (data.status == "401") {
$(modalPopupContent).html($('#device-401-content').html()); $(modalPopupContent).html($('#device-401-content').html());
$("#device-401-link").click(function () { $("#device-401-link").click(function () {
window.location = "/devicemgt/login"; window.location = "/devicemgt/login";

@ -11,7 +11,7 @@
<h3 class="uppercase">What it Does</h3> <h3 class="uppercase">What it Does</h3>
<hr> <hr>
<p class="grey margin-top">Connect your qtewttwqtttyty to WSO2 IoT Server.</p> <p class="grey margin-top">Connect your ${deviceType} to WSO2 IoT Server.</p>
<br> <br>
<p>Add brief description what this device type does</p> <p>Add brief description what this device type does</p>
<br/> <br/>
@ -30,7 +30,12 @@
<h3>Name your device and download the agent from following link.</h3> <h3>Name your device and download the agent from following link.</h3>
<br/> <br/>
<form id="downloadForm" method="GET" action="{{@app.context}}/api/devices/sketch/download"> <form id="downloadForm" method="GET"
action="#">
<div id="invalid-username-error-msg" class="alert alert-danger hidden"
role="alert">
<i class="icon fw fw-error"></i><span></span>
</div>
<div class="control-group"> <div class="control-group">
<div class="controls"> <div class="controls">
<input class="new-device-name" style="color:#3f3f3f;padding:5px" <input class="new-device-name" style="color:#3f3f3f;padding:5px"
@ -43,7 +48,8 @@
</div> </div>
</div> </div>
<div class="buttons" style="padding-bottom: 0px"> <div class="buttons" style="padding-bottom: 0px">
<a class="btn btn-operations" onclick="downloadAgent()">Download Now</a> &nbsp;&nbsp; <a class="btn btn-operations" onclick="downloadAgent()">Download Now</a>
&nbsp;&nbsp;
&nbsp;&nbsp; &nbsp;&nbsp;
</div> </div>
</form> </form>
@ -52,6 +58,16 @@
</div> </div>
</div> </div>
<div id="device-agent-downloading-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Agent will download shortly.</h3>
</div>
</div>
</div>
</div>
<div id="download-device-modal-content-links" class="hide"> <div id="download-device-modal-content-links" class="hide">
<div class="modal-content"> <div class="modal-content">
<div class="row"> <div class="row">
@ -159,7 +175,7 @@
<hr> <hr>
<ul class="list-unstyled"> <ul class="list-unstyled">
<li class="padding-top-double"><span class="circle">01</span>&nbsp;&nbsp;&nbsp;Add how you are goining to <li class="padding-top-double"><span class="circle">01</span>&nbsp;&nbsp;&nbsp;Add how you are goining to
prepeya your device prepare your device
</li> </li>
</ul> </ul>
<br> <br>
@ -168,6 +184,7 @@
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double"> <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
<h3 class="uppercase">${deviceType} Setup</h3> <h3 class="uppercase">${deviceType} Setup</h3>
<hr> <hr>
<p class="grey margin-top">Add schematic diagram of this device type</p></br>
<p class="grey margin-top">Click on the image to zoom</p> <p class="grey margin-top">Click on the image to zoom</p>
<center> <center>
<a href="{{@unit.publicUri}}/images/schematicsGuide.png" target="_blank"> <a href="{{@unit.publicUri}}/images/schematicsGuide.png" target="_blank">
@ -189,18 +206,11 @@
page. page.
</li> </li>
<li class="padding-top-double"><span class="circle">02</span>&nbsp;&nbsp;&nbsp;Select one of <li class="padding-top-double"><span class="circle">02</span>&nbsp;&nbsp;&nbsp;Select one of
connected devices and check for available control operations.</li> connected devices and check for available control operations.
</li>
</ul> </ul>
<br/> <br/>
</div>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@unit.publicUri}}/images/myDevices_analytics.png" target="_blank">
<img src="{{@unit.publicUri}}/images/myDevices_analytics.png" class="img-responsive">
</a>
</center>
</div>
<style type="text/css"> <style type="text/css">
.circle { .circle {

Loading…
Cancel
Save