changed source code according to new API changes

merge-requests/1/head
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.
~

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

@ -1,21 +1,24 @@
<!--/*
* 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"
<?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: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>${groupId}</groupId>
@ -24,10 +27,10 @@
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${artifactId}</artifactId>
<artifactId>${project-base-package}.controller</artifactId>
<version>${version}</version>
<packaging>war</packaging>
<name>${artifactId}</name>
<name>${project-base-package}.controller</name>
<url>http://wso2.com</url>
<build>
<plugins>
@ -37,15 +40,15 @@
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warName>${artifactId}</warName>
<warName>${project-base-package}.controller</warName>
</configuration>
</plugin>
</plugins>

@ -1,4 +1,3 @@
package ${groupId}.${rootArtifactId}.controller.api.util;
/*
* 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
* under the License.
*/
package ${groupId}.${rootArtifactId}.controller.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants;
@ -25,14 +27,11 @@ import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
public class ServiceUtils {
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_VERSION = "1.0.0";
/**
* sensor data are published to DAS
* Sensor data are published to DAS
* @param owner name of device owner
* @param deviceId unique identifier of the device
* @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) {
PrivilegedCarbonContext.startTenantFlow();
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.class, null);
Object metdaData[] = {owner, DeviceTypeConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};

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

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
@ -16,6 +17,7 @@
~ 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"

@ -1,4 +1,4 @@
package ${groupId}.${rootArtifactId}.manager.api;
/*
* 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
* 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.logging.Log;
import org.apache.commons.logging.LogFactory;
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.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;
@ -35,45 +43,49 @@ 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.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.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;
@SuppressWarnings("NonJaxWsWebServices")
@DeviceType(value = "${deviceType}")
public class ManagerService {
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
private HttpServletResponse response;
/**
* Register new devcie into IoTS
* Register new device into IoT Server
*
* @param deviceId unique identifier for device
* @param name name of new device
* @param owner owner of the device
* @return
* @param name name of new device
* @return registration status
*/
@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);
@QueryParam("name") String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
try {
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
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();
@ -84,7 +96,25 @@ public class ManagerService {
device.setType(DeviceTypeConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(owner);
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) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
@ -93,27 +123,30 @@ public class ManagerService {
return added;
} catch (DeviceManagementException e) {
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;
} finally {
deviceManagement.endTenantFlow();
}
}
/**
* Remove installed device
*
* @param deviceId unique identifier for device
* @param response
* @param response to request
*/
@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(DeviceTypeConstants.DEVICE_TYPE);
try {
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
@ -122,33 +155,32 @@ public class ManagerService {
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
deviceManagement.endTenantFlow();
}
}
/**
* Update device name
*
* @param deviceId unique identifier for device
* @param name new name of the device
* @param response
* @return
* @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,
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(DeviceTypeConstants.DEVICE_TYPE);
try {
Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DeviceTypeConstants.DEVICE_TYPE);
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
@ -158,49 +190,45 @@ public class ManagerService {
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage());
return false;
} finally {
deviceManagement.endTenantFlow();
}
}
/**
* Get device information
*
* @param deviceId unique identifier for device
* @return
* @return device
*/
@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(DeviceTypeConstants.DEVICE_TYPE);
try {
return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
} catch (DeviceManagementException ex) {
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
return null;
} finally {
deviceManagement.endTenantFlow();
}
}
/**
* 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 sketchType name of sketch type
* @return
* @return agent archive
*/
@Path("manager/device/{sketch_type}/download")
@GET
@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) {
try {
ZipArchive zipFile = createDownloadFile(owner, deviceName, sketchType);
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() + "\"");
@ -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
* @param owner owner of the device
*
* @param owner owner of the device
* @param deviceName name of device
* @param sketchType name of sketch type
* @return
* @return zip archive file
* @throws DeviceManagementException
* @throws AccessTokenException
* @throws DeviceControllerException
@ -234,7 +297,7 @@ public class ManagerService {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
String deviceId = APIUtil.shortUUID();
KeyGenerationUtil.createApplicationKeys(DeviceTypeConstants.DEVICE_TYPE);
TokenClient accessTokenClient = new TokenClient(DeviceTypeConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
@ -244,26 +307,15 @@ public class ManagerService {
//adding registering data
boolean status;
//Register the device with CDMF
status = register(deviceId, deviceName, owner);
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, SUPER_TENANT, sketchType, deviceId, deviceName, accessToken,
refreshToken);
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOfUser(), sketchType, deviceId,
deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
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"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
@ -16,11 +17,12 @@
~ 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>
<display-name>${deviceType}-Webapp-Manager</display-name>
<servlet>
<description>JAX-WS/JAX-RS Endpoint</description>
<display-name>JAX-WS/JAX-RS Servlet</display-name>
@ -40,7 +42,7 @@
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>false</param-value>
<param-value>true</param-value>
</context-param>
<!--publish to apim-->
<context-param>

@ -1,21 +1,24 @@
<!--/*
* 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"
<?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: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>${groupId}</groupId>
@ -25,9 +28,9 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<version>${version}</version>
<artifactId>${artifactId}</artifactId>
<artifactId>${project-base-package}.plugin</artifactId>
<packaging>bundle</packaging>
<name>${artifactId}</name>
<name>${project-base-package}.plugin</name>
<url>http://wso2.org</url>
<build>
<plugins>
@ -41,8 +44,8 @@
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
@ -52,8 +55,8 @@
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${artifactId}</Bundle-SymbolicName>
<Bundle-Name>${artifactId}</Bundle-Name>
<Bundle-SymbolicName>${project-base-package}.plugin</Bundle-SymbolicName>
<Bundle-Name>${project-base-package}.plugin</Bundle-Name>
<Bundle-Version>${version}</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>${project-base-package}.plugin.internal</Private-Package>
@ -70,7 +73,7 @@
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.context.*,
org.wso2.carbon.ndatasource.core,
org.wso2.carbon.device.mgt.iot.*,
org.wso2.carbon.device.mgt.iot.*
</Import-Package>
<Export-Package>
!${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;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import 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;
@ -40,9 +42,10 @@ import java.util.List;
*/
public class DeviceTypeManager implements DeviceManager {
private static final IotDeviceManagementDAOFactoryInterface iotDeviceManagementDAOFactory = new DeviceTypeDAO();
private static final Log log = LogFactory.getLog(DeviceTypeManager.class);
private static final DeviceTypeDAO deviceTypeDAO = new DeviceTypeDAO();
@Override
public FeatureManager getFeatureManager() {
return null;
@ -64,18 +67,17 @@ public class DeviceTypeManager 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 ${rootArtifactId} device : " + device.getDeviceIdentifier());
}
DeviceTypeDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice(iotDevice);
status = deviceTypeDAO.getDeviceTypeDAO().addDevice(device);
DeviceTypeDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
} catch (DeviceTypePluginException e) {
try {
DeviceTypeDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
} catch (DeviceTypePluginException 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();
@ -88,19 +90,17 @@ public class DeviceTypeManager 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 ${rootArtifactId} device enrollment data");
}
DeviceTypeDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO()
.updateIotDevice(iotDevice);
status = deviceTypeDAO.getDeviceTypeDAO().updateDevice(device);
DeviceTypeDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
} catch (DeviceTypePluginException e) {
try {
DeviceTypeDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
} catch (DeviceTypePluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
@ -120,13 +120,12 @@ public class DeviceTypeManager implements DeviceManager {
log.debug("Dis-enrolling ${rootArtifactId} device : " + deviceId);
}
DeviceTypeDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO()
.deleteIotDevice(deviceId.getId());
status = deviceTypeDAO.getDeviceTypeDAO().deleteDevice(deviceId.getId());
DeviceTypeDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
} catch (DeviceTypePluginException e) {
try {
DeviceTypeDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
} catch (DeviceTypePluginException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx);
}
@ -144,13 +143,12 @@ public class DeviceTypeManager implements DeviceManager {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of ${rootArtifactId} device : " + deviceId.getId());
}
IotDevice iotDevice =
iotDeviceManagementDAOFactory.getIotDeviceDAO().getIotDevice(
deviceId.getId());
Device iotDevice =
deviceTypeDAO.getDeviceTypeDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (IotDeviceManagementDAOException e) {
} catch (DeviceTypePluginException e) {
String msg = "Error while checking the enrollment status of ${rootArtifactId} device : " +
deviceId.getId();
log.error(msg, e);
@ -177,10 +175,8 @@ public class DeviceTypeManager implements DeviceManager {
if (log.isDebugEnabled()) {
log.debug("Getting the details of ${rootArtifactId} device : " + deviceId.getId());
}
IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO().
getIotDevice(deviceId.getId());
device = IotDeviceManagementUtil.convertToDevice(iotDevice);
} catch (IotDeviceManagementDAOException e) {
device = deviceTypeDAO.getDeviceTypeDAO().getDevice(deviceId.getId());
} catch (DeviceTypePluginException e) {
String msg = "Error while fetching the ${rootArtifactId} device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
@ -222,19 +218,17 @@ public class DeviceTypeManager implements DeviceManager {
@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 ${rootArtifactId} device : " + deviceIdentifier);
}
DeviceTypeDAO.beginTransaction();
status = iotDeviceManagementDAOFactory.getIotDeviceDAO()
.updateIotDevice(iotDevice);
status = deviceTypeDAO.getDeviceTypeDAO().updateDevice(device);
DeviceTypeDAO.commitTransaction();
} catch (IotDeviceManagementDAOException e) {
} catch (DeviceTypePluginException e) {
try {
DeviceTypeDAO.rollbackTransaction();
} catch (IotDeviceManagementDAOException iotDAOEx) {
} catch (DeviceTypePluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
@ -248,20 +242,13 @@ public class DeviceTypeManager implements DeviceManager {
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices = null;
List<Device> devices;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all ${rootArtifactId} devices");
}
List<IotDevice> iotDevices =
iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices();
if (iotDevices != null) {
devices = new ArrayList<Device>();
for (IotDevice iotDevice : iotDevices) {
devices.add(IotDeviceManagementUtil.convertToDevice(iotDevice));
}
}
} catch (IotDeviceManagementDAOException e) {
devices = deviceTypeDAO.getDeviceTypeDAO().getAllDevices();
} catch (DeviceTypePluginException e) {
String msg = "Error while fetching all ${rootArtifactId} devices.";
log.error(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.
*
@ -16,6 +15,9 @@ package ${groupId}.${rootArtifactId}.plugin.impl;
* specific language governing permissions and limitations
* under the License.
*/
package ${groupId}.${rootArtifactId}.plugin.impl;
import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
@ -53,7 +55,7 @@ public class DeviceTypeManagerService implements DeviceManagementService{
@Override
public void init() throws DeviceManagementException {
deviceManager= new DeviceTypeManager();
this.deviceManager = new DeviceTypeManager();
}
@Override
@ -67,7 +69,7 @@ public class DeviceTypeManagerService implements DeviceManagementService{
}
@Override
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> list) throws
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> deviceIds) throws
DeviceManagementException {
}
@ -90,17 +92,19 @@ public class DeviceTypeManagerService implements DeviceManagementService{
}
@Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> list)
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> deviceIdentifiers)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUsers(Operation operation, List<String> list)
public void installApplicationForUsers(Operation operation, List<String> userNameList)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUserRoles(Operation operation, List<String> list)
public void installApplicationForUserRoles(Operation operation, List<String> userRoleList)
throws ApplicationManagementException {
}
}

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

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

@ -25,11 +25,12 @@
{{/zone}}
{{#zone "device-thumbnail"}}
<img src="{{@unit.publicUri}}/images/current-sensor.png"/>
<img src="{{@unit.publicUri}}/images/deviceType.png"/>
{{/zone}}
{{#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>
{{/zone}}
@ -46,7 +47,8 @@
<div class="media">
<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"
data-toggle="tab" aria-controls="device_statistics">Device Statistics</a>
data-toggle="tab" aria-controls="device_statistics">Device
Statistics</a>
</li>
<ul class="list-group" role="tablist">
<li><a class="list-group-item" href="#policies" role="tab"
@ -65,7 +67,8 @@
</div>
<div class="panel panel-default tab-pane" id="policy_compliance" role="tabpanel"
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>
<div class="panel panel-default tab-pane" id="policies" role="tabpanel"
aria-labelledby="policies">

@ -56,13 +56,6 @@ function showPopup() {
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);
}
);
}else if(deviceName){
$('.controls').append('<label for="deviceName" generated="true" class="error" style="display: inline-block;">Please enter at least 4 characters.</label>');
} else if (deviceName) {
$('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">Please enter at least 4 ' +
'characters.</label>');
$('.control-group').removeClass('success').addClass('error');
} else {
$('.controls').append('<label for="deviceName" generated="true" class="error" style="display: inline-block;">This field is required.</label>');
$('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">This field is required.' +
'</label>');
$('.control-group').removeClass('success').addClass('error');
}
});
@ -127,23 +124,46 @@ function attachEvents() {
$("a#download-device-cancel-link").click(function () {
hidePopup();
});
});
}
function downloadAgent() {
$('#downloadForm').submit();
var deviceName;
var deviceName = "";
$('.new-device-name').each(function () {
if (this.value != "") {
deviceName = this.value;
}
});
if (deviceName && deviceName.length >= 4) {
setTimeout(function () {
var deviceType = "";
$('.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();
}, 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);
}
if (data.status == "200") {
$(modalPopupContent).html($('#download-device-modal-content-links').html());
$("input#download-device-url").val(data.responseText);
$("input#download-device-url").focus(function () {
$(this).select();
});
showPopup();
} else if (data.status == "401") {
if (data.status == "401") {
$(modalPopupContent).html($('#device-401-content').html());
$("#device-401-link").click(function () {
window.location = "/devicemgt/login";

@ -11,7 +11,7 @@
<h3 class="uppercase">What it Does</h3>
<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>
<p>Add brief description what this device type does</p>
<br/>
@ -30,7 +30,12 @@
<h3>Name your device and download the agent from following link.</h3>
<br/>
<form id="downloadForm" method="GET" action="{{@app.context}}/api/devices/sketch/download">
<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="controls">
<input class="new-device-name" style="color:#3f3f3f;padding:5px"
@ -43,7 +48,8 @@
</div>
</div>
<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;
</div>
</form>
@ -52,6 +58,16 @@
</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 class="modal-content">
<div class="row">
@ -159,7 +175,7 @@
<hr>
<ul class="list-unstyled">
<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>
</ul>
<br>
@ -168,6 +184,7 @@
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
<h3 class="uppercase">${deviceType} Setup</h3>
<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>
<center>
<a href="{{@unit.publicUri}}/images/schematicsGuide.png" target="_blank">
@ -189,18 +206,11 @@
page.
</li>
<li class="padding-top-double"><span class="circle">02</span>&nbsp;&nbsp;&nbsp;Select one of
connected devices and check for available control operations.</li>
connected devices and check for available control operations.
</li>
</ul>
<br/>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@unit.publicUri}}/images/myDevices_analytics.png" target="_blank">
<img src="{{@unit.publicUri}}/images/myDevices_analytics.png" class="img-responsive">
</a>
</center>
</div>
</div>
<style type="text/css">
.circle {

Loading…
Cancel
Save