forked from community/product-iots
parent
f80523f409
commit
c7c2222e4b
@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.coffeeking.api;
|
||||
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
|
||||
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
@API( name="connectedcup", version="1.0.0", context="/connectedcup" , tags = {"connectedcup"})
|
||||
@DeviceType( value = "connectedcup")
|
||||
public interface ConnectedCupControllerService {
|
||||
|
||||
@Path("device/coffeelevel")
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature(code = "coffeelevel", name = "Coffee Level", type = "monitor",
|
||||
description = "Request Coffee Level from Connected cup")
|
||||
Response readCoffeeLevel(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId);
|
||||
|
||||
@Path("device/temperature")
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature(code = "temperature", name = "Temperature", type = "monitor",
|
||||
description = "Request Temperature reading from Connected cup")
|
||||
Response readTemperature(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId);
|
||||
|
||||
|
||||
@Path("device/ordercoffee")
|
||||
@POST
|
||||
Response orderCoffee(@QueryParam("deviceId") String deviceId, @QueryParam("deviceOwner") String deviceOwner);
|
||||
|
||||
}
|
@ -0,0 +1,118 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.coffeeking.api;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
|
||||
import org.coffeeking.api.transport.ConnectedCupMQTTConnector;
|
||||
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
|
||||
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
|
||||
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
public class ConnectedCupControllerServiceImpl implements ConnectedCupControllerService {
|
||||
|
||||
private static Log log = LogFactory.getLog(ConnectedCupControllerServiceImpl.class);
|
||||
private static ConnectedCupMQTTConnector connectedCupMQTTConnector;
|
||||
|
||||
public ConnectedCupMQTTConnector getConnectedCupMQTTConnector() {
|
||||
return ConnectedCupControllerServiceImpl.connectedCupMQTTConnector;
|
||||
}
|
||||
|
||||
public void setConnectedCupMQTTConnector(
|
||||
final ConnectedCupMQTTConnector connectedCupMQTTConnector) {
|
||||
|
||||
Runnable connector = new Runnable() {
|
||||
public void run() {
|
||||
if (waitForServerStartup()) {
|
||||
return;
|
||||
}
|
||||
ConnectedCupControllerServiceImpl.connectedCupMQTTConnector = connectedCupMQTTConnector;
|
||||
if (MqttConfig.getInstance().isEnabled()) {
|
||||
connectedCupMQTTConnector.connect();
|
||||
} else {
|
||||
log.warn("MQTT disabled in 'devicemgt-config.xml'. " +
|
||||
"Hence, ConnectedCupMQTTConnector not started.");
|
||||
}
|
||||
}
|
||||
};
|
||||
Thread connectorThread = new Thread(connector);
|
||||
connectorThread.setDaemon(true);
|
||||
connectorThread.start();
|
||||
}
|
||||
|
||||
private boolean waitForServerStartup() {
|
||||
while (!IoTServerStartupListener.isServerReady()) {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Response readCoffeeLevel(String owner, String deviceId) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
|
||||
}
|
||||
|
||||
try {
|
||||
String mqttResource = ConnectedCupConstants.LEVEL_CONTEXT.replace("/", "");
|
||||
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
|
||||
|
||||
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
|
||||
ConnectedCupConstants.SENSOR_LEVEL);
|
||||
return Response.ok().entity(sensorRecord).build();
|
||||
} catch (DeviceControllerException | TransportHandlerException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response readTemperature(String owner, String deviceId) {
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Sending request to read connected cup temperature of device " + "[" + deviceId + "] via MQTT");
|
||||
}
|
||||
try {
|
||||
String mqttResource = ConnectedCupConstants.TEMPERATURE_CONTEXT.replace("/", "");
|
||||
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
|
||||
|
||||
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
|
||||
ConnectedCupConstants.SENSOR_TEMPERATURE);
|
||||
return Response.ok().entity(sensorRecord).build();
|
||||
} catch (DeviceControllerException | TransportHandlerException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response orderCoffee(String deviceId, String deviceOwner) {
|
||||
log.info("Coffee ordered....!");
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
|
||||
}
|
||||
return Response.ok().entity("Coffee ordered.").build();
|
||||
}
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.coffeeking.api;
|
||||
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
@API( name="connectedcup_mgt", version="1.0.0", context="/connectedcup_mgt", tags = {"connectedcup"})
|
||||
@DeviceType("connectedcup")
|
||||
public interface ConnectedCupManagerService {
|
||||
|
||||
@Path("devices/{device_id}")
|
||||
@DELETE
|
||||
Response removeDevice(@PathParam("device_id") String deviceId);
|
||||
|
||||
@Path("devices/{device_id}")
|
||||
@PUT
|
||||
Response updateDevice(@PathParam("device_id") String deviceId,
|
||||
@QueryParam("name") String name);
|
||||
|
||||
@Path("devices/{device_id}")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
Response getDevice(@PathParam("device_id") String deviceId);
|
||||
|
||||
}
|
@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.coffeeking.api;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.coffeeking.api.util.APIUtil;
|
||||
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
public class ConnectedCupManagerServiceImpl implements ConnectedCupManagerService{
|
||||
|
||||
private static Log log = LogFactory.getLog(ConnectedCupManagerServiceImpl.class);
|
||||
|
||||
private boolean register(String deviceId, String name) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
|
||||
return false;
|
||||
}
|
||||
Device device = new Device();
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
|
||||
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
|
||||
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
|
||||
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
|
||||
device.setName(name);
|
||||
device.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
|
||||
return added;
|
||||
} catch (DeviceManagementException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Response removeDevice(String deviceId) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
|
||||
deviceIdentifier);
|
||||
if (removed) {
|
||||
return Response.ok().build();
|
||||
} else {
|
||||
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response updateDevice(String deviceId, String name) {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
try {
|
||||
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
|
||||
device.setName(name);
|
||||
device.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
|
||||
if (updated) {
|
||||
return Response.ok().build();
|
||||
} else {
|
||||
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error(e.getErrorMessage());
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response getDevice(String deviceId) {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
try {
|
||||
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
return Response.ok().entity(device).build();
|
||||
} catch (DeviceManagementException ex) {
|
||||
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
private static String shortUUID() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
|
||||
return Long.toString(l, Character.MAX_RADIX);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package org.coffeeking.api.util;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
|
||||
/**
|
||||
* This class provides utility functions used by REST-API.
|
||||
*/
|
||||
public class APIUtil {
|
||||
|
||||
private static Log log = LogFactory.getLog(APIUtil.class);
|
||||
|
||||
public static String getAuthenticatedUser() {
|
||||
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
String username = threadLocalCarbonContext.getUsername();
|
||||
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
|
||||
if (username.endsWith(tenantDomain)) {
|
||||
return username.substring(0, username.lastIndexOf("@"));
|
||||
}
|
||||
return username;
|
||||
}
|
||||
|
||||
public static String getTenantDomainOftheUser() {
|
||||
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
|
||||
return tenantDomain;
|
||||
}
|
||||
|
||||
public static DeviceManagementProviderService getDeviceManagementService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
DeviceManagementProviderService deviceManagementProviderService =
|
||||
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
|
||||
if (deviceManagementProviderService == null) {
|
||||
String msg = "Device Management service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return deviceManagementProviderService;
|
||||
}
|
||||
|
||||
public static APIManagementProviderService getAPIManagementProviderService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
APIManagementProviderService apiManagementProviderService =
|
||||
(APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null);
|
||||
if (apiManagementProviderService == null) {
|
||||
String msg = "API management provider service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return apiManagementProviderService;
|
||||
}
|
||||
}
|
@ -1,207 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.coffeeking.controller.service;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
|
||||
import org.coffeeking.controller.service.dto.DeviceJSON;
|
||||
import org.coffeeking.controller.service.transport.ConnectedCupMQTTConnector;
|
||||
import org.coffeeking.controller.service.util.ConnectedCupServiceUtils;
|
||||
import org.json.JSONObject;
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
|
||||
import org.wso2.carbon.apimgt.annotations.device.feature.Feature;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.iot.DeviceValidator;
|
||||
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
|
||||
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
|
||||
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Calendar;
|
||||
|
||||
@API( name="connectedcup", version="1.0.0", context="/connectedcup")
|
||||
@DeviceType( value = "connectedcup")
|
||||
public class ConnectedCupControllerService {
|
||||
|
||||
private static Log log = LogFactory.getLog(ConnectedCupControllerService.class);
|
||||
private static final String SUPER_TENANT = "carbon.super";
|
||||
private static ConnectedCupMQTTConnector connectedCupMQTTConnector;
|
||||
|
||||
|
||||
public ConnectedCupMQTTConnector connectedCupMQTTConnector() {
|
||||
return ConnectedCupControllerService.connectedCupMQTTConnector;
|
||||
}
|
||||
|
||||
public void setconnectedCupMQTTConnector(
|
||||
final ConnectedCupMQTTConnector connectedCupMQTTConnector) {
|
||||
|
||||
Runnable connector = new Runnable() {
|
||||
public void run() {
|
||||
if (waitForServerStartup()) {
|
||||
return;
|
||||
}
|
||||
ConnectedCupControllerService.connectedCupMQTTConnector = connectedCupMQTTConnector;
|
||||
if (MqttConfig.getInstance().isEnabled()) {
|
||||
connectedCupMQTTConnector.connect();
|
||||
} else {
|
||||
log.warn("MQTT disabled in 'devicemgt-config.xml'. " +
|
||||
"Hence, ConnectedCupMQTTConnector not started.");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Thread connectorThread = new Thread(connector);
|
||||
connectorThread.setDaemon(true);
|
||||
connectorThread.start();
|
||||
}
|
||||
|
||||
private boolean waitForServerStartup() {
|
||||
while (!DeviceManagement.isServerReady()) {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param deviceId
|
||||
* @param owner
|
||||
*/
|
||||
@Path("controller/coffeelevel")
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature( code="coffeelevel", name="Coffee Level", type="monitor",
|
||||
description="Request Coffee Level from Connected cup")
|
||||
public SensorRecord readCoffeeLevel(@HeaderParam("owner") String owner,
|
||||
@HeaderParam("deviceId") String deviceId,
|
||||
@Context HttpServletResponse response) {
|
||||
SensorRecord sensorRecord = null;
|
||||
DeviceValidator deviceValidator = new DeviceValidator();
|
||||
try {
|
||||
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(
|
||||
deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
|
||||
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
|
||||
}
|
||||
|
||||
try {
|
||||
String mqttResource = ConnectedCupConstants.LEVEL_CONTEXT.replace("/", "");
|
||||
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
|
||||
|
||||
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
|
||||
ConnectedCupConstants.SENSOR_LEVEL);
|
||||
} catch ( DeviceControllerException | TransportHandlerException e ) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
return sensorRecord;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Path("controller/temperature")
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature( code="temperature", name="Temperature", type="monitor",
|
||||
description="Request Temperature reading from Connected cup")
|
||||
public SensorRecord readTemperature(@HeaderParam("owner") String owner,
|
||||
@HeaderParam("deviceId") String deviceId,
|
||||
@Context HttpServletResponse response) {
|
||||
SensorRecord sensorRecord = null;
|
||||
|
||||
DeviceValidator deviceValidator = new DeviceValidator();
|
||||
try {
|
||||
if (!deviceValidator.isExist(owner, SUPER_TENANT,
|
||||
new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
|
||||
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Sending request to read connected cup temperature of device " +
|
||||
"[" + deviceId + "] via MQTT");
|
||||
}
|
||||
|
||||
try {
|
||||
String mqttResource = ConnectedCupConstants.TEMPERATURE_CONTEXT.replace("/", "");
|
||||
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
|
||||
|
||||
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
|
||||
ConnectedCupConstants.SENSOR_TEMPERATURE);
|
||||
} catch ( DeviceControllerException | TransportHandlerException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
return sensorRecord;
|
||||
}
|
||||
|
||||
@Path("controller/ordercoffee")
|
||||
@POST
|
||||
public void orderCoffee(@QueryParam("deviceId") String deviceId, @QueryParam("deviceOwner") String
|
||||
deviceOwner, @Context HttpServletResponse response){
|
||||
|
||||
DeviceValidator deviceValidator = new DeviceValidator();
|
||||
try {
|
||||
if (!deviceValidator.isExist(deviceOwner, SUPER_TENANT, new DeviceIdentifier(
|
||||
deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
|
||||
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
response.setStatus(Response.Status.ACCEPTED.getStatusCode());
|
||||
log.info("Coffee ordered....!");
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
|
||||
}
|
||||
// return response;
|
||||
}
|
||||
}
|
@ -1,261 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<artifactId>device-mgt-iot-connectedcup</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
|
||||
<version>2.0.4-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.coffeeking.connectedcup.manager.service</artifactId>
|
||||
<version>2.0.4-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<name>WSO2 IoTS(Device Types) - Connected Cup Manager Service</name>
|
||||
<description>WSO2 IoTS(Device Types) - Connected Cup Manager Service</description>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
<dependencies>
|
||||
<!-- CDM -->
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2-client</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2-client</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>commons-codec.wso2</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!--CXF -->
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxws</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--MQTT -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--IOT -->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpasyncclient</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
|
||||
</dependency>
|
||||
<!--
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
-->
|
||||
|
||||
<!--JAX-RS -->
|
||||
<dependency>
|
||||
<groupId>org.codehaus.jackson</groupId>
|
||||
<artifactId>jackson-core-asl</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.jackson</groupId>
|
||||
<artifactId>jackson-jaxrs</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-web-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>jsr311-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-httpclient.wso2</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.bouncycastle.wso2</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.user.api</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.queuing</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.base</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smack</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smackx</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>jaxen</groupId>
|
||||
<artifactId>jaxen</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>commons-fileupload.wso2</groupId>
|
||||
<artifactId>commons-fileupload</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.ant.wso2</groupId>
|
||||
<artifactId>ant</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.ant.wso2</groupId>
|
||||
<artifactId>ant</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>commons-httpclient.wso2</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.eclipse.equinox</groupId>
|
||||
<artifactId>javax.servlet</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.registry.api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smack</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smackx</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
|
||||
<artifactId>org.coffeeking.connectedcup.plugin</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
|
||||
<plugins>
|
||||
<!--plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<encoding>UTF-8</encoding>
|
||||
<source>${wso2.maven.compiler.source}</source>
|
||||
<target>${wso2.maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin-->
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
<version>2.3.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<configuration>
|
||||
<warName>connectedcup</warName>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -1,242 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.coffeeking.manager.service;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
|
||||
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
|
||||
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
|
||||
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@API( name="connectedcup_mgt", version="1.0.0", context="/connectedcup_mgt")
|
||||
public class ConnectedCupManagerService {
|
||||
private static Log log = LogFactory.getLog(ConnectedCupManagerService.class);
|
||||
private static final String SUPER_TENANT = "carbon.super";
|
||||
|
||||
@Context
|
||||
private HttpServletResponse response;
|
||||
/**
|
||||
* @param name
|
||||
* @param owner
|
||||
* @return
|
||||
*/
|
||||
@Path("cup/register")
|
||||
@POST
|
||||
public boolean register(@QueryParam("name") String name, @QueryParam("owner") String owner) {
|
||||
|
||||
|
||||
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
|
||||
String deviceId = shortUUID();
|
||||
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
|
||||
try {
|
||||
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
|
||||
response.setStatus(Response.Status.CONFLICT.getStatusCode());
|
||||
return false;
|
||||
}
|
||||
|
||||
Device device = new Device();
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
|
||||
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
|
||||
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
|
||||
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
|
||||
device.setName(name);
|
||||
device.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
enrolmentInfo.setOwner(owner);
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
|
||||
KeyGenerationUtil.createApplicationKeys(ConnectedCupConstants.DEVICE_TYPE);
|
||||
|
||||
TokenClient accessTokenClient = new TokenClient(ConnectedCupConstants.DEVICE_TYPE);
|
||||
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
|
||||
|
||||
//create token
|
||||
String accessToken = accessTokenInfo.getAccess_token();
|
||||
String refreshToken = accessTokenInfo.getRefresh_token();
|
||||
List<Device.Property> properties = new ArrayList<>();
|
||||
|
||||
Device.Property accessTokenProperty = new Device.Property();
|
||||
accessTokenProperty.setName("accessToken");
|
||||
accessTokenProperty.setValue(accessToken);
|
||||
|
||||
Device.Property refreshTokenProperty = new Device.Property();
|
||||
refreshTokenProperty.setName("refreshToken");
|
||||
refreshTokenProperty.setValue(refreshToken);
|
||||
|
||||
properties.add(accessTokenProperty);
|
||||
properties.add(refreshTokenProperty);
|
||||
device.setProperties(properties);
|
||||
|
||||
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device);
|
||||
if (added) {
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
} else {
|
||||
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
|
||||
}
|
||||
|
||||
return added;
|
||||
} catch (DeviceManagementException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
return false;
|
||||
} catch (AccessTokenException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
deviceManagement.endTenantFlow();
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
@Path("/device/remove/{device_id}")
|
||||
@DELETE
|
||||
public void removeDevice(@PathParam("device_id") String deviceId,
|
||||
@Context HttpServletResponse response) {
|
||||
|
||||
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
|
||||
try {
|
||||
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(
|
||||
deviceIdentifier);
|
||||
if (removed) {
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
|
||||
} else {
|
||||
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
|
||||
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
} finally {
|
||||
deviceManagement.endTenantFlow();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Path("/device/update/{device_id}")
|
||||
@POST
|
||||
public boolean updateDevice(@PathParam("device_id") String deviceId,
|
||||
@QueryParam("name") String name,
|
||||
@Context HttpServletResponse response) {
|
||||
|
||||
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
|
||||
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
|
||||
try {
|
||||
Device device = deviceManagement.getDeviceManagementService().getDevice(
|
||||
deviceIdentifier);
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
|
||||
// device.setDeviceTypeId(deviceTypeId);
|
||||
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
|
||||
|
||||
device.setName(name);
|
||||
device.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
|
||||
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(
|
||||
device);
|
||||
|
||||
|
||||
if (updated) {
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
|
||||
} else {
|
||||
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
|
||||
|
||||
}
|
||||
return updated;
|
||||
} catch (DeviceManagementException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
return false;
|
||||
} finally {
|
||||
deviceManagement.endTenantFlow();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Path("/device/{device_id}")
|
||||
@GET
|
||||
@Consumes("application/json")
|
||||
@Produces("application/json")
|
||||
public Device getDevice(@PathParam("device_id") String deviceId) {
|
||||
|
||||
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
|
||||
|
||||
try {
|
||||
Device device = deviceManagement.getDeviceManagementService().getDevice(
|
||||
deviceIdentifier);
|
||||
|
||||
return device;
|
||||
} catch (DeviceManagementException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
return null;
|
||||
} finally {
|
||||
deviceManagement.endTenantFlow();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static String shortUUID() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
|
||||
return Long.toString(l, Character.MAX_RADIX);
|
||||
}
|
||||
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
<!--
|
||||
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<!--
|
||||
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
|
||||
-->
|
||||
<Classloading xmlns="http://wso2.org/projects/as/classloading">
|
||||
|
||||
<!-- Parent-first or child-first. Default behaviour is child-first.-->
|
||||
<ParentFirst>false</ParentFirst>
|
||||
|
||||
<!--
|
||||
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
|
||||
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
|
||||
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
|
||||
-->
|
||||
<Environments>CXF,Carbon</Environments>
|
||||
</Classloading>
|
@ -1,42 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
|
||||
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
|
||||
|
||||
|
||||
<jaxrs:server id="ConnectedCupmanager" address="/connectedcup">
|
||||
<jaxrs:serviceBeans>
|
||||
<bean id="ConnectedCupManagerService"
|
||||
class="org.coffeeking.manager.service.ConnectedCupManagerService">
|
||||
</bean>
|
||||
</jaxrs:serviceBeans>
|
||||
<jaxrs:providers>
|
||||
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
|
||||
</jaxrs:providers>
|
||||
</jaxrs:server>
|
||||
|
||||
|
||||
|
||||
</beans>
|
||||
|
@ -1,69 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
|
||||
version="2.5">
|
||||
<display-name>ConnectedCup-Webapp</display-name>
|
||||
<servlet>
|
||||
<description>JAX-WS/JAX-RS Endpoint</description>
|
||||
<display-name>JAX-WS/JAX-RS Servlet</display-name>
|
||||
<servlet-name>CXFServlet</servlet-name>
|
||||
<servlet-class>
|
||||
org.apache.cxf.transport.servlet.CXFServlet
|
||||
</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>CXFServlet</servlet-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<context-param>
|
||||
<param-name>isAdminService</param-name>
|
||||
<param-value>false</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>doAuthentication</param-name>
|
||||
<param-value>false</param-value>
|
||||
</context-param>
|
||||
|
||||
<!--publish to apim-->
|
||||
<context-param>
|
||||
<param-name>managed-api-enabled</param-name>
|
||||
<param-value>false</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-owner</param-name>
|
||||
<param-value>admin</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-context-template</param-name>
|
||||
<param-value>/connectedcup/{version}</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-application</param-name>
|
||||
<param-value>connectedcup</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-isSecured</param-name>
|
||||
<param-value>true</param-value>
|
||||
</context-param>
|
||||
|
||||
</web-app>
|
@ -1,64 +0,0 @@
|
||||
<!--
|
||||
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<parent>
|
||||
<groupId>org.homeautomation</groupId>
|
||||
<artifactId>${project-base-package}-component</artifactId>
|
||||
<version>2.0.4-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>${groupId}.currentsensor.agent</artifactId>
|
||||
<version>2.0.4-SNAPSHOT</version>
|
||||
<name>${groupId}.currentsensor.agent</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${wso2.maven.compiler.source}</source>
|
||||
<target>${wso2.maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
<configuration>
|
||||
<warName>${groupId}.currentsensor.agent</warName>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -1,23 +0,0 @@
|
||||
<!--/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/-->
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
|
||||
version="2.5">
|
||||
<display-name>Sample-Agent-Webapp</display-name>
|
||||
</web-app>
|
@ -1,22 +0,0 @@
|
||||
<%--/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/--%>
|
||||
<html>
|
||||
<body>
|
||||
<h2>Hello World!</h2>
|
||||
</body>
|
||||
</html>
|
@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.currentsensor.api;
|
||||
|
||||
import org.homeautomation.currentsensor.api.dto.DeviceJSON;
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
@API(name = "currentsensor", version = "1.0.0", context = "/currentsensor", tags = {"currentsensor"})
|
||||
@DeviceType(value = "currentsensor")
|
||||
public interface CurrentSensorControllerService {
|
||||
|
||||
@Path("device/register/{owner}/{deviceId}/{ip}/{port}")
|
||||
@POST
|
||||
Response registerDeviceIP(@PathParam("owner") String owner, @PathParam("deviceId") String deviceId,
|
||||
@PathParam("ip") String deviceIP, @PathParam("port") String devicePort);
|
||||
|
||||
/**
|
||||
* @param deviceId
|
||||
* @return
|
||||
*/
|
||||
@Path("device/read-current")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature(code = "read-current", name = "Current", type = "monitor",
|
||||
description = "Request current reading from Arduino agent")
|
||||
Response requestCurrent(@HeaderParam("deviceId") String deviceId);
|
||||
|
||||
/**
|
||||
* @param deviceId
|
||||
* @return
|
||||
*/
|
||||
@Path("device/read-power")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature(code = "read-power", name = "Power", type = "monitor",
|
||||
description = "Request power reading from Arduino agent")
|
||||
Response requestPower(@HeaderParam("deviceId") String deviceId);
|
||||
|
||||
/**
|
||||
* @param deviceId
|
||||
* @return
|
||||
*/
|
||||
@Path("device/read-flowrate")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature(code = "read-flowrate", name = "Flow Rate", type = "monitor",
|
||||
description = "Request flow rate reading from Arduino agent")
|
||||
Response requestFlowRate(@HeaderParam("deviceId") String deviceId);
|
||||
|
||||
/**
|
||||
* @param dataMsg
|
||||
*/
|
||||
@Path("device/push-data")
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
Response pushData(final DeviceJSON dataMsg);
|
||||
|
||||
}
|
@ -0,0 +1,153 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.currentsensor.api;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.homeautomation.currentsensor.api.dto.DeviceJSON;
|
||||
import org.homeautomation.currentsensor.api.util.CurrentSensorServiceUtils;
|
||||
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
|
||||
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Calendar;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class CurrentSensorControllerServiceImpl implements CurrentSensorControllerService{
|
||||
|
||||
private static Log log = LogFactory.getLog(CurrentSensorControllerServiceImpl.class);
|
||||
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
|
||||
|
||||
private boolean waitForServerStartup() {
|
||||
while (!IoTServerStartupListener.isServerReady()) {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Response registerDeviceIP(String owner, String deviceId, String deviceIP, String devicePort) {
|
||||
//TODO:: Need to get IP from the request itself
|
||||
String result;
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: " + owner);
|
||||
}
|
||||
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
|
||||
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
|
||||
result = "Device-IP Registered";
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(result);
|
||||
}
|
||||
return Response.ok().entity(result).build();
|
||||
}
|
||||
|
||||
public Response requestCurrent(String deviceId) {
|
||||
SensorRecord sensorRecord = null;
|
||||
try {
|
||||
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
|
||||
CurrentSensorConstants.SENSOR_CURRENT);
|
||||
} catch (DeviceControllerException e) {
|
||||
Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
|
||||
return Response.ok().entity(sensorRecord).build();
|
||||
}
|
||||
|
||||
public Response requestPower(String deviceId) {
|
||||
SensorRecord sensorRecord = null;
|
||||
try {
|
||||
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
|
||||
CurrentSensorConstants.SENSOR_POWER);
|
||||
} catch (DeviceControllerException e) {
|
||||
Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
return Response.ok().entity(sensorRecord).build();
|
||||
}
|
||||
|
||||
public Response requestFlowRate(String deviceId) {
|
||||
SensorRecord sensorRecord = null;
|
||||
try {
|
||||
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
|
||||
CurrentSensorConstants.SENSOR_FLOWRATE);
|
||||
} catch (DeviceControllerException e) {
|
||||
Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
return Response.ok().entity(sensorRecord).build();
|
||||
}
|
||||
|
||||
public Response pushData(final DeviceJSON dataMsg) {
|
||||
|
||||
String owner = dataMsg.owner;
|
||||
String deviceId = dataMsg.deviceId;
|
||||
String deviceIp = dataMsg.reply;
|
||||
float current = dataMsg.current;
|
||||
float flow_rate = dataMsg.flow_rate;
|
||||
|
||||
String registeredIp = deviceToIpMap.get(deviceId);
|
||||
|
||||
if (registeredIp == null) {
|
||||
log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp +
|
||||
" for device ID - " + deviceId);
|
||||
return Response.status(Response.Status.PRECONDITION_FAILED.getStatusCode()).build();
|
||||
} else if (!registeredIp.equals(deviceIp)) {
|
||||
log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId +
|
||||
" is already registered under some other IP. Re-registration required");
|
||||
return Response.status(Response.Status.CONFLICT.getStatusCode()).build();
|
||||
}
|
||||
|
||||
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_CURRENT,
|
||||
String.valueOf(current),
|
||||
Calendar.getInstance().getTimeInMillis());
|
||||
|
||||
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_POWER,
|
||||
String.valueOf(current * 230),
|
||||
Calendar.getInstance().getTimeInMillis());
|
||||
|
||||
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_FLOWRATE,
|
||||
String.valueOf(flow_rate),
|
||||
Calendar.getInstance().getTimeInMillis());
|
||||
|
||||
if (!CurrentSensorServiceUtils.publishToDASCurrent(dataMsg.deviceId, current)) {
|
||||
log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId +
|
||||
"] of owner [" + owner + "]");
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
|
||||
if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.deviceId, current * 230)) {
|
||||
log.warn("An error occured whilst trying to publish pin data of Power Sensor Data with ID [" + deviceId +
|
||||
"] of owner [" + owner + "]");
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
|
||||
if (!CurrentSensorServiceUtils.publishToDASFlowRate(dataMsg.deviceId, flow_rate)) {
|
||||
log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId +
|
||||
"] of owner [" + owner + "]");
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
return Response.ok().build();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.currentsensor.api;
|
||||
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
@API(name = "currentsensor_mgt", version = "1.0.0", context = "/currentsensor_mgt", tags = {"currentsensor"})
|
||||
@DeviceType(value = "currentsensor")
|
||||
public interface CurrentSensorManagerService {
|
||||
|
||||
@Path("devices/{device_id}")
|
||||
@DELETE
|
||||
Response removeDevice(@PathParam("device_id") String deviceId);
|
||||
|
||||
@Path("devices/{device_id}")
|
||||
@PUT
|
||||
Response updateDevice(@PathParam("device_id") String deviceId,
|
||||
@QueryParam("name") String name);
|
||||
|
||||
@Path("devices/{device_id}")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
Response getDevice(@PathParam("device_id") String deviceId);
|
||||
|
||||
@Path("devices/{sketch_type}/download")
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
Response downloadSketch(@QueryParam("deviceName") String deviceName, @PathParam("sketch_type") String
|
||||
sketchType);
|
||||
|
||||
}
|
@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.currentsensor.api;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
|
||||
import org.homeautomation.currentsensor.api.util.APIUtil;
|
||||
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
|
||||
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
|
||||
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
|
||||
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
class CurrentSensorManagerServiceImpl implements CurrentSensorManagerService {
|
||||
|
||||
private static Log log = LogFactory.getLog(CurrentSensorManagerServiceImpl.class);
|
||||
private static ApiApplicationKey apiApplicationKey;
|
||||
private static final String KEY_TYPE = "PRODUCTION";
|
||||
|
||||
private boolean register(String deviceId, String name) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
|
||||
return false;
|
||||
}
|
||||
Device device = new Device();
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
|
||||
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
|
||||
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
|
||||
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
|
||||
device.setName(name);
|
||||
device.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
|
||||
return added;
|
||||
} catch (DeviceManagementException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Response removeDevice(String deviceId) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
|
||||
deviceIdentifier);
|
||||
if (removed) {
|
||||
return Response.ok().build();
|
||||
} else {
|
||||
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response updateDevice(String deviceId, String name) {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
try {
|
||||
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
|
||||
device.setName(name);
|
||||
device.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
|
||||
if (updated) {
|
||||
return Response.ok().build();
|
||||
} else {
|
||||
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error(e.getErrorMessage());
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response getDevice(String deviceId) {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
try {
|
||||
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
return Response.ok().entity(device).build();
|
||||
} catch (DeviceManagementException ex) {
|
||||
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response downloadSketch(String deviceName, String sketchType) {
|
||||
try {
|
||||
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
|
||||
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
|
||||
rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
|
||||
return rb.build();
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return Response.status(400).entity(ex.getMessage()).build();//bad request
|
||||
} catch (DeviceManagementException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (DeviceControllerException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (JWTClientException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (APIManagerException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (UserStoreException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
}
|
||||
}
|
||||
|
||||
private ZipArchive createDownloadFile(String owner, String deviceName)
|
||||
throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException,
|
||||
UserStoreException {
|
||||
if (owner == null) {
|
||||
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
|
||||
}
|
||||
//create new device id
|
||||
String deviceId = shortUUID();
|
||||
String applicationUsername =
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
|
||||
.getAdminUserName();
|
||||
if (apiApplicationKey == null) {
|
||||
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
|
||||
String[] tags = {CurrentSensorConstants.DEVICE_TYPE};
|
||||
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
|
||||
CurrentSensorConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
|
||||
}
|
||||
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
|
||||
String scopes = "device_type_" + CurrentSensorConstants.DEVICE_TYPE + " device_" + deviceId;
|
||||
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
|
||||
apiApplicationKey.getConsumerSecret(), owner,
|
||||
scopes);
|
||||
//create token
|
||||
String accessToken = accessTokenInfo.getAccess_token();
|
||||
String refreshToken = accessTokenInfo.getRefresh_token();
|
||||
//Register the device with CDMF
|
||||
boolean status = register(deviceId, deviceName);
|
||||
if (!status) {
|
||||
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
|
||||
throw new DeviceManagementException(msg);
|
||||
}
|
||||
ZipUtil ziputil = new ZipUtil();
|
||||
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
|
||||
CurrentSensorConstants.DEVICE_TYPE, deviceId,
|
||||
deviceName, accessToken, refreshToken);
|
||||
zipFile.setDeviceId(deviceId);
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
private static String shortUUID() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
|
||||
return Long.toString(l, Character.MAX_RADIX);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package org.homeautomation.currentsensor.api.util;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
|
||||
/**
|
||||
* This class provides utility functions used by REST-API.
|
||||
*/
|
||||
public class APIUtil {
|
||||
|
||||
private static Log log = LogFactory.getLog(APIUtil.class);
|
||||
|
||||
public static String getAuthenticatedUser() {
|
||||
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
String username = threadLocalCarbonContext.getUsername();
|
||||
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
|
||||
if (username.endsWith(tenantDomain)) {
|
||||
return username.substring(0, username.lastIndexOf("@"));
|
||||
}
|
||||
return username;
|
||||
}
|
||||
|
||||
public static String getTenantDomainOftheUser() {
|
||||
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
|
||||
return tenantDomain;
|
||||
}
|
||||
|
||||
public static DeviceManagementProviderService getDeviceManagementService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
DeviceManagementProviderService deviceManagementProviderService =
|
||||
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
|
||||
if (deviceManagementProviderService == null) {
|
||||
String msg = "Device Management service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return deviceManagementProviderService;
|
||||
}
|
||||
|
||||
public static APIManagementProviderService getAPIManagementProviderService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
APIManagementProviderService apiManagementProviderService =
|
||||
(APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null);
|
||||
if (apiManagementProviderService == null) {
|
||||
String msg = "API management provider service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return apiManagementProviderService;
|
||||
}
|
||||
}
|
@ -0,0 +1,108 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<!--
|
||||
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<!-- This file contains the list of permissions that are associated with URL end points
|
||||
of the web app. Each permission should contain the name, permission path ,API path
|
||||
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
|
||||
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
|
||||
NOTE: All the endpoints of the web app should be available in this file. Otherwise
|
||||
it will result 403 error at the runtime.
|
||||
-->
|
||||
<PermissionConfiguration>
|
||||
<APIVersion></APIVersion>
|
||||
<!-- Device related APIs -->
|
||||
<Permission>
|
||||
<name>Get device</name>
|
||||
<path>/device-mgt/user/devices/list</path>
|
||||
<url>/devices/*</url>
|
||||
<method>GET</method>
|
||||
<scope>emm_admin,emm_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Add device</name>
|
||||
<path>/device-mgt/user/devices/add</path>
|
||||
<url>/devices/register</url>
|
||||
<method>PUT</method>
|
||||
<scope>emm_admin,emm_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Download device</name>
|
||||
<path>/device-mgt/user/devices/add</path>
|
||||
<url>/devices/doormanager/download</url>
|
||||
<method>GET</method>
|
||||
<scope>emm_admin,emm_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Generate link to download</name>
|
||||
<path>/device-mgt/user/devices/add</path>
|
||||
<url>/devices/doormanager/generate_link</url>
|
||||
<method>GET</method>
|
||||
<scope>emm_admin,emm_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Update device</name>
|
||||
<path>/device-mgt/user/devices/update</path>
|
||||
<url>/devices/update/*</url>
|
||||
<method>POST</method>
|
||||
<scope>emm_admin,emm_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Remove device</name>
|
||||
<path>/device-mgt/user/devices/remove</path>
|
||||
<url>/devices/remove/*</url>
|
||||
<method>DELETE</method>
|
||||
<scope>emm_admin,emm_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Register Device</name>
|
||||
<path>/device-mgt/user/device/register</path>
|
||||
<url>/device/register/*/*/*/*</url>
|
||||
<method>POST</method>
|
||||
<scope>emm_admin,emm_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Read Current</name>
|
||||
<path>/device-mgt/user/device/read-current</path>
|
||||
<url>/device/read-current</url>
|
||||
<method>GET</method>
|
||||
<scope>emm_admin,emm_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Read Power</name>
|
||||
<path>/device-mgt/user/device/read-power</path>
|
||||
<url>/device/read-power</url>
|
||||
<method>GET</method>
|
||||
<scope>emm_admin,emm_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Read Flow rate</name>
|
||||
<path>/device-mgt/user/device/read-flowrate</path>
|
||||
<url>/device/read-flowrate</url>
|
||||
<method>GET</method>
|
||||
<scope>emm_admin,emm_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Push data</name>
|
||||
<path>/device-mgt/user/device/push-data</path>
|
||||
<url>/device/push-data</url>
|
||||
<method>POST</method>
|
||||
<scope>emm_admin,emm_user</scope>
|
||||
</Permission>
|
||||
</PermissionConfiguration>
|
@ -1,225 +0,0 @@
|
||||
<!--
|
||||
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<parent>
|
||||
<groupId>org.homeautomation</groupId>
|
||||
<artifactId>${project-base-package}-component</artifactId>
|
||||
<version>2.0.4-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>${groupId}.currentsensor.controller</artifactId>
|
||||
<version>2.0.4-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<name>${groupId}.currentsensor.controller API</name>
|
||||
<url>http://wso2.com</url>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<encoding>UTF-8</encoding>
|
||||
<source>${wso2.maven.compiler.source}</source>
|
||||
<target>${wso2.maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
<configuration>
|
||||
<warName>${groupId}.currentsensor.controller</warName>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.homeautomation</groupId>
|
||||
<artifactId>${project-base-package}.plugin</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- CDM -->
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2-client</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2-client</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--CXF -->
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxws</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--IOT -->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpasyncclient</artifactId>
|
||||
<version>4.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--JAX-RS -->
|
||||
<dependency>
|
||||
<groupId>org.codehaus.jackson</groupId>
|
||||
<artifactId>jackson-core-asl</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.jackson</groupId>
|
||||
<artifactId>jackson-jaxrs</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-web-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>jsr311-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-httpclient.wso2</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.bouncycastle.wso2</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.user.api</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.queuing</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.base</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smack</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smackx</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>jaxen</groupId>
|
||||
<artifactId>jaxen</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>commons-fileupload.wso2</groupId>
|
||||
<artifactId>commons-fileupload</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.ant.wso2</groupId>
|
||||
<artifactId>ant</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.ant.wso2</groupId>
|
||||
<artifactId>ant</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>commons-httpclient.wso2</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.eclipse.equinox</groupId>
|
||||
<artifactId>javax.servlet</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.registry.api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smack</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smackx</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.json.wso2</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -1,260 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.currentsensor.manager.api;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.homeautomation.currentsensor.manager.api.dto.DeviceJSON;
|
||||
import org.homeautomation.currentsensor.manager.api.util.CurrentSensorServiceUtils;
|
||||
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
|
||||
import org.wso2.carbon.apimgt.annotations.device.feature.Feature;
|
||||
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.iot.DeviceValidator;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Calendar;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@API(name = "currentsensor", version = "1.0.0", context = "/currentsensor")
|
||||
@DeviceType(value = "currentsensor")
|
||||
public class CurrentSensorControllerService {
|
||||
|
||||
private static Log log = LogFactory.getLog(CurrentSensorControllerService.class);
|
||||
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
|
||||
private static final String SUPER_TENANT = "carbon.super";
|
||||
|
||||
private boolean waitForServerStartup() {
|
||||
while (!DeviceManagement.isServerReady()) {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@Path("controller/register/{owner}/{deviceId}/{ip}/{port}")
|
||||
@POST
|
||||
public String registerDeviceIP(@PathParam("owner") String owner,
|
||||
@PathParam("deviceId") String deviceId,
|
||||
@PathParam("ip") String deviceIP,
|
||||
@PathParam("port") String devicePort,
|
||||
@Context HttpServletResponse response,
|
||||
@Context HttpServletRequest request) {
|
||||
System.out.println("Register Call..");
|
||||
//TODO:: Need to get IP from the request itself
|
||||
String result;
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: " + owner);
|
||||
}
|
||||
|
||||
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
|
||||
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
|
||||
|
||||
result = "Device-IP Registered";
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param owner
|
||||
* @param deviceId
|
||||
* @param protocol
|
||||
* @param response
|
||||
* @return
|
||||
*/
|
||||
@Path("controller/read-current")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature(code = "read-current", name = "Current", type = "monitor",
|
||||
description = "Request current reading from Arduino agent")
|
||||
public SensorRecord requestCurrent(@HeaderParam("owner") String owner,
|
||||
@HeaderParam("deviceId") String deviceId,
|
||||
@HeaderParam("protocol") String protocol,
|
||||
@Context HttpServletResponse response) {
|
||||
SensorRecord sensorRecord = null;
|
||||
|
||||
try {
|
||||
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
|
||||
CurrentSensorConstants.SENSOR_CURRENT);
|
||||
} catch (DeviceControllerException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
return sensorRecord;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param owner
|
||||
* @param deviceId
|
||||
* @param protocol
|
||||
* @param response
|
||||
* @return
|
||||
*/
|
||||
@Path("controller/read-power")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature(code = "read-power", name = "Power x100", type = "monitor",
|
||||
description = "Request power reading from Arduino agent")
|
||||
public SensorRecord requestPower(@HeaderParam("owner") String owner,
|
||||
@HeaderParam("deviceId") String deviceId,
|
||||
@HeaderParam("protocol") String protocol,
|
||||
@Context HttpServletResponse response) {
|
||||
SensorRecord sensorRecord = null;
|
||||
|
||||
try {
|
||||
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
|
||||
CurrentSensorConstants.SENSOR_POWER);
|
||||
} catch (DeviceControllerException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
return sensorRecord;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param owner
|
||||
* @param deviceId
|
||||
* @param protocol
|
||||
* @param response
|
||||
* @return
|
||||
*/
|
||||
@Path("controller/read-flowrate")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature(code = "read-flowrate", name = "Flow Rate x100", type = "monitor",
|
||||
description = "Request flow rate reading from Arduino agent")
|
||||
public SensorRecord requestFlowRate(@HeaderParam("owner") String owner,
|
||||
@HeaderParam("deviceId") String deviceId,
|
||||
@HeaderParam("protocol") String protocol,
|
||||
@Context HttpServletResponse response) {
|
||||
SensorRecord sensorRecord = null;
|
||||
|
||||
try {
|
||||
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
|
||||
CurrentSensorConstants.SENSOR_FLOWRATE);
|
||||
} catch (DeviceControllerException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
return sensorRecord;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param dataMsg
|
||||
* @param response
|
||||
*/
|
||||
@Path("controller/push-data")
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public void pushData(final DeviceJSON dataMsg, @Context HttpServletResponse response) {
|
||||
|
||||
String owner = dataMsg.owner;
|
||||
String deviceId = dataMsg.deviceId;
|
||||
String deviceIp = dataMsg.reply;
|
||||
float current = dataMsg.current;
|
||||
float flow_rate = dataMsg.flow_rate;
|
||||
|
||||
try {
|
||||
DeviceValidator deviceValidator = new DeviceValidator();
|
||||
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId,
|
||||
CurrentSensorConstants.DEVICE_TYPE))) {
|
||||
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
|
||||
log.warn("Temperature data Received from unregistered raspberrypi device [" + deviceId +
|
||||
"] for owner [" + owner + "]");
|
||||
return;
|
||||
}
|
||||
|
||||
String registeredIp = deviceToIpMap.get(deviceId);
|
||||
|
||||
if (registeredIp == null) {
|
||||
log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp +
|
||||
" for device ID - " + deviceId);
|
||||
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
|
||||
return;
|
||||
} else if (!registeredIp.equals(deviceIp)) {
|
||||
log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId +
|
||||
" is already registered under some other IP. Re-registration required");
|
||||
response.setStatus(Response.Status.CONFLICT.getStatusCode());
|
||||
return;
|
||||
}
|
||||
|
||||
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_CURRENT,
|
||||
String.valueOf(current),
|
||||
Calendar.getInstance().getTimeInMillis());
|
||||
|
||||
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_POWER,
|
||||
String.valueOf(current * 230 / 100),
|
||||
Calendar.getInstance().getTimeInMillis());
|
||||
|
||||
SensorDataManager.getInstance().setSensorRecord(deviceId, CurrentSensorConstants.SENSOR_FLOWRATE,
|
||||
String.valueOf(flow_rate/100),
|
||||
Calendar.getInstance().getTimeInMillis());
|
||||
|
||||
if (!CurrentSensorServiceUtils.publishToDASCurrent(dataMsg.owner, dataMsg.deviceId, current)) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId +
|
||||
"] of owner [" + owner + "]");
|
||||
}
|
||||
|
||||
if (!CurrentSensorServiceUtils.publishToDASPower(dataMsg.owner, dataMsg.deviceId, current * 230 / 100)) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
log.warn("An error occured whilst trying to publish pin data of Power Sensor Data with ID [" + deviceId +
|
||||
"] of owner [" + owner + "]");
|
||||
}
|
||||
|
||||
if (!CurrentSensorServiceUtils.publishToDASFlowRate(dataMsg.owner, dataMsg.deviceId, flow_rate/100)) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
log.warn("An error occured whilst trying to publish pin data of Current Sensor Data with ID [" + deviceId +
|
||||
"] of owner [" + owner + "]");
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
String errorMsg = "Validation attempt for deviceId [" + deviceId + "] of owner [" + owner + "] failed.\n";
|
||||
log.error(errorMsg + Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase() + "\n" + e.getErrorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!--
|
||||
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
|
||||
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
|
||||
|
||||
<jaxrs:server id="CurrentSensorController" address="/">
|
||||
<jaxrs:serviceBeans>
|
||||
<bean id="CurrentSensorManagerControllerService"
|
||||
class="org.homeautomation.currentsensor.manager.api.CurrentSensorControllerService">
|
||||
</bean>
|
||||
</jaxrs:serviceBeans>
|
||||
<jaxrs:providers>
|
||||
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
|
||||
</jaxrs:providers>
|
||||
</jaxrs:server>
|
||||
|
||||
</beans>
|
||||
|
@ -1,254 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.currentsensor.manager.api;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
|
||||
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
|
||||
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
|
||||
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
|
||||
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
|
||||
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
@DeviceType(value = "currentsensor")
|
||||
public class CurrentSensorManagerService {
|
||||
|
||||
private static Log log = LogFactory.getLog(CurrentSensorManagerService.class);
|
||||
//TODO; replace this tenant domain
|
||||
private final String SUPER_TENANT = "carbon.super";
|
||||
@Context //injected response proxy supporting multiple thread
|
||||
private HttpServletResponse response;
|
||||
|
||||
@Path("manager/device/register")
|
||||
@PUT
|
||||
public boolean register(@QueryParam("deviceId") String deviceId,
|
||||
@QueryParam("name") String name, @QueryParam("owner") String owner) {
|
||||
|
||||
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
|
||||
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
try {
|
||||
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
|
||||
response.setStatus(Response.Status.CONFLICT.getStatusCode());
|
||||
return false;
|
||||
}
|
||||
|
||||
Device device = new Device();
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
|
||||
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
|
||||
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
|
||||
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
|
||||
device.setName(name);
|
||||
device.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
enrolmentInfo.setOwner(owner);
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device);
|
||||
if (added) {
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
} else {
|
||||
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
|
||||
}
|
||||
|
||||
return added;
|
||||
} catch (DeviceManagementException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
return false;
|
||||
} finally {
|
||||
deviceManagement.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Path("manager/device/remove/{device_id}")
|
||||
@DELETE
|
||||
public void removeDevice(@PathParam("device_id") String deviceId,
|
||||
@Context HttpServletResponse response) {
|
||||
|
||||
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
try {
|
||||
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(
|
||||
deviceIdentifier);
|
||||
if (removed) {
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
} else {
|
||||
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
} finally {
|
||||
deviceManagement.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Path("manager/device/update/{device_id}")
|
||||
@POST
|
||||
public boolean updateDevice(@PathParam("device_id") String deviceId,
|
||||
@QueryParam("name") String name,
|
||||
@Context HttpServletResponse response) {
|
||||
|
||||
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
|
||||
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
try {
|
||||
Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
|
||||
// device.setDeviceTypeId(deviceTypeId);
|
||||
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
|
||||
|
||||
device.setName(name);
|
||||
device.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
|
||||
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device);
|
||||
|
||||
if (updated) {
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
|
||||
} else {
|
||||
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
|
||||
}
|
||||
return updated;
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error(e.getErrorMessage());
|
||||
return false;
|
||||
} finally {
|
||||
deviceManagement.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Path("manager/device/{device_id}")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Device getDevice(@PathParam("device_id") String deviceId) {
|
||||
|
||||
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(CurrentSensorConstants.DEVICE_TYPE);
|
||||
|
||||
try {
|
||||
return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
} catch (DeviceManagementException ex) {
|
||||
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
|
||||
return null;
|
||||
} finally {
|
||||
deviceManagement.endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
@Path("manager/device/{sketch_type}/download")
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response downloadSketch(@QueryParam("owner") String owner,
|
||||
@QueryParam("deviceName") String deviceName,
|
||||
@PathParam("sketch_type") String
|
||||
sketchType) {
|
||||
|
||||
try {
|
||||
ZipArchive zipFile = createDownloadFile(owner, deviceName, sketchType);
|
||||
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
|
||||
response.type("application/zip");
|
||||
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
|
||||
return response.build();
|
||||
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return Response.status(400).entity(ex.getMessage()).build();//bad request
|
||||
} catch (DeviceManagementException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (AccessTokenException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (DeviceControllerException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (IOException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
}
|
||||
}
|
||||
|
||||
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
|
||||
throws DeviceManagementException, AccessTokenException, DeviceControllerException {
|
||||
if (owner == null) {
|
||||
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
|
||||
}
|
||||
|
||||
//create new device id
|
||||
String deviceId = shortUUID();
|
||||
|
||||
KeyGenerationUtil.createApplicationKeys("currentsensor");
|
||||
|
||||
TokenClient accessTokenClient = new TokenClient(CurrentSensorConstants.DEVICE_TYPE);
|
||||
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
|
||||
|
||||
//create token
|
||||
String accessToken = accessTokenInfo.getAccess_token();
|
||||
String refreshToken = accessTokenInfo.getRefresh_token();
|
||||
//adding registering data
|
||||
|
||||
boolean status;
|
||||
|
||||
//Register the device with CDMF
|
||||
status = register(deviceId, deviceName, owner);
|
||||
|
||||
if (!status) {
|
||||
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
|
||||
throw new DeviceManagementException(msg);
|
||||
}
|
||||
|
||||
ZipUtil ziputil = new ZipUtil();
|
||||
ZipArchive zipFile = ziputil.createZipFile(owner, SUPER_TENANT, sketchType, deviceId, deviceName, accessToken,
|
||||
refreshToken);
|
||||
zipFile.setDeviceId(deviceId);
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
private static String shortUUID() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
|
||||
return Long.toString(l, Character.MAX_RADIX);
|
||||
}
|
||||
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
|
||||
<!--
|
||||
~ Copyright 2005-2013 WSO2, Inc. (http://wso2.com)
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<!--
|
||||
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
|
||||
-->
|
||||
<Classloading xmlns="http://wso2.org/projects/as/classloading">
|
||||
|
||||
<!-- Parent-first or child-first. Default behaviour is child-first.-->
|
||||
<ParentFirst>false</ParentFirst>
|
||||
|
||||
<!--
|
||||
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
|
||||
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
|
||||
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
|
||||
-->
|
||||
<Environments>CXF,Carbon</Environments>
|
||||
</Classloading>
|
@ -1,58 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
|
||||
version="2.5">
|
||||
<display-name>Current-Sensor-Agent-Webapp</display-name>
|
||||
<servlet>
|
||||
<description>JAX-WS/JAX-RS IOT Current Sensor Endpoint</description>
|
||||
<display-name>JAX-WS/JAX-RS Servlet</display-name>
|
||||
<servlet-name>CXFServlet</servlet-name>
|
||||
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>CXFServlet</servlet-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<!--publish to apim-->
|
||||
<context-param>
|
||||
<param-name>managed-api-enabled</param-name>
|
||||
<param-value>false</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-owner</param-name>
|
||||
<param-value>admin</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-context-template</param-name>
|
||||
<param-value>/currentsensor/{version}</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-application</param-name>
|
||||
<param-value>currentsensor</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-isSecured</param-name>
|
||||
<param-value>true</param-value>
|
||||
</context-param>
|
||||
|
||||
</web-app>
|
@ -0,0 +1,56 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.currentsensor.plugin.exception;
|
||||
|
||||
public class CurrentSensorDeviceMgtPluginException extends Exception{
|
||||
|
||||
private String errorMessage;
|
||||
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setErrorMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public CurrentSensorDeviceMgtPluginException(String msg, Exception nestedEx) {
|
||||
super(msg, nestedEx);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public CurrentSensorDeviceMgtPluginException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
setErrorMessage(message);
|
||||
}
|
||||
|
||||
public CurrentSensorDeviceMgtPluginException(String msg) {
|
||||
super(msg);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public CurrentSensorDeviceMgtPluginException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public CurrentSensorDeviceMgtPluginException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,242 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.currentsensor.plugin.impl.dao.impl;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
|
||||
import org.homeautomation.currentsensor.plugin.exception.CurrentSensorDeviceMgtPluginException;
|
||||
import org.homeautomation.currentsensor.plugin.impl.dao.CurrentSensorDAOUtil;
|
||||
import org.homeautomation.currentsensor.plugin.impl.util.CurrentSensorUtils;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Implements IotDeviceDAO for current sensor Devices.
|
||||
*/
|
||||
public class CurrentSensorDAO {
|
||||
|
||||
private static final Log log = LogFactory.getLog(CurrentSensorDAO.class);
|
||||
|
||||
public Device getDevice(String deviceId) throws CurrentSensorDeviceMgtPluginException {
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
Device CurrentSensorDevice = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
conn = CurrentSensorDAOUtil.getConnection();
|
||||
String selectDBQuery =
|
||||
"SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN" +
|
||||
" FROM CURRENT_SENSOR_DEVICE WHERE CURRENT_SENSOR_DEVICE_ID = ?";
|
||||
stmt = conn.prepareStatement(selectDBQuery);
|
||||
stmt.setString(1, deviceId);
|
||||
resultSet = stmt.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
CurrentSensorDevice = new Device();
|
||||
CurrentSensorDevice.setName(resultSet.getString(
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME));
|
||||
List<Device.Property> propertyList = new ArrayList<Device.Property>();
|
||||
propertyList.add(CurrentSensorUtils.getProperty(
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN,
|
||||
resultSet.getString("ACCESS_TOKEN")));
|
||||
propertyList.add(CurrentSensorUtils.getProperty(
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN,
|
||||
resultSet.getString("REFRESH_TOKEN")));
|
||||
CurrentSensorDevice.setProperties(propertyList);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Connected Cup service " + deviceId + " data has been fetched from" +
|
||||
"Connected Cup database.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while fetching Connected Cup device : '" + deviceId + "'";
|
||||
log.error(msg, e);
|
||||
throw new CurrentSensorDeviceMgtPluginException(msg, e);
|
||||
} finally {
|
||||
CurrentSensorUtils.cleanupResources(stmt, resultSet);
|
||||
CurrentSensorDAOUtil.closeConnection();
|
||||
}
|
||||
return CurrentSensorDevice;
|
||||
}
|
||||
|
||||
|
||||
public boolean addDevice(Device CurrentSensorDevice) throws CurrentSensorDeviceMgtPluginException {
|
||||
boolean status = false;
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
conn = CurrentSensorDAOUtil.getConnection();
|
||||
String createDBQuery =
|
||||
"INSERT INTO CURRENT_SENSOR_DEVICE(CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME, " +
|
||||
"ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?)";
|
||||
|
||||
stmt = conn.prepareStatement(createDBQuery);
|
||||
stmt.setString(1, CurrentSensorDevice.getDeviceIdentifier());
|
||||
stmt.setString(2, CurrentSensorDevice.getName());
|
||||
stmt.setString(3, CurrentSensorUtils.getDeviceProperty(
|
||||
CurrentSensorDevice.getProperties(),
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN));
|
||||
stmt.setString(4, CurrentSensorUtils.getDeviceProperty(
|
||||
CurrentSensorDevice.getProperties(),
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN));
|
||||
|
||||
int rows = stmt.executeUpdate();
|
||||
if (rows > 0) {
|
||||
status = true;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Connected Cup device " + CurrentSensorDevice.getDeviceIdentifier() +
|
||||
" data has been added to the Connected Cup database.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while adding the Connected Cup device '" +
|
||||
CurrentSensorDevice.getDeviceIdentifier() + "' to the Connected Cup db.";
|
||||
log.error(msg, e);
|
||||
throw new CurrentSensorDeviceMgtPluginException(msg, e);
|
||||
} finally {
|
||||
CurrentSensorUtils.cleanupResources(stmt, null);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
public boolean updateDevice(Device CurrentSensorDevice) throws CurrentSensorDeviceMgtPluginException {
|
||||
boolean status = false;
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
conn = CurrentSensorDAOUtil.getConnection();
|
||||
String updateDBQuery =
|
||||
"UPDATE CURRENT_SENSOR_DEVICE SET DEVICE_NAME = ?, ACCESS_TOKEN=?, " +
|
||||
"REFRESH_TOKEN=? WHERE CURRENT_SENSOR_DEVICE_ID = ?";
|
||||
|
||||
stmt = conn.prepareStatement(updateDBQuery);
|
||||
|
||||
if (CurrentSensorDevice.getProperties() == null) {
|
||||
CurrentSensorDevice.setProperties(new ArrayList<Device.Property>());
|
||||
}
|
||||
stmt.setString(1, CurrentSensorDevice.getName());
|
||||
stmt.setString(2, CurrentSensorUtils.getDeviceProperty(
|
||||
CurrentSensorDevice.getProperties(),
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN));
|
||||
stmt.setString(3, CurrentSensorUtils.getDeviceProperty(
|
||||
CurrentSensorDevice.getProperties(),
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN));
|
||||
stmt.setString(4, CurrentSensorDevice.getDeviceIdentifier());
|
||||
int rows = stmt.executeUpdate();
|
||||
if (rows > 0) {
|
||||
status = true;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Connected Cup device " + CurrentSensorDevice.getDeviceIdentifier() +
|
||||
" data has been modified.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while modifying the Connected Cup device '" +
|
||||
CurrentSensorDevice.getDeviceIdentifier() + "' data.";
|
||||
log.error(msg, e);
|
||||
throw new CurrentSensorDeviceMgtPluginException(msg, e);
|
||||
} finally {
|
||||
CurrentSensorUtils.cleanupResources(stmt, null);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
public boolean deleteDevice(String deviceId) throws CurrentSensorDeviceMgtPluginException {
|
||||
boolean status = false;
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
conn = CurrentSensorDAOUtil.getConnection();
|
||||
String deleteDBQuery =
|
||||
"DELETE FROM CURRENT_SENSOR_DEVICE WHERE CURRENT_SENSOR_DEVICE_ID = ?";
|
||||
stmt = conn.prepareStatement(deleteDBQuery);
|
||||
stmt.setString(1, deviceId);
|
||||
int rows = stmt.executeUpdate();
|
||||
if (rows > 0) {
|
||||
status = true;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Connected Cup device " + deviceId + " data has deleted" +
|
||||
" from the Connected Cup database.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while deleting Connected Cup device " + deviceId;
|
||||
log.error(msg, e);
|
||||
throw new CurrentSensorDeviceMgtPluginException(msg, e);
|
||||
} finally {
|
||||
CurrentSensorUtils.cleanupResources(stmt, null);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
public List<Device> getAllDevices() throws CurrentSensorDeviceMgtPluginException {
|
||||
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet resultSet = null;
|
||||
Device CurrentSensorDevice;
|
||||
List<Device> iotDevices = new ArrayList<>();
|
||||
|
||||
try {
|
||||
conn = CurrentSensorDAOUtil.getConnection();
|
||||
String selectDBQuery =
|
||||
"SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN" +
|
||||
"FROM CURRENT_SENSOR_DEVICE";
|
||||
stmt = conn.prepareStatement(selectDBQuery);
|
||||
resultSet = stmt.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
CurrentSensorDevice = new Device();
|
||||
CurrentSensorDevice.setDeviceIdentifier(resultSet.getString(
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_ID));
|
||||
CurrentSensorDevice.setName(resultSet.getString(
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME));
|
||||
|
||||
List<Device.Property> propertyList = new ArrayList<Device.Property>();
|
||||
propertyList.add(CurrentSensorUtils.getProperty(
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN,
|
||||
resultSet.getString("ACCESS_TOKEN")));
|
||||
propertyList.add(CurrentSensorUtils.getProperty(
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN,
|
||||
resultSet.getString("REFRESH_TOKEN")));
|
||||
CurrentSensorDevice.setProperties(propertyList);
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("All Connected Cup device details have fetched from Connected Cup database" +
|
||||
".");
|
||||
}
|
||||
return iotDevices;
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while fetching all Connected Cup device data'";
|
||||
log.error(msg, e);
|
||||
throw new CurrentSensorDeviceMgtPluginException(msg, e);
|
||||
} finally {
|
||||
CurrentSensorUtils.cleanupResources(stmt, resultSet);
|
||||
CurrentSensorDAOUtil.closeConnection();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,237 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.currentsensor.plugin.impl.dao.impl;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.homeautomation.currentsensor.plugin.constants.CurrentSensorConstants;
|
||||
import org.homeautomation.currentsensor.plugin.impl.dao.CurrentSensorDAO;
|
||||
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceDAO;
|
||||
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException;
|
||||
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.util.IotDeviceManagementDAOUtil;
|
||||
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dto.IotDevice;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Implements IotDeviceDAO for current sensor Devices.
|
||||
*/
|
||||
public class CurrentSensorDeviceDAOImpl implements IotDeviceDAO {
|
||||
|
||||
|
||||
private static final Log log = LogFactory.getLog(CurrentSensorDeviceDAOImpl.class);
|
||||
|
||||
@Override
|
||||
public IotDevice getIotDevice(String iotDeviceId)
|
||||
throws IotDeviceManagementDAOException {
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
IotDevice iotDevice = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
conn = CurrentSensorDAO.getConnection();
|
||||
String selectDBQuery =
|
||||
"SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME" +
|
||||
" FROM CURRENT_SENSOR_DEVICE WHERE CURRENT_SENSOR_DEVICE_ID = ?";
|
||||
stmt = conn.prepareStatement(selectDBQuery);
|
||||
stmt.setString(1, iotDeviceId);
|
||||
resultSet = stmt.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
iotDevice = new IotDevice();
|
||||
iotDevice.setIotDeviceName(resultSet.getString(
|
||||
CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME));
|
||||
Map<String, String> propertyMap = new HashMap<String, String>();
|
||||
|
||||
|
||||
iotDevice.setDeviceProperties(propertyMap);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Current Sensor device " + iotDeviceId + " data has been fetched from " +
|
||||
"Current Sensor database.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while fetching Current Sensor device : '" + iotDeviceId + "'";
|
||||
log.error(msg, e);
|
||||
throw new IotDeviceManagementDAOException(msg, e);
|
||||
} finally {
|
||||
IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet);
|
||||
CurrentSensorDAO.closeConnection();
|
||||
}
|
||||
|
||||
return iotDevice;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addIotDevice(IotDevice iotDevice)
|
||||
throws IotDeviceManagementDAOException {
|
||||
boolean status = false;
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
conn = CurrentSensorDAO.getConnection();
|
||||
String createDBQuery =
|
||||
"INSERT INTO CURRENT_SENSOR_DEVICE(CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
|
||||
|
||||
stmt = conn.prepareStatement(createDBQuery);
|
||||
stmt.setString(1, iotDevice.getIotDeviceId());
|
||||
stmt.setString(2, iotDevice.getIotDeviceName());
|
||||
if (iotDevice.getDeviceProperties() == null) {
|
||||
iotDevice.setDeviceProperties(new HashMap<String, String>());
|
||||
}
|
||||
|
||||
|
||||
int rows = stmt.executeUpdate();
|
||||
if (rows > 0) {
|
||||
status = true;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Current Sensor device " + iotDevice.getIotDeviceId() + " data has been" +
|
||||
" added to the Current Sensor database.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while adding the Current Sensor device '" +
|
||||
iotDevice.getIotDeviceId() + "' to the Current Sensor db.";
|
||||
log.error(msg, e);
|
||||
throw new IotDeviceManagementDAOException(msg, e);
|
||||
} finally {
|
||||
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateIotDevice(IotDevice iotDevice)
|
||||
throws IotDeviceManagementDAOException {
|
||||
boolean status = false;
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
conn = CurrentSensorDAO.getConnection();
|
||||
String updateDBQuery =
|
||||
"UPDATE CURRENT_SENSOR_DEVICE SET DEVICE_NAME = ? WHERE CURRENT_SENSOR_DEVICE_ID = ?";
|
||||
|
||||
stmt = conn.prepareStatement(updateDBQuery);
|
||||
|
||||
if (iotDevice.getDeviceProperties() == null) {
|
||||
iotDevice.setDeviceProperties(new HashMap<String, String>());
|
||||
}
|
||||
stmt.setString(1, iotDevice.getIotDeviceName());
|
||||
|
||||
stmt.setString(2, iotDevice.getIotDeviceId());
|
||||
int rows = stmt.executeUpdate();
|
||||
if (rows > 0) {
|
||||
status = true;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Current Sensor device " + iotDevice.getIotDeviceId() + " data has been" +
|
||||
" modified.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while modifying the Current Sensor device '" +
|
||||
iotDevice.getIotDeviceId() + "' data.";
|
||||
log.error(msg, e);
|
||||
throw new IotDeviceManagementDAOException(msg, e);
|
||||
} finally {
|
||||
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteIotDevice(String iotDeviceId)
|
||||
throws IotDeviceManagementDAOException {
|
||||
boolean status = false;
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
conn = CurrentSensorDAO.getConnection();
|
||||
String deleteDBQuery =
|
||||
"DELETE FROM CURRENT_SENSOR_DEVICE WHERE CURRENT_SENSOR_DEVICE_ID = ?";
|
||||
stmt = conn.prepareStatement(deleteDBQuery);
|
||||
stmt.setString(1, iotDeviceId);
|
||||
int rows = stmt.executeUpdate();
|
||||
if (rows > 0) {
|
||||
status = true;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Current Sensor device " + iotDeviceId + " data has deleted" +
|
||||
" from the Current Sensor database.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while deleting Current Sensor device " + iotDeviceId;
|
||||
log.error(msg, e);
|
||||
throw new IotDeviceManagementDAOException(msg, e);
|
||||
} finally {
|
||||
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<IotDevice> getAllIotDevices()
|
||||
throws IotDeviceManagementDAOException {
|
||||
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet resultSet = null;
|
||||
IotDevice iotDevice;
|
||||
List<IotDevice> iotDevices = new ArrayList<IotDevice>();
|
||||
|
||||
try {
|
||||
conn = CurrentSensorDAO.getConnection();
|
||||
String selectDBQuery =
|
||||
"SELECT CURRENT_SENSOR_DEVICE_ID, DEVICE_NAME " +
|
||||
"FROM CURRENT_SENSOR_DEVICE";
|
||||
stmt = conn.prepareStatement(selectDBQuery);
|
||||
resultSet = stmt.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
iotDevice = new IotDevice();
|
||||
iotDevice.setIotDeviceId(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_ID));
|
||||
iotDevice.setIotDeviceName(resultSet.getString(CurrentSensorConstants.DEVICE_PLUGIN_DEVICE_NAME));
|
||||
|
||||
Map<String, String> propertyMap = new HashMap<String, String>();
|
||||
|
||||
iotDevice.setDeviceProperties(propertyMap);
|
||||
iotDevices.add(iotDevice);
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("All Current Sensor device details have fetched from Current Sensor database.");
|
||||
}
|
||||
return iotDevices;
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while fetching all Current Sensor device data'";
|
||||
log.error(msg, e);
|
||||
throw new IotDeviceManagementDAOException(msg, e);
|
||||
} finally {
|
||||
IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet);
|
||||
CurrentSensorDAO.closeConnection();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.doormanager.api;
|
||||
|
||||
import org.homeautomation.doormanager.api.dto.UserInfo;
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.FormParam;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
@SuppressWarnings("NonJaxWsWebServices")
|
||||
@API(name = "doormanager", version = "1.0.0", context = "/doormanager", tags = {"doormanager"})
|
||||
@DeviceType(value = "doormanager")
|
||||
public interface DoorManagerControllerService {
|
||||
|
||||
/**
|
||||
* Assign new user to lock
|
||||
*
|
||||
* @param owner owner of the device
|
||||
* @param deviceId unique identifier for given device
|
||||
* @param protocol transport protocol which is being using here MQTT
|
||||
* @param cardNumber RFID card number
|
||||
* @param userName user name of RFID card owner
|
||||
* @param emailAddress email address of RFID card owner
|
||||
*/
|
||||
@Path("device/assign-user")
|
||||
@POST
|
||||
@Feature(code = "assign_user", name = "Assign new user to lock", type = "operation",
|
||||
description = "Add new access card to user to control the lock ")
|
||||
Response assignUserToLock(@HeaderParam("owner") String owner,
|
||||
@HeaderParam("deviceId") String deviceId,
|
||||
@HeaderParam("protocol") String protocol,
|
||||
@FormParam("cardNumber") String cardNumber,
|
||||
@FormParam("userName") String userName,
|
||||
@FormParam("emailAddress") String emailAddress);
|
||||
|
||||
|
||||
/**
|
||||
* Change status of door lock safe: LOCK/UNLOCK
|
||||
*
|
||||
* @param owner owner of the device
|
||||
* @param deviceId unique identifier for given device
|
||||
* @param protocol transport protocol which is being using here MQTT
|
||||
* @param state status of lock safe: lock/unlock
|
||||
*/
|
||||
@Path("device/change-status")
|
||||
@POST
|
||||
@Feature(code = "change-status", name = "Change status of door lock safe: LOCK/UNLOCK", type = "operation",
|
||||
description = "Change status of door lock safe: LOCK/UNLOCK")
|
||||
Response changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
|
||||
@HeaderParam("deviceId") String deviceId,
|
||||
@HeaderParam("protocol") String protocol,
|
||||
@FormParam("state") String state);
|
||||
|
||||
/**
|
||||
* Request current status of door lock safe
|
||||
*
|
||||
* @param owner owner of the device
|
||||
* @param deviceId unique identifier for given device
|
||||
* @param protocol transport protocol which is being using here MQTT
|
||||
*/
|
||||
@GET
|
||||
@Path("device/current-status")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature(code = "current-status", name = "Door Locker Status", type = "monitor",
|
||||
description = "Request current status of door safe")
|
||||
Response requestStatusOfDoorLockSafe(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
|
||||
@HeaderParam("protocol") String protocol);
|
||||
|
||||
/**
|
||||
* @param userInfo user information which are required to test given user is authorized to open requested door
|
||||
* @return if user is authorized open the the door allow to open it
|
||||
*/
|
||||
@GET
|
||||
@Path("device/get-user-info")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@SuppressWarnings("unchecked")
|
||||
//This is to avoid unchecked call to put(k, v) into jsonObject. org.json.simple
|
||||
// library uses raw type collections internally.
|
||||
Response get_user_info(final UserInfo userInfo);
|
||||
|
||||
}
|
@ -0,0 +1,226 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.doormanager.api;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.homeautomation.doormanager.api.exception.DoorManagerException;
|
||||
import org.homeautomation.doormanager.api.transport.DoorManagerMQTTConnector;
|
||||
import org.homeautomation.doormanager.api.dto.UserInfo;
|
||||
import org.homeautomation.doormanager.api.util.APIUtil;
|
||||
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
|
||||
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
|
||||
import org.homeautomation.doormanager.plugin.impl.DoorManager;
|
||||
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
|
||||
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
|
||||
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
|
||||
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.user.api.UserStoreManager;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Calendar;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class DoorManagerControllerServiceImpl implements DoorManagerControllerService{
|
||||
|
||||
private static Log log = LogFactory.getLog(DoorManagerControllerServiceImpl.class);
|
||||
private static String CURRENT_STATUS = "doorLockerCurrentStatus";
|
||||
private DoorManager doorManager;
|
||||
private DoorManagerMQTTConnector doorManagerMQTTConnector;
|
||||
private static final String KEY_TYPE = "PRODUCTION";
|
||||
private static ApiApplicationKey apiApplicationKey;
|
||||
|
||||
DoorManagerControllerServiceImpl() {
|
||||
doorManager = new DoorManager();
|
||||
}
|
||||
|
||||
@Context //injected response proxy supporting multiple thread
|
||||
private boolean waitForServerStartup() {
|
||||
while (!IoTServerStartupListener.isServerReady()) {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public DoorManagerMQTTConnector getDoorManagerMQTTConnector() {
|
||||
return doorManagerMQTTConnector;
|
||||
}
|
||||
|
||||
public void setDoorManagerMQTTConnector(final DoorManagerMQTTConnector MQTTConnector) {
|
||||
Runnable connector = new Runnable() {
|
||||
public void run() {
|
||||
if (waitForServerStartup()) {
|
||||
return;
|
||||
}
|
||||
DoorManagerControllerServiceImpl.this.doorManagerMQTTConnector = MQTTConnector;
|
||||
if (MqttConfig.getInstance().isEnabled()) {
|
||||
doorManagerMQTTConnector.connect();
|
||||
} else {
|
||||
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, DoorManagerMQTTConnector" +
|
||||
" not started.");
|
||||
}
|
||||
}
|
||||
};
|
||||
Thread connectorThread = new Thread(connector);
|
||||
connectorThread.setDaemon(true);
|
||||
connectorThread.start();
|
||||
}
|
||||
|
||||
|
||||
public Response assignUserToLock(String owner, String deviceId, String protocol, String cardNumber, String userName,
|
||||
String emailAddress) {
|
||||
|
||||
if (userName != null && cardNumber != null && deviceId != null) {
|
||||
try {
|
||||
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
|
||||
DoorLockSafe doorLockSafe = new DoorLockSafe();
|
||||
if (userStoreManager.isExistingUser(userName)) {
|
||||
if (apiApplicationKey == null) {
|
||||
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
|
||||
.getAdminUserName();
|
||||
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
|
||||
String[] tags = {DoorManagerConstants.DEVICE_TYPE};
|
||||
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
|
||||
DoorManagerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
|
||||
}
|
||||
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
|
||||
String scopes = "device_type_" + DoorManagerConstants.DEVICE_TYPE + " device_" + deviceId;
|
||||
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
|
||||
apiApplicationKey.getConsumerSecret(), owner, scopes);
|
||||
String accessToken = accessTokenInfo.getAccess_token();
|
||||
if (accessToken == null) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
Map<String, String> claims = new HashMap<>();
|
||||
claims.put(DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, accessToken);
|
||||
claims.put(DoorManagerConstants.DEVICE_CLAIMS_REFRESH_TOKEN,
|
||||
accessTokenInfo.getRefresh_token());
|
||||
claims.put(DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, cardNumber);
|
||||
userStoreManager.setUserClaimValues(userName, claims, null);
|
||||
doorLockSafe.setAccessToken(accessTokenInfo.getAccess_token());
|
||||
doorLockSafe.setRefreshToken(accessTokenInfo.getRefresh_token());
|
||||
doorLockSafe.setDeviceId(deviceId);
|
||||
doorLockSafe.setOwner(owner);
|
||||
doorLockSafe.setEmailAddress(emailAddress);
|
||||
doorLockSafe.setUIDofUser(cardNumber);
|
||||
doorLockSafe.setSerialNumber(deviceId);
|
||||
if (doorManager.assignUserToLock(doorLockSafe)) {
|
||||
return Response.ok().build();
|
||||
} else {
|
||||
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
|
||||
}
|
||||
} else {
|
||||
return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
|
||||
}
|
||||
} catch (UserStoreException e) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
} catch (JWTClientException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
} catch (APIManagerException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
} catch (DoorManagerDeviceMgtPluginException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
} else {
|
||||
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response changeStatusOfDoorLockSafe(String owner, String deviceId, String protocol, String state) {
|
||||
try {
|
||||
int lockerCurrentState;
|
||||
if (state.toUpperCase().equals("LOCK")) {
|
||||
lockerCurrentState = 0;
|
||||
} else {
|
||||
lockerCurrentState = 1;
|
||||
}
|
||||
SensorDataManager.getInstance().setSensorRecord(deviceId, CURRENT_STATUS,
|
||||
String.valueOf(lockerCurrentState), Calendar.getInstance().getTimeInMillis());
|
||||
doorManagerMQTTConnector.sendCommandViaMQTT(owner, deviceId, "DoorManager:", state.toUpperCase());
|
||||
return Response.ok().build();
|
||||
} catch (DeviceManagementException e) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
} catch (DoorManagerException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response requestStatusOfDoorLockSafe(String owner, String deviceId, String protocol) {
|
||||
SensorRecord sensorRecord = null;
|
||||
try {
|
||||
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, CURRENT_STATUS);
|
||||
return Response.ok(sensorRecord).entity(sensorRecord).build();
|
||||
} catch (DeviceControllerException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response get_user_info(final UserInfo userInfo) {
|
||||
if (userInfo.userName != null && userInfo.cardNumber != null && userInfo.deviceId != null) {
|
||||
try {
|
||||
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
|
||||
if (userStoreManager.isExistingUser(userInfo.userName)) {
|
||||
String accessToken = userStoreManager.getUserClaimValue(userInfo.userName,
|
||||
DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, null);
|
||||
String cardNumber = userStoreManager.getUserClaimValue(userInfo.userName,
|
||||
DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, null);
|
||||
if (cardNumber != null) {
|
||||
if (cardNumber.equals(userInfo.cardNumber)) {
|
||||
if (accessToken != null) {
|
||||
JSONObject credentials = new JSONObject();
|
||||
credentials.put(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN, accessToken);
|
||||
//return Response.ok(credentials, MediaType.APPLICATION_JSON_TYPE).build();
|
||||
return Response.status(Response.Status.OK).build();
|
||||
}
|
||||
}
|
||||
return Response.status(Response.Status.UNAUTHORIZED).build();
|
||||
}
|
||||
|
||||
} else {
|
||||
return Response.status(Response.Status.UNAUTHORIZED).build();
|
||||
}
|
||||
} catch (UserStoreException e) {
|
||||
log.error(e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
}
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.doormanager.api;
|
||||
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
@SuppressWarnings("NonJaxWsWebServices")
|
||||
@DeviceType(value = "doormanager")
|
||||
@API(name = "doormanager_mgt", version = "1.0.0", context = "/doormanager_mgt" , tags = {"doormanager"})
|
||||
public interface DoorManagerManagerService {
|
||||
|
||||
@Path("devices/{device_id}")
|
||||
@DELETE
|
||||
Response removeDevice(@PathParam("device_id") String deviceId);
|
||||
|
||||
|
||||
@Path("devices/{device_id}")
|
||||
@PUT
|
||||
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
|
||||
|
||||
@Path("devices/{device_id}")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
Response getDevice(@PathParam("device_id") String deviceId);
|
||||
|
||||
@Path("devices/download")
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
Response downloadSketch(@QueryParam("deviceName") String deviceName);
|
||||
|
||||
|
||||
@Path("devices/generate_link")
|
||||
@GET
|
||||
Response generateSketchLink(@QueryParam("deviceName") String deviceName);
|
||||
|
||||
}
|
@ -0,0 +1,232 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.doormanager.api;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.homeautomation.doormanager.api.util.APIUtil;
|
||||
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
|
||||
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
|
||||
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
|
||||
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
public class DoorManagerManagerServiceImpl implements DoorManagerManagerService{
|
||||
|
||||
private static Log log = LogFactory.getLog(DoorManagerManagerServiceImpl.class);
|
||||
@Context //injected response proxy supporting multiple thread
|
||||
private HttpServletResponse response;
|
||||
private static ApiApplicationKey apiApplicationKey;
|
||||
private static final String KEY_TYPE = "PRODUCTION";
|
||||
|
||||
/**
|
||||
* Generate UUID
|
||||
*
|
||||
* @return generated UUID
|
||||
*/
|
||||
private static String shortUUID() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
|
||||
return Long.toString(l, Character.MAX_RADIX);
|
||||
}
|
||||
|
||||
private boolean register(String deviceId,String name) {
|
||||
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
|
||||
return false;
|
||||
}
|
||||
Device device = new Device();
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
|
||||
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
|
||||
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
|
||||
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
|
||||
device.setName(name);
|
||||
device.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
|
||||
return added;
|
||||
} catch (DeviceManagementException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Response removeDevice(String deviceId) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
|
||||
deviceIdentifier);
|
||||
if (removed) {
|
||||
return Response.ok().build();
|
||||
} else {
|
||||
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response updateDevice(String deviceId, String name) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
|
||||
device.setName(name);
|
||||
device.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
|
||||
if (updated) {
|
||||
return Response.ok().build();
|
||||
} else {
|
||||
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response getDevice(String deviceId) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
return Response.ok().entity(device).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response downloadSketch(String deviceName) {
|
||||
try {
|
||||
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
|
||||
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
|
||||
response.type("application/zip");
|
||||
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
|
||||
return response.build();
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return Response.status(400).entity(ex.getMessage()).build();//bad request
|
||||
} catch (DeviceManagementException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (JWTClientException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (APIManagerException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (DeviceControllerException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (IOException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (UserStoreException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Response generateSketchLink(String deviceName) {
|
||||
try {
|
||||
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
|
||||
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
|
||||
return rb.build();
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return Response.status(400).entity(ex.getMessage()).build();//bad request
|
||||
} catch (DeviceManagementException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (JWTClientException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (APIManagerException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (DeviceControllerException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (UserStoreException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
}
|
||||
}
|
||||
|
||||
private ZipArchive createDownloadFile(String owner, String deviceName)
|
||||
throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException,
|
||||
UserStoreException {
|
||||
if (owner == null) {
|
||||
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
|
||||
}
|
||||
//create new device id
|
||||
String deviceId = shortUUID();
|
||||
String applicationUsername =
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
|
||||
.getAdminUserName();
|
||||
if (apiApplicationKey == null) {
|
||||
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
|
||||
String[] tags = {DoorManagerConstants.DEVICE_TYPE};
|
||||
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
|
||||
DoorManagerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
|
||||
}
|
||||
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
|
||||
String scopes = "device_type_" + DoorManagerConstants.DEVICE_TYPE + " device_" + deviceId;
|
||||
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
|
||||
apiApplicationKey.getConsumerSecret(), owner,
|
||||
scopes);
|
||||
//create token
|
||||
String accessToken = accessTokenInfo.getAccess_token();
|
||||
String refreshToken = accessTokenInfo.getRefresh_token();
|
||||
//Register the device with CDMF
|
||||
boolean status = register(deviceId, deviceName);
|
||||
if (!status) {
|
||||
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
|
||||
throw new DeviceManagementException(msg);
|
||||
}
|
||||
ZipUtil ziputil = new ZipUtil();
|
||||
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
|
||||
DoorManagerConstants.DEVICE_TYPE, deviceId,
|
||||
deviceName, accessToken, refreshToken);
|
||||
zipFile.setDeviceId(deviceId);
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
}
|
@ -1,228 +0,0 @@
|
||||
<!--/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/-->
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.homeautomation</groupId>
|
||||
<artifactId>doormanager-component</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.homeautomation.doormanager.controller</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<name>org.homeautomation.doormanager.controller</name>
|
||||
<url>http://wso2.com</url>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<encoding>UTF-8</encoding>
|
||||
<source>${wso2.maven.compiler.source}</source>
|
||||
<target>${wso2.maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>${maven-war-plugin.version}</version>
|
||||
<configuration>
|
||||
<warName>org.homeautomation.doormanager.controller</warName>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.homeautomation</groupId>
|
||||
<artifactId>org.homeautomation.doormanager.plugin</artifactId>
|
||||
</dependency>
|
||||
<!-- CDM -->
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2-client</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2-client</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--CXF -->
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxws</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--IOT -->
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpasyncclient</artifactId>
|
||||
<version>4.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--MQTT -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--JAX-RS -->
|
||||
<dependency>
|
||||
<groupId>org.codehaus.jackson</groupId>
|
||||
<artifactId>jackson-core-asl</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.jackson</groupId>
|
||||
<artifactId>jackson-jaxrs</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-web-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>jsr311-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-httpclient.wso2</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.bouncycastle.wso2</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.user.api</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.queuing</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.base</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smack</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smackx</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>jaxen</groupId>
|
||||
<artifactId>jaxen</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>commons-fileupload.wso2</groupId>
|
||||
<artifactId>commons-fileupload</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.ant.wso2</groupId>
|
||||
<artifactId>ant</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.ant.wso2</groupId>
|
||||
<artifactId>ant</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>commons-httpclient.wso2</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.eclipse.equinox</groupId>
|
||||
<artifactId>javax.servlet</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.registry.api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smack</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smackx</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.json.wso2</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.user.core</artifactId>
|
||||
<version>4.4.3</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -1,326 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.doormanager.controller.api;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.homeautomation.doormanager.controller.api.dto.UserInfo;
|
||||
import org.homeautomation.doormanager.controller.api.exception.DoorManagerException;
|
||||
import org.homeautomation.doormanager.controller.api.transport.DoorManagerMQTTConnector;
|
||||
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
|
||||
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
|
||||
import org.homeautomation.doormanager.plugin.impl.DoorManager;
|
||||
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
|
||||
import org.wso2.carbon.apimgt.annotations.device.feature.Feature;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
|
||||
import org.wso2.carbon.device.mgt.iot.DeviceValidator;
|
||||
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
|
||||
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
|
||||
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.user.api.UserStoreManager;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.FormParam;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Calendar;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@SuppressWarnings("NonJaxWsWebServices")
|
||||
@API(name = "doormanager", version = "1.0.0", context = "/doormanager")
|
||||
@DeviceType(value = "doormanager")
|
||||
public class DoorManagerControllerService {
|
||||
|
||||
private static Log log = LogFactory.getLog(DoorManagerControllerService.class);
|
||||
private static String CURRENT_STATUS = "doorLockerCurrentStatus";
|
||||
private DoorManager doorManager;
|
||||
private DoorManagerMQTTConnector doorManagerMQTTConnector;
|
||||
|
||||
DoorManagerControllerService() {
|
||||
doorManager = new DoorManager();
|
||||
}
|
||||
|
||||
@Context //injected response proxy supporting multiple thread
|
||||
private boolean waitForServerStartup() {
|
||||
while (!DeviceManagement.isServerReady()) {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public DoorManagerMQTTConnector getDoorManagerMQTTConnector() {
|
||||
return doorManagerMQTTConnector;
|
||||
}
|
||||
|
||||
public void setDoorManagerMQTTConnector(final DoorManagerMQTTConnector MQTTConnector) {
|
||||
Runnable connector = new Runnable() {
|
||||
public void run() {
|
||||
if (waitForServerStartup()) {
|
||||
return;
|
||||
}
|
||||
DoorManagerControllerService.this.doorManagerMQTTConnector = MQTTConnector;
|
||||
if (MqttConfig.getInstance().isEnabled()) {
|
||||
doorManagerMQTTConnector.connect();
|
||||
} else {
|
||||
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, DoorManagerMQTTConnector" +
|
||||
" not started.");
|
||||
}
|
||||
}
|
||||
};
|
||||
Thread connectorThread = new Thread(connector);
|
||||
connectorThread.setDaemon(true);
|
||||
connectorThread.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign new user to lock
|
||||
*
|
||||
* @param owner owner of the device
|
||||
* @param deviceId unique identifier for given device
|
||||
* @param protocol transport protocol which is being using here MQTT
|
||||
* @param cardNumber RFID card number
|
||||
* @param userName user name of RFID card owner
|
||||
* @param emailAddress email address of RFID card owner
|
||||
*/
|
||||
@Path("controller/assign_user")
|
||||
@POST
|
||||
@Feature(code = "assign_user", name = "Assign new user to lock", type = "operation",
|
||||
description = "Add new access card to user to control the lock ")
|
||||
public void assignUserToLock(@HeaderParam("owner") String owner,
|
||||
@HeaderParam("deviceId") String deviceId,
|
||||
@HeaderParam("protocol") String protocol,
|
||||
@FormParam("cardNumber") String cardNumber,
|
||||
@FormParam("userName") String userName,
|
||||
@FormParam("emailAddress") String emailAddress,
|
||||
@Context HttpServletResponse response) {
|
||||
|
||||
if (userName != null && cardNumber != null && deviceId != null) {
|
||||
try {
|
||||
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
|
||||
DoorLockSafe doorLockSafe = new DoorLockSafe();
|
||||
if (userStoreManager.isExistingUser(userName)) {
|
||||
TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
|
||||
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(deviceId, userName);
|
||||
String accessToken = accessTokenInfo.getAccess_token();
|
||||
if (accessToken == null) {
|
||||
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
|
||||
}
|
||||
Map<String, String> claims = new HashMap<>();
|
||||
claims.put(DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, accessToken);
|
||||
claims.put(DoorManagerConstants.DEVICE_CLAIMS_REFRESH_TOKEN,
|
||||
accessTokenInfo.getRefresh_token());
|
||||
claims.put(DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, cardNumber);
|
||||
userStoreManager.setUserClaimValues(userName, claims, null);
|
||||
doorLockSafe.setAccessToken(accessTokenInfo.getAccess_token());
|
||||
doorLockSafe.setRefreshToken(accessTokenInfo.getRefresh_token());
|
||||
doorLockSafe.setDeviceId(deviceId);
|
||||
doorLockSafe.setOwner(owner);
|
||||
doorLockSafe.setEmailAddress(emailAddress);
|
||||
doorLockSafe.setUIDofUser(cardNumber);
|
||||
doorLockSafe.setSerialNumber(deviceId);
|
||||
if (doorManager.assignUserToLock(doorLockSafe)) {
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
} else {
|
||||
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
|
||||
}
|
||||
} else {
|
||||
response.setStatus(Response.Status.NOT_FOUND.getStatusCode());
|
||||
}
|
||||
} catch (UserStoreException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
log.error(e);
|
||||
} catch (DoorManagerDeviceMgtPluginException | AccessTokenException e) {
|
||||
log.error(e);
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
} else {
|
||||
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Change status of door lock safe: LOCK/UNLOCK
|
||||
*
|
||||
* @param owner owner of the device
|
||||
* @param deviceId unique identifier for given device
|
||||
* @param protocol transport protocol which is being using here MQTT
|
||||
* @param state status of lock safe: lock/unlock
|
||||
*/
|
||||
@Path("controller/change-status")
|
||||
@POST
|
||||
@Feature(code = "change-status", name = "Change status of door lock safe: LOCK/UNLOCK", type = "operation",
|
||||
description = "Change status of door lock safe: LOCK/UNLOCK")
|
||||
public void changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
|
||||
@HeaderParam("deviceId") String deviceId,
|
||||
@HeaderParam("protocol") String protocol,
|
||||
@FormParam("state") String state,
|
||||
@Context HttpServletResponse response) {
|
||||
try {
|
||||
int lockerCurrentState;
|
||||
if (state.toUpperCase().equals("LOCK")) {
|
||||
lockerCurrentState = 0;
|
||||
} else {
|
||||
lockerCurrentState = 1;
|
||||
}
|
||||
SensorDataManager.getInstance().setSensorRecord(deviceId, CURRENT_STATUS,
|
||||
String.valueOf(lockerCurrentState), Calendar.getInstance().getTimeInMillis());
|
||||
doorManagerMQTTConnector.sendCommandViaMQTT(owner, deviceId, "DoorManager:", state.toUpperCase());
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error(e);
|
||||
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
|
||||
} catch (DoorManagerException e) {
|
||||
log.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request current status of door lock safe
|
||||
*
|
||||
* @param owner owner of the device
|
||||
* @param deviceId unique identifier for given device
|
||||
* @param protocol transport protocol which is being using here MQTT
|
||||
* @param response http servlet response object
|
||||
*/
|
||||
@GET
|
||||
@Path("controller/current-status")
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Feature(code = "current-status", name = "Door Locker Status", type = "monitor",
|
||||
description = "Request current status of door safe")
|
||||
public SensorRecord requestStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
|
||||
@HeaderParam("deviceId") String deviceId,
|
||||
@HeaderParam("protocol") String protocol,
|
||||
@Context HttpServletResponse response) {
|
||||
SensorRecord sensorRecord = null;
|
||||
DeviceValidator deviceValidator = new DeviceValidator();
|
||||
try {
|
||||
if (!deviceValidator.isExist(owner, CarbonContext.getThreadLocalCarbonContext().getTenantDomain(),
|
||||
new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE))) {
|
||||
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
|
||||
}
|
||||
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, CURRENT_STATUS);
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
} catch (DeviceControllerException | DeviceManagementException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
return sensorRecord;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param userInfo user information which are required to test given user is authorized to open requested door
|
||||
* @return if user is authorized open the the door allow to open it
|
||||
*/
|
||||
@POST
|
||||
@Path("controller/get_user_info")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@SuppressWarnings("unchecked") //This is to avoid unchecked call to put(k, v) into jsonObject. org.json.simple
|
||||
// library uses raw type collections internally.
|
||||
public Response get_user_info(final UserInfo userInfo) {
|
||||
if (userInfo.userName != null && userInfo.cardNumber != null && userInfo.deviceId != null) {
|
||||
try {
|
||||
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
|
||||
if (userStoreManager.isExistingUser(userInfo.userName)) {
|
||||
String accessToken = userStoreManager.getUserClaimValue(userInfo.userName,
|
||||
DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, null);
|
||||
String cardNumber = userStoreManager.getUserClaimValue(userInfo.userName,
|
||||
DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, null);
|
||||
if (cardNumber != null) {
|
||||
if (cardNumber.equals(userInfo.cardNumber)) {
|
||||
if (accessToken != null) {
|
||||
JSONObject credentials = new JSONObject();
|
||||
credentials.put(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN, accessToken);
|
||||
//return Response.ok(credentials, MediaType.APPLICATION_JSON_TYPE).build();
|
||||
return Response.status(Response.Status.OK).build();
|
||||
}
|
||||
}
|
||||
return Response.status(Response.Status.UNAUTHORIZED).build();
|
||||
}
|
||||
|
||||
} else {
|
||||
return Response.status(Response.Status.UNAUTHORIZED).build();
|
||||
}
|
||||
} catch (UserStoreException e) {
|
||||
log.error(e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (JSONException e) {
|
||||
log.error(e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
}
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
|
||||
/*
|
||||
private void sendCEPEvent(String deviceId, String cardId, boolean accessStatus){
|
||||
String cepEventReciever = "http://localhost:9768/endpoints/LockEventReciever";
|
||||
|
||||
HttpClient httpClient = new SystemDefaultHttpClient();
|
||||
HttpPost method = new HttpPost(cepEventReciever);
|
||||
JsonObject event = new JsonObject();
|
||||
JsonObject metaData = new JsonObject();
|
||||
|
||||
metaData.addProperty("deviceID", deviceId);
|
||||
metaData.addProperty("cardID", cardId);
|
||||
|
||||
event.add("metaData", metaData);
|
||||
|
||||
String eventString = "{\"event\": " + event + "}";
|
||||
|
||||
try {
|
||||
StringEntity entity = new StringEntity(eventString);
|
||||
method.setEntity(entity);
|
||||
if (cepEventReciever.startsWith("https")) {
|
||||
method.setHeader("Authorization", "Basic " + Base64.encode(("admin" + ":" + "admin").getBytes()));
|
||||
}
|
||||
httpClient.execute(method).getEntity().getContent().close();
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
log.error("Error while constituting CEP event"+ e.getMessage());
|
||||
} catch (ClientProtocolException e) {
|
||||
log.error("Error while sending message to CEP "+ e.getMessage());
|
||||
} catch (IOException e) {
|
||||
log.error("Error while sending message to CEP "+ e.getMessage());
|
||||
}
|
||||
}*/
|
||||
}
|
@ -1,336 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.homeautomation.doormanager.manager.api;
|
||||
|
||||
import org.apache.commons.httpclient.HttpStatus;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.homeautomation.doormanager.manager.api.util.APIUtil;
|
||||
import org.homeautomation.doormanager.manager.api.util.ResponsePayload;
|
||||
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
|
||||
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
|
||||
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
|
||||
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@SuppressWarnings("NonJaxWsWebServices")
|
||||
@DeviceType(value = "doormanager")
|
||||
@API(name = "doormanager_mgt", version = "1.0.0", context = "/doormanager_mgt")
|
||||
public class DoorManagerManagerService {
|
||||
|
||||
private static Log log = LogFactory.getLog(DoorManagerManagerService.class);
|
||||
@Context //injected response proxy supporting multiple thread
|
||||
private HttpServletResponse response;
|
||||
|
||||
/**
|
||||
* Generate UUID
|
||||
*
|
||||
* @return generated UUID
|
||||
*/
|
||||
private static String shortUUID() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
|
||||
return Long.toString(l, Character.MAX_RADIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register new device into IoT Server
|
||||
*
|
||||
* @param name name of new device
|
||||
* @return registration status
|
||||
*/
|
||||
@Path("manager/device/register")
|
||||
@POST
|
||||
public boolean register(@QueryParam("deviceId") String deviceId,
|
||||
@QueryParam("name") String name) {
|
||||
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
try {
|
||||
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
|
||||
response.setStatus(Response.Status.CONFLICT.getStatusCode());
|
||||
return false;
|
||||
}
|
||||
String owner = APIUtil.getAuthenticatedUser();
|
||||
Device device = new Device();
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
|
||||
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
|
||||
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
|
||||
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
|
||||
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
|
||||
device.setName(name);
|
||||
device.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
enrolmentInfo.setOwner(owner);
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
KeyGenerationUtil.createApplicationKeys(DoorManagerConstants.DEVICE_TYPE);
|
||||
TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
|
||||
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
|
||||
|
||||
//create token
|
||||
String accessToken = accessTokenInfo.getAccess_token();
|
||||
String refreshToken = accessTokenInfo.getRefresh_token();
|
||||
List<Device.Property> properties = new ArrayList<>();
|
||||
|
||||
Device.Property accessTokenProperty = new Device.Property();
|
||||
accessTokenProperty.setName(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN);
|
||||
log.warn("locker access Token :" + accessToken);
|
||||
accessTokenProperty.setValue(accessToken);
|
||||
|
||||
Device.Property refreshTokenProperty = new Device.Property();
|
||||
refreshTokenProperty.setName(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN);
|
||||
refreshTokenProperty.setValue(refreshToken);
|
||||
|
||||
properties.add(accessTokenProperty);
|
||||
properties.add(refreshTokenProperty);
|
||||
device.setProperties(properties);
|
||||
|
||||
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
|
||||
if (added) {
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
} else {
|
||||
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
|
||||
}
|
||||
return added;
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error(e);
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
return false;
|
||||
} catch (AccessTokenException e) {
|
||||
log.error(e);
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove installed device
|
||||
*
|
||||
* @param deviceId unique identifier for device
|
||||
* @param response to request
|
||||
*/
|
||||
@Path("manager/device/remove/{device_id}")
|
||||
@DELETE
|
||||
public void removeDevice(@PathParam("device_id") String deviceId,
|
||||
@Context HttpServletResponse response) {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
try {
|
||||
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
|
||||
deviceIdentifier);
|
||||
if (removed) {
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
} else {
|
||||
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update device name
|
||||
*
|
||||
* @param deviceId unique identifier for device
|
||||
* @param name new name of the device
|
||||
* @param response to request
|
||||
* @return update status
|
||||
*/
|
||||
@Path("manager/device/update/{device_id}")
|
||||
@POST
|
||||
public boolean updateDevice(@PathParam("device_id") String deviceId,
|
||||
@QueryParam("name") String name,
|
||||
@Context HttpServletResponse response) {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
try {
|
||||
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
|
||||
device.setName(name);
|
||||
device.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
|
||||
if (updated) {
|
||||
response.setStatus(Response.Status.OK.getStatusCode());
|
||||
} else {
|
||||
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
|
||||
}
|
||||
return updated;
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error(e.getErrorMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get device information
|
||||
*
|
||||
* @param deviceId unique identifier for device
|
||||
* @return device
|
||||
*/
|
||||
@Path("manager/device/{device_id}")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Device getDevice(@PathParam("device_id") String deviceId) {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
try {
|
||||
return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
} catch (DeviceManagementException ex) {
|
||||
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This will download the agent for given device type
|
||||
*
|
||||
* @param deviceName name of the device which is to be created
|
||||
* @param sketchType name of sketch type
|
||||
* @return agent archive
|
||||
*/
|
||||
@Path("manager/device/{sketch_type}/download")
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
|
||||
@PathParam("sketch_type") String sketchType) {
|
||||
try {
|
||||
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
|
||||
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
|
||||
response.type("application/zip");
|
||||
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
|
||||
|
||||
return response.build();
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return Response.status(400).entity(ex.getMessage()).build();//bad request
|
||||
} catch (DeviceManagementException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (AccessTokenException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (DeviceControllerException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (IOException ex) {
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This will give link to generated agent
|
||||
*
|
||||
* @param deviceName name of the device which is to be created
|
||||
* @param sketchType name of sketch type
|
||||
* @return link to generated agent
|
||||
*/
|
||||
@Path("manager/device/{sketch_type}/generate_link")
|
||||
@GET
|
||||
public Response generateSketchLink(@QueryParam("deviceName") String deviceName,
|
||||
@PathParam("sketch_type") String sketchType) {
|
||||
try {
|
||||
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
|
||||
ResponsePayload responsePayload = new ResponsePayload();
|
||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||
responsePayload.setMessageFromServer("Sending Requested sketch by type: " + sketchType +
|
||||
" and id: " + zipFile.getDeviceId() + ".");
|
||||
responsePayload.setResponseContent(zipFile.getDeviceId());
|
||||
return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(ex.getMessage()).build();
|
||||
} catch (DeviceManagementException ex) {
|
||||
log.error("Error occurred while creating device with name " + deviceName + "\n", ex);
|
||||
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
|
||||
} catch (AccessTokenException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
|
||||
} catch (DeviceControllerException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This will give link to generated agent
|
||||
*
|
||||
* @param deviceName name of the device which is to be created
|
||||
* @param sketchType name of sketch type
|
||||
* @return link to generated agent
|
||||
*/
|
||||
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
|
||||
throws DeviceManagementException, AccessTokenException, DeviceControllerException {
|
||||
if (owner == null) {
|
||||
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
|
||||
}
|
||||
//create new device id
|
||||
String deviceId = shortUUID();
|
||||
KeyGenerationUtil.createApplicationKeys(DoorManagerConstants.DEVICE_TYPE);
|
||||
TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
|
||||
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
|
||||
//create token
|
||||
String accessToken = accessTokenInfo.getAccess_token();
|
||||
String refreshToken = accessTokenInfo.getRefresh_token();
|
||||
//adding registering data
|
||||
boolean status;
|
||||
//Register the device with CDMF
|
||||
status = register(deviceId, deviceName);
|
||||
if (!status) {
|
||||
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
|
||||
throw new DeviceManagementException(msg);
|
||||
}
|
||||
ZipUtil ziputil = new ZipUtil();
|
||||
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOfUser(), sketchType,
|
||||
deviceId, deviceName, accessToken, refreshToken);
|
||||
zipFile.setDeviceId(deviceId);
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
<!--
|
||||
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<!--
|
||||
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
|
||||
-->
|
||||
<Classloading xmlns="http://wso2.org/projects/as/classloading">
|
||||
|
||||
<!-- Parent-first or child-first. Default behaviour is child-first.-->
|
||||
<ParentFirst>false</ParentFirst>
|
||||
|
||||
<!--
|
||||
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
|
||||
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
|
||||
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
|
||||
-->
|
||||
<Environments>CXF,Carbon</Environments>
|
||||
</Classloading>
|
@ -1,38 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!--
|
||||
~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
|
||||
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
|
||||
|
||||
<jaxrs:server id="DoorManager" address="/">
|
||||
<jaxrs:serviceBeans>
|
||||
<bean id="DoorManagerService"
|
||||
class="org.homeautomation.doormanager.manager.api.DoorManagerManagerService">
|
||||
</bean>
|
||||
</jaxrs:serviceBeans>
|
||||
<jaxrs:providers>
|
||||
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
|
||||
</jaxrs:providers>
|
||||
</jaxrs:server>
|
||||
|
||||
</beans>
|
||||
|
@ -1,66 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
|
||||
version="2.5">
|
||||
<display-name>Sample-Webapp-Manager</display-name>
|
||||
<servlet>
|
||||
<description>JAX-WS/JAX-RS Endpoint</description>
|
||||
<display-name>JAX-WS/JAX-RS Servlet</display-name>
|
||||
<servlet-name>CXFServlet</servlet-name>
|
||||
<servlet-class>
|
||||
org.apache.cxf.transport.servlet.CXFServlet
|
||||
</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>CXFServlet</servlet-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
<context-param>
|
||||
<param-name>isAdminService</param-name>
|
||||
<param-value>false</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>doAuthentication</param-name>
|
||||
<param-value>true</param-value>
|
||||
</context-param>
|
||||
<!--publish to apim-->
|
||||
<context-param>
|
||||
<param-name>managed-api-enabled</param-name>
|
||||
<param-value>false</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-owner</param-name>
|
||||
<param-value>admin</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-context-template</param-name>
|
||||
<param-value>/doormanager/{version}</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-application</param-name>
|
||||
<param-value>doormanager</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>managed-api-isSecured</param-name>
|
||||
<param-value>true</param-value>
|
||||
</context-param>
|
||||
</web-app>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue