mirror of
https://repository.entgra.net/community/product-iots.git
synced 2025-09-16 23:32:19 +00:00
merged controller and manager apis
This commit is contained in:
parent
7ab6046d31
commit
8a013279a4
@ -144,11 +144,6 @@
|
|||||||
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
|
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
|
||||||
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
|
|
||||||
<scope>provided</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.wso2.carbon.analytics</groupId>
|
<groupId>org.wso2.carbon.analytics</groupId>
|
||||||
<artifactId>org.wso2.carbon.analytics.api</artifactId>
|
<artifactId>org.wso2.carbon.analytics.api</artifactId>
|
||||||
|
|||||||
@ -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<String, DeviceJSON> 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<SortByField> sortByFields = new ArrayList<>();
|
|
||||||
SortByField sortByField = new SortByField("time", SORT.ASC, false);
|
|
||||||
sortByFields.add(sortByField);
|
|
||||||
List<SensorRecord> 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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -18,29 +18,23 @@
|
|||||||
|
|
||||||
package ${groupId}.${rootArtifactId}.api;
|
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.dto.DeviceJSON;
|
||||||
import ${groupId}.${rootArtifactId}.api.transport.MQTTConnector;
|
|
||||||
|
|
||||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
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.DeviceType;
|
||||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
|
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.servlet.http.HttpServletResponse;
|
||||||
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.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.Produces;
|
||||||
import javax.ws.rs.QueryParam;
|
|
||||||
import javax.ws.rs.PathParam;
|
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.Context;
|
||||||
import javax.ws.rs.core.MediaType;
|
import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
@ -52,7 +46,7 @@ import javax.ws.rs.core.Response;
|
|||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
@API(name = "${deviceType}", version = "1.0.0", context = "/${deviceType}", tags = "${deviceType}")
|
@API(name = "${deviceType}", version = "1.0.0", context = "/${deviceType}", tags = "${deviceType}")
|
||||||
@DeviceType(value = "${deviceType}")
|
@DeviceType(value = "${deviceType}")
|
||||||
public interface ControllerService {
|
public interface DeviceTypeService {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param agentInfo device owner,id and sensor value
|
* @param agentInfo device owner,id and sensor value
|
||||||
@ -61,6 +55,7 @@ public interface ControllerService {
|
|||||||
@Path("device/register")
|
@Path("device/register")
|
||||||
@POST
|
@POST
|
||||||
@Consumes(MediaType.APPLICATION_JSON)
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
@Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/user/register"})
|
||||||
Response registerDevice(final DeviceJSON agentInfo);
|
Response registerDevice(final DeviceJSON agentInfo);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -70,11 +65,12 @@ public interface ControllerService {
|
|||||||
*/
|
*/
|
||||||
@Path("device/{deviceId}/change-status")
|
@Path("device/{deviceId}/change-status")
|
||||||
@POST
|
@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")
|
description = "Change status of sensor: on/off")
|
||||||
|
@Permission(scope = "${deviceType}_user", permissions = {"/permission/admin/device-mgt/change-status"})
|
||||||
Response changeStatus(@PathParam("deviceId") String deviceId,
|
Response changeStatus(@PathParam("deviceId") String deviceId,
|
||||||
@QueryParam("state") String state,
|
@QueryParam("state") String state,
|
||||||
@Context HttpServletResponse response);
|
@Context HttpServletResponse response);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve Sensor data for the ${deviceType}
|
* Retrieve Sensor data for the ${deviceType}
|
||||||
@ -83,8 +79,37 @@ public interface ControllerService {
|
|||||||
@GET
|
@GET
|
||||||
@Consumes("application/json")
|
@Consumes("application/json")
|
||||||
@Produces("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,
|
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);
|
||||||
}
|
}
|
||||||
@ -1,29 +1,37 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
*
|
*
|
||||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
* Version 2.0 (the "License"); you may not use this file except
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
* in compliance with the License.
|
* in compliance with the License.
|
||||||
* You may obtain a copy of the License at
|
* You may obtain a copy of the License at
|
||||||
*
|
*
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
*
|
*
|
||||||
* Unless required by applicable law or agreed to in writing,
|
* Unless required by applicable law or agreed to in writing,
|
||||||
* software distributed under the License is distributed on an
|
* software distributed under the License is distributed on an
|
||||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
* KIND, either express or implied. See the License for the
|
* KIND, either express or implied. See the License for the
|
||||||
* specific language governing permissions and limitations
|
* specific language governing permissions and limitations
|
||||||
* under the License.
|
* under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package ${groupId}.${rootArtifactId}.api;
|
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.APIUtil;
|
||||||
|
import ${groupId}.${rootArtifactId}.api.util.ZipUtil;
|
||||||
import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants;
|
import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants;
|
||||||
|
import ${groupId}.${rootArtifactId}.api.DeviceTypeService;
|
||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
import org.apache.commons.io.FileUtils;
|
||||||
import org.apache.commons.logging.Log;
|
import org.apache.commons.logging.Log;
|
||||||
import org.apache.commons.logging.LogFactory;
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import 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.APIManagementProviderService;
|
||||||
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
|
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
|
||||||
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
|
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.DeviceManagementException;
|
||||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
|
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.device.mgt.iot.util.ZipArchive;
|
||||||
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
|
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.dto.AccessTokenInfo;
|
||||||
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
|
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
|
||||||
import org.wso2.carbon.user.api.UserStoreException;
|
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.MediaType;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
import java.nio.charset.StandardCharsets;
|
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.ArrayList;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.List;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@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 final String KEY_TYPE = "PRODUCTION";
|
||||||
|
private static Log log = LogFactory.getLog(DeviceTypeService.class);
|
||||||
private static ApiApplicationKey apiApplicationKey;
|
private static ApiApplicationKey apiApplicationKey;
|
||||||
private static Log log = LogFactory.getLog(ManagerServiceImpl.class);
|
private ConcurrentHashMap<String, DeviceJSON> deviceToIpMap = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
private static String shortUUID() {
|
private static String shortUUID() {
|
||||||
UUID uuid = UUID.randomUUID();
|
UUID uuid = UUID.randomUUID();
|
||||||
@ -64,7 +94,96 @@ public class ManagerServiceImpl implements ManagerService {
|
|||||||
return Long.toString(l, Character.MAX_RADIX);
|
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<String, String> 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<SortByField> sortByFields = new ArrayList<>();
|
||||||
|
SortByField sortByField = new SortByField("time", SORT.ASC, false);
|
||||||
|
sortByFields.add(sortByField);
|
||||||
|
List<SensorRecord> 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
|
@DELETE
|
||||||
public Response removeDevice(@PathParam("device_id") String deviceId) {
|
public Response removeDevice(@PathParam("device_id") String deviceId) {
|
||||||
try {
|
try {
|
||||||
@ -90,7 +209,7 @@ public class ManagerServiceImpl implements ManagerService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Path("/devices/{device_id}")
|
@Path("/device/{device_id}")
|
||||||
@PUT
|
@PUT
|
||||||
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
|
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
|
||||||
try {
|
try {
|
||||||
@ -120,7 +239,7 @@ public class ManagerServiceImpl implements ManagerService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Path("/devices/{device_id}")
|
@Path("/device/{device_id}")
|
||||||
@GET
|
@GET
|
||||||
@Consumes(MediaType.APPLICATION_JSON)
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
@Produces(MediaType.APPLICATION_JSON)
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
@ -166,7 +285,7 @@ public class ManagerServiceImpl implements ManagerService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Path("/devices/download")
|
@Path("/device/download")
|
||||||
@GET
|
@GET
|
||||||
@Produces("application/zip")
|
@Produces("application/zip")
|
||||||
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
|
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
|
||||||
@ -191,9 +310,6 @@ public class ManagerServiceImpl implements ManagerService {
|
|||||||
} catch (APIManagerException ex) {
|
} catch (APIManagerException ex) {
|
||||||
log.error(ex.getMessage(), ex);
|
log.error(ex.getMessage(), ex);
|
||||||
return Response.status(500).entity(ex.getMessage()).build();
|
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) {
|
} catch (IOException ex) {
|
||||||
log.error(ex.getMessage(), ex);
|
log.error(ex.getMessage(), ex);
|
||||||
return Response.status(500).entity(ex.getMessage()).build();
|
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)
|
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
|
||||||
throws DeviceManagementException, APIManagerException, JWTClientException, DeviceControllerException,
|
throws DeviceManagementException, JWTClientException, APIManagerException,
|
||||||
UserStoreException {
|
UserStoreException {
|
||||||
//create new device id
|
//create new device id
|
||||||
String deviceId = shortUUID();
|
String deviceId = shortUUID();
|
||||||
if (apiApplicationKey == null) {
|
if (apiApplicationKey == null) {
|
||||||
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
|
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
|
||||||
.getAdminUserName();
|
.getRealmConfiguration().getAdminUserName();
|
||||||
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
|
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
|
||||||
String[] tags = {DeviceTypeConstants.DEVICE_TYPE};
|
String[] tags = {DeviceTypeConstants.DEVICE_TYPE};
|
||||||
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
|
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
|
||||||
@ -250,20 +366,17 @@ public class ManagerServiceImpl implements ManagerService {
|
|||||||
String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId;
|
String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId;
|
||||||
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
|
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
|
||||||
apiApplicationKey.getConsumerSecret(), owner, scopes);
|
apiApplicationKey.getConsumerSecret(), owner, scopes);
|
||||||
|
//create token
|
||||||
String accessToken = accessTokenInfo.getAccessToken();
|
String accessToken = accessTokenInfo.getAccessToken();
|
||||||
String refreshToken = accessTokenInfo.getRefreshToken();
|
String refreshToken = accessTokenInfo.getRefreshToken();
|
||||||
boolean status;
|
boolean status = register(deviceId, deviceName);
|
||||||
status = register(deviceId, deviceName);
|
|
||||||
if (!status) {
|
if (!status) {
|
||||||
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
|
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
|
||||||
throw new DeviceManagementException(msg);
|
throw new DeviceManagementException(msg);
|
||||||
}
|
}
|
||||||
ZipUtil ziputil = new ZipUtil();
|
ZipUtil ziputil = new ZipUtil();
|
||||||
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, deviceId,
|
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
|
||||||
deviceName, accessToken, refreshToken);
|
deviceId, deviceName, accessToken, refreshToken);
|
||||||
zipFile.setDeviceId(deviceId);
|
|
||||||
return zipFile;
|
return zipFile;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
|
||||||
|
|
||||||
@ -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);
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -15,6 +15,7 @@
|
|||||||
* specific language governing permissions and limitations
|
* specific language governing permissions and limitations
|
||||||
* under the License.
|
* under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package ${groupId}.${rootArtifactId}.api.dto;
|
package ${groupId}.${rootArtifactId}.api.dto;
|
||||||
|
|
||||||
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
|
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
|
||||||
@ -22,12 +23,15 @@ import javax.xml.bind.annotation.XmlElement;
|
|||||||
import javax.xml.bind.annotation.XmlRootElement;
|
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
|
@XmlRootElement
|
||||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
public class DeviceJSON {
|
public class DeviceJSON {
|
||||||
@XmlElement(required = true) public String owner;
|
@XmlElement(required = true)
|
||||||
@XmlElement(required = true) public String deviceId;
|
public String owner;
|
||||||
@XmlElement(required = true) public Float sensorValue;
|
@XmlElement(required = true)
|
||||||
|
public String deviceId;
|
||||||
|
@XmlElement(required = true)
|
||||||
|
public Float sensorValue;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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;
|
package ${groupId}.${rootArtifactId}.api.dto;
|
||||||
|
|
||||||
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
|
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
|
||||||
@ -9,17 +27,19 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@XmlRootElement
|
|
||||||
/**
|
/**
|
||||||
* This stores sensor event data for android sense.
|
* This stores sensor event data for android sense.
|
||||||
*/
|
*/
|
||||||
|
@XmlRootElement
|
||||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
public class SensorRecord {
|
public class SensorRecord {
|
||||||
|
|
||||||
@XmlElementWrapper(required = true, name = "values")
|
@XmlElementWrapper(required = true, name = "values")
|
||||||
private Map<String, Object> values;
|
private Map<String, Object> values;
|
||||||
|
|
||||||
/** The id. */
|
/**
|
||||||
|
* The id.
|
||||||
|
*/
|
||||||
@XmlElement(required = false, name = "id")
|
@XmlElement(required = false, name = "id")
|
||||||
private String id;
|
private String id;
|
||||||
|
|
||||||
@ -39,14 +59,6 @@ public class SensorRecord {
|
|||||||
this.values = values;
|
this.values = values;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets the id.
|
|
||||||
* @param id the new id
|
|
||||||
*/
|
|
||||||
public void setId(String id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the id.
|
* Gets the id.
|
||||||
* @return the id
|
* @return the id
|
||||||
@ -55,8 +67,16 @@ public class SensorRecord {
|
|||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the id.
|
||||||
|
* @param id the new id
|
||||||
|
*/
|
||||||
|
public void setId(String id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString(){
|
public String toString() {
|
||||||
List<String> valueList = new ArrayList<String>();
|
List<String> valueList = new ArrayList<String>();
|
||||||
for (Map.Entry<String, Object> entry : values.entrySet()) {
|
for (Map.Entry<String, Object> entry : values.entrySet()) {
|
||||||
valueList.add(entry.getKey() + ":" + entry.getValue());
|
valueList.add(entry.getKey() + ":" + entry.getValue());
|
||||||
|
|||||||
@ -24,14 +24,6 @@ public class DeviceTypeException extends Exception {
|
|||||||
|
|
||||||
private String errorMessage;
|
private String errorMessage;
|
||||||
|
|
||||||
public String getErrorMessage() {
|
|
||||||
return errorMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setErrorMessage(String errorMessage) {
|
|
||||||
this.errorMessage = errorMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
public DeviceTypeException(String msg, DeviceTypeException nestedEx) {
|
public DeviceTypeException(String msg, DeviceTypeException nestedEx) {
|
||||||
super(msg, nestedEx);
|
super(msg, nestedEx);
|
||||||
setErrorMessage(msg);
|
setErrorMessage(msg);
|
||||||
@ -54,4 +46,12 @@ public class DeviceTypeException extends Exception {
|
|||||||
public DeviceTypeException(Throwable cause) {
|
public DeviceTypeException(Throwable cause) {
|
||||||
super(cause);
|
super(cause);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getErrorMessage() {
|
||||||
|
return errorMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setErrorMessage(String errorMessage) {
|
||||||
|
this.errorMessage = errorMessage;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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 {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,6 +1,8 @@
|
|||||||
package ${groupId}.${rootArtifactId}.api.util;
|
package ${groupId}.${rootArtifactId}.api.util;
|
||||||
|
|
||||||
import ${groupId}.${rootArtifactId}.api.dto.SensorRecord;
|
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.api.AnalyticsDataAPI;
|
||||||
import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils;
|
import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils;
|
||||||
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
|
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
|
||||||
@ -172,12 +174,6 @@ public class APIUtil {
|
|||||||
return ids;
|
return ids;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates the SensorDatas from records.
|
|
||||||
*
|
|
||||||
* @param records the records
|
|
||||||
* @return the Map of SensorRecord <id, SensorRecord>
|
|
||||||
*/
|
|
||||||
public static Map<String, SensorRecord> createSensorData(List<Record> records) {
|
public static Map<String, SensorRecord> createSensorData(List<Record> records) {
|
||||||
Map<String, SensorRecord> sensorDatas = new HashMap<>();
|
Map<String, SensorRecord> sensorDatas = new HashMap<>();
|
||||||
for (Record record : records) {
|
for (Record record : records) {
|
||||||
@ -187,12 +183,6 @@ public class APIUtil {
|
|||||||
return sensorDatas;
|
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) {
|
public static SensorRecord createSensorData(Record record) {
|
||||||
SensorRecord recordBean = new SensorRecord();
|
SensorRecord recordBean = new SensorRecord();
|
||||||
recordBean.setId(record.getId());
|
recordBean.setId(record.getId());
|
||||||
@ -211,4 +201,21 @@ public class APIUtil {
|
|||||||
}
|
}
|
||||||
return analyticsDataAPI;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -25,8 +25,8 @@ import org.wso2.carbon.user.core.Permission;
|
|||||||
*/
|
*/
|
||||||
public class Constants {
|
public class Constants {
|
||||||
|
|
||||||
public static final String DEFAULT_PERMISSION_RESOURCE = "/permission/admin/device-mgt/${deviceType}/user";
|
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 String DEFAULT_ROLE_NAME = "${deviceType}_user";
|
||||||
public static final Permission DEFAULT_PERMISSION[] = new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE,
|
public static final Permission DEFAULT_PERMISSION[]
|
||||||
"ui.execute")};
|
= new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE, "ui.execute")};
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,8 +19,10 @@
|
|||||||
package ${groupId}.${rootArtifactId}.api.util;
|
package ${groupId}.${rootArtifactId}.api.util;
|
||||||
|
|
||||||
import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants;
|
import ${groupId}.${rootArtifactId}.plugin.constants.DeviceTypeConstants;
|
||||||
|
|
||||||
import org.apache.commons.logging.Log;
|
import org.apache.commons.logging.Log;
|
||||||
import org.apache.commons.logging.LogFactory;
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
|
||||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
|
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.device.mgt.analytics.data.publisher.service.EventsPublisherService;
|
||||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||||
@ -28,9 +30,11 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
|
|||||||
|
|
||||||
public class ServiceUtils {
|
public class ServiceUtils {
|
||||||
private static final Log log = LogFactory.getLog(ServiceUtils.class);
|
private static final Log log = LogFactory.getLog(ServiceUtils.class);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sensor data are published to DAS
|
* 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
|
* @param sensorValue current value of sensor which is set at agent side
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
@ -42,8 +46,8 @@ public class ServiceUtils {
|
|||||||
Object metdaData[] = {owner, DeviceTypeConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
|
Object metdaData[] = {owner, DeviceTypeConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
|
||||||
Object payloadData[] = {sensorValue};
|
Object payloadData[] = {sensorValue};
|
||||||
try {
|
try {
|
||||||
deviceAnalyticsService.publishEvent(DeviceTypeConstants.TEMPERATURE_STREAM_DEFINITION,
|
deviceAnalyticsService.publishEvent(DeviceTypeConstants.SENSOR_STREAM_DEFINITION,
|
||||||
DeviceTypeConstants.TEMPERATURE_STREAM_DEFINITION_VERSION, metdaData, new Object[0], payloadData);
|
DeviceTypeConstants.SENSOR_STREAM_DEFINITION_VERSION, metdaData, new Object[0], payloadData);
|
||||||
} catch (DataPublisherConfigurationException e) {
|
} catch (DataPublisherConfigurationException e) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,12 +18,10 @@
|
|||||||
|
|
||||||
package ${groupId}.${rootArtifactId}.api.util;
|
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.common.DeviceManagementException;
|
||||||
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
|
import org.wso2.carbon.device.mgt.iot.util.Utils;
|
||||||
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.ZipArchive;
|
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
|
||||||
import org.wso2.carbon.utils.CarbonUtils;
|
import org.wso2.carbon.utils.CarbonUtils;
|
||||||
|
|
||||||
@ -50,30 +48,24 @@ public class ZipUtil {
|
|||||||
|
|
||||||
String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches";
|
String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches";
|
||||||
String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" +
|
String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" +
|
||||||
File.separator + deviceId;
|
File.separator + deviceId;
|
||||||
String templateSketchPath = sketchFolder + File.separator + deviceType;
|
String templateSketchPath = sketchFolder + File.separator + deviceType;
|
||||||
String iotServerIP;
|
String iotServerIP;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
iotServerIP = IoTUtil.getHostName();
|
iotServerIP = Utils.getServerUrl();
|
||||||
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
|
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
|
||||||
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
|
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
|
||||||
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
|
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
|
||||||
String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort;
|
String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort;
|
||||||
String apimEndpoint = httpsServerEP;
|
String apimEndpoint = httpsServerEP;
|
||||||
String mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint();
|
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
|
||||||
if (mqttEndpoint.contains(LOCALHOST)) {
|
if (mqttEndpoint.contains(LOCALHOST)) {
|
||||||
mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
|
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<String, String> contextParams = new HashMap<>();
|
Map<String, String> contextParams = new HashMap<>();
|
||||||
contextParams.put("SERVER_NAME", "wso2/" + APIUtil.getTenantDomainOftheUser());
|
contextParams.put("SERVER_NAME", APIUtil.getTenantDomainOftheUser());
|
||||||
contextParams.put("DEVICE_OWNER", owner);
|
contextParams.put("DEVICE_OWNER", owner);
|
||||||
contextParams.put("DEVICE_ID", deviceId);
|
contextParams.put("DEVICE_ID", deviceId);
|
||||||
contextParams.put("DEVICE_NAME", deviceName);
|
contextParams.put("DEVICE_NAME", deviceName);
|
||||||
@ -81,15 +73,12 @@ public class ZipUtil {
|
|||||||
contextParams.put("HTTP_EP", httpServerEP);
|
contextParams.put("HTTP_EP", httpServerEP);
|
||||||
contextParams.put("APIM_EP", apimEndpoint);
|
contextParams.put("APIM_EP", apimEndpoint);
|
||||||
contextParams.put("MQTT_EP", mqttEndpoint);
|
contextParams.put("MQTT_EP", mqttEndpoint);
|
||||||
contextParams.put("XMPP_EP", xmppEndpoint);
|
|
||||||
contextParams.put("DEVICE_TOKEN", token);
|
contextParams.put("DEVICE_TOKEN", token);
|
||||||
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
|
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
|
||||||
|
|
||||||
ZipArchive zipFile;
|
ZipArchive zipFile;
|
||||||
zipFile = IotDeviceManagementUtil.getSketchArchive(archivesPath, templateSketchPath, contextParams);
|
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
|
||||||
return zipFile;
|
return zipFile;
|
||||||
} catch (IoTException e) {
|
|
||||||
throw new DeviceManagementException(e.getMessage());
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new DeviceManagementException("Zip File Creation Failed", e);
|
throw new DeviceManagementException("Zip File Creation Failed", e);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -26,40 +26,40 @@
|
|||||||
it will result 403 error at the runtime.
|
it will result 403 error at the runtime.
|
||||||
-->
|
-->
|
||||||
<PermissionConfiguration>
|
<PermissionConfiguration>
|
||||||
<APIVersion></APIVersion>
|
<APIVersion></APIVersion>
|
||||||
<!-- Device related APIs -->
|
<!-- Device related APIs -->
|
||||||
<Permission>
|
<Permission>
|
||||||
<name>Get device</name>
|
<name>Get device</name>
|
||||||
<path>/device-mgt/${deviceType}/user</path>
|
<path>/device-mgt/${deviceType}/user</path>
|
||||||
<url>/enrollment/devices/*</url>
|
<url>/device/*</url>
|
||||||
<method>GET</method>
|
<method>GET</method>
|
||||||
<scope>${deviceType}_user</scope>
|
<scope>${deviceType}_user</scope>
|
||||||
</Permission>
|
</Permission>
|
||||||
<Permission>
|
<Permission>
|
||||||
<name>Remove device</name>
|
<name>Remove device</name>
|
||||||
<path>/device-mgt/${deviceType}/user</path>
|
<path>/device-mgt/${deviceType}/user</path>
|
||||||
<url>/enrollment/devices/*</url>
|
<url>/device/*</url>
|
||||||
<method>DELETE</method>
|
<method>DELETE</method>
|
||||||
<scope>${deviceType}_user</scope>
|
<scope>${deviceType}_user</scope>
|
||||||
</Permission>
|
</Permission>
|
||||||
<Permission>
|
<Permission>
|
||||||
<name>Download device</name>
|
<name>Download device</name>
|
||||||
<path>/device-mgt/user</path>
|
<path>/device-mgt/${deviceType}/user</path>
|
||||||
<url>/enrollment/devices/download</url>
|
<url>/device/download</url>
|
||||||
<method>GET</method>
|
<method>GET</method>
|
||||||
<scope>${deviceType}_user</scope>
|
<scope>${deviceType}_user</scope>
|
||||||
</Permission>
|
</Permission>
|
||||||
<Permission>
|
<Permission>
|
||||||
<name>Update device</name>
|
<name>Update device</name>
|
||||||
<path>/device-mgt/${deviceType}/user</path>
|
<path>/device-mgt/${deviceType}/user</path>
|
||||||
<url>/enrollment/devices/*</url>
|
<url>/device/*</url>
|
||||||
<method>POST</method>
|
<method>POST</method>
|
||||||
<scope>${deviceType}_user</scope>
|
<scope>${deviceType}_user</scope>
|
||||||
</Permission>
|
</Permission>
|
||||||
<Permission>
|
<Permission>
|
||||||
<name>Get Devices</name>
|
<name>Get Devices</name>
|
||||||
<path>/device-mgt/${deviceType}/user</path>
|
<path>/device-mgt/${deviceType}/user</path>
|
||||||
<url>/enrollment/devices</url>
|
<url>/device</url>
|
||||||
<method>GET</method>
|
<method>GET</method>
|
||||||
<scope>${deviceType}_user</scope>
|
<scope>${deviceType}_user</scope>
|
||||||
</Permission>
|
</Permission>
|
||||||
|
|||||||
@ -25,19 +25,12 @@
|
|||||||
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
|
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
|
||||||
<jaxrs:server id="${deviceType}" address="/">
|
<jaxrs:server id="${deviceType}" address="/">
|
||||||
<jaxrs:serviceBeans>
|
<jaxrs:serviceBeans>
|
||||||
<bean id="ControllerService"
|
<bean id="DeviceTypeService"
|
||||||
class="${groupId}.${rootArtifactId}.api.ControllerServiceImpl">
|
class="${groupId}.${rootArtifactId}.api.DeviceTypeServiceImpl">
|
||||||
<property name="MQTTConnector" ref="communicationHandler"/>
|
|
||||||
</bean>
|
|
||||||
<bean id="ManagerService"
|
|
||||||
class="${groupId}.${rootArtifactId}.api.ManagerServiceImpl">
|
|
||||||
</bean>
|
</bean>
|
||||||
</jaxrs:serviceBeans>
|
</jaxrs:serviceBeans>
|
||||||
<jaxrs:providers>
|
<jaxrs:providers>
|
||||||
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
|
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
|
||||||
</jaxrs:providers>
|
</jaxrs:providers>
|
||||||
</jaxrs:server>
|
</jaxrs:server>
|
||||||
<bean id="communicationHandler"
|
|
||||||
class="${groupId}.${rootArtifactId}.api.transport.MQTTConnector" >
|
|
||||||
</bean>
|
|
||||||
</beans>
|
</beans>
|
||||||
@ -26,7 +26,7 @@
|
|||||||
</context-param>
|
</context-param>
|
||||||
<context-param>
|
<context-param>
|
||||||
<param-name>isSharedWithAllTenants</param-name>
|
<param-name>isSharedWithAllTenants</param-name>
|
||||||
<param-value>true</param-value>
|
<param-value>false</param-value>
|
||||||
</context-param>
|
</context-param>
|
||||||
<context-param>
|
<context-param>
|
||||||
<param-name>providerTenantDomain</param-name>
|
<param-name>providerTenantDomain</param-name>
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user