changing source code according to new API changes

merge-requests/1/head
GPrathap 9 years ago
parent e2ce28767e
commit 5dd57a157e

@ -15,19 +15,19 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/--> */-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<groupId>org.homeautomation</groupId> <groupId>org.homeautomation</groupId>
<artifactId>component</artifactId> <artifactId>doormanager-component</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>${groupId}.doormanager.controller</artifactId> <artifactId>org.homeautomation.doormanager.controller</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>${groupId}.doormanager.controller</name> <name>org.homeautomation.doormanager.controller</name>
<url>http://wso2.com</url> <url>http://wso2.com</url>
<build> <build>
<plugins> <plugins>
@ -45,7 +45,7 @@
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version> <version>${maven-war-plugin.version}</version>
<configuration> <configuration>
<warName>${groupId}.doormanager.controller</warName> <warName>org.homeautomation.doormanager.controller</warName>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
@ -53,7 +53,7 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.homeautomation</groupId> <groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId> <artifactId>org.homeautomation.doormanager.plugin</artifactId>
</dependency> </dependency>
<!-- CDM --> <!-- CDM -->
<dependency> <dependency>

@ -20,18 +20,19 @@ package org.homeautomation.doormanager.controller.api;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.controller.api.dto.DeviceJSON; import org.homeautomation.doormanager.controller.api.dto.UserInfo;
import org.homeautomation.doormanager.controller.api.exception.DoorManagerException; import org.homeautomation.doormanager.controller.api.exception.DoorManagerException;
import org.homeautomation.doormanager.controller.api.util.DoorManagerMQTTConnector; import org.homeautomation.doormanager.controller.api.transport.DoorManagerMQTTConnector;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants; import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException; import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.DoorManager;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe; import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAO; import org.json.JSONException;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType; import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.annotations.device.feature.Feature; import org.wso2.carbon.apimgt.annotations.device.feature.Feature;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.DeviceManagement; import org.wso2.carbon.device.mgt.iot.DeviceManagement;
@ -45,63 +46,37 @@ 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.sensormgt.SensorRecord;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam; import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam; import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.Context; import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.Calendar; import java.util.Calendar;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "doormanager", version = "1.0.0", context = "/doormanager") @API(name = "doormanager", version = "1.0.0", context = "/doormanager")
@DeviceType(value = "doormanager") @DeviceType(value = "doormanager")
public class DoorManagerControllerService { public class DoorManagerControllerService {
private static final DoorManagerDAO DOOR_MANAGER_DAO = new DoorManagerDAO();
private static Log log = LogFactory.getLog(DoorManagerControllerService.class); private static Log log = LogFactory.getLog(DoorManagerControllerService.class);
private HttpServletResponse response; private static String CURRENT_STATUS = "doorLockerCurrentStatus";
private DoorManager doorManager;
private DoorManagerMQTTConnector doorManagerMQTTConnector; private DoorManagerMQTTConnector doorManagerMQTTConnector;
private ConcurrentHashMap<String, DeviceJSON> deviceToIpMap = new ConcurrentHashMap<>();
private PrivilegedCarbonContext ctx;
@Context //injected response proxy supporting multiple thread DoorManagerControllerService() {
doorManager = new DoorManager();
private UserStoreManager getUserStoreManager() throws UserStoreException {
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
PrivilegedCarbonContext.startTenantFlow();
ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(tenantDomain, true);
if (log.isDebugEnabled()) {
log.debug("Getting thread local carbon context for tenant domain: " + tenantDomain);
}
RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
return realmService.getTenantUserRealm(ctx.getTenantId()).getUserStoreManager();
}
/**
* Ends tenant flow.
*/
private void endTenantFlow() {
PrivilegedCarbonContext.endTenantFlow();
ctx = null;
if (log.isDebugEnabled()) {
log.debug("Tenant flow ended");
}
} }
@Context //injected response proxy supporting multiple thread
private boolean waitForServerStartup() { private boolean waitForServerStartup() {
while (!DeviceManagement.isServerReady()) { while (!DeviceManagement.isServerReady()) {
try { try {
@ -137,22 +112,31 @@ public class DoorManagerControllerService {
connectorThread.start(); 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") @Path("controller/assign_user")
@POST @POST
@Feature(code = "assign_user", name = "Assign new user to lock", type = "operation", @Feature(code = "assign_user", name = "Assign new user to lock", type = "operation",
description = "Add new access card to user to control the lock with given policy") description = "Add new access card to user to control the lock ")
public void assignUseToLock(@HeaderParam("owner") String owner, public void assignUserToLock(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId, @HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol, @HeaderParam("protocol") String protocol,
@FormParam("policy") String policy,
@FormParam("cardNumber") String cardNumber, @FormParam("cardNumber") String cardNumber,
@FormParam("userName") String userName, @FormParam("userName") String userName,
@FormParam("emailAddress") String emailAddress, @FormParam("emailAddress") String emailAddress,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
try {
if (userName != null && cardNumber != null && deviceId != null) { if (userName != null && cardNumber != null && deviceId != null) {
try { try {
UserStoreManager userStoreManager = this.getUserStoreManager(); UserStoreManager userStoreManager = doorManager.getUserStoreManager();
DoorLockSafe doorLockSafe = new DoorLockSafe(); DoorLockSafe doorLockSafe = new DoorLockSafe();
if (userStoreManager.isExistingUser(userName)) { if (userStoreManager.isExistingUser(userName)) {
TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE); TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
@ -160,12 +144,12 @@ public class DoorManagerControllerService {
String accessToken = accessTokenInfo.getAccess_token(); String accessToken = accessTokenInfo.getAccess_token();
if (accessToken == null) { if (accessToken == null) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
return;
} }
Map<String, String> claims = new HashMap<>(); Map<String, String> claims = new HashMap<>();
claims.put("http://wso2.org/claims/lock/accesstoken", accessToken); claims.put(DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, accessToken);
claims.put("http://wso2.org/claims/lock/refreshtoken", accessTokenInfo.getRefresh_token()); claims.put(DoorManagerConstants.DEVICE_CLAIMS_REFRESH_TOKEN,
claims.put("http://wso2.org/claims/lock/cardnumber", cardNumber); accessTokenInfo.getRefresh_token());
claims.put(DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, cardNumber);
userStoreManager.setUserClaimValues(userName, claims, null); userStoreManager.setUserClaimValues(userName, claims, null);
doorLockSafe.setAccessToken(accessTokenInfo.getAccess_token()); doorLockSafe.setAccessToken(accessTokenInfo.getAccess_token());
doorLockSafe.setRefreshToken(accessTokenInfo.getRefresh_token()); doorLockSafe.setRefreshToken(accessTokenInfo.getRefresh_token());
@ -173,184 +157,38 @@ public class DoorManagerControllerService {
doorLockSafe.setOwner(owner); doorLockSafe.setOwner(owner);
doorLockSafe.setEmailAddress(emailAddress); doorLockSafe.setEmailAddress(emailAddress);
doorLockSafe.setUIDofUser(cardNumber); doorLockSafe.setUIDofUser(cardNumber);
doorLockSafe.setPolicy(policy);
doorLockSafe.setSerialNumber(deviceId); doorLockSafe.setSerialNumber(deviceId);
boolean status; if (doorManager.assignUserToLock(doorLockSafe)) {
try {
DoorManagerDAO.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().registerDoorLockSafe(doorLockSafe);
DoorManagerDAO.commitTransaction();
if (status) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
} else { } else {
response.setStatus(Response.Status.FORBIDDEN.getStatusCode()); response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
}
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAO.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
String msg = "Error while updating the enrollment of the Door Manager Locker device : "
+ doorLockSafe.getOwner();
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(msg, e);
}
} }
response.setStatus(Response.Status.OK.getStatusCode());
} else { } else {
response.setStatus(Response.Status.NOT_FOUND.getStatusCode()); response.setStatus(Response.Status.NOT_FOUND.getStatusCode());
} }
} catch (UserStoreException e) { } catch (UserStoreException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e); log.error(e);
} } catch (DoorManagerDeviceMgtPluginException | AccessTokenException e) {
} else {
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
}
} catch (AccessTokenException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e); log.error(e);
}
}
/* @Path("controller/registerNewUser")
@POST
@Feature(code = "registerNewUser", name = "Assign to new user", type = "operation",
description = "Assign to new user")
public void registerDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("policy") String policy,
@FormParam("UIDofRFID") String UIDofRFID,
@FormParam("userName") String userName,
@FormParam("emailAddress") String emailAddress,
@Context HttpServletResponse response) {
try {
TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(deviceId, UIDofRFID);
DoorLockSafe doorLockSafe = new DoorLockSafe();
String accessToken = accessTokenInfo.getAccess_token();
if (accessToken == null) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} else {
if (emailAddress != null && UIDofRFID != null && deviceId != null) {
boolean status;
doorLockSafe.setAccessToken(accessTokenInfo.getAccess_token());
doorLockSafe.setRefreshToken(accessTokenInfo.getRefresh_token());
doorLockSafe.setDeviceId(deviceId);
doorLockSafe.setOwner(owner);
doorLockSafe.setEmailAddress(emailAddress);
doorLockSafe.setUIDofUser(UIDofRFID);
doorLockSafe.setPolicy(policy);
doorLockSafe.setSerialNumber(deviceId);
try {
DoorManagerDAO.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().registerDoorLockSafe(doorLockSafe);
DoorManagerDAO.commitTransaction();
if (status) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.FORBIDDEN.getStatusCode());
}
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAO.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
String msg = "Error while updating the enrollment of the Door Manager Locker device : "
+ doorLockSafe.getOwner();
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(msg, e);
}
} }
} else { } else {
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode()); response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
} }
} }
} catch (AccessTokenException e) {
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
log.error(e);
}
}*/
/*@Path("controller/registerNewUser") /**
@POST * Change status of door lock safe: LOCK/UNLOCK
@Feature(code = "registerNewUser", name = "Assign to new user", type = "operation", *
description = "Assign to new user") * @param owner owner of the device
public void registerDoorLockSafe(@HeaderParam("owner") String owner, * @param deviceId unique identifier for given device
@HeaderParam("deviceId") String deviceId, * @param protocol transport protocol which is being using here MQTT
@HeaderParam("protocol") String protocol, * @param state status of lock safe: lock/unlock
@FormParam("policy") String policy, */
@FormParam("cardNumber") String cardNumber, @Path("controller/change-status")
@FormParam("userName") String userName,
@FormParam("emailAddress") String emailAddress,
@Context HttpServletResponse response) {
try {
TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(deviceId, userName);
DoorLockSafe doorLockSafe = new DoorLockSafe();
String accessToken = accessTokenInfo.getAccess_token();
if (accessToken == null) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} else {
if (emailAddress != null && cardNumber != null && deviceId != null) {
boolean status;
doorLockSafe.setAccessToken(accessTokenInfo.getAccess_token());
doorLockSafe.setRefreshToken(accessTokenInfo.getRefresh_token());
doorLockSafe.setDeviceId(deviceId);
doorLockSafe.setOwner(owner);
doorLockSafe.setEmailAddress(emailAddress);
doorLockSafe.setUIDofUser(cardNumber);
doorLockSafe.setPolicy(policy);
doorLockSafe.setSerialNumber(deviceId);
try {
UserStoreManager userStoreManager = this.getUserStoreManager();
if (userStoreManager.isExistingUser(userName)) {
if (accessToken == null) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
return;
}
Map<String, String> claims = new HashMap<>();
claims.put("http://wso2.org/claims/lock/accesstoken", accessToken);
claims.put("http://wso2.org/claims/lock/refreshtoken", accessTokenInfo.getRefresh_token());
claims.put("http://wso2.org/claims/lock/cardnumber", cardNumber);
userStoreManager.setUserClaimValues(userName, claims, null);
} else {
response.setStatus(Response.Status.NOT_FOUND.getStatusCode());
}
DoorManagerDAO.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().registerDoorLockSafe(doorLockSafe);
DoorManagerDAO.commitTransaction();
if (status) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.FORBIDDEN.getStatusCode());
}
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAO.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
String msg = "Error while updating the enrollment of the Door Manager Locker device : "
+ doorLockSafe.getOwner();
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(msg, e);
}
} catch (UserStoreException e) {
log.error(e);
}
} else {
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
}
}
} catch (AccessTokenException e) {
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
log.error(e);
}
}*/
@Path("controller/changeStatusOfDoorLockSafe")
@POST @POST
@Feature(code = "changeStatusOfDoorLockSafe", name = "Change status of door lock safe: LOCK/UNLOCK", type = "operation", @Feature(code = "change-status", name = "Change status of door lock safe: LOCK/UNLOCK", type = "operation",
description = "Change status of door lock safe: LOCK/UNLOCK") description = "Change status of door lock safe: LOCK/UNLOCK")
public void changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner, public void changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId, @HeaderParam("deviceId") String deviceId,
@ -364,7 +202,7 @@ public class DoorManagerControllerService {
} else { } else {
lockerCurrentState = 1; lockerCurrentState = 1;
} }
SensorDataManager.getInstance().setSensorRecord(deviceId, "door_locker_state", SensorDataManager.getInstance().setSensorRecord(deviceId, CURRENT_STATUS,
String.valueOf(lockerCurrentState), Calendar.getInstance().getTimeInMillis()); String.valueOf(lockerCurrentState), Calendar.getInstance().getTimeInMillis());
doorManagerMQTTConnector.sendCommandViaMQTT(owner, deviceId, "DoorManager:", state.toUpperCase()); doorManagerMQTTConnector.sendCommandViaMQTT(owner, deviceId, "DoorManager:", state.toUpperCase());
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
@ -376,78 +214,20 @@ public class DoorManagerControllerService {
} }
} }
/*@Path("controller/shareDoorLockSafe") /**
@POST * Request current status of door lock safe
@Feature(code = "shareDoorLockSafe", name = "Share lock safe with new user", type = "operation", *
description = "Share lock safe with new user") * @param owner owner of the device
public void shareDoorLockSafe(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId, * @param deviceId unique identifier for given device
@HeaderParam("protocol") String protocol, * @param protocol transport protocol which is being using here MQTT
@FormParam("UIDofUser") String UIDofUser,@FormParam("policy") String policy, * @param response http servlet response object
@Context HttpServletResponse response) { */
try {
DoorLockSafe doorLockSafe = new DoorLockSafe();
if(deviceId != null && UIDofUser != null && policy != null){
boolean status;
doorLockSafe.setDeviceId(deviceId);
doorLockSafe.setOwner(owner);
doorLockSafe.setPolicy(policy);
doorLockSafe.setSerialNumber(deviceId);
doorLockSafe.setUIDofUser(UIDofUser);
try{
DoorManagerDAO.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().shareDoorLockSafe(doorLockSafe);
DoorManagerDAO.commitTransaction();
if(status){
response.setStatus(Response.Status.OK.getStatusCode());
}else{
response.setStatus(Response.Status.FORBIDDEN.getStatusCode());
}
}
catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAO.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
String msg = "Error while sharing the enrollment of the Door Manager Locker device : "
+ doorLockSafe.getOwner();
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(msg, e);
}
}
}else{
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
}
} catch (Exception e) {
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
log.error(e);
}
}*/
@Path("controller/addDoorOpenedUser")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response addDoorOpenedUser(final DeviceJSON lockSafeInfo) {
try {
if (lockSafeInfo.serialNumber != null && lockSafeInfo.UIDofUser != null) {
log.warn(lockSafeInfo.serialNumber);
log.warn(lockSafeInfo.UIDofUser);
deviceToIpMap.put(lockSafeInfo.serialNumber, lockSafeInfo);
return Response.ok(Response.Status.OK.getStatusCode()).build();
} else {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
} catch (Exception e) {
log.error(e);
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
}
@GET @GET
@Path("controller/requestStatusOfDoorLockSafe") @Path("controller/current-status")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Feature(code = "requestStatusOfDoorLockSafe", name = "Door Locker Status", type = "monitor", @Feature(code = "current-status", name = "Door Locker Status", type = "monitor",
description = "Request door locker current status") description = "Request current status of door safe")
public SensorRecord requestStatusOfDoorLockSafe(@HeaderParam("owner") String owner, public SensorRecord requestStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId, @HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol, @HeaderParam("protocol") String protocol,
@ -459,40 +239,88 @@ public class DoorManagerControllerService {
new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE))) { new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} }
} catch (DeviceManagementException e) { sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, CURRENT_STATUS);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
} } catch (DeviceControllerException | DeviceManagementException e) {
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, "door_locker_state");
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} }
response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord; return sensorRecord;
} }
@GET /**
@Path("controller/getRegisteredDoorLockSafe") * @param userInfo user information which are required to test given user is authorized to open requested door
@Consumes(MediaType.APPLICATION_JSON) * @return if user is authorized open the the door allow to open it
*/
@POST
@Path("controller/get_user_info")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response getRegisteredDoorLocks(@HeaderParam("owner") String owner, @Consumes(MediaType.APPLICATION_JSON)
@HeaderParam("deviceId") String deviceId, @SuppressWarnings("unchecked") //This is to avoid unchecked call to put(k, v) into jsonObject. org.json.simple
@Context HttpServletResponse response) { // library uses raw type collections internally.
List<String> doorLockSafes; public Response get_user_info(final UserInfo userInfo) {
try { if (userInfo.userName != null && userInfo.cardNumber != null && userInfo.deviceId != null) {
DoorManagerDAO.beginTransaction();
doorLockSafes = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().getRegisteredDoorLocks(deviceId);
DoorManagerDAO.commitTransaction();
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DoorManagerDeviceMgtPluginException e) {
try { try {
DoorManagerDAO.rollbackTransaction(); UserStoreManager userStoreManager = doorManager.getUserStoreManager();
} catch (DoorManagerDeviceMgtPluginException e1) { if (userStoreManager.isExistingUser(userInfo.userName)) {
String msg = "Error while updating the enrollment of the Door Manager Locker device : " + deviceId; String accessToken = userStoreManager.getUserClaimValue(userInfo.userName,
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, null);
log.error(msg, e); 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();
} }
return Response.ok().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());
} }
}*/
} }

