From 8a013279a40929a015a8695cf36a6634d96d33fe Mon Sep 17 00:00:00 2001 From: GPrathap Date: Tue, 17 May 2016 18:55:45 +0530 Subject: [PATCH] merged controller and manager apis --- .../archetype-resources/component/api/pom.xml | 5 - .../api/ControllerServiceImpl.java | 201 ----------------- ...lerService.java => DeviceTypeService.java} | 57 +++-- ...ceImpl.java => DeviceTypeServiceImpl.java} | 197 ++++++++++++---- .../api/ManagerService.java | 56 ----- .../api/dto/DeviceJSON.java | 12 +- .../api/dto/SensorRecord.java | 42 +++- .../api/exception/DeviceTypeException.java | 16 +- .../api/transport/MQTTConnector.java | 211 ------------------ .../__rootArtifactId__/api/util/APIUtil.java | 31 ++- .../api/util/Constants.java | 8 +- .../api/util/ServiceUtils.java | 10 +- .../__rootArtifactId__/api/util/ZipUtil.java | 27 +-- .../src/main/webapp/META-INF/permissions.xml | 62 ++--- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 11 +- .../api/src/main/webapp/WEB-INF/web.xml | 2 +- 16 files changed, 315 insertions(+), 633 deletions(-) delete mode 100644 modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ControllerServiceImpl.java rename modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/{ControllerService.java => DeviceTypeService.java} (55%) rename modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/{ManagerServiceImpl.java => DeviceTypeServiceImpl.java} (61%) delete mode 100644 modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ManagerService.java delete mode 100644 modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/transport/MQTTConnector.java diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/pom.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/pom.xml index fbe78494..72b48405 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/pom.xml +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/pom.xml @@ -144,11 +144,6 @@ org.wso2.carbon.apimgt.annotations provided - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.webapp.publisher - provided - org.wso2.carbon.analytics org.wso2.carbon.analytics.api diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ControllerServiceImpl.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ControllerServiceImpl.java deleted file mode 100644 index 5e3aac6e..00000000 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ControllerServiceImpl.java +++ /dev/null @@ -1,201 +0,0 @@ -/* -* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you under the Apache License, -* Version 2.0 (the "License"); you may not use this file except -* in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -*/ - -package ${groupId}.${rootArtifactId}.api; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -import ${groupId}.${rootArtifactId}.api.util.APIUtil; -import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; -import ${groupId}.${rootArtifactId}.api.dto.DeviceJSON; -import ${groupId}.${rootArtifactId}.api.transport.MQTTConnector; -import ${groupId}.${rootArtifactId}.api.dto.SensorRecord; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.wso2.carbon.analytics.dataservice.commons.SortByField; -import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; -import org.wso2.carbon.analytics.dataservice.commons.SORT; -import org.wso2.carbon.apimgt.annotations.api.API; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; -import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; -import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature; -import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; -import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener; -import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; - -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.FormParam; -import javax.ws.rs.QueryParam; -import javax.ws.rs.PathParam; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - - -/** - * This is the controller API which is used to control agent side functionality - */ -@SuppressWarnings("NonJaxWsWebServices") -@API(name = "${deviceType}", version = "1.0.0", context = "/${deviceType}", tags = "${deviceType}") -@DeviceType(value = "${deviceType}") -public class ControllerServiceImpl implements ControllerService{ - - private static Log log = LogFactory.getLog(ControllerService.class); - private MQTTConnector mqttConnector; - private ConcurrentHashMap deviceToIpMap = new ConcurrentHashMap<>(); - - private boolean waitForServerStartup() { - while (!IoTServerStartupListener.isServerReady()) { - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - return true; - } - } - return false; - } - - public MQTTConnector getMQTTConnector() { - return mqttConnector; - } - - public void setMQTTConnector(final MQTTConnector MQTTConnector) { - Runnable connector = new Runnable() { - public void run() { - if (waitForServerStartup()) { - return; - } - //The delay is added for the server to starts up. - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - ControllerServiceImpl.this.mqttConnector = MQTTConnector; - if (MqttConfig.getInstance().isEnabled()) { - mqttConnector.connect(); - } else { - log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, MQTTConnector" + - " not started."); - } - } - }; - Thread connectorThread = new Thread(connector); - connectorThread.setDaemon(true); - connectorThread.start(); - } - - /** - * @param agentInfo device owner,id and sensor value - * @return - */ - @Path("device/register") - @POST - @Consumes(MediaType.APPLICATION_JSON) - public Response registerDevice(final DeviceJSON agentInfo) { - String deviceId = agentInfo.deviceId; - if ((agentInfo.deviceId != null) && (agentInfo.owner != null)) { - deviceToIpMap.put(deviceId, agentInfo); - return Response.status(Response.Status.OK).build(); - } - return Response.status(Response.Status.NOT_ACCEPTABLE).build(); - } - - /** - * @param deviceId unique identifier for given device type - * @param state change status of sensor: on/off - * @param response - */ - @Path("device/{deviceId}/change-status") - @POST - @Feature(code = "change-status", name = "Change status of sensor: on/off", type = "operation", - description = "Change status of sensor: on/off") - public Response changeStatus(@PathParam("deviceId") String deviceId, - @QueryParam("state") String state, - @Context HttpServletResponse response) { - try { - if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, - DeviceTypeConstants.DEVICE_TYPE))) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - String sensorState = state.toUpperCase(); - if (!sensorState.equals(DeviceTypeConstants.STATE_ON) && !sensorState.equals( - DeviceTypeConstants.STATE_OFF)) { - log.error("The requested state change should be either - 'ON' or 'OFF'"); - return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build(); - } - String mqttResource = DeviceTypeConstants.SENSOR_CONTEXT.replace("/", ""); - mqttConnector.publishDeviceData(deviceId, mqttResource, sensorState); - return Response.ok().build(); - } catch (TransportHandlerException e) { - log.error("Failed to send switch-bulb request to device [" + deviceId + "]"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (DeviceAccessAuthorizationException e) { - log.error(e.getErrorMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } - } - - /** - * Retrieve Sensor data for the ${deviceType} - */ - @Path("device/stats/{deviceId}") - @GET - @Consumes("application/json") - @Produces("application/json") - public Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, - @QueryParam("to") long to){ - String fromDate = String.valueOf(from); - String toDate = String.valueOf(to); - String query = "deviceId:" + deviceId + " AND deviceType:" + - DeviceTypeConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]"; - String sensorTableName = DeviceTypeConstants.TEMPERATURE_EVENT_TABLE; - try { - if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, - DeviceTypeConstants.DEVICE_TYPE))) { - return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); - } - if (sensorTableName != null) { - List sortByFields = new ArrayList<>(); - SortByField sortByField = new SortByField("time", SORT.ASC, false); - sortByFields.add(sortByField); - List sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields); - return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build(); - } - } catch (AnalyticsException e) { - String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; - log.error(errorMsg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); - } catch (DeviceAccessAuthorizationException e) { - log.error(e.getErrorMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } - return Response.status(Response.Status.BAD_REQUEST).build(); - } -} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ControllerService.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeService.java similarity index 55% rename from modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ControllerService.java rename to modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeService.java index f6968246..8724a93c 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ControllerService.java +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeService.java @@ -18,29 +18,23 @@ package ${groupId}.${rootArtifactId}.api; -import java.util.concurrent.ConcurrentHashMap; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import ${groupId}.${rootArtifactId}.api.dto.DeviceJSON; -import ${groupId}.${rootArtifactId}.api.transport.MQTTConnector; import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature; -import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; -import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener; import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Path; import javax.ws.rs.Consumes; -import javax.ws.rs.FormParam; import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; -import javax.ws.rs.Path; import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.PUT; +import javax.ws.rs.DELETE; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -52,7 +46,7 @@ import javax.ws.rs.core.Response; @SuppressWarnings("NonJaxWsWebServices") @API(name = "${deviceType}", version = "1.0.0", context = "/${deviceType}", tags = "${deviceType}") @DeviceType(value = "${deviceType}") -public interface ControllerService { +public interface DeviceTypeService { /** * @param agentInfo device owner,id and sensor value @@ -61,6 +55,7 @@ public interface ControllerService { @Path("device/register") @POST @Consumes(MediaType.APPLICATION_JSON) + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/user/register"}) Response registerDevice(final DeviceJSON agentInfo); /** @@ -70,11 +65,12 @@ public interface ControllerService { */ @Path("device/{deviceId}/change-status") @POST - @Feature(code = "change-status", name = "Change status of sensor: on/off", type = "operation", + @Feature(code = "change-status", name = "Change status of sensor: on/off", description = "Change status of sensor: on/off") + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/change-status"}) Response changeStatus(@PathParam("deviceId") String deviceId, - @QueryParam("state") String state, - @Context HttpServletResponse response); + @QueryParam("state") String state, + @Context HttpServletResponse response); /** * Retrieve Sensor data for the ${deviceType} @@ -83,8 +79,37 @@ public interface ControllerService { @GET @Consumes("application/json") @Produces("application/json") + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/stats"}) Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, - @QueryParam("to") long to); + @QueryParam("to") long to); + + @Path("/device/{device_id}") + @DELETE + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/removeDevice"}) + Response removeDevice(@PathParam("device_id") String deviceId); + @Path("/device/{device_id}") + @PUT + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/updateDevice"}) + Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name); + @Path("/device/{device_id}") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/updateDevice"}) + Response getDevice(@PathParam("device_id") String deviceId); + + @Path("/devices") + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/devices"}) + Response getAllDevices(); + + @Path("/device/download") + @GET + @Produces("application/zip") + @Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/download"}) + Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType); } \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ManagerServiceImpl.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeServiceImpl.java similarity index 61% rename from modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ManagerServiceImpl.java rename to modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeServiceImpl.java index 45fc7555..eebd47ee 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ManagerServiceImpl.java +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/DeviceTypeServiceImpl.java @@ -1,29 +1,37 @@ /* - * 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. - */ +* 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}.api; -import ${groupId}.${rootArtifactId}.api.util.ZipUtil; +import ${groupId}.${rootArtifactId}.api.dto.DeviceJSON; +import ${groupId}.${rootArtifactId}.api.dto.SensorRecord; import ${groupId}.${rootArtifactId}.api.util.APIUtil; +import ${groupId}.${rootArtifactId}.api.util.ZipUtil; import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; +import ${groupId}.${rootArtifactId}.api.DeviceTypeService; + import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.analytics.dataservice.commons.SORT; +import org.wso2.carbon.analytics.dataservice.commons.SortByField; +import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; +import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; @@ -33,30 +41,52 @@ 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.common.authorization.DeviceAccessAuthorizationException; -import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType; +import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature; import org.wso2.carbon.device.mgt.iot.util.ZipArchive; import org.wso2.carbon.identity.jwt.client.extension.JWTClient; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.user.api.UserStoreException; -import javax.ws.rs.*; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Path; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Produces; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.PUT; +import javax.ws.rs.DELETE; +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.UUID; +import java.util.Map; +import java.util.List; +import java.util.HashMap; import java.util.ArrayList; import java.util.Date; -import java.util.List; -import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; -@Path("enrollment") -public class ManagerServiceImpl implements ManagerService { + +/** + * This is the controller API which is used to control agent side functionality + */ +@SuppressWarnings("NonJaxWsWebServices") +@API(name = "${deviceType}", version = "1.0.0", context = "/${deviceType}", tags = "${deviceType}") +@DeviceType(value = "${deviceType}") +public class DeviceTypeServiceImpl implements DeviceTypeService { private static final String KEY_TYPE = "PRODUCTION"; + private static Log log = LogFactory.getLog(DeviceTypeService.class); private static ApiApplicationKey apiApplicationKey; - private static Log log = LogFactory.getLog(ManagerServiceImpl.class); + private ConcurrentHashMap deviceToIpMap = new ConcurrentHashMap<>(); private static String shortUUID() { UUID uuid = UUID.randomUUID(); @@ -64,7 +94,96 @@ public class ManagerServiceImpl implements ManagerService { return Long.toString(l, Character.MAX_RADIX); } - @Path("/devices/{device_id}") + /** + * @param agentInfo device owner,id and sensor value + * @return + */ + @Path("device/register") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public Response registerDevice(final DeviceJSON agentInfo) { + String deviceId = agentInfo.deviceId; + if ((agentInfo.deviceId != null) && (agentInfo.owner != null)) { + deviceToIpMap.put(deviceId, agentInfo); + return Response.status(Response.Status.OK).build(); + } + return Response.status(Response.Status.NOT_ACCEPTABLE).build(); + } + + /** + * @param deviceId unique identifier for given device type + * @param state change status of sensor: on/off + * @param response + */ + @Path("device/{deviceId}/change-status") + @POST + @Feature(code = "change-status", name = "Change status of sensor: on/off", + description = "Change status of sensor: on/off") + public Response changeStatus(@PathParam("deviceId") String deviceId, + @QueryParam("state") String state, + @Context HttpServletResponse response) { + try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, + DeviceTypeConstants.DEVICE_TYPE))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + String sensorState = state.toUpperCase(); + if (!sensorState.equals(DeviceTypeConstants.STATE_ON) && !sensorState.equals( + DeviceTypeConstants.STATE_OFF)) { + log.error("The requested state change should be either - 'ON' or 'OFF'"); + return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build(); + } + Map dynamicProperties = new HashMap<>(); + String publishTopic = APIUtil.getAuthenticatedUserTenantDomain() + + "/" + DeviceTypeConstants.DEVICE_TYPE + "/" + deviceId + "/command"; + dynamicProperties.put(DeviceTypeConstants.ADAPTER_TOPIC_PROPERTY, publishTopic); + APIUtil.getOutputEventAdapterService().publish(DeviceTypeConstants.MQTT_ADAPTER_NAME, + dynamicProperties, state); + return Response.ok().build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + } + + /** + * Retrieve Sensor data for the + */ + @Path("device/stats/{deviceId}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, + @QueryParam("to") long to) { + String fromDate = String.valueOf(from); + String toDate = String.valueOf(to); + String query = "deviceId:" + deviceId + " AND deviceType:" + + DeviceTypeConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]"; + String sensorTableName = DeviceTypeConstants.TEMPERATURE_EVENT_TABLE; + try { + if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, + DeviceTypeConstants.DEVICE_TYPE))) { + return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); + } + if (sensorTableName != null) { + List sortByFields = new ArrayList<>(); + SortByField sortByField = new SortByField("time", SORT.ASC, false); + sortByFields.add(sortByField); + List sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields); + return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build(); + } + } catch (AnalyticsException e) { + String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; + log.error(errorMsg); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); + } catch (DeviceAccessAuthorizationException e) { + log.error(e.getErrorMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); + } + return Response.status(Response.Status.BAD_REQUEST).build(); + } + + @Path("/device/{device_id}") @DELETE public Response removeDevice(@PathParam("device_id") String deviceId) { try { @@ -90,7 +209,7 @@ public class ManagerServiceImpl implements ManagerService { } } - @Path("/devices/{device_id}") + @Path("/device/{device_id}") @PUT public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) { try { @@ -120,7 +239,7 @@ public class ManagerServiceImpl implements ManagerService { } } - @Path("/devices/{device_id}") + @Path("/device/{device_id}") @GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @@ -166,7 +285,7 @@ public class ManagerServiceImpl implements ManagerService { } } - @Path("/devices/download") + @Path("/device/download") @GET @Produces("application/zip") public Response downloadSketch(@QueryParam("deviceName") String deviceName, @@ -191,9 +310,6 @@ public class ManagerServiceImpl implements ManagerService { } catch (APIManagerException ex) { log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); - } catch (DeviceControllerException ex) { - log.error(ex.getMessage(), ex); - return Response.status(500).entity(ex.getMessage()).build(); } catch (IOException ex) { log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); @@ -234,13 +350,13 @@ public class ManagerServiceImpl implements ManagerService { } private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) - throws DeviceManagementException, APIManagerException, JWTClientException, DeviceControllerException, + throws DeviceManagementException, JWTClientException, APIManagerException, UserStoreException { //create new device id String deviceId = shortUUID(); if (apiApplicationKey == null) { - String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration() - .getAdminUserName(); + String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() + .getRealmConfiguration().getAdminUserName(); APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); String[] tags = {DeviceTypeConstants.DEVICE_TYPE}; apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( @@ -250,20 +366,17 @@ public class ManagerServiceImpl implements ManagerService { String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId; AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret(), owner, scopes); + //create token String accessToken = accessTokenInfo.getAccessToken(); String refreshToken = accessTokenInfo.getRefreshToken(); - boolean status; - status = register(deviceId, deviceName); + boolean status = register(deviceId, deviceName); if (!status) { String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner; throw new DeviceManagementException(msg); } ZipUtil ziputil = new ZipUtil(); - ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, deviceId, - deviceName, accessToken, refreshToken); - zipFile.setDeviceId(deviceId); + ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, + deviceId, deviceName, accessToken, refreshToken); return zipFile; } - -} - +} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ManagerService.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ManagerService.java deleted file mode 100644 index 69d59414..00000000 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/ManagerService.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package ${groupId}.${rootArtifactId}.api; - -import org.wso2.carbon.apimgt.annotations.api.API; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -@Path("enrollment") -@API(name = "${deviceType}_mgt", version = "1.0.0", context = "/${deviceType}_mgt", tags = "${deviceType}") -public interface ManagerService { - - @Path("/devices/{device_id}") - @DELETE - Response removeDevice(@PathParam("device_id") String deviceId); - - @Path("/devices/{device_id}") - @PUT - Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name); - - @Path("/devices/{device_id}") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - Response getDevice(@PathParam("device_id") String deviceId); - - @Path("/devices") - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - Response getAllDevices(); - - @Path("/devices/download") - @GET - @Produces("application/zip") - Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType); - -} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/DeviceJSON.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/DeviceJSON.java index 54d2654a..be3a86c0 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/DeviceJSON.java +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/DeviceJSON.java @@ -15,6 +15,7 @@ * specific language governing permissions and limitations * under the License. */ + package ${groupId}.${rootArtifactId}.api.dto; import org.codehaus.jackson.annotate.JsonIgnoreProperties; @@ -22,12 +23,15 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** - *These information are sent by agent in each request to server + * These information are sent by agent in each request to server */ @XmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class DeviceJSON { - @XmlElement(required = true) public String owner; - @XmlElement(required = true) public String deviceId; - @XmlElement(required = true) public Float sensorValue; + @XmlElement(required = true) + public String owner; + @XmlElement(required = true) + public String deviceId; + @XmlElement(required = true) + public Float sensorValue; } diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/SensorRecord.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/SensorRecord.java index dd097a89..8a197967 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/SensorRecord.java +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/dto/SensorRecord.java @@ -1,3 +1,21 @@ +/* + * 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}.api.dto; import org.codehaus.jackson.annotate.JsonIgnoreProperties; @@ -9,17 +27,19 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -@XmlRootElement /** * This stores sensor event data for android sense. */ +@XmlRootElement @JsonIgnoreProperties(ignoreUnknown = true) public class SensorRecord { @XmlElementWrapper(required = true, name = "values") private Map values; - /** The id. */ + /** + * The id. + */ @XmlElement(required = false, name = "id") private String id; @@ -39,14 +59,6 @@ public class SensorRecord { this.values = values; } - /** - * Sets the id. - * @param id the new id - */ - public void setId(String id) { - this.id = id; - } - /** * Gets the id. * @return the id @@ -55,8 +67,16 @@ public class SensorRecord { return id; } + /** + * Sets the id. + * @param id the new id + */ + public void setId(String id) { + this.id = id; + } + @Override - public String toString(){ + public String toString() { List valueList = new ArrayList(); for (Map.Entry entry : values.entrySet()) { valueList.add(entry.getKey() + ":" + entry.getValue()); diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/exception/DeviceTypeException.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/exception/DeviceTypeException.java index e2e996dc..84fbf846 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/exception/DeviceTypeException.java +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/exception/DeviceTypeException.java @@ -24,14 +24,6 @@ public class DeviceTypeException extends Exception { private String errorMessage; - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - public DeviceTypeException(String msg, DeviceTypeException nestedEx) { super(msg, nestedEx); setErrorMessage(msg); @@ -54,4 +46,12 @@ public class DeviceTypeException extends Exception { public DeviceTypeException(Throwable cause) { super(cause); } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } } diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/transport/MQTTConnector.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/transport/MQTTConnector.java deleted file mode 100644 index 495f9dc5..00000000 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/transport/MQTTConnector.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package ${groupId}.${rootArtifactId}.api.transport; - -import java.nio.charset.StandardCharsets; - -import ${groupId}.${rootArtifactId}.api.util.APIUtil; -import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eclipse.paho.client.mqttv3.MqttException; -import org.eclipse.paho.client.mqttv3.MqttMessage; -import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; -import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; -import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; -import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; -import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler; -import org.wso2.carbon.identity.jwt.client.extension.JWTClient; -import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; -import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; -import org.wso2.carbon.user.api.UserStoreException; - -import java.nio.charset.StandardCharsets; -import java.util.UUID; - - -import java.io.File; -import java.util.Calendar; -import java.util.UUID; - -/** - * MQTT is used as transport protocol. So this will provide basic functional requirement in order to communicate over - * MQTT - */ -@SuppressWarnings("no JAX-WS annotation") -public class MQTTConnector extends MQTTTransportHandler { - - private static final String publisherContext = "publisher"; - private static final String subscriberContext = "subscriber"; - private static final String subscribeTopic = "wso2/+/"+ DeviceTypeConstants.DEVICE_TYPE + "/+/" + publisherContext; - private static final String KEY_TYPE = "PRODUCTION"; - private static final String EMPTY_STRING = ""; - private static final String JSON_SERIAL_KEY = "SerialNumber"; - private static final String JSON_TENANT_KEY = "Tenant"; - private static Log log = LogFactory.getLog(MQTTConnector.class); - private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5); - - private MQTTConnector() { - super(iotServerSubscriber, DeviceTypeConstants.DEVICE_TYPE, - MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic); - } - - /** - * {@inheritDoc} - * This method will initialize connection with message broker - */ - @Override - public void connect() { - Runnable connector = new Runnable() { - public void run() { - while (!isConnected()) { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( - DeviceTypeConstants.DEVICE_TYPE_PROVIDER_DOMAIN, true); - try { - String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() - .getRealmConfiguration().getAdminUserName(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(applicationUsername); - APIManagementProviderService apiManagementProviderService = APIUtil - .getAPIManagementProviderService(); - String[] tags = {DeviceTypeConstants.DEVICE_TYPE}; - ApiApplicationKey apiApplicationKey = apiManagementProviderService - .generateAndRetrieveApplicationKeys(DeviceTypeConstants.DEVICE_TYPE, tags, KEY_TYPE, - applicationUsername, true); - JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient(); - String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_mqtt_connector"; - AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), - apiApplicationKey.getConsumerSecret(), applicationUsername, scopes); - //create token - String accessToken = accessTokenInfo.getAccessToken(); - setUsernameAndPassword(accessToken, EMPTY_STRING); - connectToQueue(); - } catch (TransportHandlerException e) { - log.error("Connection/Subscription to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e); - try { - Thread.sleep(timeoutInterval); - } catch (InterruptedException ex) { - log.error("MQTT-Connector: Thread Sleep Interrupt Exception.", ex); - } - } catch (JWTClientException e) { - log.error("Failed to retrieve token from JWT Client.", e); - return; - } catch (UserStoreException e) { - log.error("Failed to retrieve the user.", e); - return; - } catch (APIManagerException e) { - log.error("Failed to create an application and generate keys.", e); - return; - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } - } - }; - - Thread connectorThread = new Thread(connector); - connectorThread.start(); - } - - /** - * This callback function will be called by message broker when some messages available to subscribed topic - * - * @param message mqtt message which is comming form agent side - * @param messageParams metadata of mqtt message - */ - @Override - public void processIncomingMessage(MqttMessage message, String... messageParams) throws TransportHandlerException { - - } - - /** - * connection with message broker can be terminated - */ - @Override - public void disconnect() { - Runnable stopConnection = new Runnable() { - public void run() { - while (isConnected()) { - try { - closeConnection(); - } catch (MqttException e) { - if (log.isDebugEnabled()) { - log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint); - } - try { - Thread.sleep(timeoutInterval); - } catch (InterruptedException e1) { - log.error("MQTT-Terminator: Thread Sleep Interrupt Exception"); - } - } - } - } - }; - Thread terminatorThread = new Thread(stopConnection); - terminatorThread.setDaemon(true); - terminatorThread.start(); - } - - - @Override - public void publishDeviceData() throws TransportHandlerException { - - } - - @Override - public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException { - - } - - @Override - public void publishDeviceData(String... publishData) throws TransportHandlerException { - if (publishData.length != 3) { - String errorMsg = "Incorrect number of arguments received to SEND-MQTT Message. " + - "Need to be [owner, deviceId, resource{SENSOR}, state{ON/OFF or null}]"; - log.error(errorMsg); - throw new TransportHandlerException(errorMsg); - } - - String deviceId = publishData[0]; - String resource = publishData[1]; - String state = publishData[2]; - - MqttMessage pushMessage = new MqttMessage(); - String publishTopic = "wso2/" + APIUtil.getTenantDomainOftheUser() + "/" + DeviceTypeConstants.DEVICE_TYPE - + "/" + deviceId; - String actualMessage = resource + ":" + state; - pushMessage.setPayload(actualMessage.getBytes(StandardCharsets.UTF_8)); - pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE); - pushMessage.setRetained(false); - publishToQueue(publishTopic, pushMessage); - } - - @Override - public void processIncomingMessage() { - - } - - @Override - public void processIncomingMessage(MqttMessage message) throws TransportHandlerException { - - } - -} \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/APIUtil.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/APIUtil.java index 1ef00669..4d54030c 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/APIUtil.java +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/APIUtil.java @@ -1,6 +1,8 @@ package ${groupId}.${rootArtifactId}.api.util; import ${groupId}.${rootArtifactId}.api.dto.SensorRecord; + +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService; import org.wso2.carbon.analytics.api.AnalyticsDataAPI; import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils; import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; @@ -172,12 +174,6 @@ public class APIUtil { return ids; } - /** - * Creates the SensorDatas from records. - * - * @param records the records - * @return the Map of SensorRecord - */ public static Map createSensorData(List records) { Map sensorDatas = new HashMap<>(); for (Record record : records) { @@ -187,12 +183,6 @@ public class APIUtil { return sensorDatas; } - /** - * Create a SensorRecord object out of a Record object - * - * @param record the record object - * @return SensorRecord object - */ public static SensorRecord createSensorData(Record record) { SensorRecord recordBean = new SensorRecord(); recordBean.setId(record.getId()); @@ -211,4 +201,21 @@ public class APIUtil { } return analyticsDataAPI; } + + public static String getAuthenticatedUserTenantDomain() { + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + return threadLocalCarbonContext.getTenantDomain(); + } + + public static OutputEventAdapterService getOutputEventAdapterService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + OutputEventAdapterService outputEventAdapterService = + (OutputEventAdapterService) ctx.getOSGiService(OutputEventAdapterService.class, null); + if (outputEventAdapterService == null) { + String msg = "Device Authorization service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return outputEventAdapterService; + } } diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/Constants.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/Constants.java index ba838aae..86cc5bc0 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/Constants.java +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/Constants.java @@ -25,8 +25,8 @@ import org.wso2.carbon.user.core.Permission; */ public class Constants { - public static final String DEFAULT_PERMISSION_RESOURCE = "/permission/admin/device-mgt/${deviceType}/user"; - public static final String DEFAULT_ROLE_NAME = "${deviceType}_user"; - public static final Permission DEFAULT_PERMISSION[] = new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE, - "ui.execute")}; + public static final String DEFAULT_PERMISSION_RESOURCE = "/permission/admin/device-mgt/${deviceType}/user"; + public static final String DEFAULT_ROLE_NAME = "${deviceType}_user"; + public static final Permission DEFAULT_PERMISSION[] + = new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE, "ui.execute")}; } diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ServiceUtils.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ServiceUtils.java index 485be466..df682a51 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ServiceUtils.java +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ServiceUtils.java @@ -19,8 +19,10 @@ package ${groupId}.${rootArtifactId}.api.util; import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -28,9 +30,11 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; public class ServiceUtils { private static final Log log = LogFactory.getLog(ServiceUtils.class); + /** * Sensor data are published to DAS - * @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 * @return */ @@ -42,8 +46,8 @@ public class ServiceUtils { Object metdaData[] = {owner, DeviceTypeConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object payloadData[] = {sensorValue}; try { - deviceAnalyticsService.publishEvent(DeviceTypeConstants.TEMPERATURE_STREAM_DEFINITION, - DeviceTypeConstants.TEMPERATURE_STREAM_DEFINITION_VERSION, metdaData, new Object[0], payloadData); + deviceAnalyticsService.publishEvent(DeviceTypeConstants.SENSOR_STREAM_DEFINITION, + DeviceTypeConstants.SENSOR_STREAM_DEFINITION_VERSION, metdaData, new Object[0], payloadData); } catch (DataPublisherConfigurationException e) { return false; } diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ZipUtil.java b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ZipUtil.java index d28e3e84..ec72a87b 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ZipUtil.java +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/java/__groupId__/__rootArtifactId__/api/util/ZipUtil.java @@ -18,12 +18,10 @@ package ${groupId}.${rootArtifactId}.api.util; +import ${groupId}.${rootArtifactId}.plugin.mqtt.MqttConfig; + import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; -import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig; -import org.wso2.carbon.device.mgt.iot.exception.IoTException; -import org.wso2.carbon.device.mgt.iot.util.IoTUtil; -import org.wso2.carbon.device.mgt.iot.util.IotDeviceManagementUtil; +import org.wso2.carbon.device.mgt.iot.util.Utils; import org.wso2.carbon.device.mgt.iot.util.ZipArchive; import org.wso2.carbon.utils.CarbonUtils; @@ -50,30 +48,24 @@ public class ZipUtil { String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches"; String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" + - File.separator + deviceId; + File.separator + deviceId; String templateSketchPath = sketchFolder + File.separator + deviceType; String iotServerIP; try { - iotServerIP = IoTUtil.getHostName(); + iotServerIP = Utils.getServerUrl(); String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY); String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY); String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort; String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort; String apimEndpoint = httpsServerEP; - String mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint(); + String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint(); if (mqttEndpoint.contains(LOCALHOST)) { mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP); } - String xmppEndpoint = XmppConfig.getInstance().getXmppEndpoint(); - int indexOfChar = xmppEndpoint.lastIndexOf(":"); - if (indexOfChar != -1) { - xmppEndpoint = xmppEndpoint.substring(0, indexOfChar); - } - xmppEndpoint = xmppEndpoint + ":" + XmppConfig.getInstance().getSERVER_CONNECTION_PORT(); Map contextParams = new HashMap<>(); - contextParams.put("SERVER_NAME", "wso2/" + APIUtil.getTenantDomainOftheUser()); + contextParams.put("SERVER_NAME", APIUtil.getTenantDomainOftheUser()); contextParams.put("DEVICE_OWNER", owner); contextParams.put("DEVICE_ID", deviceId); contextParams.put("DEVICE_NAME", deviceName); @@ -81,15 +73,12 @@ public class ZipUtil { contextParams.put("HTTP_EP", httpServerEP); contextParams.put("APIM_EP", apimEndpoint); contextParams.put("MQTT_EP", mqttEndpoint); - contextParams.put("XMPP_EP", xmppEndpoint); contextParams.put("DEVICE_TOKEN", token); contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken); ZipArchive zipFile; - zipFile = IotDeviceManagementUtil.getSketchArchive(archivesPath, templateSketchPath, contextParams); + zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); return zipFile; - } catch (IoTException e) { - throw new DeviceManagementException(e.getMessage()); } catch (IOException e) { throw new DeviceManagementException("Zip File Creation Failed", e); } diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/META-INF/permissions.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/META-INF/permissions.xml index c45b9a19..87c3aa3d 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/META-INF/permissions.xml +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/META-INF/permissions.xml @@ -26,40 +26,40 @@ it will result 403 error at the runtime. --> - - - - Get device - /device-mgt/${deviceType}/user - /enrollment/devices/* - GET - ${deviceType}_user - - - Remove device - /device-mgt/${deviceType}/user - /enrollment/devices/* - DELETE - ${deviceType}_user - - - Download device - /device-mgt/user - /enrollment/devices/download - GET - ${deviceType}_user - - - Update device - /device-mgt/${deviceType}/user - /enrollment/devices/* - POST - ${deviceType}_user - + + + + Get device + /device-mgt/${deviceType}/user + /device/* + GET + ${deviceType}_user + + + Remove device + /device-mgt/${deviceType}/user + /device/* + DELETE + ${deviceType}_user + + + Download device + /device-mgt/${deviceType}/user + /device/download + GET + ${deviceType}_user + + + Update device + /device-mgt/${deviceType}/user + /device/* + POST + ${deviceType}_user + Get Devices /device-mgt/${deviceType}/user - /enrollment/devices + /device GET ${deviceType}_user diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/cxf-servlet.xml index f6ed0e7a..a47a6891 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -25,19 +25,12 @@ http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> - - - - + - - \ No newline at end of file diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/web.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/web.xml index 2f18393c..e2641b15 100644 --- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/web.xml +++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/archetype-resources/component/api/src/main/webapp/WEB-INF/web.xml @@ -26,7 +26,7 @@ isSharedWithAllTenants - true + false providerTenantDomain