diff --git a/modules/samples/doormanager/component/agent/pom.xml b/modules/samples/doormanager/component/agent/pom.xml
deleted file mode 100644
index c9bff98f..00000000
--- a/modules/samples/doormanager/component/agent/pom.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-
-
-
- org.homeautomation
- component
- 1.0.0-SNAPSHOT
- ../pom.xml
-
- 4.0.0
- ${groupId}.doormanager.agent
- 1.0.0-SNAPSHOT
- ${groupId}.doormanager.agent
- war
-
-
- junit
- junit
- ${junit.version}
- test
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
-
- ${wso2.maven.compiler.target}
-
-
-
- maven-war-plugin
- ${maven-war-plugin.version}
-
- ${groupId}.doormanager.agent_agent
-
-
-
-
-
\ No newline at end of file
diff --git a/modules/samples/doormanager/component/agent/src/main/webapp/WEB-INF/web.xml b/modules/samples/doormanager/component/agent/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index f39e4103..00000000
--- a/modules/samples/doormanager/component/agent/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
- Sample-Agent-Webapp
-
diff --git a/modules/samples/doormanager/component/agent/src/main/webapp/index.jsp b/modules/samples/doormanager/component/agent/src/main/webapp/index.jsp
deleted file mode 100644
index fa3b38f0..00000000
--- a/modules/samples/doormanager/component/agent/src/main/webapp/index.jsp
+++ /dev/null
@@ -1,22 +0,0 @@
-<%--/*
-* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-*
-* WSO2 Inc. licenses this file to you under the Apache License,
-* Version 2.0 (the "License"); you may not use this file except
-* in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing,
-* software distributed under the License is distributed on an
-* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-* KIND, either express or implied. See the License for the
-* specific language governing permissions and limitations
-* under the License.
-*/--%>
-
-
-
Hello World!
-
-
\ No newline at end of file
diff --git a/modules/samples/doormanager/component/analytics/build.xml b/modules/samples/doormanager/component/analytics/build.xml
index 8ae090c7..6a72f27e 100644
--- a/modules/samples/doormanager/component/analytics/build.xml
+++ b/modules/samples/doormanager/component/analytics/build.xml
@@ -20,9 +20,9 @@
-
+
-
+
diff --git a/modules/samples/doormanager/component/analytics/pom.xml b/modules/samples/doormanager/component/analytics/pom.xml
index efa32fef..f2935ab4 100644
--- a/modules/samples/doormanager/component/analytics/pom.xml
+++ b/modules/samples/doormanager/component/analytics/pom.xml
@@ -1,3 +1,4 @@
+
-org.homeautomation
- component
+ doormanager-component1.0.0-SNAPSHOT../pom.xml4.0.0
- ${groupId}.doormanager.analytics
+ org.homeautomation.doormanager.analytics1.0.0-SNAPSHOTpom
- ${groupId}.doormanager.analytics
+ org.homeautomation.doormanager.analyticshttp://wso2.org
@@ -65,7 +66,7 @@
maven-assembly-plugin2.5.5
- ${project.artifactId}-1.0.0-SNAPSHOT
+ org.homeautomation.doormanager.analytics-1.0.0-SNAPSHOTfalsesrc/assembly/src.xml
diff --git a/modules/samples/doormanager/component/analytics/src/assembly/src.xml b/modules/samples/doormanager/component/analytics/src/assembly/src.xml
index a5a37501..5469255f 100644
--- a/modules/samples/doormanager/component/analytics/src/assembly/src.xml
+++ b/modules/samples/doormanager/component/analytics/src/assembly/src.xml
@@ -1,3 +1,4 @@
+
src
diff --git a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstore_sensor_1.0.0/org_wso2_iot_devices_sensor.xml b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstore_sensor_1.0.0/org_wso2_iot_devices_sensor.xml
deleted file mode 100644
index 75f6153c..00000000
--- a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstore_sensor_1.0.0/org_wso2_iot_devices_sensor.xml
+++ /dev/null
@@ -1,62 +0,0 @@
-
-
-
-
-
- EVENT_STORE
-
-
- meta_owner
- true
- true
- false
- STRING
-
-
- meta_deviceType
- true
- true
- false
- STRING
-
-
- meta_deviceId
- true
- true
- false
- STRING
-
-
- meta_time
- true
- true
- false
- LONG
-
-
- sensorValue
- false
- false
- false
- FLOAT
-
-
-
diff --git a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstream_sensor_1.0.0/org.wso2.iot.devices.sensor_1.0.0.json b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstream_sensor_1.0.0/org.wso2.iot.devices.sensor_1.0.0.json
deleted file mode 100644
index 1ad0e99b..00000000
--- a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstream_sensor_1.0.0/org.wso2.iot.devices.sensor_1.0.0.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "name": "org.wso2.iot.devices.sensor",
- "version": "1.0.0",
- "nickName": "Flow Rate Data",
- "description": "Sensor data received from the Device",
- "metaData": [
- {"name":"owner","type":"STRING"},
- {"name":"deviceType","type":"STRING"},
- {"name":"deviceId","type":"STRING"},
- {"name":"time","type":"LONG"}
- ],
- "payloadData": [
- {
- "name": "sensorValue","type": "FLOAT"
- }
- ]
-}
diff --git a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventreceiver_sensor_1.0.0/EventReceiver_sensor.xml b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventreceiver_smartLock_1.0.0/EventReceiver_smartLock.xml
similarity index 86%
rename from modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventreceiver_sensor_1.0.0/EventReceiver_sensor.xml
rename to modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventreceiver_smartLock_1.0.0/EventReceiver_smartLock.xml
index 846f3a26..1a53d098 100644
--- a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventreceiver_sensor_1.0.0/EventReceiver_sensor.xml
+++ b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventreceiver_smartLock_1.0.0/EventReceiver_smartLock.xml
@@ -17,11 +17,11 @@
~ under the License.
-->
-false
-
+
diff --git a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventreceiver_sensor_1.0.0/artifact.xml b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventreceiver_smartLock_1.0.0/artifact.xml
similarity index 82%
rename from modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventreceiver_sensor_1.0.0/artifact.xml
rename to modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventreceiver_smartLock_1.0.0/artifact.xml
index 9a5ba578..8fb0293e 100644
--- a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventreceiver_sensor_1.0.0/artifact.xml
+++ b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventreceiver_smartLock_1.0.0/artifact.xml
@@ -17,6 +17,6 @@
~ under the License.
-->
-
- EventReceiver_sensor.xml
+
+ EventReceiver_smartLock.xml
diff --git a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstore_sensor_1.0.0/artifact.xml b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstore_smartLock_1.0.0/artifact.xml
similarity index 81%
rename from modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstore_sensor_1.0.0/artifact.xml
rename to modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstore_smartLock_1.0.0/artifact.xml
index e6ff436f..c039213e 100644
--- a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstore_sensor_1.0.0/artifact.xml
+++ b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstore_smartLock_1.0.0/artifact.xml
@@ -17,6 +17,6 @@
~ under the License.
-->
-
- org_wso2_iot_devices_sensor.xml
+
+ org_wso2_iot_devices_smartLock.xml
diff --git a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstore_smartLock_1.0.0/org_wso2_iot_devices_smartLock.xml b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstore_smartLock_1.0.0/org_wso2_iot_devices_smartLock.xml
new file mode 100644
index 00000000..e177b155
--- /dev/null
+++ b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstore_smartLock_1.0.0/org_wso2_iot_devices_smartLock.xml
@@ -0,0 +1,62 @@
+
+
+
+
+
+ EVENT_STORE
+
+
+ meta_owner
+ true
+ true
+ false
+ STRING
+
+
+ meta_deviceType
+ true
+ true
+ false
+ STRING
+
+
+ meta_deviceId
+ true
+ true
+ false
+ STRING
+
+
+ meta_time
+ true
+ true
+ false
+ LONG
+
+
+ smartLock
+ false
+ false
+ false
+ FLOAT
+
+
+
\ No newline at end of file
diff --git a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstream_sensor_1.0.0/artifact.xml b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstream_smartLock_1.0.0/artifact.xml
similarity index 81%
rename from modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstream_sensor_1.0.0/artifact.xml
rename to modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstream_smartLock_1.0.0/artifact.xml
index b8afeda8..67da309f 100644
--- a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Eventstream_sensor_1.0.0/artifact.xml
+++ b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstream_smartLock_1.0.0/artifact.xml
@@ -17,6 +17,7 @@
~ under the License.
-->
-
- org.wso2.iot.devices.sensor_1.0.0.json
+
+ org.wso2.iot.devices.smartLock_1.0.0.json
+
diff --git a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstream_smartLock_1.0.0/org.wso2.iot.devices.smartLock_1.0.0.json b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstream_smartLock_1.0.0/org.wso2.iot.devices.smartLock_1.0.0.json
new file mode 100644
index 00000000..fa4e05d6
--- /dev/null
+++ b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Eventstream_smartLock_1.0.0/org.wso2.iot.devices.smartLock_1.0.0.json
@@ -0,0 +1,33 @@
+{
+ "name": "org.wso2.iot.devices.smartLock",
+ "version": "1.0.0",
+ "nickName": "smartLock",
+ "description": "smartLock data received from the Device",
+ "metaData": [
+ {
+ "name": "owner",
+ "type": "STRING"
+ },
+ {
+ "name": "deviceType",
+ "type": "STRING"
+ },
+ {
+ "name": "deviceId",
+ "type": "STRING"
+ },
+ {
+ "name": "time",
+ "type": "LONG"
+ }
+ ],
+ "payloadData": [
+ {
+ "name": "smartLock",
+ "type": "FLOAT"
+ }
+ ]
+}
+
+
+
diff --git a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Sparkscripts_1.0.0/artifact.xml b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Sparkscripts_1.0.0/artifact.xml
similarity index 95%
rename from modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Sparkscripts_1.0.0/artifact.xml
rename to modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Sparkscripts_1.0.0/artifact.xml
index 85400ae3..f7da0d0c 100644
--- a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Sparkscripts_1.0.0/artifact.xml
+++ b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Sparkscripts_1.0.0/artifact.xml
@@ -18,5 +18,5 @@
-->
- Sensor_Script.xml
+ smartLock_Script.xml
diff --git a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Sparkscripts_1.0.0/Sensor_Script.xml b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Sparkscripts_1.0.0/smartLock_Script.xml
similarity index 51%
rename from modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Sparkscripts_1.0.0/Sensor_Script.xml
rename to modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Sparkscripts_1.0.0/smartLock_Script.xml
index 77abc2a3..848ef9e7 100644
--- a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/Sparkscripts_1.0.0/Sensor_Script.xml
+++ b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/Sparkscripts_1.0.0/smartLock_Script.xml
@@ -18,13 +18,18 @@
-->
- Sensor_Script
+ IoTServer_smartLock_Script0 * * * * ?
diff --git a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/artifacts.xml b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/artifacts.xml
similarity index 67%
rename from modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/artifacts.xml
rename to modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/artifacts.xml
index eab2a8d1..4385705f 100644
--- a/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/Sensor/artifacts.xml
+++ b/modules/samples/doormanager/component/analytics/src/main/resources/carbonapps/smartLock/artifacts.xml
@@ -18,11 +18,10 @@
-->
-
-
-
-
+
+
+
+
diff --git a/modules/samples/doormanager/component/controller/pom.xml b/modules/samples/doormanager/component/controller/pom.xml
index 9d222daf..68a46768 100644
--- a/modules/samples/doormanager/component/controller/pom.xml
+++ b/modules/samples/doormanager/component/controller/pom.xml
@@ -15,19 +15,19 @@
* specific language governing permissions and limitations
* under the License.
*/-->
-org.homeautomation
- component
+ doormanager-component1.0.0-SNAPSHOT../pom.xml4.0.0
- ${groupId}.doormanager.controller
+ org.homeautomation.doormanager.controller1.0.0-SNAPSHOTwar
- ${groupId}.doormanager.controller
+ org.homeautomation.doormanager.controllerhttp://wso2.com
@@ -45,7 +45,7 @@
maven-war-plugin${maven-war-plugin.version}
- ${groupId}.doormanager.controller
+ org.homeautomation.doormanager.controller
@@ -53,7 +53,7 @@
org.homeautomation
- ${project-base-package}.plugin
+ org.homeautomation.doormanager.plugin
diff --git a/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/DoorManagerControllerService.java b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/DoorManagerControllerService.java
index eb51bf19..511acf0b 100644
--- a/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/DoorManagerControllerService.java
+++ b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/DoorManagerControllerService.java
@@ -20,18 +20,19 @@ package org.homeautomation.doormanager.controller.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.homeautomation.doormanager.controller.api.dto.DeviceJSON;
+import org.homeautomation.doormanager.controller.api.dto.UserInfo;
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.exception.DoorManagerDeviceMgtPluginException;
+import org.homeautomation.doormanager.plugin.impl.DoorManager;
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.device.DeviceType;
import org.wso2.carbon.apimgt.annotations.device.feature.Feature;
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.DeviceManagementException;
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.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
-import org.wso2.carbon.user.core.service.RealmService;
import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
-import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
+import javax.ws.rs.GET;
import javax.ws.rs.Produces;
+import javax.ws.rs.Consumes;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Calendar;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
+@SuppressWarnings("NonJaxWsWebServices")
@API(name = "doormanager", version = "1.0.0", context = "/doormanager")
@DeviceType(value = "doormanager")
public class DoorManagerControllerService {
- private static final DoorManagerDAO DOOR_MANAGER_DAO = new DoorManagerDAO();
-
private static Log log = LogFactory.getLog(DoorManagerControllerService.class);
- private HttpServletResponse response;
+ private static String CURRENT_STATUS = "doorLockerCurrentStatus";
+ private DoorManager doorManager;
private DoorManagerMQTTConnector doorManagerMQTTConnector;
- private ConcurrentHashMap deviceToIpMap = new ConcurrentHashMap<>();
-
- private PrivilegedCarbonContext ctx;
-
- @Context //injected response proxy supporting multiple thread
- 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");
- }
+ DoorManagerControllerService() {
+ doorManager = new DoorManager();
}
+ @Context //injected response proxy supporting multiple thread
private boolean waitForServerStartup() {
while (!DeviceManagement.isServerReady()) {
try {
@@ -128,7 +103,7 @@ public class DoorManagerControllerService {
doorManagerMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, DoorManagerMQTTConnector" +
- " not started.");
+ " not started.");
}
}
};
@@ -137,220 +112,83 @@ public class DoorManagerControllerService {
connectorThread.start();
}
+ /**
+ * Assign new user to lock
+ *
+ * @param owner owner of the device
+ * @param deviceId unique identifier for given device
+ * @param protocol transport protocol which is being using here MQTT
+ * @param cardNumber RFID card number
+ * @param userName user name of RFID card owner
+ * @param emailAddress email address of RFID card owner
+ */
@Path("controller/assign_user")
@POST
@Feature(code = "assign_user", name = "Assign new user to lock", type = "operation",
- description = "Add new access card to user to control the lock with given policy")
- public void assignUseToLock(@HeaderParam("owner") String owner,
- @HeaderParam("deviceId") String deviceId,
- @HeaderParam("protocol") String protocol,
- @FormParam("policy") String policy,
- @FormParam("cardNumber") String cardNumber,
- @FormParam("userName") String userName,
- @FormParam("emailAddress") String emailAddress,
- @Context HttpServletResponse response) {
- try {
- if (userName != null && cardNumber != null && deviceId != null) {
- try {
- UserStoreManager userStoreManager = this.getUserStoreManager();
- DoorLockSafe doorLockSafe = new DoorLockSafe();
- if (userStoreManager.isExistingUser(userName)) {
- TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
- AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(deviceId, userName);
- String accessToken = accessTokenInfo.getAccess_token();
- if (accessToken == null) {
- response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
- return;
- }
- Map 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);
- 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);
- boolean status;
- 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());
- log.error(msg, e);
- }
- }
+ description = "Add new access card to user to control the lock ")
+ public void assignUserToLock(@HeaderParam("owner") String owner,
+ @HeaderParam("deviceId") String deviceId,
+ @HeaderParam("protocol") String protocol,
+ @FormParam("cardNumber") String cardNumber,
+ @FormParam("userName") String userName,
+ @FormParam("emailAddress") String emailAddress,
+ @Context HttpServletResponse response) {
- response.setStatus(Response.Status.OK.getStatusCode());
- } else {
- response.setStatus(Response.Status.NOT_FOUND.getStatusCode());
- }
- } catch (UserStoreException e) {
- response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
- log.error(e);
- }
- } else {
- response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
- }
-
- } catch (AccessTokenException e) {
- response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
- 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());
- log.error(msg, e);
- }
+ if (userName != null && cardNumber != null && deviceId != null) {
+ try {
+ UserStoreManager userStoreManager = doorManager.getUserStoreManager();
+ DoorLockSafe doorLockSafe = new DoorLockSafe();
+ if (userStoreManager.isExistingUser(userName)) {
+ TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
+ AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(deviceId, userName);
+ String accessToken = accessTokenInfo.getAccess_token();
+ if (accessToken == null) {
+ response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
- } else {
- response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
- }
- }
- } catch (AccessTokenException e) {
- response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
- 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("cardNumber") String cardNumber,
- @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;
+ Map claims = new HashMap<>();
+ claims.put(DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, accessToken);
+ claims.put(DoorManagerConstants.DEVICE_CLAIMS_REFRESH_TOKEN,
+ accessTokenInfo.getRefresh_token());
+ claims.put(DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, cardNumber);
+ userStoreManager.setUserClaimValues(userName, claims, null);
doorLockSafe.setAccessToken(accessTokenInfo.getAccess_token());
doorLockSafe.setRefreshToken(accessTokenInfo.getRefresh_token());
doorLockSafe.setDeviceId(deviceId);
doorLockSafe.setOwner(owner);
doorLockSafe.setEmailAddress(emailAddress);
doorLockSafe.setUIDofUser(cardNumber);
- doorLockSafe.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 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);
+ if (doorManager.assignUserToLock(doorLockSafe)) {
+ response.setStatus(Response.Status.OK.getStatusCode());
+ } else {
+ response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
}
} else {
- response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
+ response.setStatus(Response.Status.NOT_FOUND.getStatusCode());
}
+ } catch (UserStoreException e) {
+ response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
+ log.error(e);
+ } catch (DoorManagerDeviceMgtPluginException | AccessTokenException e) {
+ log.error(e);
+ response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
- } catch (AccessTokenException e) {
+ } else {
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
- log.error(e);
}
- }*/
+ }
- @Path("controller/changeStatusOfDoorLockSafe")
+ /**
+ * Change status of door lock safe: LOCK/UNLOCK
+ *
+ * @param owner owner of the device
+ * @param deviceId unique identifier for given device
+ * @param protocol transport protocol which is being using here MQTT
+ * @param state status of lock safe: lock/unlock
+ */
+ @Path("controller/change-status")
@POST
- @Feature(code = "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")
public void changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@@ -364,8 +202,8 @@ public class DoorManagerControllerService {
} else {
lockerCurrentState = 1;
}
- SensorDataManager.getInstance().setSensorRecord(deviceId, "door_locker_state",
- String.valueOf(lockerCurrentState), Calendar.getInstance().getTimeInMillis());
+ SensorDataManager.getInstance().setSensorRecord(deviceId, CURRENT_STATUS,
+ String.valueOf(lockerCurrentState), Calendar.getInstance().getTimeInMillis());
doorManagerMQTTConnector.sendCommandViaMQTT(owner, deviceId, "DoorManager:", state.toUpperCase());
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
@@ -376,78 +214,20 @@ public class DoorManagerControllerService {
}
}
- /*@Path("controller/shareDoorLockSafe")
- @POST
- @Feature(code = "shareDoorLockSafe", name = "Share lock safe with new user", type = "operation",
- description = "Share lock safe with new user")
- public void shareDoorLockSafe(@HeaderParam("owner") String owner, @HeaderParam("deviceId") String deviceId,
- @HeaderParam("protocol") String protocol,
- @FormParam("UIDofUser") String UIDofUser,@FormParam("policy") String policy,
- @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();
- }
- }
-
+ /**
+ * Request current status of door lock safe
+ *
+ * @param owner owner of the device
+ * @param deviceId unique identifier for given device
+ * @param protocol transport protocol which is being using here MQTT
+ * @param response http servlet response object
+ */
@GET
- @Path("controller/requestStatusOfDoorLockSafe")
+ @Path("controller/current-status")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
- @Feature(code = "requestStatusOfDoorLockSafe", name = "Door Locker Status", type = "monitor",
- description = "Request door locker current status")
+ @Feature(code = "current-status", name = "Door Locker Status", type = "monitor",
+ description = "Request current status of door safe")
public SensorRecord requestStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@@ -456,43 +236,91 @@ public class DoorManagerControllerService {
DeviceValidator deviceValidator = new DeviceValidator();
try {
if (!deviceValidator.isExist(owner, CarbonContext.getThreadLocalCarbonContext().getTenantDomain(),
- new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE))) {
+ new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
- } catch (DeviceManagementException e) {
- response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
- }
- try {
- sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, "door_locker_state");
- } catch (DeviceControllerException e) {
+ sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, CURRENT_STATUS);
+ response.setStatus(Response.Status.OK.getStatusCode());
+ } catch (DeviceControllerException | DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
- response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord;
}
- @GET
- @Path("controller/getRegisteredDoorLockSafe")
- @Consumes(MediaType.APPLICATION_JSON)
+ /**
+ * @param userInfo user information which are required to test given user is authorized to open requested door
+ * @return if user is authorized open the the door allow to open it
+ */
+ @POST
+ @Path("controller/get_user_info")
@Produces(MediaType.APPLICATION_JSON)
- public Response getRegisteredDoorLocks(@HeaderParam("owner") String owner,
- @HeaderParam("deviceId") String deviceId,
- @Context HttpServletResponse response) {
- List doorLockSafes;
- try {
- DoorManagerDAO.beginTransaction();
- doorLockSafes = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().getRegisteredDoorLocks(deviceId);
- DoorManagerDAO.commitTransaction();
- response.setStatus(Response.Status.OK.getStatusCode());
- } catch (DoorManagerDeviceMgtPluginException e) {
+ @Consumes(MediaType.APPLICATION_JSON)
+ @SuppressWarnings("unchecked") //This is to avoid unchecked call to put(k, v) into jsonObject. org.json.simple
+ // library uses raw type collections internally.
+ public Response get_user_info(final UserInfo userInfo) {
+ if (userInfo.userName != null && userInfo.cardNumber != null && userInfo.deviceId != null) {
try {
- DoorManagerDAO.rollbackTransaction();
- } catch (DoorManagerDeviceMgtPluginException e1) {
- String msg = "Error while updating the enrollment of the Door Manager Locker device : " + deviceId;
- response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
- log.error(msg, e);
+ UserStoreManager userStoreManager = doorManager.getUserStoreManager();
+ if (userStoreManager.isExistingUser(userInfo.userName)) {
+ String accessToken = userStoreManager.getUserClaimValue(userInfo.userName,
+ DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, null);
+ String cardNumber = userStoreManager.getUserClaimValue(userInfo.userName,
+ DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, null);
+ if (cardNumber != null) {
+ if (cardNumber.equals(userInfo.cardNumber)) {
+ if (accessToken != null) {
+ JSONObject credentials = new JSONObject();
+ credentials.put(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN, accessToken);
+ //return Response.ok(credentials, MediaType.APPLICATION_JSON_TYPE).build();
+ return Response.status(Response.Status.OK).build();
+ }
+ }
+ return Response.status(Response.Status.UNAUTHORIZED).build();
+ }
+
+ } else {
+ return Response.status(Response.Status.UNAUTHORIZED).build();
+ }
+ } catch (UserStoreException e) {
+ log.error(e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
+ } catch (JSONException e) {
+ log.error(e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
- return Response.ok().build();
+ return Response.status(Response.Status.BAD_REQUEST).build();
}
+
+ /*
+ private void sendCEPEvent(String deviceId, String cardId, boolean accessStatus){
+ String cepEventReciever = "http://localhost:9768/endpoints/LockEventReciever";
+
+ HttpClient httpClient = new SystemDefaultHttpClient();
+ HttpPost method = new HttpPost(cepEventReciever);
+ JsonObject event = new JsonObject();
+ JsonObject metaData = new JsonObject();
+
+ metaData.addProperty("deviceID", deviceId);
+ metaData.addProperty("cardID", cardId);
+
+ event.add("metaData", metaData);
+
+ String eventString = "{\"event\": " + event + "}";
+
+ try {
+ StringEntity entity = new StringEntity(eventString);
+ method.setEntity(entity);
+ if (cepEventReciever.startsWith("https")) {
+ method.setHeader("Authorization", "Basic " + Base64.encode(("admin" + ":" + "admin").getBytes()));
+ }
+ httpClient.execute(method).getEntity().getContent().close();
+ } catch (UnsupportedEncodingException e) {
+ log.error("Error while constituting CEP event"+ e.getMessage());
+ } catch (ClientProtocolException e) {
+ log.error("Error while sending message to CEP "+ e.getMessage());
+ } catch (IOException e) {
+ log.error("Error while sending message to CEP "+ e.getMessage());
+ }
+ }*/
}
diff --git a/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/dto/DeviceJSON.java b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/dto/DeviceJSON.java
index f812dade..4496b0b8 100644
--- a/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/dto/DeviceJSON.java
+++ b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/dto/DeviceJSON.java
@@ -27,8 +27,12 @@ import javax.xml.bind.annotation.XmlRootElement;
@JsonIgnoreProperties(ignoreUnknown = true)
public class DeviceJSON {
- @XmlElement(required = true) public String owner;
- @XmlElement(required = true) public String deviceId;
- @XmlElement(required = true) public String UIDofUser;
- @XmlElement(required = true) public String serialNumber;
+ @XmlElement(required = true)
+ public String owner;
+ @XmlElement(required = true)
+ public String deviceId;
+ @XmlElement(required = true)
+ public String UIDofUser;
+ @XmlElement(required = true)
+ public String serialNumber;
}
diff --git a/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/dto/UserInfo.java b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/dto/UserInfo.java
similarity index 75%
rename from modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/dto/UserInfo.java
rename to modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/dto/UserInfo.java
index b7ef2c10..5d89ea2f 100644
--- a/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/dto/UserInfo.java
+++ b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/dto/UserInfo.java
@@ -16,7 +16,7 @@
* under the License.
*/
-package org.homeautomation.doormanager.manager.api.dto;
+package org.homeautomation.doormanager.controller.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@@ -27,8 +27,10 @@ import javax.xml.bind.annotation.XmlRootElement;
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserInfo {
- @XmlElement(required = true) public String serialNumber;
- @XmlElement(required = true) public String deviceId;
- @XmlElement(required = true) public String cardNumber;
- @XmlElement(required = true) public String userName;
+ @XmlElement(required = true)
+ public String deviceId;
+ @XmlElement(required = true)
+ public String cardNumber;
+ @XmlElement(required = true)
+ public String userName;
}
diff --git a/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/exception/DoorManagerException.java b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/exception/DoorManagerException.java
index 63673efc..554967bc 100644
--- a/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/exception/DoorManagerException.java
+++ b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/exception/DoorManagerException.java
@@ -1,4 +1,3 @@
-package org.homeautomation.doormanager.controller.api.exception;
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
@@ -16,20 +15,16 @@ package org.homeautomation.doormanager.controller.api.exception;
* specific language governing permissions and limitations
* under the License.
*/
+
+package org.homeautomation.doormanager.controller.api.exception;
+
public class DoorManagerException extends Exception {
private static final long serialVersionUID = 2736466230451105441L;
private String errorMessage;
- public String getErrorMessage() {
- return errorMessage;
- }
-
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
-
+ @SuppressWarnings("unused")
public DoorManagerException(String msg, DoorManagerException nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
@@ -40,18 +35,30 @@ public class DoorManagerException extends Exception {
setErrorMessage(message);
}
+ @SuppressWarnings("unused")
public DoorManagerException(String msg) {
super(msg);
setErrorMessage(msg);
}
+ @SuppressWarnings("unused")
public DoorManagerException() {
super();
}
+ @SuppressWarnings("unused")
public DoorManagerException(Throwable cause) {
super(cause);
}
+ @SuppressWarnings("unused")
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
}
diff --git a/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/util/DoorManagerMQTTConnector.java b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/transport/DoorManagerMQTTConnector.java
similarity index 54%
rename from modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/util/DoorManagerMQTTConnector.java
rename to modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/transport/DoorManagerMQTTConnector.java
index bf61fdb8..6dc076ab 100644
--- a/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/util/DoorManagerMQTTConnector.java
+++ b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/transport/DoorManagerMQTTConnector.java
@@ -1,37 +1,65 @@
-package org.homeautomation.doormanager.controller.api.util;
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.homeautomation.doormanager.controller.api.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.homeautomation.doormanager.controller.api.exception.DoorManagerException;
+import org.homeautomation.doormanager.controller.api.util.DoorManagerServiceUtils;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
+import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler;
-import javax.ws.rs.core.Response;
import java.io.File;
import java.util.Calendar;
import java.util.UUID;
+/**
+ * MQTT is used as transport protocol. So this will provide basic functional requirement in order to communicate over
+ * MQTT
+ */
@SuppressWarnings("no JAX-WS annotation")
public class DoorManagerMQTTConnector extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(DoorManagerMQTTConnector.class);
- private static final String subscribeTopic =
- "wso2" + File.separator + "iot" + File.separator + "+" + File.separator +
- DoorManagerConstants.DEVICE_TYPE + File.separator + "+" + File.separator +
- "lockStatusPublisher"+ File.separator;
- private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
+ private static String PUBLISHER_CONTEXT = "publisher";
+ private static String SUBSCRIBER_CONTEXT = "subscriber";
+ private static String SUBCRIBER_TOPIC = "wso2" + File.separator + "iot" + File.separator + "+" + File.separator +
+ DoorManagerConstants.DEVICE_TYPE + File.separator + "+" + File.separator + PUBLISHER_CONTEXT;
+ private static String PUBLISHER_TOPIC = "wso2/iot/%s/" + DoorManagerConstants.DEVICE_TYPE + "/%s/"
+ + SUBSCRIBER_CONTEXT;
+ private static String SUBSCRIBER = UUID.randomUUID().toString().substring(0, 5);
private DoorManagerMQTTConnector() {
- super(iotServerSubscriber, DoorManagerConstants.DEVICE_TYPE,
- MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic);
+ super(SUBSCRIBER, DoorManagerConstants.DEVICE_TYPE,
+ MqttConfig.getInstance().getMqttQueueEndpoint(), SUBCRIBER_TOPIC);
}
+ /**
+ * This method will initialize connection with message broker
+ */
@Override
public void connect() {
Runnable connector = new Runnable() {
@@ -63,79 +91,103 @@ public class DoorManagerMQTTConnector extends MQTTTransportHandler {
connectorThread.start();
}
+ /**
+ * This callback function will be called by message broker when some messages available to subscribed topic
+ *
+ * @param message mqtt message which is coming form agent side
+ * @param messageParams metadata of mqtt message
+ */
@Override
public void processIncomingMessage(MqttMessage message, String... messageParams) {
String topic = messageParams[0];
String ownerAndId = topic.replace("wso2" + File.separator + "iot" + File.separator, "");
ownerAndId = ownerAndId.replace(File.separator + DoorManagerConstants.DEVICE_TYPE
+ File.separator, ":");
- ownerAndId = ownerAndId.replace(File.separator + "lockStatusPublisher", "");
+ ownerAndId = ownerAndId.replace(File.separator + PUBLISHER_CONTEXT, "");
String owner = ownerAndId.split(":")[0];
String deviceId = ownerAndId.split(":")[1];
log.warn(deviceId);
-
String[] messageData = message.toString().split(":");
-
- if (log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("Received MQTT message for: [OWNER-" + owner + "] & [DEVICE.ID-" + deviceId + "]");
}
if (messageData.length == 2) {
- log.warn("-------------------------------------------");
- log.warn(messageData[0]);
- log.warn(messageData[1]);
String lockerCurrentState = messageData[1];
+ float lockerStatus;
+ if (lockerCurrentState.equals("LOCKED")) {
+ lockerStatus = 0;
+ } else {
+ lockerStatus = 1;
+ }
try {
- SensorDataManager.getInstance().setSensorRecord(deviceId, "door_locker_state",
- String.valueOf(1), Calendar.getInstance().getTimeInMillis());
- if (!DoorManagerServiceUtils.publishToDASCurrent(owner, deviceId, 1)) {
- log.warn("An error occured whilst trying to publish with ID [" + deviceId +
- "] of owner [" + owner + "]");
+ SensorDataManager.getInstance().setSensorRecord(deviceId, "doorLockerCurrentStatus",
+ String.valueOf(lockerStatus), Calendar.getInstance().getTimeInMillis());
+ if (!DoorManagerServiceUtils.publishToDASLockerStatus(owner, deviceId, lockerStatus)) {
+ log.warn("An error occurred while trying to publish with ID [" + deviceId + "] of owner ["
+ + owner + "]");
}
- } catch(Exception e){
- log.error(e);
- }
- if(log.isDebugEnabled()){
- //log.debug("Return result " + result + " for Request " + requestMessage);
+ } catch (Exception e) {
+ log.error(e);
}
}
}
+ /**
+ * Publish a MQTT message to device through message broker
+ *
+ * @param topic mqtt topic which will be used to uniquely identify who are the subscribers to this topic
+ * @param payLoad message is to be published
+ * @param qos level of qos(quality of service):1,2,3
+ * @param retained klkkl
+ * @throws TransportHandlerException
+ */
private void publishToAutomaticDoorLocker(String topic, String payLoad, int qos, boolean retained)
throws TransportHandlerException {
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("Publishing message [" + payLoad + "to topic [" + topic + "].");
}
publishToQueue(topic, payLoad, qos, retained);
}
+ /**
+ * Publish a MQTT message to device through message broker
+ *
+ * @param deviceOwner person who own the device
+ * @param deviceId unique identifier for each device
+ * @param operation command is to executed at agent side e.g: off, on
+ * @param param additional payload
+ * @throws DeviceManagementException
+ * @throws DoorManagerException
+ */
public void sendCommandViaMQTT(String deviceOwner, String deviceId, String operation, String param)
throws DeviceManagementException, DoorManagerException {
- String PUBLISH_TOPIC = "wso2/iot/%s/doormanager/%s/lockController";
- String topic = String.format(PUBLISH_TOPIC, deviceOwner, deviceId);
+ String topic = String.format(PUBLISHER_TOPIC, deviceOwner, deviceId);
String payload = operation + param;
try {
publishToAutomaticDoorLocker(topic, payload, 2, false);
- if(param.equals("LOCK")){
- if (!DoorManagerServiceUtils.publishToDASCurrent(deviceOwner, deviceId, 0)) {
- log.warn("An error occured whilst trying to publish with ID [" + deviceId +
- "] of owner [" + deviceOwner + "]");
+ if (param.equals("LOCK")) {
+ if (!DoorManagerServiceUtils.publishToDASLockerStatus(deviceOwner, deviceId, 0)) {
+ log.warn("An error occurred whilst trying to publish with ID [" + deviceId + "] of owner [" +
+ deviceOwner + "]");
}
- }else{
- if (!DoorManagerServiceUtils.publishToDASCurrent(deviceOwner, deviceId, 1)) {
- log.warn("An error occured whilst trying to publish with ID [" + deviceId +
- "] of owner [" + deviceOwner + "]");
+ } else {
+ if (!DoorManagerServiceUtils.publishToDASLockerStatus(deviceOwner, deviceId, 1)) {
+ log.warn("An error occurred whilst trying to publish with ID [" + deviceId + "] of owner [" +
+ deviceOwner + "]");
}
}
- if (!DoorManagerServiceUtils.publishToDASCurrent(deviceOwner, deviceId, 1)) {
- log.warn("An error occured whilst trying to publish with ID [" + deviceId +
- "] of owner [" + deviceOwner + "]");
- }
} catch (TransportHandlerException e) {
String errorMessage = "Error publishing data to device with ID " + deviceId;
throw new DoorManagerException(errorMessage, e);
+ } catch (DataPublisherConfigurationException e) {
+ String errorMessage = "Error publishing data to DAS with ID " + deviceId;
+ throw new DoorManagerException(errorMessage, e);
}
}
+ /**
+ * Connection with message broker can be terminated
+ */
@Override
public void disconnect() {
Runnable stopConnection = new Runnable() {
@@ -143,8 +195,7 @@ public class DoorManagerMQTTConnector extends MQTTTransportHandler {
while (isConnected()) {
try {
closeConnection();
- }
- catch (MqttException e) {
+ } catch (MqttException e) {
if (log.isDebugEnabled()) {
log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint);
}
diff --git a/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/util/DoorManagerServiceUtils.java b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/util/DoorManagerServiceUtils.java
index 7775005a..d71e07f9 100644
--- a/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/util/DoorManagerServiceUtils.java
+++ b/modules/samples/doormanager/component/controller/src/main/java/org.homeautomation/doormanager/controller/api/util/DoorManagerServiceUtils.java
@@ -27,28 +27,43 @@ import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
public class DoorManagerServiceUtils {
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";
- private static final String CURRENT_STREAM_DEFINITION = "org.wso2.iot.devices.sensor";
+ /**
+ * Publish door locker current status to DAS
+ *
+ * @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 ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
- ctx.setTenantDomain(SUPER_TENANT, true);
+ ctx.setUsername(owner);
+ if (ctx.getTenantDomain(true) == null) {
+ ctx.setTenantDomain("carbon.super", true);
+ }
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null);
- Object metdaData[] = {owner, DoorManagerConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
- Object payloadCurrent[] = {current};
-
+ Object metaData[] = {owner, DoorManagerConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
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) {
+ log.error(e);
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return true;
}
-
}
diff --git a/modules/samples/doormanager/component/controller/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/samples/doormanager/component/controller/src/main/webapp/WEB-INF/cxf-servlet.xml
index 1d024638..1a62e429 100644
--- a/modules/samples/doormanager/component/controller/src/main/webapp/WEB-INF/cxf-servlet.xml
+++ b/modules/samples/doormanager/component/controller/src/main/webapp/WEB-INF/cxf-servlet.xml
@@ -16,9 +16,9 @@
~ limitations under the License.
-->
-
@@ -30,12 +30,12 @@
-
+
+ class="org.homeautomation.doormanager.controller.api.transport.DoorManagerMQTTConnector">
diff --git a/modules/samples/doormanager/component/manager/pom.xml b/modules/samples/doormanager/component/manager/pom.xml
index 130acacd..469db75c 100644
--- a/modules/samples/doormanager/component/manager/pom.xml
+++ b/modules/samples/doormanager/component/manager/pom.xml
@@ -19,15 +19,15 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
org.homeautomation
- component
+ doormanager-component1.0.0-SNAPSHOT../pom.xml4.0.0
- ${groupId}.doormanager.manager
+ org.homeautomation.doormanager.managerwar1.0.0-SNAPSHOT
- ${groupId}.doormanager.manager
+ org.homeautomation.doormanager.manager http://wso2.org${basedir}/src/main/java
@@ -46,7 +46,7 @@
maven-war-plugin${maven-war-plugin.version}
- ${groupId}.doormanager.manager_mgt
+ org.homeautomation.doormanager.manager_mgt
@@ -54,7 +54,7 @@
org.homeautomation
- ${project-base-package}.plugin
+ org.homeautomation.doormanager.pluginorg.wso2.carbon.devicemgt
diff --git a/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/DoorManagerManagerService.java b/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/DoorManagerManagerService.java
index 87eed7b8..62421bda 100644
--- a/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/DoorManagerManagerService.java
+++ b/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/DoorManagerManagerService.java
@@ -18,447 +18,319 @@
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.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.apache.geronimo.mail.util.Base64;
-import org.apache.http.client.ClientProtocolException;
-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.manager.api.util.APIUtil;
+import org.homeautomation.doormanager.manager.api.util.ResponsePayload;
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.device.DeviceType;
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.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
-import org.wso2.carbon.device.mgt.iot.DeviceManagement;
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
-import 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.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.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
-import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
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")
-@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 {
- 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
- private HttpServletResponse response;
- private PrivilegedCarbonContext ctx;
-
- 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();
- }
-
- @Path("manager/device/register")
- @POST
- public boolean register(@QueryParam("name") String name, @QueryParam("owner") String owner,
- @QueryParam("serialNumber") String serialNumber) {
-
- log.warn("---------------------------------------");
- log.warn(serialNumber);
- DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
- String deviceId = serialNumber;
-
- DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
- deviceIdentifier.setId(deviceId);
- deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
-
- try {
- if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
- response.setStatus(Response.Status.CONFLICT.getStatusCode());
- return false;
- }
-
- Device device = new Device();
- device.setDeviceIdentifier(deviceId);
- EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
- enrolmentInfo.setDateOfEnrolment(new Date().getTime());
- enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
- enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
- device.setName(name);
- device.setType(DoorManagerConstants.DEVICE_TYPE);
- enrolmentInfo.setOwner(owner);
- device.setEnrolmentInfo(enrolmentInfo);
-
- KeyGenerationUtil.createApplicationKeys(DoorManagerConstants.DEVICE_TYPE);
-
- TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
- AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
-
- //create token
- String accessToken = accessTokenInfo.getAccess_token();
- String refreshToken = accessTokenInfo.getRefresh_token();
- List properties = new ArrayList<>();
-
- Device.Property accessTokenProperty = new Device.Property();
- accessTokenProperty.setName(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN);
- log.warn("locker access Token :"+ accessToken);
- accessTokenProperty.setValue(accessToken);
-
- Device.Property refreshTokenProperty = new Device.Property();
- refreshTokenProperty.setName(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN);
- refreshTokenProperty.setValue(refreshToken);
-
- properties.add(accessTokenProperty);
- properties.add(refreshTokenProperty);
- device.setProperties(properties);
-
- boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device);
- if (added) {
- response.setStatus(Response.Status.OK.getStatusCode());
- } else {
- response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
- }
-
- return added;
- } catch (DeviceManagementException e) {
- response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
- return false;
- } catch (AccessTokenException e) {
- e.printStackTrace();
- } finally {
- deviceManagement.endTenantFlow();
- }
- return true;
- }
-
- @Path("manager/device/remove/{device_id}")
- @DELETE
- public void removeDevice(@PathParam("device_id") String deviceId,
- @Context HttpServletResponse response) {
- DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
- DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
- deviceIdentifier.setId(deviceId);
- deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
- try {
- boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(
- deviceIdentifier);
- if (removed) {
- response.setStatus(Response.Status.OK.getStatusCode());
- } else {
- response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
- }
- } catch (DeviceManagementException e) {
- response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
- } finally {
- deviceManagement.endTenantFlow();
- }
- }
-
- @Path("manager/device/update/{device_id}")
- @POST
- public boolean updateDevice(@PathParam("device_id") String deviceId,
- @QueryParam("name") String name,
- @Context HttpServletResponse response) {
- DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
- DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
- deviceIdentifier.setId(deviceId);
- deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
- try {
- Device device = deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
- device.setDeviceIdentifier(deviceId);
- device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
- device.setName(name);
- device.setType(DoorManagerConstants.DEVICE_TYPE);
- boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device);
- if (updated) {
- response.setStatus(Response.Status.OK.getStatusCode());
- } else {
- response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
- }
- return updated;
- } catch (DeviceManagementException e) {
- log.error(e.getErrorMessage());
- return false;
- } finally {
- deviceManagement.endTenantFlow();
- }
- }
-
- @POST
- @Path("manager/getUserCredentials")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- public Response getUserCredentials(final UserInfo userInfo, @Context HttpServletRequest request, @Context HttpServletResponse response) {
- /*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 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();*/
+ private static Log log = LogFactory.getLog(DoorManagerManagerService.class);
+ @Context //injected response proxy supporting multiple thread
+ private HttpServletResponse response;
+
+ /**
+ * Generate UUID
+ *
+ * @return generated UUID
+ */
+ private static String shortUUID() {
+ UUID uuid = UUID.randomUUID();
+ long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
+ return Long.toString(l, Character.MAX_RADIX);
+ }
+
+ /**
+ * Register new device into IoT Server
+ *
+ * @param name name of new device
+ * @return registration status
+ */
+ @Path("manager/device/register")
+ @POST
+ public boolean register(@QueryParam("deviceId") String deviceId,
+ @QueryParam("name") String name) {
+
+ DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
+ deviceIdentifier.setId(deviceId);
+ deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
try {
- 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();
- }
+ if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
+ response.setStatus(Response.Status.CONFLICT.getStatusCode());
+ return false;
}
- else {
- return Response.status(Response.Status.BAD_REQUEST).build();
+ String owner = APIUtil.getAuthenticatedUser();
+ Device device = new Device();
+ device.setDeviceIdentifier(deviceId);
+ EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
+ enrolmentInfo.setDateOfEnrolment(new Date().getTime());
+ enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
+ enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
+ enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
+ device.setName(name);
+ device.setType(DoorManagerConstants.DEVICE_TYPE);
+ enrolmentInfo.setOwner(owner);
+ device.setEnrolmentInfo(enrolmentInfo);
+ KeyGenerationUtil.createApplicationKeys(DoorManagerConstants.DEVICE_TYPE);
+ TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
+ AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
+
+ //create token
+ String accessToken = accessTokenInfo.getAccess_token();
+ String refreshToken = accessTokenInfo.getRefresh_token();
+ List properties = new ArrayList<>();
+
+ Device.Property accessTokenProperty = new Device.Property();
+ accessTokenProperty.setName(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN);
+ log.warn("locker access Token :" + accessToken);
+ accessTokenProperty.setValue(accessToken);
+
+ Device.Property refreshTokenProperty = new Device.Property();
+ refreshTokenProperty.setName(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN);
+ refreshTokenProperty.setValue(refreshToken);
+
+ properties.add(accessTokenProperty);
+ properties.add(refreshTokenProperty);
+ device.setProperties(properties);
+
+ boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
+ if (added) {
+ response.setStatus(Response.Status.OK.getStatusCode());
+ } else {
+ response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
-
- } catch (Exception e) {
+ return added;
+ } catch (DeviceManagementException e) {
log.error(e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
+ response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
+ return false;
+ } catch (AccessTokenException e) {
+ log.error(e);
+ response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
+ return false;
}
- 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) {
+ }
+
+ /**
+ * Remove installed device
+ *
+ * @param deviceId unique identifier for device
+ * @param response to request
+ */
+ @Path("manager/device/remove/{device_id}")
+ @DELETE
+ public void removeDevice(@PathParam("device_id") String deviceId,
+ @Context HttpServletResponse response) {
+ DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
+ deviceIdentifier.setId(deviceId);
+ deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
try {
- 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();
- }
+ boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
+ deviceIdentifier);
+ if (removed) {
+ response.setStatus(Response.Status.OK.getStatusCode());
+ } else {
+ response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
- else {
- return Response.status(Response.Status.BAD_REQUEST).build();
+ } catch (DeviceManagementException e) {
+ response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
+ }
+ }
+
+ /**
+ * Update device name
+ *
+ * @param deviceId unique identifier for device
+ * @param name new name of the device
+ * @param response to request
+ * @return update status
+ */
+ @Path("manager/device/update/{device_id}")
+ @POST
+ public boolean updateDevice(@PathParam("device_id") String deviceId,
+ @QueryParam("name") String name,
+ @Context HttpServletResponse response) {
+ DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
+ deviceIdentifier.setId(deviceId);
+ deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
+ try {
+ Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
+ device.setDeviceIdentifier(deviceId);
+ device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
+ device.setName(name);
+ device.setType(DoorManagerConstants.DEVICE_TYPE);
+ boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
+ if (updated) {
+ response.setStatus(Response.Status.OK.getStatusCode());
+ } else {
+ response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
-
- } catch (Exception e) {
- log.error(e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
+ return updated;
+ } catch (DeviceManagementException e) {
+ log.error(e.getErrorMessage());
+ return false;
}
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
-
- }
-
- @Path("manager/device/{device_id}")
- @GET
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Device getDevice(@PathParam("device_id") String deviceId) {
- DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
- DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
- deviceIdentifier.setId(deviceId);
- deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
- try {
- return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier);
- } catch (DeviceManagementException ex) {
- log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
- return null;
- } finally {
- deviceManagement.endTenantFlow();
- }
- }
-
- @Path("manager/device/{sketch_type}/download")
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public Response downloadSketch(@QueryParam("owner") String owner,
- @QueryParam("deviceName") String deviceName,
- @PathParam("sketch_type") String sketchType) {
- try {
- ZipArchive zipFile = createDownloadFile(owner, deviceName, sketchType);
- Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
- response.type("application/zip");
- response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
- return response.build();
- } catch (IllegalArgumentException ex) {
- return Response.status(400).entity(ex.getMessage()).build();//bad request
- } catch (DeviceManagementException ex) {
- return Response.status(500).entity(ex.getMessage()).build();
- } catch (AccessTokenException ex) {
- return Response.status(500).entity(ex.getMessage()).build();
- } catch (DeviceControllerException ex) {
- return Response.status(500).entity(ex.getMessage()).build();
- } catch (IOException ex) {
- return Response.status(500).entity(ex.getMessage()).build();
- }
- }
-
- private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
- throws DeviceManagementException, AccessTokenException, DeviceControllerException {
- if (owner == null) {
- throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
- }
- //create new device id
- String deviceId = shortUUID();
- KeyGenerationUtil.createApplicationKeys(DoorManagerConstants.DEVICE_TYPE);
- TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
- AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
- //create token
- String accessToken = accessTokenInfo.getAccess_token();
- String refreshToken = accessTokenInfo.getRefresh_token();
- //adding registering data
- boolean status;
- //Register the device with CDMF
- //status = register(deviceId, deviceName, owner);
- status = true;
- if (!status) {
- String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
- throw new DeviceManagementException(msg);
- }
- ZipUtil ziputil = new ZipUtil();
- ZipArchive zipFile = ziputil.createZipFile(owner, SUPER_TENANT, sketchType, deviceId, deviceName, accessToken,
- refreshToken);
- zipFile.setDeviceId(deviceId);
- return zipFile;
- }
-
- private static String shortUUID() {
- UUID uuid = UUID.randomUUID();
- long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
- return Long.toString(l, Character.MAX_RADIX);
- }
+ }
+
+ /**
+ * Get device information
+ *
+ * @param deviceId unique identifier for device
+ * @return device
+ */
+ @Path("manager/device/{device_id}")
+ @GET
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Device getDevice(@PathParam("device_id") String deviceId) {
+ DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
+ deviceIdentifier.setId(deviceId);
+ deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
+ try {
+ return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
+ } catch (DeviceManagementException ex) {
+ log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
+ return null;
+ }
+ }
+
+ /**
+ * This will download the agent for given device type
+ *
+ * @param deviceName name of the device which is to be created
+ * @param sketchType name of sketch type
+ * @return agent archive
+ */
+ @Path("manager/device/{sketch_type}/download")
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response downloadSketch(@QueryParam("deviceName") String deviceName,
+ @PathParam("sketch_type") String sketchType) {
+ try {
+ ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
+ Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
+ response.type("application/zip");
+ response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
+
+ return response.build();
+ } catch (IllegalArgumentException ex) {
+ return Response.status(400).entity(ex.getMessage()).build();//bad request
+ } catch (DeviceManagementException ex) {
+ return Response.status(500).entity(ex.getMessage()).build();
+ } catch (AccessTokenException ex) {
+ return Response.status(500).entity(ex.getMessage()).build();
+ } catch (DeviceControllerException ex) {
+ return Response.status(500).entity(ex.getMessage()).build();
+ } catch (IOException ex) {
+ return Response.status(500).entity(ex.getMessage()).build();
+ }
+ }
+
+ /**
+ * This will give link to generated agent
+ *
+ * @param deviceName name of the device which is to be created
+ * @param sketchType name of sketch type
+ * @return link to generated agent
+ */
+ @Path("manager/device/{sketch_type}/generate_link")
+ @GET
+ public Response generateSketchLink(@QueryParam("deviceName") String deviceName,
+ @PathParam("sketch_type") String sketchType) {
+ try {
+ ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
+ ResponsePayload responsePayload = new ResponsePayload();
+ responsePayload.setStatusCode(HttpStatus.SC_OK);
+ responsePayload.setMessageFromServer("Sending Requested sketch by type: " + sketchType +
+ " and id: " + zipFile.getDeviceId() + ".");
+ responsePayload.setResponseContent(zipFile.getDeviceId());
+ return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
+ } catch (IllegalArgumentException ex) {
+ return Response.status(HttpStatus.SC_BAD_REQUEST).entity(ex.getMessage()).build();
+ } catch (DeviceManagementException ex) {
+ log.error("Error occurred while creating device with name " + deviceName + "\n", ex);
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
+ } catch (AccessTokenException ex) {
+ log.error(ex.getMessage(), ex);
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
+ } catch (DeviceControllerException ex) {
+ log.error(ex.getMessage(), ex);
+ return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
+ }
+ }
+
+ /**
+ * This will give link to generated agent
+ *
+ * @param deviceName name of the device which is to be created
+ * @param sketchType name of sketch type
+ * @return link to generated agent
+ */
+ private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
+ throws DeviceManagementException, AccessTokenException, DeviceControllerException {
+ if (owner == null) {
+ throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
+ }
+ //create new device id
+ String deviceId = shortUUID();
+ KeyGenerationUtil.createApplicationKeys(DoorManagerConstants.DEVICE_TYPE);
+ TokenClient accessTokenClient = new TokenClient(DoorManagerConstants.DEVICE_TYPE);
+ AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
+ //create token
+ String accessToken = accessTokenInfo.getAccess_token();
+ String refreshToken = accessTokenInfo.getRefresh_token();
+ //adding registering data
+ boolean status;
+ //Register the device with CDMF
+ status = register(deviceId, deviceName);
+ if (!status) {
+ String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
+ throw new DeviceManagementException(msg);
+ }
+ ZipUtil ziputil = new ZipUtil();
+ ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOfUser(), sketchType,
+ deviceId, deviceName, accessToken, refreshToken);
+ zipFile.setDeviceId(deviceId);
+ return zipFile;
+ }
}
diff --git a/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/util/APIUtil.java b/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/util/APIUtil.java
new file mode 100644
index 00000000..f9dcb32d
--- /dev/null
+++ b/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/util/APIUtil.java
@@ -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;
+ }
+}
diff --git a/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/util/ResponsePayload.java b/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/util/ResponsePayload.java
new file mode 100644
index 00000000..bcf798eb
--- /dev/null
+++ b/modules/samples/doormanager/component/manager/src/main/java/org.homeautomation/doormanager/manager/api/util/ResponsePayload.java
@@ -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;
+ }
+ }
+
+}
diff --git a/modules/samples/doormanager/component/manager/src/main/webapp/META-INF/permissions.xml b/modules/samples/doormanager/component/manager/src/main/webapp/META-INF/permissions.xml
new file mode 100644
index 00000000..53ab317b
--- /dev/null
+++ b/modules/samples/doormanager/component/manager/src/main/webapp/META-INF/permissions.xml
@@ -0,0 +1,73 @@
+
+
+
+
+
+
+
+
+
+ Get device
+ /device-mgt/user/devices/list
+ /manager/device/*
+ GET
+ emm_admin,emm_user
+
+
+ Add device
+ /device-mgt/user/devices/add
+ /manager/device/register
+ PUT
+ emm_admin,emm_user
+
+
+ Download device
+ /device-mgt/user/devices/add
+ /manager/device/doormanager/download
+ GET
+ emm_admin,emm_user
+
+
+ Generate link to download
+ /device-mgt/user/devices/add
+ /manager/device/doormanager/generate_link
+ GET
+ emm_admin,emm_user
+
+
+ Update device
+ /device-mgt/user/devices/update
+ /manager/device/update/*
+ POST
+ emm_admin,emm_user
+
+
+ Remove device
+ /device-mgt/user/devices/remove
+ /manager/device/remove/*
+ DELETE
+ emm_admin,emm_user
+
+
\ No newline at end of file
diff --git a/modules/samples/doormanager/component/manager/src/main/webapp/WEB-INF/web.xml b/modules/samples/doormanager/component/manager/src/main/webapp/WEB-INF/web.xml
index 8772fc93..bdf6edc9 100644
--- a/modules/samples/doormanager/component/manager/src/main/webapp/WEB-INF/web.xml
+++ b/modules/samples/doormanager/component/manager/src/main/webapp/WEB-INF/web.xml
@@ -40,7 +40,7 @@
doAuthentication
- false
+ true
diff --git a/modules/samples/doormanager/component/plugin/pom.xml b/modules/samples/doormanager/component/plugin/pom.xml
index a2cd366e..57d70d57 100644
--- a/modules/samples/doormanager/component/plugin/pom.xml
+++ b/modules/samples/doormanager/component/plugin/pom.xml
@@ -19,15 +19,15 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
org.homeautomation
- component
+ doormanager-component1.0.0-SNAPSHOT../pom.xml4.0.01.0.0-SNAPSHOT
- ${groupId}.doormanager.plugin
+ org.homeautomation.doormanager.pluginbundle
- ${groupId}.doormanager.plugin
+ org.homeautomation.doormanager.pluginhttp://wso2.org
@@ -52,8 +52,8 @@
true
- ${groupId}.doormanager.plugin
- ${groupId}.doormanager.plugin
+ org.homeautomation.doormanager.plugin
+ org.homeautomation.doormanager.plugin1.0.0-SNAPSHOTIoT Server Impl Bundleorg.homeautomation.doormanager.plugin.internal
@@ -61,10 +61,8 @@
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
- javax.xml.bind.*,
javax.naming,
javax.sql,
- javax.xml.bind.annotation.*,
javax.xml.parsers,
javax.net,
javax.net.ssl,
@@ -74,6 +72,8 @@
org.wso2.carbon.context.*,
org.wso2.carbon.ndatasource.core,
org.wso2.carbon.device.mgt.iot.*,
+ org.wso2.carbon.user.api.*,
+ org.wso2.carbon.user.core.service.*
!org.homeautomation.doormanager.plugin.internal,
@@ -117,9 +117,67 @@
org.wso2.carbonorg.wso2.carbon.user.api
-
+
+ org.wso2.carbon
+ org.wso2.carbon.utils
+
+
+ org.bouncycastle.wso2
+ bcprov-jdk15on
+
+
+ org.wso2.carbon
+ org.wso2.carbon.user.api
+
+
+ org.wso2.carbon
+ org.wso2.carbon.queuing
+
+
+ org.wso2.carbon
+ org.wso2.carbon.base
+
+
+ org.apache.axis2.wso2
+ axis2
+
+
+ org.igniterealtime.smack.wso2
+ smack
+
+
+ org.igniterealtime.smack.wso2
+ smackx
+
+
+ jaxen
+ jaxen
+
+
+ commons-fileupload.wso2
+ commons-fileupload
+
+
+ org.apache.ant.wso2
+ ant
+
+
+ org.apache.ant.wso2
+ ant
+
+
+ commons-httpclient.wso2
+ commons-httpclient
+
+
+ org.eclipse.equinox
+ javax.servlet
+
+
+ org.wso2.carbon
+ org.wso2.carbon.registry.api
+
+
+
\ No newline at end of file
diff --git a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/constants/DoorManagerConstants.java b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/constants/DoorManagerConstants.java
index d6f282ca..8f6ec4e0 100644
--- a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/constants/DoorManagerConstants.java
+++ b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/constants/DoorManagerConstants.java
@@ -27,4 +27,8 @@ public class DoorManagerConstants {
public static final String DATA_SOURCE_NAME = "jdbc/doormanagerDM_DB";
public final static String DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN = "ACCESS_TOKEN";
public final static String DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN = "REFRESH_TOKEN";
+ public final static String DEVICE_CLAIMS_ACCESS_TOKEN = "http://wso2.org/claims/lock/accesstoken";
+ public final static String DEVICE_CLAIMS_REFRESH_TOKEN = "http://wso2.org/claims/lock/refreshtoken";
+ public final static String DEVICE_CLAIMS_CARD_NUMBER = "http://wso2.org/claims/lock/cardnumber";
+
}
diff --git a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/exception/DoorManagerDeviceMgtPluginException.java b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/exception/DoorManagerDeviceMgtPluginException.java
index 295bb587..78dd8484 100644
--- a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/exception/DoorManagerDeviceMgtPluginException.java
+++ b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/exception/DoorManagerDeviceMgtPluginException.java
@@ -18,18 +18,10 @@
package org.homeautomation.doormanager.plugin.exception;
-public class DoorManagerDeviceMgtPluginException extends Exception{
+public class DoorManagerDeviceMgtPluginException extends Exception {
private String errorMessage;
- public String getErrorMessage() {
- return errorMessage;
- }
-
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
-
public DoorManagerDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
@@ -53,4 +45,12 @@ public class DoorManagerDeviceMgtPluginException extends Exception{
super(cause);
}
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
}
diff --git a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManagerManager.java b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManager.java
similarity index 75%
rename from modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManagerManager.java
rename to modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManager.java
index 7523c4ed..8c9c46ef 100644
--- a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManagerManager.java
+++ b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManager.java
@@ -22,19 +22,25 @@ package org.homeautomation.doormanager.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.wso2.carbon.context.CarbonContext;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
+import org.wso2.carbon.user.api.UserStoreException;
+import org.wso2.carbon.user.api.UserStoreManager;
+import org.wso2.carbon.user.core.service.RealmService;
import java.util.List;
-public class DoorManagerManager implements DeviceManager {
-
- private static final Log log = LogFactory.getLog(DoorManagerManager.class);
+public class DoorManager implements DeviceManager {
+ private static final Log log = LogFactory.getLog(DoorManager.class);
private static final DoorManagerDAO DOOR_MANAGER_DAO = new DoorManagerDAO();
+ private PrivilegedCarbonContext ctx;
@Override
public FeatureManager getFeatureManager() {
@@ -44,13 +50,11 @@ public class DoorManagerManager implements DeviceManager {
@Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration)
throws DeviceManagementException {
- //TODO implement this
return false;
}
@Override
public TenantConfiguration getConfiguration() throws DeviceManagementException {
- //TODO implement this
return null;
}
@@ -94,7 +98,7 @@ public class DoorManagerManager implements DeviceManager {
e1.printStackTrace();
}
String msg = "Error while updating the enrollment of the Automatic Door Locker device : " +
- device.getDeviceIdentifier();
+ device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@@ -137,7 +141,7 @@ public class DoorManagerManager implements DeviceManager {
}
} catch (DoorManagerDeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of Automatic Door Locker device : " +
- deviceId.getId();
+ deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@@ -158,7 +162,8 @@ public class DoorManagerManager implements DeviceManager {
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
- try {if (log.isDebugEnabled()) {
+ try {
+ if (log.isDebugEnabled()) {
log.debug("Getting the details of Automatic Door Locker device : " + deviceId.getId());
}
device = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().getDevice(deviceId.getId());
@@ -230,7 +235,7 @@ public class DoorManagerManager implements DeviceManager {
@Override
public List getAllDevices() throws DeviceManagementException {
- List devices = null;
+ List devices;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Automatic Door Locker devices");
@@ -244,4 +249,62 @@ public class DoorManagerManager implements DeviceManager {
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;
+ }
+
}
\ No newline at end of file
diff --git a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManagerManagerService.java b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManagerManagerService.java
deleted file mode 100644
index 3a8f0d11..00000000
--- a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManagerManagerService.java
+++ /dev/null
@@ -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 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 deviceIdentifiers)
- throws ApplicationManagementException {
-
- }
-
- @Override
- public void installApplicationForUsers(Operation operation, List userNameList)
- throws ApplicationManagementException {
-
- }
-
- @Override
- public void installApplicationForUserRoles(Operation operation, List userRoleList)
- throws ApplicationManagementException {
-
- }
-}
diff --git a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManagerService.java b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManagerService.java
new file mode 100644
index 00000000..7f8aa7f6
--- /dev/null
+++ b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/DoorManagerService.java
@@ -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 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 deviceIdentifiers)
+ throws ApplicationManagementException {
+
+ }
+
+ @Override
+ public void installApplicationForUsers(Operation operation, List userNameList)
+ throws ApplicationManagementException {
+
+ }
+
+ @Override
+ public void installApplicationForUserRoles(Operation operation, List userRoleList)
+ throws ApplicationManagementException {
+
+ }
+}
diff --git a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/DoorLockSafe.java b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/DoorLockSafe.java
index 52d3679f..2e7fa720 100644
--- a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/DoorLockSafe.java
+++ b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/DoorLockSafe.java
@@ -1,7 +1,4 @@
-package org.homeautomation.doormanager.plugin.impl.dao;
-/*
-
-*/
+ ~ under the License.*/
+package org.homeautomation.doormanager.plugin.impl.dao;
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() {
return owner;
}
@@ -84,13 +89,4 @@ public class DoorLockSafe {
public void setRefreshToken(String 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;
}
diff --git a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/DoorManagerDAO.java b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/DoorManagerDAO.java
index 542bf099..a9ee7e66 100644
--- a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/DoorManagerDAO.java
+++ b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/DoorManagerDAO.java
@@ -24,7 +24,6 @@ import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.dao.impl.DoorManagerDAOImpl;
-
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
@@ -34,101 +33,100 @@ import java.sql.SQLException;
public class DoorManagerDAO {
- private static final Log log = LogFactory.getLog(DoorManagerDAO.class);
- static DataSource dataSource;
- private static ThreadLocal currentConnection = new ThreadLocal();
+ private static final Log log = LogFactory.getLog(DoorManagerDAO.class);
+ static DataSource dataSource;
+ private static ThreadLocal currentConnection = new ThreadLocal();
- public DoorManagerDAO() {
+ public DoorManagerDAO() {
initAutomaticDoorLOckerDAO();
- }
-
- public static void initAutomaticDoorLOckerDAO() {
- try {
- Context ctx = new InitialContext();
- dataSource = (DataSource) ctx.lookup(DoorManagerConstants.DATA_SOURCE_NAME);
- } catch (NamingException e) {
- log.error("Error while looking up the data source: " +
- DoorManagerConstants.DATA_SOURCE_NAME);
- }
-
- }
-
-
- public DoorManagerDAOImpl getAutomaticDoorLockerDeviceDAO() {
- return new DoorManagerDAOImpl();
- }
-
- public static void beginTransaction() throws DoorManagerDeviceMgtPluginException {
- try {
- Connection conn = dataSource.getConnection();
- conn.setAutoCommit(false);
- currentConnection.set(conn);
- } catch (SQLException e) {
- throw new DoorManagerDeviceMgtPluginException(
- "Error occurred while retrieving datasource connection", e);
- }
- }
-
- public static Connection getConnection() throws DoorManagerDeviceMgtPluginException {
- if (currentConnection.get() == null) {
- try {
- currentConnection.set(dataSource.getConnection());
- } catch (SQLException e) {
- throw new DoorManagerDeviceMgtPluginException(
- "Error occurred while retrieving data source connection", e);
- }
- }
- return currentConnection.get();
- }
-
- public static void commitTransaction() throws DoorManagerDeviceMgtPluginException {
- try {
- Connection conn = currentConnection.get();
- if (conn != null) {
- conn.commit();
- } else {
- if (log.isDebugEnabled()) {
- log.debug("Datasource connection associated with the current thread is null, " +
- "hence commit has not been attempted");
- }
- }
- } catch (SQLException e) {
- throw new DoorManagerDeviceMgtPluginException(
- "Error occurred while committing the transaction", e);
- } finally {
- closeConnection();
- }
- }
-
- public static void closeConnection() throws DoorManagerDeviceMgtPluginException {
-
- Connection con = currentConnection.get();
- if (con != null) {
- try {
- con.close();
- } catch (SQLException e) {
- log.error("Error occurred while close the connection");
- }
- }
- currentConnection.remove();
- }
-
- public static void rollbackTransaction() throws DoorManagerDeviceMgtPluginException {
- try {
- Connection conn = currentConnection.get();
- if (conn != null) {
- conn.rollback();
- } else {
- if (log.isDebugEnabled()) {
- log.debug(
- "Datasource connection associated with the current thread is null, " +
+ }
+
+ public static void initAutomaticDoorLOckerDAO() {
+ try {
+ Context ctx = new InitialContext();
+ dataSource = (DataSource) ctx.lookup(DoorManagerConstants.DATA_SOURCE_NAME);
+ } catch (NamingException e) {
+ log.error("Error while looking up the data source: " +
+ DoorManagerConstants.DATA_SOURCE_NAME);
+ }
+
+ }
+
+ public static void beginTransaction() throws DoorManagerDeviceMgtPluginException {
+ try {
+ Connection conn = dataSource.getConnection();
+ conn.setAutoCommit(false);
+ currentConnection.set(conn);
+ } catch (SQLException e) {
+ throw new DoorManagerDeviceMgtPluginException(
+ "Error occurred while retrieving datasource connection", e);
+ }
+ }
+
+ public static Connection getConnection() throws DoorManagerDeviceMgtPluginException {
+ if (currentConnection.get() == null) {
+ try {
+ currentConnection.set(dataSource.getConnection());
+ } catch (SQLException e) {
+ throw new DoorManagerDeviceMgtPluginException(
+ "Error occurred while retrieving data source connection", e);
+ }
+ }
+ return currentConnection.get();
+ }
+
+ public static void commitTransaction() throws DoorManagerDeviceMgtPluginException {
+ try {
+ Connection conn = currentConnection.get();
+ if (conn != null) {
+ conn.commit();
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Datasource connection associated with the current thread is null, " +
+ "hence commit has not been attempted");
+ }
+ }
+ } catch (SQLException e) {
+ throw new DoorManagerDeviceMgtPluginException(
+ "Error occurred while committing the transaction", e);
+ } finally {
+ closeConnection();
+ }
+ }
+
+ public static void closeConnection() throws DoorManagerDeviceMgtPluginException {
+
+ Connection con = currentConnection.get();
+ if (con != null) {
+ try {
+ con.close();
+ } catch (SQLException e) {
+ log.error("Error occurred while close the connection");
+ }
+ }
+ currentConnection.remove();
+ }
+
+ public static void rollbackTransaction() throws DoorManagerDeviceMgtPluginException {
+ try {
+ Connection conn = currentConnection.get();
+ if (conn != null) {
+ conn.rollback();
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug(
+ "Datasource connection associated with the current thread is null, " +
"hence rollback has not been attempted");
- }
- }
- } catch (SQLException e) {
- throw new DoorManagerDeviceMgtPluginException("Error occurred while rollback the transaction", e);
- } finally {
- closeConnection();
- }
- }
+ }
+ }
+ } catch (SQLException e) {
+ throw new DoorManagerDeviceMgtPluginException("Error occurred while rollback the transaction", e);
+ } finally {
+ closeConnection();
+ }
+ }
+
+ public DoorManagerDAOImpl getAutomaticDoorLockerDeviceDAO() {
+ return new DoorManagerDAOImpl();
+ }
}
\ No newline at end of file
diff --git a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/impl/DoorManagerDAOImpl.java b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/impl/DoorManagerDAOImpl.java
index 56d5affa..a4512d73 100644
--- a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/impl/DoorManagerDAOImpl.java
+++ b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/impl/DoorManagerDAOImpl.java
@@ -22,8 +22,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
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.DoorManagerDAO;
import org.homeautomation.doormanager.plugin.impl.dao.util.DoorManagerUtils;
import org.wso2.carbon.device.mgt.common.Device;
@@ -32,9 +32,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
/**
* Device Dao for automatic door locker Devices.
@@ -42,434 +40,435 @@ import java.util.Map;
public class DoorManagerDAOImpl {
- private static final Log log = LogFactory.getLog(DoorManagerDAOImpl.class);
+ private static final Log log = LogFactory.getLog(DoorManagerDAOImpl.class);
- public Device getDevice(String deviceId) throws DoorManagerDeviceMgtPluginException {
- Connection conn = null;
- PreparedStatement stmt = null;
- Device automaticDoorLockerDevice = null;
- ResultSet resultSet = null;
- try {
- conn = DoorManagerDAO.getConnection();
- String selectDBQuery =
- "SELECT doormanager_DEVICE_ID, DEVICE_NAME" +
- " FROM doormanager_DEVICE WHERE doormanager_DEVICE_ID = ?";
- stmt = conn.prepareStatement(selectDBQuery);
- stmt.setString(1, deviceId);
- resultSet = stmt.executeQuery();
- if (resultSet.next()) {
- automaticDoorLockerDevice = new Device();
- automaticDoorLockerDevice.setName(resultSet.getString(
- DoorManagerConstants.DEVICE_PLUGIN_DEVICE_NAME));
- List properties = new ArrayList<>();
- automaticDoorLockerDevice.setProperties(properties);
- if (log.isDebugEnabled()) {
- log.debug("Locker Manager service " + deviceId + " data has been fetched from" +
- "Locker Manager database.");
- }
- }
- } catch (SQLException e) {
- String msg = "Error occurred while fetching Locker Manager device : '" + deviceId + "'";
- log.error(msg, e);
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, resultSet);
- DoorManagerDAO.closeConnection();
- }
- return automaticDoorLockerDevice;
- }
+ public Device getDevice(String deviceId) throws DoorManagerDeviceMgtPluginException {
+ Connection conn = null;
+ PreparedStatement stmt = null;
+ Device automaticDoorLockerDevice = null;
+ ResultSet resultSet = null;
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String selectDBQuery =
+ "SELECT doormanager_DEVICE_ID, DEVICE_NAME" +
+ " FROM doormanager_DEVICE WHERE doormanager_DEVICE_ID = ?";
+ stmt = conn.prepareStatement(selectDBQuery);
+ stmt.setString(1, deviceId);
+ resultSet = stmt.executeQuery();
+ if (resultSet.next()) {
+ automaticDoorLockerDevice = new Device();
+ automaticDoorLockerDevice.setName(resultSet.getString(
+ DoorManagerConstants.DEVICE_PLUGIN_DEVICE_NAME));
+ List properties = new ArrayList<>();
+ automaticDoorLockerDevice.setProperties(properties);
+ if (log.isDebugEnabled()) {
+ log.debug("Locker Manager service " + deviceId + " data has been fetched from" +
+ "Locker Manager database.");
+ }
+ }
+ } catch (SQLException e) {
+ String msg = "Error occurred while fetching Locker Manager device : '" + deviceId + "'";
+ log.error(msg, e);
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, resultSet);
+ DoorManagerDAO.closeConnection();
+ }
+ return automaticDoorLockerDevice;
+ }
- public boolean addDevice(Device automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
- boolean status = false;
- Connection conn = null;
- PreparedStatement stmt = null;
- try {
- conn = DoorManagerDAO.getConnection();
- String createDBQuery =
- "INSERT INTO doormanager_DEVICE(doormanager_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?)";
+ public boolean addDevice(Device automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
+ boolean status = false;
+ Connection conn = null;
+ PreparedStatement stmt = null;
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String createDBQuery =
+ "INSERT INTO doormanager_DEVICE(doormanager_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?)";
- stmt = conn.prepareStatement(createDBQuery);
- stmt.setString(1, automaticDoorLOcker.getDeviceIdentifier());
- stmt.setString(2, automaticDoorLOcker.getName());
- stmt.setString(3, DoorManagerUtils.getDeviceProperty(
- automaticDoorLOcker.getProperties(),
- DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN));
- stmt.setString(4, DoorManagerUtils.getDeviceProperty(
- automaticDoorLOcker.getProperties(),
- DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN));
- int rows = stmt.executeUpdate();
- if (rows > 0) {
- status = true;
- if (log.isDebugEnabled()) {
- log.debug("Locker Manager device " + automaticDoorLOcker.getDeviceIdentifier() +
- " data has been added to the Locker Manager database.");
- }
- }
- } catch (SQLException e) {
- String msg = "Error occurred while adding the Locker Manager device '" +
- automaticDoorLOcker.getDeviceIdentifier() + "' to the Locker Manager db.";
- log.error(msg, e);
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, null);
- }
- return status;
- }
+ stmt = conn.prepareStatement(createDBQuery);
+ stmt.setString(1, automaticDoorLOcker.getDeviceIdentifier());
+ stmt.setString(2, automaticDoorLOcker.getName());
+ stmt.setString(3, DoorManagerUtils.getDeviceProperty(
+ automaticDoorLOcker.getProperties(),
+ DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN));
+ stmt.setString(4, DoorManagerUtils.getDeviceProperty(
+ automaticDoorLOcker.getProperties(),
+ DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN));
+ int rows = stmt.executeUpdate();
+ if (rows > 0) {
+ status = true;
+ if (log.isDebugEnabled()) {
+ log.debug("Locker Manager device " + automaticDoorLOcker.getDeviceIdentifier() +
+ " data has been added to the Locker Manager database.");
+ }
+ }
+ } catch (SQLException e) {
+ String msg = "Error occurred while adding the Locker Manager device '" +
+ automaticDoorLOcker.getDeviceIdentifier() + "' to the Locker Manager db.";
+ log.error(msg, e);
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, null);
+ }
+ return status;
+ }
- public boolean registerDoorLockSafe(DoorLockSafe automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
- boolean status = false;
- Connection conn = null;
- PreparedStatement stmt = null;
- try {
- conn = DoorManagerDAO.getConnection();
- String createDBQuery =
- "INSERT INTO REGISTERED_DOORLOCK_SAFE(doormanager_DEVICE_ID, SERIAL_NUMBER, UID_of_USER, POLICY, " +
- "EMAIL_ADDRESS, ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?, ?, ?, ?)";
- stmt = conn.prepareStatement(createDBQuery);
- stmt.setString(1, automaticDoorLOcker.getDeviceId());
- stmt.setString(2, automaticDoorLOcker.getSerialNumber());
- stmt.setString(3, automaticDoorLOcker.getUIDofUser());
- stmt.setString(4, automaticDoorLOcker.getPolicy());
- stmt.setString(5, automaticDoorLOcker.getEmailAddress());
- stmt.setString(6, automaticDoorLOcker.getAccessToken());
- stmt.setString(7, automaticDoorLOcker.getRefreshToken());
- int rows = stmt.executeUpdate();
- if (rows > 0) {
- status = true;
- if (log.isDebugEnabled()) {
- log.debug("Locker Manager device " + automaticDoorLOcker.getOwner() +
- " data has been added to the Locker Manager database.");
- }
- }
- } catch (SQLException e) {
- String msg = "Error occurred while adding the Locker Manager device '" +
- automaticDoorLOcker.getOwner() + "' to the Locker Manager db.";
- log.error(msg, e);
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, null);
- }
- return status;
- }
+ public boolean registerDoorLockSafe(DoorLockSafe automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
+ boolean status = false;
+ Connection conn = null;
+ PreparedStatement stmt = null;
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String createDBQuery =
+ "INSERT INTO REGISTERED_DOORLOCK_SAFE(doormanager_DEVICE_ID, SERIAL_NUMBER, UID_of_USER, POLICY, " +
+ "EMAIL_ADDRESS, ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?, ?, ?, ?)";
+ stmt = conn.prepareStatement(createDBQuery);
+ stmt.setString(1, automaticDoorLOcker.getDeviceId());
+ stmt.setString(2, automaticDoorLOcker.getSerialNumber());
+ stmt.setString(3, automaticDoorLOcker.getUIDofUser());
+ stmt.setString(4, automaticDoorLOcker.getPolicy());
+ stmt.setString(5, automaticDoorLOcker.getEmailAddress());
+ stmt.setString(6, automaticDoorLOcker.getAccessToken());
+ stmt.setString(7, automaticDoorLOcker.getRefreshToken());
+ int rows = stmt.executeUpdate();
+ if (rows > 0) {
+ status = true;
+ if (log.isDebugEnabled()) {
+ log.debug("Locker Manager device " + automaticDoorLOcker.getOwner() +
+ " data has been added to the Locker Manager database.");
+ }
+ }
+ } catch (SQLException e) {
+ String msg = "Error occurred while adding the Locker Manager device '" +
+ automaticDoorLOcker.getOwner() + "' to the Locker Manager db.";
+ log.error(msg, e);
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, null);
+ }
+ return status;
+ }
- public boolean isDoorLockSafeRegistered(String serialNumber, String deviceId) throws DoorManagerDeviceMgtPluginException {
+ public boolean isDoorLockSafeRegistered(String serialNumber, String deviceId) throws DoorManagerDeviceMgtPluginException {
- Connection conn = null;
- PreparedStatement stmt = null;
- ResultSet resultSet = null;
- try {
- conn = DoorManagerDAO.getConnection();
- String selectDBQuery =
- "SELECT SERIAL_NUMBER FROM REGISTERED_DOORLOCK_SAFE WHERE SERIAL_NUMBER = ? AND doormanager_DEVICE_ID = ?";
- stmt = conn.prepareStatement(selectDBQuery);
- stmt.setString(1, serialNumber);
- stmt.setString(2, deviceId);
- resultSet = stmt.executeQuery();
- if(resultSet.next()){
+ Connection conn = null;
+ PreparedStatement stmt = null;
+ ResultSet resultSet = null;
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String selectDBQuery =
+ "SELECT SERIAL_NUMBER FROM REGISTERED_DOORLOCK_SAFE WHERE SERIAL_NUMBER = ? AND doormanager_DEVICE_ID = ?";
+ stmt = conn.prepareStatement(selectDBQuery);
+ stmt.setString(1, serialNumber);
+ stmt.setString(2, deviceId);
+ resultSet = stmt.executeQuery();
+ if (resultSet.next()) {
String result = resultSet.getString(DoorManagerConstants.DEVICE_PLUGIN_DEVICE_SERIAL_NUMBER);
log.warn(result);
return true;
- }else{
+ } else {
return false;
}
- } catch (SQLException e) {
- String msg = "Error occurred while fetching all Automatic Door Locker device data'";
- log.error(msg, e);
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, resultSet);
- DoorManagerDAO.closeConnection();
- }
+ } catch (SQLException e) {
+ String msg = "Error occurred while fetching all Automatic Door Locker device data'";
+ log.error(msg, e);
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, resultSet);
+ DoorManagerDAO.closeConnection();
+ }
- }
+ }
- public boolean isUserAllowed(String serialNumber, String UIDofUser, String deviceId) throws DoorManagerDeviceMgtPluginException {
- Connection conn = null;
- PreparedStatement stmt = null;
- ResultSet resultSet = null;
- try {
- conn = DoorManagerDAO.getConnection();
- String selectDBQuery =
- "SELECT UID_OF_USER FROM REGISTERED_DOORLOCK_SAFE WHERE SERIAL_NUMBER = ? AND DOORMANAGER_DEVICE_ID = ?";
- stmt = conn.prepareStatement(selectDBQuery);
- stmt.setString(1, serialNumber);
- stmt.setString(2, deviceId);
- resultSet = stmt.executeQuery();
+ public boolean isUserAllowed(String serialNumber, String UIDofUser, String deviceId) throws DoorManagerDeviceMgtPluginException {
+ Connection conn = null;
+ PreparedStatement stmt = null;
+ ResultSet resultSet = null;
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String selectDBQuery =
+ "SELECT UID_OF_USER FROM REGISTERED_DOORLOCK_SAFE WHERE SERIAL_NUMBER = ? AND DOORMANAGER_DEVICE_ID = ?";
+ stmt = conn.prepareStatement(selectDBQuery);
+ stmt.setString(1, serialNumber);
+ stmt.setString(2, deviceId);
+ resultSet = stmt.executeQuery();
String result;
- if(resultSet.next()){
+ if (resultSet.next()) {
result = resultSet.getString(DoorManagerConstants.DEVICE_PLUGIN_DEVICE_UID_OF_USER);
log.warn(result);
return true;
- }else {
- selectDBQuery =
- "SELECT UID_OF_USER FROM SHARED_DOORLOCK_SAFE WHERE SERIAL_NUMBER = ? AND DOORMANAGER_DEVICE_ID = ? AND UID_OF_USER = ?";
- stmt = conn.prepareStatement(selectDBQuery);
- stmt.setString(1, serialNumber);
- stmt.setString(2, deviceId);
- stmt.setString(3, UIDofUser);
- resultSet = stmt.executeQuery();
- if(resultSet.next()){
+ } else {
+ selectDBQuery =
+ "SELECT UID_OF_USER FROM SHARED_DOORLOCK_SAFE WHERE SERIAL_NUMBER = ? AND DOORMANAGER_DEVICE_ID = ? AND UID_OF_USER = ?";
+ stmt = conn.prepareStatement(selectDBQuery);
+ stmt.setString(1, serialNumber);
+ stmt.setString(2, deviceId);
+ stmt.setString(3, UIDofUser);
+ resultSet = stmt.executeQuery();
+ if (resultSet.next()) {
result = resultSet.getString(DoorManagerConstants.DEVICE_PLUGIN_DEVICE_UID_OF_USER);
log.warn(result);
return true;
}
return false;
- }
- } catch (SQLException e) {
- String msg = "Error occurred while validating: whether user is registered or not";
- log.error(msg, e);
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, resultSet);
- DoorManagerDAO.closeConnection();
- }
+ }
+ } catch (SQLException e) {
+ String msg = "Error occurred while validating: whether user is registered or not";
+ log.error(msg, e);
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, resultSet);
+ DoorManagerDAO.closeConnection();
+ }
- }
+ }
- public boolean shareDoorLockSafe(DoorLockSafe automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
- boolean status = false;
- Connection conn = null;
- PreparedStatement stmt = null;
- try {
- conn = DoorManagerDAO.getConnection();
- String createDBQuery =
- "INSERT INTO SHARED_DOORLOCK_SAFE(doormanager_DEVICE_ID, SERIAL_NUMBER, UID_of_USER, POLICY) VALUES (?, ?, ?, ?)";
- stmt = conn.prepareStatement(createDBQuery);
- stmt.setString(1, automaticDoorLOcker.getDeviceId());
- stmt.setString(2, automaticDoorLOcker.getSerialNumber());
- stmt.setString(3, automaticDoorLOcker.getUIDofUser());
- stmt.setString(4, automaticDoorLOcker.getPolicy());
- int rows = stmt.executeUpdate();
- if (rows > 0) {
- status = true;
- if (log.isDebugEnabled()) {
- log.debug("Locker Manager device " + automaticDoorLOcker.getOwner() +
- " data has been added to the Locker Manager database.");
- }
- }
- } catch (SQLException e) {
- String msg = "Error occurred while adding the Locker Manager device '" +
- automaticDoorLOcker.getOwner() + "' to the Locker Manager db.";
- log.error(msg, e);
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, null);
- }
- return status;
- }
+ public boolean shareDoorLockSafe(DoorLockSafe automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
+ boolean status = false;
+ Connection conn = null;
+ PreparedStatement stmt = null;
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String createDBQuery =
+ "INSERT INTO SHARED_DOORLOCK_SAFE(doormanager_DEVICE_ID, SERIAL_NUMBER, UID_of_USER, POLICY) VALUES (?, ?, ?, ?)";
+ stmt = conn.prepareStatement(createDBQuery);
+ stmt.setString(1, automaticDoorLOcker.getDeviceId());
+ stmt.setString(2, automaticDoorLOcker.getSerialNumber());
+ stmt.setString(3, automaticDoorLOcker.getUIDofUser());
+ stmt.setString(4, automaticDoorLOcker.getPolicy());
+ int rows = stmt.executeUpdate();
+ if (rows > 0) {
+ status = true;
+ if (log.isDebugEnabled()) {
+ log.debug("Locker Manager device " + automaticDoorLOcker.getOwner() +
+ " data has been added to the Locker Manager database.");
+ }
+ }
+ } catch (SQLException e) {
+ String msg = "Error occurred while adding the Locker Manager device '" +
+ automaticDoorLOcker.getOwner() + "' to the Locker Manager db.";
+ log.error(msg, e);
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, null);
+ }
+ return status;
+ }
+
+ public boolean checkCardDoorAssociation(String cardNum, String deviceID) throws DoorManagerDeviceMgtPluginException {
+ Connection conn;
+ PreparedStatement stmt = null;
+ ResultSet resultSet = null;
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String selectDBQuery = "SELECT * FROM REGISTERED_DOORLOCK_SAFE WHERE UID_of_USER = ? AND doormanager_DEVICE_ID = ?";
+ stmt = conn.prepareStatement(selectDBQuery);
+ stmt.setString(1, cardNum);
+ stmt.setString(2, deviceID);
+ resultSet = stmt.executeQuery();
+ String result;
+ if (resultSet.next()) {
+ return true;
+ } else {
+ return false;
+ }
+ } catch (SQLException e) {
+ String msg = "No associations were found between lock : " + deviceID + " and card : " + cardNum;
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, null);
+ }
+ }
- public boolean checkCardDoorAssociation(String cardNum, String deviceID) throws DoorManagerDeviceMgtPluginException {
- Connection conn;
- PreparedStatement stmt = null;
- ResultSet resultSet = null;
- try {
- conn = DoorManagerDAO.getConnection();
- String selectDBQuery = "SELECT * FROM REGISTERED_DOORLOCK_SAFE WHERE UID_of_USER = ? AND doormanager_DEVICE_ID = ?";
- stmt = conn.prepareStatement(selectDBQuery);
- stmt.setString(1, cardNum);
- stmt.setString(2, deviceID);
- resultSet = stmt.executeQuery();
- String result;
- if(resultSet.next()){
- return true;
- }else{
- return false;
- }
- } catch (SQLException e) {
- String msg = "No associations were found between lock : "+ deviceID +" and card : "+ cardNum;
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, null);
- }
- }
+ public String getUserEmailAddress(String cardNum) throws DoorManagerDeviceMgtPluginException {
+ Connection conn;
+ PreparedStatement stmt = null;
+ ResultSet resultSet = null;
+ String email;
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String selectDBQuery = "SELECT EMAIL_ADDRESS FROM REGISTERED_DOORLOCK_SAFE WHERE UID_of_USER = ?";
+ stmt = conn.prepareStatement(selectDBQuery);
+ stmt.setString(1, cardNum);
+ resultSet = stmt.executeQuery();
+ if (resultSet.next()) {
+ email = resultSet.getString("EMAIL_ADDRESS");
+ log.warn(email);
+ return email;
+ }
+ return null;
+ } catch (SQLException e) {
+ String msg = "No email found for the and card : " + cardNum;
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, null);
+ }
+ }
- public String getUserEmailAddress(String cardNum) throws DoorManagerDeviceMgtPluginException {
- Connection conn;
- PreparedStatement stmt = null;
- ResultSet resultSet = null;
- String email;
- try {
- conn = DoorManagerDAO.getConnection();
- String selectDBQuery = "SELECT EMAIL_ADDRESS FROM REGISTERED_DOORLOCK_SAFE WHERE UID_of_USER = ?";
- stmt = conn.prepareStatement(selectDBQuery);
- stmt.setString(1, cardNum);
- resultSet = stmt.executeQuery();
- if(resultSet.next()){
- email = resultSet.getString("EMAIL_ADDRESS");
- log.warn(email);
- return email;
- }
- return null;
- } catch (SQLException e) {
- String msg = "No email found for the and card : "+ cardNum;
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, null);
- }
- }
- public List getUserCredentials(String deviceId, String UIDofUser) throws DoorManagerDeviceMgtPluginException {
+ public List getUserCredentials(String deviceId, String UIDofUser) throws DoorManagerDeviceMgtPluginException {
- Connection conn = null;
- PreparedStatement stmt = null;
- ResultSet resultSet = null;
- List userCredentials = new ArrayList<>();
- try {
- conn = DoorManagerDAO.getConnection();
- String selectDBQuery =
- "SELECT ACCESS_TOKEN, REFRESH_TOKEN FROM REGISTERED_DOORLOCK_SAFE WHERE DOORMANAGER_DEVICE_ID = ? AND UID_OF_USER = ?";
- stmt = conn.prepareStatement(selectDBQuery);
- stmt.setString(1, deviceId);
- stmt.setString(2, UIDofUser);
- resultSet = stmt.executeQuery();
- if (log.isDebugEnabled()) {
- log.debug("Get user credentials from Automatic Door Locker database.");
- }
- log.warn("getting user credentials");
- if(resultSet.next()){
+ Connection conn = null;
+ PreparedStatement stmt = null;
+ ResultSet resultSet = null;
+ List userCredentials = new ArrayList<>();
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String selectDBQuery =
+ "SELECT ACCESS_TOKEN, REFRESH_TOKEN FROM REGISTERED_DOORLOCK_SAFE WHERE DOORMANAGER_DEVICE_ID = ? AND UID_OF_USER = ?";
+ stmt = conn.prepareStatement(selectDBQuery);
+ stmt.setString(1, deviceId);
+ stmt.setString(2, UIDofUser);
+ resultSet = stmt.executeQuery();
+ if (log.isDebugEnabled()) {
+ log.debug("Get user credentials from Automatic Door Locker database.");
+ }
+ log.warn("getting user credentials");
+ if (resultSet.next()) {
String accessToken = resultSet.getString(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN);
String refreshToken = resultSet.getString(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN);
log.warn(accessToken);
userCredentials.add(accessToken);
userCredentials.add(refreshToken);
}
- return userCredentials;
- } catch (SQLException e) {
- String msg = "Error occurred while getting user credentials";
- log.error(msg, e);
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, resultSet);
- DoorManagerDAO.closeConnection();
- }
+ return userCredentials;
+ } catch (SQLException e) {
+ String msg = "Error occurred while getting user credentials";
+ log.error(msg, e);
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, resultSet);
+ DoorManagerDAO.closeConnection();
+ }
- }
+ }
- public List getRegisteredDoorLocks(String deviceId) throws DoorManagerDeviceMgtPluginException {
+ public List getRegisteredDoorLocks(String deviceId) throws DoorManagerDeviceMgtPluginException {
- Connection conn = null;
- PreparedStatement stmt = null;
- ResultSet resultSet = null;
- List doorLockSafes = new ArrayList<>();
- try {
- conn = DoorManagerDAO.getConnection();
- String selectDBQuery =
- "SELECT SERIAL_NUMBER FROM REGISTERED_DOORLOCK_SAFE WHERE doormanager_DEVICE_ID = ?";
- stmt = conn.prepareStatement(selectDBQuery);
- stmt.setString(1, deviceId);
- resultSet = stmt.executeQuery();
- while (resultSet.next()) {
- doorLockSafes.add(resultSet.getString(DoorManagerConstants.DEVICE_PLUGIN_DEVICE_SERIAL_NUMBER));
- }
- if (log.isDebugEnabled()) {
- log.debug("All Locker Manager device details have fetched from Automatic Door Locker database.");
- }
- return doorLockSafes;
- } catch (SQLException e) {
- String msg = "Error occurred while fetching all Automatic Door Locker device data'";
- log.error(msg, e);
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, resultSet);
- DoorManagerDAO.closeConnection();
- }
- }
+ Connection conn = null;
+ PreparedStatement stmt = null;
+ ResultSet resultSet = null;
+ List doorLockSafes = new ArrayList<>();
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String selectDBQuery =
+ "SELECT SERIAL_NUMBER FROM REGISTERED_DOORLOCK_SAFE WHERE doormanager_DEVICE_ID = ?";
+ stmt = conn.prepareStatement(selectDBQuery);
+ stmt.setString(1, deviceId);
+ resultSet = stmt.executeQuery();
+ while (resultSet.next()) {
+ doorLockSafes.add(resultSet.getString(DoorManagerConstants.DEVICE_PLUGIN_DEVICE_SERIAL_NUMBER));
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("All Locker Manager device details have fetched from Automatic Door Locker database.");
+ }
+ return doorLockSafes;
+ } catch (SQLException e) {
+ String msg = "Error occurred while fetching all Automatic Door Locker device data'";
+ log.error(msg, e);
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, resultSet);
+ DoorManagerDAO.closeConnection();
+ }
+ }
- public boolean updateDevice(Device automaticDoorLocker) throws DoorManagerDeviceMgtPluginException {
- boolean status = false;
- Connection conn = null;
- PreparedStatement stmt = null;
- try {
- conn = DoorManagerDAO.getConnection();
- String updateDBQuery =
- "UPDATE doormanager_DEVICE SET DEVICE_NAME = ? WHERE doormanager_DEVICE_ID = ?";
- stmt = conn.prepareStatement(updateDBQuery);
- if (automaticDoorLocker.getProperties() == null) {
- automaticDoorLocker.setProperties(new ArrayList());
- }
- stmt.setString(1, automaticDoorLocker.getName());
- stmt.setString(2, automaticDoorLocker.getDeviceIdentifier());
- int rows = stmt.executeUpdate();
- if (rows > 0) {
- status = true;
- if (log.isDebugEnabled()) {
- log.debug("Locker Manager device " + automaticDoorLocker.getDeviceIdentifier() +
- " data has been modified.");
- }
- }
- } catch (SQLException e) {
- String msg = "Error occurred while modifying the Locker Manager device '" +
- automaticDoorLocker.getDeviceIdentifier() + "' data.";
- log.error(msg, e);
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, null);
- }
- return status;
- }
+ public boolean updateDevice(Device automaticDoorLocker) throws DoorManagerDeviceMgtPluginException {
+ boolean status = false;
+ Connection conn = null;
+ PreparedStatement stmt = null;
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String updateDBQuery =
+ "UPDATE doormanager_DEVICE SET DEVICE_NAME = ? WHERE doormanager_DEVICE_ID = ?";
+ stmt = conn.prepareStatement(updateDBQuery);
+ if (automaticDoorLocker.getProperties() == null) {
+ automaticDoorLocker.setProperties(new ArrayList());
+ }
+ stmt.setString(1, automaticDoorLocker.getName());
+ stmt.setString(2, automaticDoorLocker.getDeviceIdentifier());
+ int rows = stmt.executeUpdate();
+ if (rows > 0) {
+ status = true;
+ if (log.isDebugEnabled()) {
+ log.debug("Locker Manager device " + automaticDoorLocker.getDeviceIdentifier() +
+ " data has been modified.");
+ }
+ }
+ } catch (SQLException e) {
+ String msg = "Error occurred while modifying the Locker Manager device '" +
+ automaticDoorLocker.getDeviceIdentifier() + "' data.";
+ log.error(msg, e);
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, null);
+ }
+ return status;
+ }
- public boolean deleteDevice(String deviceId) throws DoorManagerDeviceMgtPluginException {
- boolean status = false;
- Connection conn = null;
- PreparedStatement stmt = null;
- try {
- conn = DoorManagerDAO.getConnection();
- String deleteDBQuery =
- "DELETE FROM doormanager_DEVICE WHERE doormanager_DEVICE_ID = ?";
- stmt = conn.prepareStatement(deleteDBQuery);
- stmt.setString(1, deviceId);
- int rows = stmt.executeUpdate();
- if (rows > 0) {
- status = true;
- if (log.isDebugEnabled()) {
- log.debug("Automatic Door Locker device " + deviceId + " data has deleted" +
- " from the Automatic Door Locker database.");
- }
- }
- } catch (SQLException e) {
- String msg = "Error occurred while deleting Automatic Door Locker device " + deviceId;
- log.error(msg, e);
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, null);
- }
- return status;
- }
+ public boolean deleteDevice(String deviceId) throws DoorManagerDeviceMgtPluginException {
+ boolean status = false;
+ Connection conn = null;
+ PreparedStatement stmt = null;
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String deleteDBQuery =
+ "DELETE FROM doormanager_DEVICE WHERE doormanager_DEVICE_ID = ?";
+ stmt = conn.prepareStatement(deleteDBQuery);
+ stmt.setString(1, deviceId);
+ int rows = stmt.executeUpdate();
+ if (rows > 0) {
+ status = true;
+ if (log.isDebugEnabled()) {
+ log.debug("Automatic Door Locker device " + deviceId + " data has deleted" +
+ " from the Automatic Door Locker database.");
+ }
+ }
+ } catch (SQLException e) {
+ String msg = "Error occurred while deleting Automatic Door Locker device " + deviceId;
+ log.error(msg, e);
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, null);
+ }
+ return status;
+ }
- public List getAllDevices() throws DoorManagerDeviceMgtPluginException {
+ public List getAllDevices() throws DoorManagerDeviceMgtPluginException {
- Connection conn = null;
- PreparedStatement stmt = null;
- ResultSet resultSet = null;
- Device connectedCupDevice;
- List iotDevices = new ArrayList<>();
- try {
- conn = DoorManagerDAO.getConnection();
- String selectDBQuery =
- "SELECT doormanager_DEVICE_ID, DEVICE_NAME FROM doormanager_DEVICE";
- stmt = conn.prepareStatement(selectDBQuery);
- resultSet = stmt.executeQuery();
- while (resultSet.next()) {
- connectedCupDevice = new Device();
- connectedCupDevice.setDeviceIdentifier(resultSet.getString(
- DoorManagerConstants.DEVICE_PLUGIN_DEVICE_ID));
- connectedCupDevice.setName(resultSet.getString(
- DoorManagerConstants.DEVICE_PLUGIN_DEVICE_NAME));
- }
- if (log.isDebugEnabled()) {
- log.debug("All Locker Manager device details have fetched from Automatic Door Locker database.");
- }
- return iotDevices;
- } catch (SQLException e) {
- String msg = "Error occurred while fetching all Automatic Door Locker device data'";
- log.error(msg, e);
- throw new DoorManagerDeviceMgtPluginException(msg, e);
- } finally {
- DoorManagerUtils.cleanupResources(stmt, resultSet);
- DoorManagerDAO.closeConnection();
- }
- }
+ Connection conn = null;
+ PreparedStatement stmt = null;
+ ResultSet resultSet = null;
+ Device connectedCupDevice;
+ List iotDevices = new ArrayList<>();
+ try {
+ conn = DoorManagerDAO.getConnection();
+ String selectDBQuery =
+ "SELECT doormanager_DEVICE_ID, DEVICE_NAME FROM doormanager_DEVICE";
+ stmt = conn.prepareStatement(selectDBQuery);
+ resultSet = stmt.executeQuery();
+ while (resultSet.next()) {
+ connectedCupDevice = new Device();
+ connectedCupDevice.setDeviceIdentifier(resultSet.getString(
+ DoorManagerConstants.DEVICE_PLUGIN_DEVICE_ID));
+ connectedCupDevice.setName(resultSet.getString(
+ DoorManagerConstants.DEVICE_PLUGIN_DEVICE_NAME));
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("All Locker Manager device details have fetched from Automatic Door Locker database.");
+ }
+ return iotDevices;
+ } catch (SQLException e) {
+ String msg = "Error occurred while fetching all Automatic Door Locker device data'";
+ log.error(msg, e);
+ throw new DoorManagerDeviceMgtPluginException(msg, e);
+ } finally {
+ DoorManagerUtils.cleanupResources(stmt, resultSet);
+ DoorManagerDAO.closeConnection();
+ }
+ }
}
\ No newline at end of file
diff --git a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/util/DoorManagerUtils.java b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/util/DoorManagerUtils.java
index 4dedb8c9..c343a1b3 100644
--- a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/util/DoorManagerUtils.java
+++ b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/dao/util/DoorManagerUtils.java
@@ -37,8 +37,8 @@ public class DoorManagerUtils {
public static String getDeviceProperty(List deviceProperties, String propertyKey) {
String deviceProperty = "";
- for(Device.Property property :deviceProperties){
- if(propertyKey.equals(property.getName())){
+ for (Device.Property property : deviceProperties) {
+ if (propertyKey.equals(property.getName())) {
deviceProperty = property.getValue();
}
}
diff --git a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/util/DoorManagerUtils.java b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/util/DoorManagerUtils.java
deleted file mode 100644
index 060c3e76..00000000
--- a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/impl/util/DoorManagerUtils.java
+++ /dev/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 deviceProperties, String property) {
- String deviceProperty = deviceProperties.get(property);
- if (deviceProperty == null) {
- return "";
- }
- return deviceProperty;
- }
-}
diff --git a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/internal/DoorManagerManagementServiceComponent.java b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/internal/DoorManagerManagementServiceComponent.java
index 9018344e..3363bf41 100644
--- a/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/internal/DoorManagerManagementServiceComponent.java
+++ b/modules/samples/doormanager/component/plugin/src/main/java/org.homeautomation/doormanager/plugin/internal/DoorManagerManagementServiceComponent.java
@@ -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,
* Version 2.0 (the "License"); you may not use this file except
@@ -11,7 +11,7 @@
* 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
+ * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@@ -20,23 +20,16 @@ package org.homeautomation.doormanager.plugin.internal;
import org.apache.commons.logging.Log;
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.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
-import org.wso2.carbon.device.mgt.iot.service.DeviceTypeService;
/**
* @scr.component name="org.homeautomation.doormanager.plugin.internal.DoorManagerManagementServiceComponent"
* 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 {
@@ -51,7 +44,7 @@ public class DoorManagerManagementServiceComponent {
BundleContext bundleContext = ctx.getBundleContext();
automaticDoorLocker =
bundleContext.registerService(DeviceManagementService.class.getName(),
- new DoorManagerManagerService(), null);
+ new DoorManagerService(), null);
if (log.isDebugEnabled()) {
log.debug("DoorOpener Device Management Service Component has been successfully activated");
}
@@ -74,20 +67,8 @@ public class DoorManagerManagementServiceComponent {
}
} catch (Throwable e) {
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
- }
-
-
}
diff --git a/modules/samples/doormanager/component/pom.xml b/modules/samples/doormanager/component/pom.xml
index dd9ea9aa..5be5a50d 100644
--- a/modules/samples/doormanager/component/pom.xml
+++ b/modules/samples/doormanager/component/pom.xml
@@ -15,7 +15,9 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
-*/-->
+*/-->
+org.homeautomationdoormanager
@@ -24,7 +26,7 @@
4.0.01.0.0-SNAPSHOT
- component
+ doormanager-componentpom
@@ -271,12 +273,11 @@
-
- plugin
- controller
- manager
- agent
- analytics
- ui
-
+
+ plugin
+ controller
+ manager
+ analytics
+ ui
+
\ No newline at end of file
diff --git a/modules/samples/doormanager/component/ui/pom.xml b/modules/samples/doormanager/component/ui/pom.xml
index bbfca272..d618b978 100644
--- a/modules/samples/doormanager/component/ui/pom.xml
+++ b/modules/samples/doormanager/component/ui/pom.xml
@@ -16,18 +16,18 @@
~ specific language governing permissions and limitations
~ under the License.
-->
-org.homeautomation
- component
+ doormanager-component1.0.0-SNAPSHOT../pom.xml4.0.0
- ${groupId}.doormanager.ui
- ${groupId}.doormanager.ui
+ org.homeautomation.doormanager.ui
+ org.homeautomation.doormanager.uipom
@@ -35,7 +35,7 @@
maven-assembly-plugin2.5.5
- ${project.artifactId}-1.0.0-SNAPSHOT
+ org.homeautomation.doormanager.ui-1.0.0-SNAPSHOTfalsesrc/assembly/src.xml
diff --git a/modules/samples/doormanager/component/ui/src/assembly/src.xml b/modules/samples/doormanager/component/ui/src/assembly/src.xml
index 8e784014..5e2e656a 100644
--- a/modules/samples/doormanager/component/ui/src/assembly/src.xml
+++ b/modules/samples/doormanager/component/ui/src/assembly/src.xml
@@ -17,8 +17,8 @@
-->
src
diff --git a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/device-view.hbs b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/device-view.hbs
index 4fc403d6..47a4ca68 100644
--- a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/device-view.hbs
+++ b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/device-view.hbs
@@ -44,6 +44,7 @@
{{#zone "device-detail-properties"}}
+
Device Statistics
diff --git a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/device-view.js b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/device-view.js
index 646a4db0..9e6e6747 100644
--- a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/device-view.js
+++ b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/device-view.js
@@ -1,22 +1,3 @@
-/*
- * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * WSO2 Inc. licenses this file to you under the Apache License,
- * Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
@@ -48,10 +29,9 @@ function onRequest(context) {
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId);
-
if (device && device.status != "error") {
log.info(device);
- return {"device": device, "port" : port, "host" : host , "sessionId" : sessionId};
+ return {"device": device, "port": port, "host": host, "sessionId": sessionId};
}
}
}
\ No newline at end of file
diff --git a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/images/current-sensor.png b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/images/current-sensor.png
deleted file mode 100644
index b1ce4901..00000000
Binary files a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/images/current-sensor.png and /dev/null differ
diff --git a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/images/lock.png b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/images/lock.png
deleted file mode 100644
index 33cc638d..00000000
Binary files a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/images/lock.png and /dev/null differ
diff --git a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/images/unlock.png b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/images/unlock.png
deleted file mode 100644
index e3ae59a5..00000000
Binary files a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/images/unlock.png and /dev/null differ
diff --git a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/js/device-stats.js b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/js/device-stats.js
deleted file mode 100644
index c5719adc..00000000
--- a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/public/js/device-stats.js
+++ /dev/null
@@ -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);
-}
\ No newline at end of file
diff --git a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/images/current-sensor.png b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/images/current-sensor.png
deleted file mode 100644
index b1ce4901..00000000
Binary files a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/images/current-sensor.png and /dev/null differ
diff --git a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/images/doormanager-icon.png b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/images/doormanager-icon.png
new file mode 100644
index 00000000..a44f50fc
Binary files /dev/null and b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/images/doormanager-icon.png differ
diff --git a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/images/drone-icon.png b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/images/drone-icon.png
deleted file mode 100644
index 0c7744ff..00000000
Binary files a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/images/drone-icon.png and /dev/null differ
diff --git a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/js/download.js b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/js/download.js
index 221170b2..faefdefb 100644
--- a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/js/download.js
+++ b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/public/js/download.js
@@ -86,8 +86,6 @@ function attachEvents() {
var deviceType = $(this).data("devicetype");
var downloadDeviceAPI = "/devicemgt/api/devices/sketch/generate_link";
var payload = {"sketchType": sketchType, "deviceType": deviceType};
-
- console.log("-------------------------->"+JSON.stringify(payload));
$(modalPopupContent).html($('#download-device-modal-content').html());
showPopup();
var deviceName;
@@ -110,55 +108,105 @@ function attachEvents() {
doAction(data);
}
);
- }else if(deviceName){
- $('.controls').append('');
+ } else if (deviceName) {
+ $('.controls').append('');
$('.control-group').removeClass('success').addClass('error');
} else {
- $('.controls').append('');
+ $('.controls').append('');
$('.control-group').removeClass('success').addClass('error');
}
});
+
$("a#download-device-cancel-link").click(function () {
hidePopup();
});
+
});
}
function downloadAgent() {
- var $inputs = $('#downloadForm :input');
- var values = {};
- $inputs.each(function() {
- values[this.name] = $(this).val();
- });
- var payload = {};
- payload.name = $inputs[0].value;
- payload.owner = $inputs[3].value;
- payload.serialNumber = $inputs[1].value;
+ /*var $inputs = $('#downloadForm :input');
+ var values = {};
+ $inputs.each(function() {
+ values[this.name] = $(this).val();
+ });
+ var payload = {};
+ payload.name = $inputs[0].value;
+ //payload.owner = $inputs[3].value;
+ payload.serialNumber = $inputs[1].value;
- var doorManagerRegisterURL = "/doormanager_mgt/manager/device/register?" +
- "name=" + encodeURI(payload.name) + "&owner=" + payload.owner + "&serialNumber=" + payload.serialNumber;
+ var doorManagerRegisterURL = "/doormanager_mgt/manager/device/register?" +
+ "name=" + encodeURI(payload.name) + "&deviceId=" + payload.serialNumber;
- invokerUtil.post(
- doorManagerRegisterURL,
- payload,
- function (data, textStatus, jqxhr) {
- hidePopup();
- },
- function (data) {
- hidePopup();
- }
- );
- var deviceName;
+ invokerUtil.post(
+ doorManagerRegisterURL,
+ payload,
+ function (data, textStatus, jqxhr) {
+ hidePopup();
+ },
+ function (data) {
+ hidePopup();
+ }
+ );
+ var deviceName;
+ $('.new-device-name').each(function () {
+ if (this.value != "") {
+ deviceName = this.value;
+ }
+ });
+ if (deviceName && deviceName.length >= 4) {
+ setTimeout(function () {
+ hidePopup();
+ }, 1000);
+ }*/
+ var deviceName = "";
$('.new-device-name').each(function () {
if (this.value != "") {
deviceName = this.value;
}
});
- if (deviceName && deviceName.length >= 4) {
- setTimeout(function () {
+ var deviceType = "";
+ $('.deviceType').each(function () {
+ if (this.value != "") {
+ deviceType = this.value;
+ }
+ });
+ var sketchType = "";
+ $('.sketchType').each(function () {
+ if (this.value != "") {
+ sketchType = this.value;
+ }
+ });
+ /*var 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();
- }, 1000);
+ doAction(data);
+ });
+ } else {
+ $("#invalid-username-error-msg span").text("Invalid device name");
+ $("#invalid-username-error-msg").removeClass("hidden");
}
}
diff --git a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/type-view.hbs b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/type-view.hbs
index cab924e0..a52bdebc 100644
--- a/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/type-view.hbs
+++ b/modules/samples/doormanager/component/ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/type-view.hbs
@@ -49,23 +49,26 @@
-
Enter your device name serial number and then register {{@uriParams.deviceType}} the agent from following link.
+
Enter your device name serial number and then register {{@uriParams.deviceType}} the agent
+ from following link.
-
+
+
+
+
+
Device Agent will download shortly.
+
+
+
+
+
+
+
+
+
+
Please download the file from following link(Press CTRL+C).
+
+
+
+
+
+
+
+
+
+
@@ -182,7 +211,8 @@
04 Copy downloaded Agent into your
RaspberryPi.
-
05 Run "Agent.sh" script with root privileges.
+
05 Run "Agent.sh" script with root
+ privileges.
@@ -237,15 +267,19 @@
width: 50px;
color: #fff;
}
+
.padding-top-double {
padding-top: 20px;
}
+
.padding-double {
padding: 20px;
}
+
.grey {
color: #333;
}
+
hr {
display: block;
height: 1px;
@@ -255,21 +289,26 @@
padding: 0;
opacity: 0.2;
}
+
.light-grey {
color: #7c7c7c;
}
+
.uppercase {
text-transform: uppercase;
}
+
.grey-bg {
background-color: #f6f4f4;
}
+
.doc-link {
background: #11375B;
padding: 20px;
color: white;
margin-top: 0;
}
+
.doc-link a {
color: white;
}
diff --git a/modules/samples/doormanager/feature/feature/pom.xml b/modules/samples/doormanager/feature/feature/pom.xml
index 1a76d94c..4e499c6d 100644
--- a/modules/samples/doormanager/feature/feature/pom.xml
+++ b/modules/samples/doormanager/feature/feature/pom.xml
@@ -1,3 +1,4 @@
+
-org.homeautomation
- feature
+ doormanager-feature1.0.0-SNAPSHOT../pom.xml4.0.01.0.0-SNAPSHOT
- ${groupId}.doormanager.feature
+ org.homeautomation.doormanager.featurepom
- ${project.artifactId}
- http://wso2.org
+ ${project.artifactId}
+ http://wso2.orgorg.homeautomation
@@ -47,12 +48,6 @@
1.0.0-SNAPSHOTwar
-
- org.homeautomation
- ${project-base-package}.agent
- 1.0.0-SNAPSHOT
- war
- com.h2database.wso2h2-database-engine
@@ -63,6 +58,7 @@
maven-resources-plugin
+ 2.7copy-resources
@@ -104,7 +100,7 @@
ziptrue
- ${basedir}/src/main/resources/carbonapps
+ ${project.build.directory}/maven-shared-archive-resources/carbonapps
**/*
@@ -115,7 +111,9 @@
${project.version}ziptrue
- ${basedir}/src/main/resources/jaggeryapps/
+
+ ${project.build.directory}/maven-shared-archive-resources/jaggeryapps
+ **/*
@@ -134,7 +132,9 @@
${project-base-package}.managerwartrue
- ${basedir}/src/main/resources/webapps/
+
+ ${project.build.directory}/maven-shared-archive-resources/webapps/
+ doormanager_mgt.war
@@ -153,31 +153,14 @@
${project-base-package}.controllerwartrue
- ${basedir}/src/main/resources/webapps/
+
+ ${project.build.directory}/maven-shared-archive-resources/webapps/
+ doormanager.war
-
- copy-jaxrs-agent-war
- package
-
- copy
-
-
-
-
- org.homeautomation
- ${project-base-package}.agent
- war
- true
- ${basedir}/src/main/resources/webapps/
- doormanager_agent.war
-
-
-
-
@@ -198,7 +181,7 @@
+ value="jdbc:h2:file:${basedir}/${db.dir}/doormanagerDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
org.wso2.mavencarbon-p2-plugin
+ ${carbon-p2-plugin.version}p2-feature-generation
diff --git a/modules/samples/doormanager/feature/feature/src/main/resources/agent/deviceConfig.properties b/modules/samples/doormanager/feature/feature/src/main/resources/agent/deviceConfig.properties
index a9abf738..c0b9ccc7 100644
--- a/modules/samples/doormanager/feature/feature/src/main/resources/agent/deviceConfig.properties
+++ b/modules/samples/doormanager/feature/feature/src/main/resources/agent/deviceConfig.properties
@@ -1,4 +1,3 @@
-#
# Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,18 +11,20 @@
# 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.
-#
-#
[Device-Configurations]
+server-name=${SERVER_NAME}
owner=${DEVICE_OWNER}
+username=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
+manager-context=/doormanager/controller/get_user_info
controller-context=/doormanager/controller
+https-ep=${HTTPS_EP}
+http-ep=${HTTP_EP}
+apim-ep=${APIM_EP}
mqtt-ep=${MQTT_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15
-
-
diff --git a/modules/samples/doormanager/feature/feature/src/main/resources/agent/sketch.properties b/modules/samples/doormanager/feature/feature/src/main/resources/agent/sketch.properties
index b520c3f9..9d8c6fd2 100644
--- a/modules/samples/doormanager/feature/feature/src/main/resources/agent/sketch.properties
+++ b/modules/samples/doormanager/feature/feature/src/main/resources/agent/sketch.properties
@@ -1,16 +1,3 @@
-#/*
-# * 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.
-# */
templates=deviceConfig.properties
zipfilename=doormanager.zip
+
diff --git a/modules/samples/doormanager/feature/feature/src/main/resources/agent/src/DoorManagerAgent.log b/modules/samples/doormanager/feature/feature/src/main/resources/agent/src/DoorManagerAgent.log
new file mode 100644
index 00000000..e69de29b
diff --git a/modules/samples/doormanager/feature/feature/src/main/resources/agent/src/DoorManagerAgent.py b/modules/samples/doormanager/feature/feature/src/main/resources/agent/src/DoorManagerAgent.py
new file mode 100644
index 00000000..ad24a818
--- /dev/null
+++ b/modules/samples/doormanager/feature/feature/src/main/resources/agent/src/DoorManagerAgent.py
@@ -0,0 +1,194 @@
+#!/usr/bin/env python
+"""
+/**
+* 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.
+**/
+"""
+
+import argparse
+import httplib
+import logging
+import logging.handlers
+import signal
+import ssl
+import sys
+import threading
+import time
+from functools import wraps
+
+import RPi.GPIO as GPIO
+
+import MQTTHandler
+import RFIDReader
+import iotUtils
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# Overriding the default SSL version used in some of the Python (2.7.x) versions
+# This is a known issue in earlier Python releases
+# But was fixed in later versions. Ex-2.7.11
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+def sslwrap(func):
+ @wraps(func)
+ def bar(*args, **kw):
+ kw['ssl_version'] = ssl.PROTOCOL_TLSv1
+ return func(*args, **kw)
+
+ return bar
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+PUSH_INTERVAL = 5000 # time interval between successive data pushes in seconds
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# Logger defaults
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+LOG_FILENAME = "DoorManagerAgent.log"
+logging_enabled = False
+LOG_LEVEL = logging.INFO # Could be e.g. "DEBUG" or "WARNING"
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# Python version
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+if sys.version_info < (2, 6, 0):
+ sys.stderr.write("You need python 2.6.0 or later to run this script\n")
+ exit(1)
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# Define and parse command line arguments
+# If the log file is specified on the command line then override the default
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+parser = argparse.ArgumentParser(description="Python service to push RPi info to the Device Cloud")
+parser.add_argument("-l", "--log", help="file to write log to (default '" + LOG_FILENAME + "')")
+
+help_string_for_data_push_interval = "time interval between successive locker status push to server(default '" + str(
+ PUSH_INTERVAL) + "')"
+parser.add_argument("-i", "--interval", type=int, help=help_string_for_data_push_interval)
+
+args = parser.parse_args()
+if args.log:
+ LOG_FILENAME = args.log
+
+if args.interval:
+ PUSH_INTERVAL = args.interval
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# A class we can use to capture stdout and sterr in the log
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+class IOTLogger(object):
+ def __init__(self, logger, level):
+ """Needs a logger and a logger level."""
+ self.logger = logger
+ self.level = level
+
+ def write(self, message):
+ if message.rstrip() != "": # Only log if there is a message (not just a new line)
+ self.logger.log(self.level, message.rstrip())
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# Configure logging to log to a file,
+# making a new file at midnight and keeping the last 3 day's data
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+def configureLogger(loggerName):
+ logger = logging.getLogger(loggerName)
+ logger.setLevel(LOG_LEVEL) # Set the log level to LOG_LEVEL
+ handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when="midnight",
+ backupCount=3) # Handler that writes to a file,
+ # ~~~make new file at midnight and keep 3 backups
+ formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s') # Format each log message like this
+ handler.setFormatter(formatter) # Attach the formatter to the handler
+ logger.addHandler(handler) # Attach the handler to the logger
+
+ if (logging_enabled):
+ sys.stdout = IOTLogger(logger, logging.INFO) # Replace stdout with logging to file at INFO level
+ sys.stderr = IOTLogger(logger, logging.ERROR) # Replace stderr with logging to file at ERROR level
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# This is a Thread object for reading RFID card
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+class ListenRFIDhread(object):
+ def __init__(self):
+ thread = threading.Thread(target=self.run, args=())
+ thread.daemon = True # Daemonize thread
+ thread.start() # Start the execution
+
+ def run(self):
+ RFIDReader.main()
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# This is a Thread object for listening for MQTT Messages
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+class ListenMQTTThread(object):
+ def __init__(self):
+ thread = threading.Thread(target=self.run, args=())
+ thread.daemon = True # Daemonize thread
+ thread.start() # Start the execution
+
+ def run(self):
+ MQTTHandler.main()
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# When sysvinit sends the TERM signal, cleanup before exiting
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+def sigterm_handler(_signo, _stack_frame):
+ print("[] received signal {}, exiting...".format(_signo))
+ sys.exit(0)
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+signal.signal(signal.SIGTERM, sigterm_handler)
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# This method used to initialize GPIO ports
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+def initDoorLock():
+ # GPIO.setmode(GPIO.BOARD)
+ GPIO.setup(iotUtils.DOOR_LOCKER_1_PORT, GPIO.OUT, initial=GPIO.HIGH)
+ GPIO.setup(iotUtils.DOOR_LOCKER_2_PORT, GPIO.OUT, initial=GPIO.HIGH)
+ GPIO.setup(iotUtils.LOCK_STATE_ON_NOTIFY_PORT, GPIO.OUT, initial=GPIO.LOW)
+ GPIO.setup(iotUtils.LOCK_STATE_OFF_NOTIFY_PORT, GPIO.OUT, initial=GPIO.LOW)
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# The Main method of the Automatic Door Locker Agent
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+def main():
+ configureLogger("AutomaticDoorLocker")
+ ListenMQTTThread()
+ ListenRFIDhread()
+ initDoorLock()
+ # registerUIDofRFIDCard() # Call the register endpoint and register Device I
+ # ListenMQTTThread()
+ while True:
+ try:
+ time.sleep(PUSH_INTERVAL)
+ except (KeyboardInterrupt, Exception) as e:
+ print "AutomaticDoorLockerStats: Exception in RaspberryAgentThread (either KeyboardInterrupt or Other)"
+ print ("AutomaticDoorLockerStats: " + str(e))
+ print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
+ pass
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+if __name__ == "__main__":
+ main()
diff --git a/modules/samples/doormanager/feature/feature/src/main/resources/agent/src/MFRC522.py b/modules/samples/doormanager/feature/feature/src/main/resources/agent/src/MFRC522.py
new file mode 100644
index 00000000..9e15c843
--- /dev/null
+++ b/modules/samples/doormanager/feature/feature/src/main/resources/agent/src/MFRC522.py
@@ -0,0 +1,396 @@
+#!/usr/bin/env python
+# -*- coding: utf8 -*-
+
+import RPi.GPIO as GPIO
+import spi
+import signal
+import time
+
+class MFRC522:
+ NRSTPD = 22
+
+ MAX_LEN = 16
+
+ PCD_IDLE = 0x00
+ PCD_AUTHENT = 0x0E
+ PCD_RECEIVE = 0x08
+ PCD_TRANSMIT = 0x04
+ PCD_TRANSCEIVE = 0x0C
+ PCD_RESETPHASE = 0x0F
+ PCD_CALCCRC = 0x03
+
+ PICC_REQIDL = 0x26
+ PICC_REQALL = 0x52
+ PICC_ANTICOLL = 0x93
+ PICC_SElECTTAG = 0x93
+ PICC_AUTHENT1A = 0x60
+ PICC_AUTHENT1B = 0x61
+ PICC_READ = 0x30
+ PICC_WRITE = 0xA0
+ PICC_DECREMENT = 0xC0
+ PICC_INCREMENT = 0xC1
+ PICC_RESTORE = 0xC2
+ PICC_TRANSFER = 0xB0
+ PICC_HALT = 0x50
+
+ MI_OK = 0
+ MI_NOTAGERR = 1
+ MI_ERR = 2
+
+ Reserved00 = 0x00
+ CommandReg = 0x01
+ CommIEnReg = 0x02
+ DivlEnReg = 0x03
+ CommIrqReg = 0x04
+ DivIrqReg = 0x05
+ ErrorReg = 0x06
+ Status1Reg = 0x07
+ Status2Reg = 0x08
+ FIFODataReg = 0x09
+ FIFOLevelReg = 0x0A
+ WaterLevelReg = 0x0B
+ ControlReg = 0x0C
+ BitFramingReg = 0x0D
+ CollReg = 0x0E
+ Reserved01 = 0x0F
+
+ Reserved10 = 0x10
+ ModeReg = 0x11
+ TxModeReg = 0x12
+ RxModeReg = 0x13
+ TxControlReg = 0x14
+ TxAutoReg = 0x15
+ TxSelReg = 0x16
+ RxSelReg = 0x17
+ RxThresholdReg = 0x18
+ DemodReg = 0x19
+ Reserved11 = 0x1A
+ Reserved12 = 0x1B
+ MifareReg = 0x1C
+ Reserved13 = 0x1D
+ Reserved14 = 0x1E
+ SerialSpeedReg = 0x1F
+
+ Reserved20 = 0x20
+ CRCResultRegM = 0x21
+ CRCResultRegL = 0x22
+ Reserved21 = 0x23
+ ModWidthReg = 0x24
+ Reserved22 = 0x25
+ RFCfgReg = 0x26
+ GsNReg = 0x27
+ CWGsPReg = 0x28
+ ModGsPReg = 0x29
+ TModeReg = 0x2A
+ TPrescalerReg = 0x2B
+ TReloadRegH = 0x2C
+ TReloadRegL = 0x2D
+ TCounterValueRegH = 0x2E
+ TCounterValueRegL = 0x2F
+
+ Reserved30 = 0x30
+ TestSel1Reg = 0x31
+ TestSel2Reg = 0x32
+ TestPinEnReg = 0x33
+ TestPinValueReg = 0x34
+ TestBusReg = 0x35
+ AutoTestReg = 0x36
+ VersionReg = 0x37
+ AnalogTestReg = 0x38
+ TestDAC1Reg = 0x39
+ TestDAC2Reg = 0x3A
+ TestADCReg = 0x3B
+ Reserved31 = 0x3C
+ Reserved32 = 0x3D
+ Reserved33 = 0x3E
+ Reserved34 = 0x3F
+
+ serNum = []
+
+ def __init__(self, dev='/dev/spidev0.0', spd=1000000):
+ spi.openSPI(device=dev,speed=spd)
+ GPIO.setmode(GPIO.BOARD)
+ GPIO.setup(22, GPIO.OUT)
+ GPIO.output(self.NRSTPD, 1)
+ self.MFRC522_Init()
+
+ def MFRC522_Reset(self):
+ self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)
+
+ def Write_MFRC522(self, addr, val):
+ spi.transfer(((addr<<1)&0x7E,val))
+
+ def Read_MFRC522(self, addr):
+ val = spi.transfer((((addr<<1)&0x7E) | 0x80,0))
+ return val[1]
+
+ def SetBitMask(self, reg, mask):
+ tmp = self.Read_MFRC522(reg)
+ self.Write_MFRC522(reg, tmp | mask)
+
+ def ClearBitMask(self, reg, mask):
+ tmp = self.Read_MFRC522(reg);
+ self.Write_MFRC522(reg, tmp & (~mask))
+
+ def AntennaOn(self):
+ temp = self.Read_MFRC522(self.TxControlReg)
+ if(~(temp & 0x03)):
+ self.SetBitMask(self.TxControlReg, 0x03)
+
+ def AntennaOff(self):
+ self.ClearBitMask(self.TxControlReg, 0x03)
+
+ def MFRC522_ToCard(self,command,sendData):
+ backData = []
+ backLen = 0
+ status = self.MI_ERR
+ irqEn = 0x00
+ waitIRq = 0x00
+ lastBits = None
+ n = 0
+ i = 0
+
+ if command == self.PCD_AUTHENT:
+ irqEn = 0x12
+ waitIRq = 0x10
+ if command == self.PCD_TRANSCEIVE:
+ irqEn = 0x77
+ waitIRq = 0x30
+
+ self.Write_MFRC522(self.CommIEnReg, irqEn|0x80)
+ self.ClearBitMask(self.CommIrqReg, 0x80)
+ self.SetBitMask(self.FIFOLevelReg, 0x80)
+
+ self.Write_MFRC522(self.CommandReg, self.PCD_IDLE);
+
+ while(i self.MAX_LEN:
+ n = self.MAX_LEN
+
+ i = 0
+ while i
-
- jdbc/doormanagerDM_DB
-
+
+ jdbc/doormanagerDM_DB
+
diff --git a/modules/samples/doormanager/feature/feature/src/main/resources/database/doormanagerDM_DB.h2.db b/modules/samples/doormanager/feature/feature/src/main/resources/database/doormanagerDM_DB.h2.db
index 6be5a907..e3cd583d 100644
Binary files a/modules/samples/doormanager/feature/feature/src/main/resources/database/doormanagerDM_DB.h2.db and b/modules/samples/doormanager/feature/feature/src/main/resources/database/doormanagerDM_DB.h2.db differ
diff --git a/modules/samples/doormanager/feature/feature/src/main/resources/datasources/doormanager-datasources.xml b/modules/samples/doormanager/feature/feature/src/main/resources/datasources/doormanager-datasources.xml
index 483b22df..ed8376e0 100644
--- a/modules/samples/doormanager/feature/feature/src/main/resources/datasources/doormanager-datasources.xml
+++ b/modules/samples/doormanager/feature/feature/src/main/resources/datasources/doormanager-datasources.xml
@@ -1,3 +1,4 @@
+
-
+org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReaderdoormanagerDM_DB
- The datasource used for the this device type
+ The datasource used for the this device typejdbc/doormanagerDM_DB
diff --git a/modules/samples/doormanager/feature/feature/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/device-view.hbs b/modules/samples/doormanager/feature/feature/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/device-view.hbs
deleted file mode 100644
index 7506942d..00000000
--- a/modules/samples/doormanager/feature/feature/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view/device-view.hbs
+++ /dev/null
@@ -1,127 +0,0 @@
-
-{{#zone "topCss"}}
-
-{{/zone}}
-
-{{#zone "device-thumbnail"}}
-
-{{/zone}}
-
-{{#zone "operation-status"}}
-
-
-{{#zone "topCss"}}
-
-{{/zone}}
-
-{{#zone "bottomJs"}}
- {{js "/js/download.js"}}
- {{js "/js/jquery.validate.js"}}
-{{/zone}}
\ No newline at end of file
diff --git a/modules/samples/doormanager/feature/feature/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/type-view.json b/modules/samples/doormanager/feature/feature/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/type-view.json
deleted file mode 100644
index 2def3808..00000000
--- a/modules/samples/doormanager/feature/feature/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view/type-view.json
+++ /dev/null
@@ -1,20 +0,0 @@
-/**/
-{
- "version": "1.0.0"
-}
\ No newline at end of file
diff --git a/modules/samples/doormanager/feature/pom.xml b/modules/samples/doormanager/feature/pom.xml
index 66655a65..28e141e1 100644
--- a/modules/samples/doormanager/feature/pom.xml
+++ b/modules/samples/doormanager/feature/pom.xml
@@ -15,18 +15,21 @@
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
- -->
+ -->
+
+org.homeautomationdoormanager1.0.0-SNAPSHOT../pom.xml
- feature
+ doormanager-feature4.0.0pom1.0.0-SNAPSHOT
-
- feature
-
+
+ feature
+
\ No newline at end of file
diff --git a/modules/samples/doormanager/pom.xml b/modules/samples/doormanager/pom.xml
index d3f1f1fd..373e681d 100644
--- a/modules/samples/doormanager/pom.xml
+++ b/modules/samples/doormanager/pom.xml
@@ -1,3 +1,4 @@
+
-
+
+ org.wso2
+ wso2
+ 1
+ org.homeautomationdoormanager1.0.0-SNAPSHOT
@@ -140,11 +146,11 @@
4.1provided
-
- com.google.code.gson
- gson
- 2.2.4
-
+
+ com.google.code.gson
+ gson
+ 2.2.4
+
@@ -234,14 +240,14 @@
4.4.31.1.0-SNAPSHOT1.1.0.SNAPSHOT
+ 1.5.31.0.23.0.0.wso2v13.8.1.v20120830-144521
- 1.9.2-SNAPSHOT
- 1.9.2.SNAPSHOT
+ 2.0.4-SNAPSHOT
+ 2.0.4.SNAPSHOT1.1.12.4
-
3.0.4.wso2v13.0.4.wso2v12.6.1
diff --git a/modules/tools/cdmf-devicetype-archetype/README.md b/modules/tools/cdmf-devicetype-archetype/README.md
index 8ee77d26..926825ed 100644
--- a/modules/tools/cdmf-devicetype-archetype/README.md
+++ b/modules/tools/cdmf-devicetype-archetype/README.md
@@ -1,59 +1,89 @@
-# cdmf-devicetype-archetype
+# Install cdmf-devicetype-archetype
-To install this maven archetype
-
-go to this folder `cdmf-devicetype-archetype`
-
- mvn clean install
+First you need to download this maven archetype. To download
-To create new project
+ git clone https://github.com/GPrathap/cdmf-devicetype-archetype.git
-go to this folder `/wso2iots-1.0.0-SNAPSHOT/samples`
-
- mvn archetype:generate -DarchetypeCatalog=local
-
-Then select the `cdmf.devicetype:cdmf-devicetype-archetype` as new archetype. Then you need to provide groupId, artifactId,
-version, packaging, name of your device type and name for sensor as shown bellow.
+To install this maven archetype into your local system, inside the cdmf-devicetype-archetype
- Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): : 3
+ mvn clean install
+
+# Create sample device type plugin using cdmf-devicetype-archetype
+
+First download WOS2 IoT Server and copy the downloaded file to a preferred location and unzip it. The unzipped folder rename as IOTS_HOME.
+To create new project go to this folder: IOTS_HOME/samples
+
+ mvn archetype:generate -DarchetypeCatalog=local
+
+Then select the cdmf.devicetype:cdmf-devicetype-archetype as new archetype.
+
+ jobs@jobs-ThinkPad-T530:~/wso2/IoT/m3/product/IOTS_HOME/samples$
+ mvn archetype:generate -DarchetypeCatalog=local
+ [INFO] Scanning for projects...
+ [INFO]
+ [INFO] ------------------------------------------------------------------------
+ [INFO] Building Maven Stub Project (No POM) 1
+ [INFO] ------------------------------------------------------------------------
+ [INFO]
+ [INFO] >>> maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom >>>
+ [INFO]
+ [INFO] <<< maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom <<<
+ [INFO]
+ [INFO] --- maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom ---
+ [INFO] Generating project in Interactive mode
+ [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
+ Choose archetype:
+ 1: local -> org.apache.synapse:synapse-package-archetype (This archetype can be used to create Maven projects that bundle a mediation
+ into a standalone distribution ready to be executed)
+ 2: local -> org.wso2.mdm:mdm-android-agent-archetype (Creates a MDM-Android agent project)
+ 3: local -> org.wso2.cdmf.devicetype:cdmf-devicetype-archetype (WSO2 CDMF Device Type Archetype)
+ Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): : 3
+
+
+ Then you need to provide groupId, artifactId, version, packaging, name of your device type and name for sensor as shown below.
+
Define value for property 'groupId': : org.homeautomation
- Define value for property 'artifactId': : safeLocker
+ Define value for property 'artifactId': : currentsensor
Define value for property 'version': 1.0-SNAPSHOT: : 1.0.0-SNAPSHOT
Define value for property 'package': org.homeautomation: :
- Define value for property 'deviceType': : safeLocker
- Define value for property 'nameOfTheSensor': : lock
+ Define value for property 'deviceType': : currentsensor
+ Define value for property 'nameOfTheSensor': : current
Confirm properties configuration:
groupId: org.homeautomation
- artifactId: safeLocker
+ artifactId: currentsensor
version: 1.0.0-SNAPSHOT
package: org.homeautomation
- deviceType: safeLocker
- nameOfTheSensor: lock
-
-
-To install sample app into IOTS
- open `device-deployer.xml` which is located in wso2iots-1.0.0-SNAPSHOT directory
-
-Under modules tag add name of sample which you created as module
-
- samples/safeLocker
-
-Under featureArtifacts tag add feature artifact definition as below
-
-
- org.homeautomation:org.homeautomation.safeLocker.feature:1.0.0-SNAPSHOT
-
-
-Under features tag add feature group definition as below
+ deviceType: currentsensor
+ nameOfTheSensor: current
+
+
+
+# Configure the device-deployer.xml file that is in the IoTS_HOME directory.
+
+Add the new module under the tag.
+
+
+ samples/currentsensor
+
+
+Add the device type feature under the `` tag.
+
+ org.homeautomation:org.homeautomation.currentsensor.feature:1.0.0-SNAPSHOT
+
+
+
+Add the device type feature group under the tag.
+
- org.homeautomation.safeLocker.feature.group
- 1.0.0-SNAPSHOT
+ org.homeautomation.currentsensor.feature.group
+ 1.0.0-SNAPSHOT
-
-Finally to deploy sample device type into IoT Server
-
- mvn clean install -f device-deployer.xml
-
-Note: This command should be executed place where `device-deployer.xml` is located
+
+
+
+To deploy sample device type into IoT Server
+ mvn clean install -f device-deployer.xml
+
+Note: This command should be executed place where `device-deployer.xml` is located
diff --git a/modules/tools/cdmf-devicetype-archetype/pom.xml b/modules/tools/cdmf-devicetype-archetype/pom.xml
index 4f4cbfb8..ccef2c78 100644
--- a/modules/tools/cdmf-devicetype-archetype/pom.xml
+++ b/modules/tools/cdmf-devicetype-archetype/pom.xml
@@ -20,12 +20,12 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
org.wso2.iot
- wso2cdmf-tools
+ wso2iot-parent1.0.0-SNAPSHOT../pom.xml4.0.0
- cdmf.devicetype
+ org.wso2.cdmf.devicetypecdmf-devicetype-archetype1.0.0-SNAPSHOTWSO2 CDMF Device Type Archetype
diff --git a/modules/tools/cdmf-devicetype-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml b/modules/tools/cdmf-devicetype-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml
index d2cff1cb..1c326478 100644
--- a/modules/tools/cdmf-devicetype-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml
+++ b/modules/tools/cdmf-devicetype-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml
@@ -1,3 +1,4 @@
+
-
- IoTServer_Sensor_Script
+ IoTServer_${nameOfTheSensor}_Script