@ -27,28 +27,43 @@ import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
public class DoorManagerServiceUtils { public class DoorManagerServiceUtils {
private static final Log log = LogFactory.getLog(DoorManagerServiceUtils.class); private static final Log log = LogFactory.getLog(DoorManagerServiceUtils.class);
private static final String STREAM_DEFINITION = "org.wso2.iot.devices.smartLock";
private static final String STREAM_DEFINITION_VERSION = "1.0.0";
//TODO; replace this tenant domain /**
private static final String SUPER_TENANT = "carbon.super"; * Publish door locker current status to DAS
private static final String CURRENT_STREAM_DEFINITION = "org.wso2.iot.devices.sensor"; *
* @param owner owner of the device
* @param deviceId unique identifier of device
* @param status current status of lock:- 1: open, 0: close
* @return status
*/
public static boolean publishToDASLockerStatus(String owner, String deviceId, float status) throws
DataPublisherConfigurationException {
Object payloadCurrent[] = {status};
return publishToDAS(owner, deviceId, payloadCurrent, STREAM_DEFINITION);
}
public static boolean publishToDASCurrent(String owner, String deviceId, float current) { private static boolean publishToDAS(String owner, String deviceId, Object[] payloadCurrent,
String definition) {
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true); ctx.setUsername(owner);
if (ctx.getTenantDomain(true) == null) {
ctx.setTenantDomain("carbon.super", true);
}
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null); DeviceAnalyticsService.class, null);
Object metdaData[] = {owner, DoorManagerConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object metaData[] = {owner, DoorManagerConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payloadCurrent[] = {current};
try { try {
deviceAnalyticsService.publishEvent(CURRENT_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadCurrent); deviceAnalyticsService.publishEvent(definition, STREAM_DEFINITION_VERSION, metaData,
new Object[0], payloadCurrent);
} catch (DataPublisherConfigurationException e) { } catch (DataPublisherConfigurationException e) {
log.error(e);
return false; return false;
} finally { } finally {
PrivilegedCarbonContext.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
} }
return true; return true;
} }
} }

@ -18,111 +18,99 @@
package org.homeautomation.doormanager.manager.api; package org.homeautomation.doormanager.manager.api;
import com.google.gson.JsonObject; import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.geronimo.mail.util.Base64; import org.homeautomation.doormanager.manager.api.util.APIUtil;
import org.apache.http.client.ClientProtocolException; import org.homeautomation.doormanager.manager.api.util.ResponsePayload;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.SystemDefaultHttpClient;
import org.homeautomation.doormanager.manager.api.dto.UserInfo;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants; import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAO;
import org.json.simple.JSONObject;
import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType; import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil; import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo; import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient; import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException; import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; 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.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*; 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.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@SuppressWarnings("NonJaxWsWebServices")
@DeviceType(value = "doormanager") @DeviceType(value = "doormanager")
@API(name = "doormanager_mgt", version = "1.0.0", context = "/doormanager_mgt") @API(name = "doormanager_mgt", version = "1.0.0", context = "/doormanager_mgt")
public class DoorManagerManagerService { public class DoorManagerManagerService {
private static Log log = LogFactory.getLog(DoorManagerManagerService.class); private static Log log = LogFactory.getLog(DoorManagerManagerService.class);
//TODO; replace this tenant domain
private static final DoorManagerDAO doorManagerDAO = new DoorManagerDAO();
private final String SUPER_TENANT = "carbon.super";
@Context //injected response proxy supporting multiple thread @Context //injected response proxy supporting multiple thread
private HttpServletResponse response; private HttpServletResponse response;
private PrivilegedCarbonContext ctx;
private UserStoreManager getUserStoreManager() throws UserStoreException { /**
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); * Generate UUID
PrivilegedCarbonContext.startTenantFlow(); *
ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); * @return generated UUID
ctx.setTenantDomain(tenantDomain, true); */
if (log.isDebugEnabled()) { private static String shortUUID() {
log.debug("Getting thread local carbon context for tenant domain: " + tenantDomain); UUID uuid = UUID.randomUUID();
} long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null); return Long.toString(l, Character.MAX_RADIX);
return realmService.getTenantUserRealm(ctx.getTenantId()).getUserStoreManager();
} }
/**
* Register new device into IoT Server
*
* @param name name of new device
* @return registration status
*/
@Path("manager/device/register") @Path("manager/device/register")
@POST @POST
public boolean register(@QueryParam("name") String name, @QueryParam("owner") String owner, public boolean register(@QueryParam("deviceId") String deviceId,
@QueryParam("serialNumber") String serialNumber) { @QueryParam("name") String name) {
log.warn("---------------------------------------");
log.warn(serialNumber);
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
String deviceId = serialNumber;
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE); deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
try { try {
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode()); response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false; return false;
} }
String owner = APIUtil.getAuthenticatedUser();
Device device = new Device(); Device device = new Device();
device.setDeviceIdentifier(deviceId); device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime()); enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name); device.setName(name);
device.setType(DoorManagerConstants.DEVICE_TYPE); device.setType(DoorManagerConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(owner); enrolmentInfo.setOwner(owner);
device.setEnrolmentInfo(enrolmentInfo); device.setEnrolmentInfo(enrolmentInfo);
KeyGenerationUtil.createApplicationKeys(DoorManagerConstants.DEVICE_TYPE); KeyGenerationUtil.createApplicationKeys(DoorManagerConstants.DEVICE_TYPE);
TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE); TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
@ -144,35 +132,39 @@ public class DoorManagerManagerService {
properties.add(refreshTokenProperty); properties.add(refreshTokenProperty);
device.setProperties(properties); device.setProperties(properties);
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) { if (added) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
} else { } else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
} }
return added; return added;
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false; return false;
} catch (AccessTokenException e) { } catch (AccessTokenException e) {
e.printStackTrace(); log.error(e);
} finally { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
deviceManagement.endTenantFlow(); return false;
} }
return true;
} }
/**
* Remove installed device
*
* @param deviceId unique identifier for device
* @param response to request
*/
@Path("manager/device/remove/{device_id}") @Path("manager/device/remove/{device_id}")
@DELETE @DELETE
public void removeDevice(@PathParam("device_id") String deviceId, public void removeDevice(@PathParam("device_id") String deviceId,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE); deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
try { try {
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier); deviceIdentifier);
if (removed) { if (removed) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
@ -181,27 +173,32 @@ public class DoorManagerManagerService {
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
deviceManagement.endTenantFlow();
} }
} }
/**
* Update device name
*
* @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}") @Path("manager/device/update/{device_id}")
@POST @POST
public boolean updateDevice(@PathParam("device_id") String deviceId, public boolean updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name, @QueryParam("name") String name,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE); deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
try { try {
Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId); device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name); device.setName(name);
device.setType(DoorManagerConstants.DEVICE_TYPE); device.setType(DoorManagerConstants.DEVICE_TYPE);
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device); boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) { if (updated) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
} else { } else {
@ -211,207 +208,49 @@ public class DoorManagerManagerService {
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
log.error(e.getErrorMessage()); log.error(e.getErrorMessage());
return false; return false;
} finally {
deviceManagement.endTenantFlow();
} }
} }
@POST /**
@Path("manager/getUserCredentials") * Get device information
@Produces(MediaType.APPLICATION_JSON) *
@Consumes(MediaType.APPLICATION_JSON) * @param deviceId unique identifier for device
public Response getUserCredentials(final UserInfo userInfo, @Context HttpServletRequest request, @Context HttpServletResponse response) { * @return device
/*try{ */
String accessToken, refreshToken;
DoorManagerDAO.beginTransaction();
if(doorManagerDAO.getAutomaticDoorLockerDeviceDAO().isDoorLockSafeRegistered(userInfo.serialNumber,
userInfo.deviceId)){
if(doorManagerDAO.getAutomaticDoorLockerDeviceDAO().isUserAllowed(userInfo.serialNumber,
userInfo.UIDofUser, userInfo.deviceId)){
List<String> userCredentials = doorManagerDAO.getAutomaticDoorLockerDeviceDAO()
.getUserCredentials(userInfo.deviceId, userInfo.UIDofUser);
DoorManagerDAO.commitTransaction();
if(!userCredentials.isEmpty()){
accessToken = userCredentials.get(0);
refreshToken = userCredentials.get(1);
if(accessToken != null && refreshToken != null){
JSONObject credentials = new JSONObject();
credentials.put("accessToken", accessToken);
credentials.put("refreshToken", refreshToken);
return Response.ok(credentials, MediaType.APPLICATION_JSON_TYPE).build();
}else{
return Response.status(Response.Status.UNAUTHORIZED)
.entity("{You have not been registered yet}").build();
}
}else{
return Response.status(Response.Status.UNAUTHORIZED)
.entity("{You have not been registered yet}").build();
}
}else{
return Response.status(Response.Status.UNAUTHORIZED)
.entity("{You are not allowed open this door}").build();
}
}else{
return Response.status(Response.Status.UNAUTHORIZED)
.entity("{This door hasn't been registered yet}").build();
}
}catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAO.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
String msg = "Error while retrieving the user credentials of " + userInfo.deviceId;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("{Internal server error has occurred.}").build();
}
}
return Response.status(Response.Status.NOT_ACCEPTABLE).build();*/
try {
log.warn("=========================================");
log.warn("get info");
log.warn(userInfo.userName);
log.warn(userInfo.cardNumber);
log.warn(userInfo.deviceId);
if (userInfo.userName != null && userInfo.cardNumber != null && userInfo.deviceId != null) {
try {
UserStoreManager userStoreManager = this.getUserStoreManager();
if (userStoreManager.isExistingUser(userInfo.userName)) {
String accessToken = userStoreManager.getUserClaimValue(userInfo.userName, "http://wso2.org/claims/lock/accesstoken", null);
String cardNumber = userStoreManager.getUserClaimValue(userInfo.userName, "http://wso2.org/claims/lock/cardnumber", null);
log.warn(accessToken);
log.warn(cardNumber);
if(cardNumber.equals(userInfo.cardNumber)){
if(accessToken != null && doorManagerDAO.getAutomaticDoorLockerDeviceDAO().
checkCardDoorAssociation(cardNumber, userInfo.deviceId)){
JSONObject credentials = new JSONObject();
credentials.put(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN, accessToken);
credentials.put(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN, accessToken);
sendCEPEvent(userInfo.deviceId, cardNumber, true);
log.warn(doorManagerDAO.getAutomaticDoorLockerDeviceDAO().getUserEmailAddress(cardNumber));
return Response.ok(credentials, MediaType.APPLICATION_JSON_TYPE).build();
}
}
} else {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} catch (UserStoreException e) {
log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
else {
return Response.status(Response.Status.BAD_REQUEST).build();
}
} catch (Exception e) {
log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).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());
}
}
@POST
@Path("manager/get_user_info")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response get_user_info(final UserInfo userInfo) {
try {
if (userInfo.userName != null && userInfo.cardNumber != null && userInfo.deviceId != null) {
try {
UserStoreManager userStoreManager = this.getUserStoreManager();
if (userStoreManager.isExistingUser(userInfo.userName)) {
String accessToken = userStoreManager.getUserClaimValue(userInfo.userName, "http://wso2.org/claims/lock/accesstoken", null);
String cardNumber = userStoreManager.getUserClaimValue(userInfo.userName, "http://wso2.org/claims/lock/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();
}
}
} else {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} catch (UserStoreException e) {
log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
else {
return Response.status(Response.Status.BAD_REQUEST).build();
}
} catch (Exception e) {
log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
@Path("manager/device/{device_id}") @Path("manager/device/{device_id}")
@GET @GET
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Device getDevice(@PathParam("device_id") String deviceId) { public Device getDevice(@PathParam("device_id") String deviceId) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE); deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
try { try {
return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
} catch (DeviceManagementException ex) { } catch (DeviceManagementException ex) {
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex); log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
return null; return null;
} finally {
deviceManagement.endTenantFlow();
} }
} }
/**
* This will download the agent for given device type
*
* @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") @Path("manager/device/{sketch_type}/download")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response downloadSketch(@QueryParam("owner") String owner, public Response downloadSketch(@QueryParam("deviceName") String deviceName,
@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType) { @PathParam("sketch_type") String sketchType) {
try { try {
ZipArchive zipFile = createDownloadFile(owner, deviceName, sketchType); ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.type("application/zip"); response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return response.build(); return response.build();
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request return Response.status(400).entity(ex.getMessage()).build();//bad request
@ -426,6 +265,46 @@ public class DoorManagerManagerService {
} }
} }
/**
* 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) private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
throws DeviceManagementException, AccessTokenException, DeviceControllerException { throws DeviceManagementException, AccessTokenException, DeviceControllerException {
if (owner == null) { if (owner == null) {
@ -442,23 +321,16 @@ public class DoorManagerManagerService {
//adding registering data //adding registering data
boolean status; boolean status;
//Register the device with CDMF //Register the device with CDMF
//status = register(deviceId, deviceName, owner); status = register(deviceId, deviceName);
status = true;
if (!status) { if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner; String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
ZipUtil ziputil = new ZipUtil(); ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, SUPER_TENANT, sketchType, deviceId, deviceName, accessToken, ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOfUser(), sketchType,
refreshToken); deviceId, deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId); zipFile.setDeviceId(deviceId);
return zipFile; 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,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.homeautomation.doormanager.manager.api.util;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
/**
* This class provides utility functions used by REST-API.
*/
public class APIUtil {
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
if (username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@"));
}
return username;
}
public static String getTenantDomainOfUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
return threadLocalCarbonContext.getTenantDomain();
}
public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management service has not initialized.";
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
}

@ -0,0 +1,108 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.manager.api.util;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class ResponsePayload {
private int statusCode;
private String messageFromServer;
private Object responseContent;
public static ResponsePayload.ResponsePayloadBuilder statusCode(int statusCode) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().statusCode(statusCode);
}
public static ResponsePayload.ResponsePayloadBuilder messageFromServer(
String messageFromServer) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().messageFromServer(messageFromServer);
}
public static ResponsePayload.ResponsePayloadBuilder responseContent(String responseContent) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().responseContent(responseContent);
}
@XmlElement
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
@XmlElement
public String getMessageFromServer() {
return messageFromServer;
}
public void setMessageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
}
@XmlElement
public Object getResponseContent() {
return responseContent;
}
public void setResponseContent(Object responseContent) {
this.responseContent = responseContent;
}
private ResponsePayload.ResponsePayloadBuilder getBuilder() {
return new ResponsePayload.ResponsePayloadBuilder();
}
public class ResponsePayloadBuilder {
private int statusCode;
private String messageFromServer;
private Object responseContent;
public ResponsePayloadBuilder statusCode(int statusCode) {
this.statusCode = statusCode;
return this;
}
public ResponsePayloadBuilder messageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
return this;
}
public ResponsePayloadBuilder responseContent(String responseContent) {
this.responseContent = responseContent;
return this;
}
public ResponsePayload build() {
ResponsePayload payload = new ResponsePayload();
payload.setStatusCode(statusCode);
payload.setMessageFromServer(messageFromServer);
payload.setResponseContent(responseContent);
return payload;
}
}
}

@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/manager/device/*</url>
<method>GET</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Add device</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device/register</url>
<method>PUT</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device/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>/manager/device/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>/manager/device/update/*</url>
<method>POST</method>
<scope>emm_admin,emm_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/manager/device/remove/*</url>
<method>DELETE</method>
<scope>emm_admin,emm_user</scope>
</Permission>
</PermissionConfiguration>

@ -40,7 +40,7 @@
</context-param> </context-param>
<context-param> <context-param>
<param-name>doAuthentication</param-name> <param-name>doAuthentication</param-name>
<param-value>false</param-value> <param-value>true</param-value>
</context-param> </context-param>
<!--publish to apim--> <!--publish to apim-->
<context-param> <context-param>

@ -19,15 +19,15 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<groupId>org.homeautomation</groupId> <groupId>org.homeautomation</groupId>
<artifactId>component</artifactId> <artifactId>doormanager-component</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<artifactId>${groupId}.doormanager.plugin</artifactId> <artifactId>org.homeautomation.doormanager.plugin</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>${groupId}.doormanager.plugin</name> <name>org.homeautomation.doormanager.plugin</name>
<url>http://wso2.org</url> <url>http://wso2.org</url>
<build> <build>
<plugins> <plugins>
@ -52,8 +52,8 @@
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<instructions> <instructions>
<Bundle-SymbolicName>${groupId}.doormanager.plugin</Bundle-SymbolicName> <Bundle-SymbolicName>org.homeautomation.doormanager.plugin</Bundle-SymbolicName>
<Bundle-Name>${groupId}.doormanager.plugin</Bundle-Name> <Bundle-Name>org.homeautomation.doormanager.plugin</Bundle-Name>
<Bundle-Version>1.0.0-SNAPSHOT</Bundle-Version> <Bundle-Version>1.0.0-SNAPSHOT</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description> <Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.homeautomation.doormanager.plugin.internal</Private-Package> <Private-Package>org.homeautomation.doormanager.plugin.internal</Private-Package>
@ -61,10 +61,8 @@
org.osgi.framework, org.osgi.framework,
org.osgi.service.component, org.osgi.service.component,
org.apache.commons.logging, org.apache.commons.logging,
javax.xml.bind.*,
javax.naming, javax.naming,
javax.sql, javax.sql,
javax.xml.bind.annotation.*,
javax.xml.parsers, javax.xml.parsers,
javax.net, javax.net,
javax.net.ssl, javax.net.ssl,
@ -74,6 +72,8 @@
org.wso2.carbon.context.*, org.wso2.carbon.context.*,
org.wso2.carbon.ndatasource.core, org.wso2.carbon.ndatasource.core,
org.wso2.carbon.device.mgt.iot.*, org.wso2.carbon.device.mgt.iot.*,
org.wso2.carbon.user.api.*,
org.wso2.carbon.user.core.service.*
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
!org.homeautomation.doormanager.plugin.internal, !org.homeautomation.doormanager.plugin.internal,
@ -117,9 +117,67 @@
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId> <artifactId>org.wso2.carbon.user.api</artifactId>
</dependency> </dependency>
<!--<dependency> <dependency>
<groupId>org.codehaus.jackson</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>jackson-core-asl</artifactId> <artifactId>org.wso2.carbon.utils</artifactId>
</dependency>--> <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>
</dependencies> </dependencies>
</project> </project>

@ -22,14 +22,6 @@ public class DoorManagerDeviceMgtPluginException extends Exception{
private String errorMessage; private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public DoorManagerDeviceMgtPluginException(String msg, Exception nestedEx) { public DoorManagerDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx); super(msg, nestedEx);
setErrorMessage(msg); setErrorMessage(msg);
@ -53,4 +45,12 @@ public class DoorManagerDeviceMgtPluginException extends Exception{
super(cause); super(cause);
} }
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
} }

@ -22,19 +22,25 @@ package org.homeautomation.doormanager.plugin.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException; import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAO; import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAO;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import java.util.List; import java.util.List;
public class DoorManagerManager implements DeviceManager { public class DoorManager implements DeviceManager {
private static final Log log = LogFactory.getLog(DoorManagerManager.class);
private static final Log log = LogFactory.getLog(DoorManager.class);
private static final DoorManagerDAO DOOR_MANAGER_DAO = new DoorManagerDAO(); private static final DoorManagerDAO DOOR_MANAGER_DAO = new DoorManagerDAO();
private PrivilegedCarbonContext ctx;
@Override @Override
public FeatureManager getFeatureManager() { public FeatureManager getFeatureManager() {
@ -44,13 +50,11 @@ public class DoorManagerManager implements DeviceManager {
@Override @Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration) public boolean saveConfiguration(TenantConfiguration tenantConfiguration)
throws DeviceManagementException { throws DeviceManagementException {
//TODO implement this
return false; return false;
} }
@Override @Override
public TenantConfiguration getConfiguration() throws DeviceManagementException { public TenantConfiguration getConfiguration() throws DeviceManagementException {
//TODO implement this
return null; return null;
} }
@ -158,7 +162,8 @@ public class DoorManagerManager implements DeviceManager {
@Override @Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device; Device device;
try {if (log.isDebugEnabled()) { try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Automatic Door Locker device : " + deviceId.getId()); log.debug("Getting the details of Automatic Door Locker device : " + deviceId.getId());
} }
device = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().getDevice(deviceId.getId()); device = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().getDevice(deviceId.getId());
@ -230,7 +235,7 @@ public class DoorManagerManager implements DeviceManager {
@Override @Override
public List<Device> getAllDevices() throws DeviceManagementException { public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices = null; List<Device> devices;
try { try {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Automatic Door Locker devices"); log.debug("Fetching the details of all Automatic Door Locker devices");
@ -244,4 +249,62 @@ public class DoorManagerManager implements DeviceManager {
return devices; return devices;
} }
/**
* Get userStore manager
*
* @return
* @throws UserStoreException
*/
public UserStoreManager getUserStoreManager() throws UserStoreException {
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
PrivilegedCarbonContext.startTenantFlow();
ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(tenantDomain, true);
if (log.isDebugEnabled()) {
log.debug("Getting thread local carbon context for tenant domain: " + tenantDomain);
}
RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
return realmService.getTenantUserRealm(ctx.getTenantId()).getUserStoreManager();
}
/**
* Ends tenant flow.
*/
private void endTenantFlow() {
PrivilegedCarbonContext.endTenantFlow();
ctx = null;
if (log.isDebugEnabled()) {
log.debug("Tenant flow ended");
}
}
public boolean assignUserToLock(DoorLockSafe doorLockSafe) throws DoorManagerDeviceMgtPluginException {
boolean status;
try {
DoorManagerDAO.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().registerDoorLockSafe(doorLockSafe);
DoorManagerDAO.commitTransaction();
return status;
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAO.rollbackTransaction();
throw new DoorManagerDeviceMgtPluginException(e);
} catch (DoorManagerDeviceMgtPluginException e1) {
String msg = "Error while adding new access card to user to control the lock "
+ doorLockSafe.getOwner();
log.error(msg, e);
throw new DoorManagerDeviceMgtPluginException(msg, e);
}
}
}
public boolean checkCardDoorAssociation(String cardNumber, String deviceId)
throws DoorManagerDeviceMgtPluginException {
boolean status;
DoorManagerDAO.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().checkCardDoorAssociation(cardNumber, deviceId);
DoorManagerDAO.commitTransaction();
return status;
}
} }

@ -1,113 +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.homeautomation.doormanager.plugin.impl;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List;
public class DoorManagerManagerService implements DeviceManagementService{
private DeviceManager deviceManager;
@Override
public String getType() {
return DoorManagerConstants.DEVICE_TYPE;
}
@Override
public String getProviderTenantDomain() {
return "carbon.super";
}
@Override
public boolean isSharedWithAllTenants() {
return true;
}
@Override
public String[] getSharedTenantsDomain() {
return new String[0];
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager=new DoorManagerManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> deviceIds)
throws DeviceManagementException {
}
@Override
public Application[] getApplications(String domain, int pageNumber, int size)
throws ApplicationManagementException {
return new Application[0];
}
@Override
public void updateApplicationStatus(DeviceIdentifier deviceId, Application application,
String status) throws ApplicationManagementException {
}
@Override
public String getApplicationStatus(DeviceIdentifier deviceId, Application application)
throws ApplicationManagementException {
return null;
}
@Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> deviceIdentifiers)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUsers(Operation operation, List<String> userNameList)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUserRoles(Operation operation, List<String> userRoleList)
throws ApplicationManagementException {
}
}

@ -0,0 +1,113 @@
/*
* 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.plugin.impl;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List;
public class DoorManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
@Override
public String getType() {
return DoorManagerConstants.DEVICE_TYPE;
}
@Override
public String getProviderTenantDomain() {
return "carbon.super";
}
@Override
public boolean isSharedWithAllTenants() {
return true;
}
@Override
public String[] getSharedTenantsDomain() {
return new String[0];
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager = new DoorManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> deviceIds)
throws DeviceManagementException {
}
@Override
public Application[] getApplications(String domain, int pageNumber, int size)
throws ApplicationManagementException {
return new Application[0];
}
@Override
public void updateApplicationStatus(DeviceIdentifier deviceId, Application application,
String status) throws ApplicationManagementException {
}
@Override
public String getApplicationStatus(DeviceIdentifier deviceId, Application application)
throws ApplicationManagementException {
return null;
}
@Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> deviceIdentifiers)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUsers(Operation operation, List<String> userNameList)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUserRoles(Operation operation, List<String> userRoleList)
throws ApplicationManagementException {
}
}

@ -1,7 +1,4 @@
package org.homeautomation.doormanager.plugin.impl.dao; /*~ Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
/*
<!--
~ Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~ ~
~ WSO2 Inc. licenses this file to you under the Apache License, ~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except ~ Version 2.0 (the "License"); you may not use this file except
@ -15,12 +12,20 @@ package org.homeautomation.doormanager.plugin.impl.dao;
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the ~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations ~ specific language governing permissions and limitations
~ under the License. ~ under the License.*/
-->
*/
package org.homeautomation.doormanager.plugin.impl.dao;
public class DoorLockSafe { public class DoorLockSafe {
private String owner;
private String deviceId;
private String UIDofUser;
private String serialNumber;
private String policy;
private String emailAddress;
private String accessToken;
private String refreshToken;
public String getOwner() { public String getOwner() {
return owner; return owner;
} }
@ -84,13 +89,4 @@ public class DoorLockSafe {
public void setRefreshToken(String refreshToken) { public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken; this.refreshToken = refreshToken;
} }
private String owner;
private String deviceId;
private String UIDofUser;
private String serialNumber;
private String policy;
private String emailAddress;
private String accessToken;
private String refreshToken;
} }

@ -24,7 +24,6 @@ import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException; import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.dao.impl.DoorManagerDAOImpl; import org.homeautomation.doormanager.plugin.impl.dao.impl.DoorManagerDAOImpl;
import javax.naming.Context; import javax.naming.Context;
import javax.naming.InitialContext; import javax.naming.InitialContext;
import javax.naming.NamingException; import javax.naming.NamingException;
@ -53,11 +52,6 @@ public class DoorManagerDAO {
} }
public DoorManagerDAOImpl getAutomaticDoorLockerDeviceDAO() {
return new DoorManagerDAOImpl();
}
public static void beginTransaction() throws DoorManagerDeviceMgtPluginException { public static void beginTransaction() throws DoorManagerDeviceMgtPluginException {
try { try {
Connection conn = dataSource.getConnection(); Connection conn = dataSource.getConnection();
@ -131,4 +125,8 @@ public class DoorManagerDAO {
closeConnection(); closeConnection();
} }
} }
public DoorManagerDAOImpl getAutomaticDoorLockerDeviceDAO() {
return new DoorManagerDAOImpl();
}
} }

@ -22,8 +22,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants; import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException; import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAO;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe; import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAO;
import org.homeautomation.doormanager.plugin.impl.dao.util.DoorManagerUtils; import org.homeautomation.doormanager.plugin.impl.dao.util.DoorManagerUtils;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
@ -32,9 +32,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* Device Dao for automatic door locker Devices. * Device Dao for automatic door locker Devices.
@ -311,6 +309,7 @@ public class DoorManagerDAOImpl {
DoorManagerUtils.cleanupResources(stmt, null); DoorManagerUtils.cleanupResources(stmt, null);
} }
} }
public List<String> getUserCredentials(String deviceId, String UIDofUser) throws DoorManagerDeviceMgtPluginException { public List<String> getUserCredentials(String deviceId, String UIDofUser) throws DoorManagerDeviceMgtPluginException {
Connection conn = null; Connection conn = null;

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

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
@ -20,23 +20,16 @@ package org.homeautomation.doormanager.plugin.internal;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.impl.DoorManagerManagerService; import org.homeautomation.doormanager.plugin.impl.DoorManagerService;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration; import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.service.DeviceTypeService;
/** /**
* @scr.component name="org.homeautomation.doormanager.plugin.internal.DoorManagerManagementServiceComponent" * @scr.component name="org.homeautomation.doormanager.plugin.internal.DoorManagerManagementServiceComponent"
* immediate="true" * immediate="true"
* @scr.reference name="org.wso2.carbon.device.mgt.iot.service.DeviceTypeServiceImpl"
* interface="org.wso2.carbon.device.mgt.iot.service.DeviceTypeService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDeviceTypeService"
* unbind="unsetDeviceTypeService"
*/ */
public class DoorManagerManagementServiceComponent { public class DoorManagerManagementServiceComponent {
@ -51,7 +44,7 @@ public class DoorManagerManagementServiceComponent {
BundleContext bundleContext = ctx.getBundleContext(); BundleContext bundleContext = ctx.getBundleContext();
automaticDoorLocker = automaticDoorLocker =
bundleContext.registerService(DeviceManagementService.class.getName(), bundleContext.registerService(DeviceManagementService.class.getName(),
new DoorManagerManagerService(), null); new DoorManagerService(), null);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("DoorOpener Device Management Service Component has been successfully activated"); log.debug("DoorOpener Device Management Service Component has been successfully activated");
} }
@ -74,20 +67,8 @@ public class DoorManagerManagementServiceComponent {
} }
} catch (Throwable e) { } catch (Throwable e) {
log.error( log.error(
"Error occurred while de-activating Door Opener Device Management bundle", e); "Error occurred while de-activating Door Locker Device Management bundle", e);
} }
} }
protected void setDeviceTypeService(DeviceTypeService deviceTypeService) {
/* This is to avoid this component getting initialized before the common registered */
if (log.isDebugEnabled()) {
log.debug("Data source service set to mobile service component");
}
}
protected void unsetDeviceTypeService(DeviceTypeService deviceTypeService) {
//do nothing
}
} }

@ -44,6 +44,7 @@
{{#zone "device-detail-properties"}} {{#zone "device-detail-properties"}}
<div class="media"> <div class="media">
<div class="media-left col-xs-12 col-sm-2 col-md-2 col-lg-2"> <div class="media-left col-xs-12 col-sm-2 col-md-2 col-lg-2">
<li class="active"><a class="list-group-item" href="#device_statistics" role="tab" <li class="active"><a class="list-group-item" href="#device_statistics" role="tab"
data-toggle="tab" aria-controls="device_statistics">Device Statistics</a> data-toggle="tab" aria-controls="device_statistics">Device Statistics</a>

@ -16,25 +16,6 @@
* under the License. * under the License.
*/ */
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function onRequest(context) { function onRequest(context) {
var log = new Log("device-view.js"); var log = new Log("device-view.js");
@ -48,7 +29,6 @@ function onRequest(context) {
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require("/app/modules/device.js").deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") { if (device && device.status != "error") {
log.info(device); log.info(device);
return {"device": device, "port": port, "host": host, "sessionId": sessionId}; return {"device": device, "port": port, "host": host, "sessionId": sessionId};

@ -1,56 +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.
*/
var deviceType = $("#details").data("devicetype");
var deviceId = $(".device-id").data("deviceid");
var monitor_operations = $("#details").data("monitor");
var appContext = $("#details").data("appcontext");
var publicURL =$("#details").data("unitpublicuri");
$(window).on('resize', function () {
location.reload(false);
});
$(document).ready(function () {
updateGraphs();
});
function updateGraphs() {
var tv = 2000;
var iv = setInterval(function () {
var getStatsRequest = $.ajax({
url: appContext + "/api/operations/" + deviceType + "/stats?deviceId=" + deviceId,
method: "get"
});
getStatsRequest.done(function (data) {
var data = data.data;
if(data[0].door_locker_state){
var currentStateOfTheLock=data[0].door_locker_state;
console.log(currentStateOfTheLock);
if( currentStateOfTheLock == "UNLOCKED"){
$("#lockerCurrentState").attr("src", publicURL+"/images/unlock.png");
}else{
$("#lockerCurrentState").attr("src", publicURL+"/images/lock.png");
}
}else{
console.log("Backend server not available");
}
});
}, tv);
}

@ -86,8 +86,6 @@ function attachEvents() {
var deviceType = $(this).data("devicetype"); var deviceType = $(this).data("devicetype");
var downloadDeviceAPI = "/devicemgt/api/devices/sketch/generate_link"; var downloadDeviceAPI = "/devicemgt/api/devices/sketch/generate_link";
var payload = {"sketchType": sketchType, "deviceType": deviceType}; var payload = {"sketchType": sketchType, "deviceType": deviceType};
console.log("-------------------------->"+JSON.stringify(payload));
$(modalPopupContent).html($('#download-device-modal-content').html()); $(modalPopupContent).html($('#download-device-modal-content').html());
showPopup(); showPopup();
var deviceName; var deviceName;
@ -111,33 +109,39 @@ function attachEvents() {
} }
); );
} else if (deviceName) { } else if (deviceName) {
$('.controls').append('<label for="deviceName" generated="true" class="error" style="display: inline-block;">Please enter at least 4 characters.</label>'); $('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">Please enter at least 4 ' +
'characters.</label>');
$('.control-group').removeClass('success').addClass('error'); $('.control-group').removeClass('success').addClass('error');
} else { } else {
$('.controls').append('<label for="deviceName" generated="true" class="error" style="display: inline-block;">This field is required.</label>'); $('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">This field is required.' +
'</label>');
$('.control-group').removeClass('success').addClass('error'); $('.control-group').removeClass('success').addClass('error');
} }
}); });
$("a#download-device-cancel-link").click(function () { $("a#download-device-cancel-link").click(function () {
hidePopup(); hidePopup();
}); });
}); });
} }
function downloadAgent() { function downloadAgent() {
var $inputs = $('#downloadForm :input'); /*var $inputs = $('#downloadForm :input');
var values = {}; var values = {};
$inputs.each(function() { $inputs.each(function() {
values[this.name] = $(this).val(); values[this.name] = $(this).val();
}); });
var payload = {}; var payload = {};
payload.name = $inputs[0].value; payload.name = $inputs[0].value;
payload.owner = $inputs[3].value; //payload.owner = $inputs[3].value;
payload.serialNumber = $inputs[1].value; payload.serialNumber = $inputs[1].value;
var doorManagerRegisterURL = "/doormanager_mgt/manager/device/register?" + var doorManagerRegisterURL = "/doormanager_mgt/manager/device/register?" +
"name=" + encodeURI(payload.name) + "&owner=" + payload.owner + "&serialNumber=" + payload.serialNumber; "name=" + encodeURI(payload.name) + "&deviceId=" + payload.serialNumber;
invokerUtil.post( invokerUtil.post(
doorManagerRegisterURL, doorManagerRegisterURL,
@ -159,6 +163,50 @@ function downloadAgent() {
setTimeout(function () { setTimeout(function () {
hidePopup(); hidePopup();
}, 1000); }, 1000);
}*/
var deviceName = "";
$('.new-device-name').each(function () {
if (this.value != "") {
deviceName = this.value;
}
});
var deviceType = "";
$('.deviceType').each(function () {
if (this.value != "") {
deviceType = this.value;
}
});
var sketchType = "";
$('.sketchType').each(function () {
if (this.value != "") {
sketchType = this.value;
}
});
/*var serialNumber = "";
$('.device-serial-number').each(function () {
if (this.value != "") {
serialNumber = this.value;
}
});*/
var deviceNameFormat = /^[^~?!#$:;%^*`+={}\[\]\\()|<>,'"]{1,30}$/;
if (deviceName && deviceNameFormat.test(deviceName)) {
$(modalPopupContent).html($('#device-agent-downloading-content').html());
var successCallback = function (data) {
data = JSON.parse(data);
hidePopup();
window.location = "/devicemgt/api/devices/sketch/download/" + data.responseContent;
};
var generateLink = "/" + deviceType + "_mgt/manager/device/" + sketchType
+ "/generate_link?deviceName=" + deviceName;
console.log("generated link"+ generateLink);
invokerUtil.get(generateLink, successCallback, function (message) {
console.log(message.content);
hidePopup();
doAction(data);
});
} else {
$("#invalid-username-error-msg span").text("Invalid device name");
$("#invalid-username-error-msg").removeClass("hidden");
} }
} }

@ -49,9 +49,10 @@
<div class="modal-content"> <div class="modal-content">
<div class="row"> <div class="row">
<div class="col-md-7 center-container"> <div class="col-md-7 center-container">
<h3>Enter your device name serial number and then register {{@uriParams.deviceType}} the agent from following link.</h3> <h3>Enter your device name serial number and then register {{@uriParams.deviceType}} the agent
from following link.</h3>
<br/> <br/>
<form id="downloadForm"> <form id="downloadForm" method="GET" action="#">
<div class="control-group"> <div class="control-group">
<div class="controls"> <div class="controls">
Device Name: <input class="new-device-name" style="color:#3f3f3f;padding:5px" Device Name: <input class="new-device-name" style="color:#3f3f3f;padding:5px"
@ -61,11 +62,13 @@
Serial Number: <input style="color:#3f3f3f;padding:5px" Serial Number: <input style="color:#3f3f3f;padding:5px"
type="text" type="text"
placeholder="Ex. serial number" placeholder="Ex. serial number"
name="serialNumber" size="60" required> name="serialNumber" size="60"
class="device-serial-number" required>
<br/> <br/>
<input type="hidden" class="deviceType" name="deviceType" <input type="hidden" class="deviceType" name="deviceType"
value="doormanager"/> value="doormanager"/>
<input type="hidden" class="owner" name="owner" value={{@user.username}} /> <input type="hidden" class="sketchType" name="sketchType"
value="doormanager"/>
</div> </div>
</div> </div>
<br/> <br/>
@ -79,6 +82,32 @@
</div> </div>
</div> </div>
<div id="device-agent-downloading-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Agent will download shortly.</h3>
</div>
</div>
</div>
</div>
<div id="download-device-modal-content-links" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Please download the file from following link(Press CTRL+C).</h3>
<br/>
<div>
<input id="download-device-url" style="color:#3f3f3f;padding:5px"
type="text" value="" placeholder="Type here" size="60">
</div>
</div>
</div>
</div>
</div>
<div id="device-400-content" class="hide"> <div id="device-400-content" class="hide">
<div class="modal-content"> <div class="modal-content">
<div class="row"> <div class="row">
@ -182,7 +211,8 @@
<li class="padding-top-double"><span class="circle">04</span>&nbsp;&nbsp;&nbsp;Copy downloaded Agent into your <li class="padding-top-double"><span class="circle">04</span>&nbsp;&nbsp;&nbsp;Copy downloaded Agent into your
RaspberryPi. RaspberryPi.
</li> </li>
<li class="padding-top-double"><span class="circle">05</span>&nbsp;&nbsp;&nbsp; Run "Agent.sh" script with root privileges. <li class="padding-top-double"><span class="circle">05</span>&nbsp;&nbsp;&nbsp; Run "Agent.sh" script with root
privileges.
</li> </li>
</ul> </ul>
<br> <br>
@ -237,15 +267,19 @@
width: 50px; width: 50px;
color: #fff; color: #fff;
} }
.padding-top-double { .padding-top-double {
padding-top: 20px; padding-top: 20px;
} }
.padding-double { .padding-double {
padding: 20px; padding: 20px;
} }
.grey { .grey {
color: #333; color: #333;
} }
hr { hr {
display: block; display: block;
height: 1px; height: 1px;
@ -255,21 +289,26 @@
padding: 0; padding: 0;
opacity: 0.2; opacity: 0.2;
} }
.light-grey { .light-grey {
color: #7c7c7c; color: #7c7c7c;
} }
.uppercase { .uppercase {
text-transform: uppercase; text-transform: uppercase;
} }
.grey-bg { .grey-bg {
background-color: #f6f4f4; background-color: #f6f4f4;
} }
.doc-link { .doc-link {
background: #11375B; background: #11375B;
padding: 20px; padding: 20px;
color: white; color: white;
margin-top: 0; margin-top: 0;
} }
.doc-link a { .doc-link a {
color: white; color: white;
} }

Loading…
Cancel
Save