removing older sample: doormanager

application-manager-new
GPrathap 9 years ago
parent 62a602848f
commit 6193a0421a

@ -1,34 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/-->
<project name="create-sample-sensor-capps" default="zip" basedir=".">
<property name="project-name" value="${ant.project.name}"/>
<property name="target-dir" value="target/carbonapps"/>
<property name="src-dir" value="src/main/resources/carbonapps"/>
<property name="sensor_dir" value="smartLock"/>
<target name="clean">
<delete dir="${target-dir}"/>
</target>
<target name="zip" depends="clean">
<mkdir dir="${target-dir}"/>
<zip destfile="${target-dir}/${sensor_dir}.car">
<zipfileset dir="${src-dir}/${sensor_dir}"/>
</zip>
</target>
</project>

@ -1,87 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager-component</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.homeautomation.doormanager.analytics</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>org.homeautomation.doormanager.analytics</name>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>${maven-clean-plugin.version}</version>
<executions>
<execution>
<id>auto-clean</id>
<phase>initialize</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>${wso2.maven.compiler.source}</version>
<executions>
<execution>
<phase>process-resources</phase>
<configuration>
<target>
<ant antfile="build.xml" target="zip"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<finalName>org.homeautomation.doormanager.analytics-1.0.0-SNAPSHOT</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/src.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>create-archive</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,37 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<assembly
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>src</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<baseDirectory>${basedir}/src</baseDirectory>
<fileSets>
<fileSet>
<directory>${basedir}/target/carbonapps</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>
</assembly>

@ -1,27 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<eventReceiver name="EventReceiver_smartLock" statistics="disable" trace="disable"
xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="wso2event">
<property name="events.duplicated.in.cluster">false</property>
</from>
<mapping customMapping="disable" type="wso2event"/>
<to streamName="org.wso2.iot.devices.smartLock" version="1.0.0"/>
</eventReceiver>

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="Eventreceiver_smartLock" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>EventReceiver_smartLock.xml</file>
</artifact>

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="Eventstore_smartLock" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_smartLock.xml</file>
</artifact>

@ -1,62 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<EventStoreConfiguration>
<Source>
<StreamId>org.wso2.iot.devices.smartLock:1.0.0</StreamId>
</Source>
<RecordStoreName>EVENT_STORE</RecordStoreName>
<TableSchema>
<ColumnDefinition>
<Name>meta_owner</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceType</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceId</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_time</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>smartLock</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>FLOAT</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>

@ -1,23 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="Eventstream_smartLock" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.smartLock_1.0.0.json</file>
</artifact>

@ -1,33 +0,0 @@
{
"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"
}
]
}

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="Sparkscripts" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
<file>smartLock_Script.xml</file>
</artifact>

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<Analytics>
<Name>IoTServer_smartLock_Script</Name>
<Script>
CREATE TEMPORARY TABLE DevicesmartLockData USING CarbonAnalytics OPTIONS(tableName
"ORG_WSO2_IOT_DEVICES_smartLock");
CREATE TEMPORARY TABLE DevicesmartLockSummaryData USING CarbonAnalytics OPTIONS (tableName
"DEVICE_smartLock_SUMMARY", schema "smartLock FLOAT, deviceType STRING -i, deviceId STRING -i, owner STRING -i,
time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
insert overwrite table DevicesmartLockSummaryData select smartLock, meta_deviceType as deviceType, meta_deviceId
as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DevicesmartLockData group by
smartLock, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
</Analytics>

@ -1,27 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifacts>
<artifact name="smartLock_CAPP" version="1.0.0" type="carbon/application">
<dependency artifact="Eventstream_smartLock" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventstore_smartLock" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventreceiver_smartLock" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Sparkscripts" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -1,257 +0,0 @@
<!--/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager-component</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.homeautomation.doormanager.api</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>org.homeautomation.doormanager.api </name>
<url>http://wso2.org</url>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warName>org.homeautomation.doormanager.manager_mgt</warName>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>org.homeautomation.doormanager.plugin</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.wso2v1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
</dependencies>
</project>

@ -1,93 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.api;
import org.homeautomation.doormanager.api.dto.UserInfo;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "doormanager", version = "1.0.0", context = "/doormanager", tags = {"doormanager"})
@DeviceType(value = "doormanager")
public interface DoorManagerControllerService {
/**
* Assign new user to lock
*
* @param owner owner of the device
* @param deviceId unique identifier for given device
* @param protocol transport protocol which is being using here MQTT
* @param cardNumber RFID card number
* @param userName user name of RFID card owner
* @param emailAddress email address of RFID card owner
*/
@Path("device/assign-user")
@POST
@Feature(code = "assign_user", name = "Assign new user to lock", type = "operation",
description = "Add new access card to user to control the lock ")
Response assignUserToLock(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("cardNumber") String cardNumber,
@FormParam("userName") String userName,
@FormParam("emailAddress") String emailAddress);
/**
* Change status of door lock safe: LOCK/UNLOCK
*
* @param owner owner of the device
* @param deviceId unique identifier for given device
* @param protocol transport protocol which is being using here MQTT
* @param state status of lock safe: lock/unlock
*/
@Path("device/change-status")
@POST
@Feature(code = "change-status", name = "Change status of door lock safe: LOCK/UNLOCK", type = "operation",
description = "Change status of door lock safe: LOCK/UNLOCK")
Response changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("state") String state);
/**
* @param userInfo user information which are required to test given user is authorized to open requested door
* @return if user is authorized open the the door allow to open it
*/
@GET
@Path("device/get-user-info")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@SuppressWarnings("unchecked")
//This is to avoid unchecked call to put(k, v) into jsonObject. org.json.simple
// library uses raw type collections internally.
Response get_user_info(final UserInfo userInfo);
}

@ -1,233 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.api.exception.DoorManagerException;
import org.homeautomation.doormanager.api.transport.DoorManagerMQTTConnector;
import org.homeautomation.doormanager.api.dto.UserInfo;
import org.homeautomation.doormanager.api.util.APIUtil;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
import org.homeautomation.doormanager.plugin.impl.DoorManager;
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
import org.json.simple.JSONObject;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class DoorManagerControllerServiceImpl implements DoorManagerControllerService {
private static Log log = LogFactory.getLog(DoorManagerControllerServiceImpl.class);
private static String CURRENT_STATUS = "doorLockerCurrentStatus";
private DoorManager doorManager;
private DoorManagerMQTTConnector doorManagerMQTTConnector;
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
DoorManagerControllerServiceImpl() {
doorManager = new DoorManager();
}
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public DoorManagerMQTTConnector getDoorManagerMQTTConnector() {
return doorManagerMQTTConnector;
}
public void setDoorManagerMQTTConnector(final DoorManagerMQTTConnector MQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
DoorManagerControllerServiceImpl.this.doorManagerMQTTConnector = MQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
doorManagerMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, DoorManagerMQTTConnector" +
" not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
@Path("device/assign-user")
@POST
public Response assignUserToLock(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("cardNumber") String cardNumber,
@FormParam("userName") String userName,
@FormParam("emailAddress") String emailAddress) {
if (userName != null && cardNumber != null && deviceId != null) {
try {
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
DoorLockSafe doorLockSafe = new DoorLockSafe();
if (userStoreManager.isExistingUser(userName)) {
if (apiApplicationKey == null) {
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DoorManagerConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DoorManagerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + DoorManagerConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes);
String accessToken = accessTokenInfo.getAccessToken();
if (accessToken == null) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
Map<String, String> claims = new HashMap<>();
claims.put(DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, accessToken);
claims.put(DoorManagerConstants.DEVICE_CLAIMS_REFRESH_TOKEN,
accessTokenInfo.getRefreshToken());
claims.put(DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, cardNumber);
userStoreManager.setUserClaimValues(userName, claims, null);
doorLockSafe.setAccessToken(accessTokenInfo.getAccessToken());
doorLockSafe.setRefreshToken(accessTokenInfo.getRefreshToken());
doorLockSafe.setDeviceId(deviceId);
doorLockSafe.setOwner(owner);
doorLockSafe.setEmailAddress(emailAddress);
doorLockSafe.setUIDofUser(cardNumber);
doorLockSafe.setSerialNumber(deviceId);
if (doorManager.assignUserToLock(doorLockSafe)) {
return Response.ok().build();
} else {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
} else {
return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
}
} catch (UserStoreException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (JWTClientException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (APIManagerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DoorManagerDeviceMgtPluginException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
} else {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
}
@Path("device/change-status")
@POST
public Response changeStatusOfDoorLockSafe(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol,
@FormParam("state") String state) {
try {
int lockerCurrentState;
if (state.toUpperCase().equals("LOCK")) {
lockerCurrentState = 0;
} else {
lockerCurrentState = 1;
}
doorManagerMQTTConnector.sendCommandViaMQTT(owner, deviceId, "DoorManager:", state.toUpperCase());
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DoorManagerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@GET
@Path("device/get-user-info")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@SuppressWarnings("unchecked")
public Response get_user_info(final UserInfo userInfo) {
if (userInfo.userName != null && userInfo.cardNumber != null && userInfo.deviceId != null) {
try {
UserStoreManager userStoreManager = doorManager.getUserStoreManager();
if (userStoreManager.isExistingUser(userInfo.userName)) {
String accessToken = userStoreManager.getUserClaimValue(userInfo.userName,
DoorManagerConstants.DEVICE_CLAIMS_ACCESS_TOKEN, null);
String cardNumber = userStoreManager.getUserClaimValue(userInfo.userName,
DoorManagerConstants.DEVICE_CLAIMS_CARD_NUMBER, null);
if (cardNumber != null) {
if (cardNumber.equals(userInfo.cardNumber)) {
if (accessToken != null) {
JSONObject credentials = new JSONObject();
credentials.put(DoorManagerConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN, accessToken);
//return Response.ok(credentials, MediaType.APPLICATION_JSON_TYPE).build();
return Response.status(Response.Status.OK).build();
}
}
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} else {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
} catch (UserStoreException e) {
log.error(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
return Response.status(Response.Status.BAD_REQUEST).build();
}
}

@ -1,65 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.api;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("enrollment")
@SuppressWarnings("NonJaxWsWebServices")
@DeviceType(value = "doormanager")
@API(name = "doormanager_mgt", version = "1.0.0", context = "/doormanager_mgt" , tags = {"doormanager"})
public interface DoorManagerManagerService {
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
Response downloadSketch(@QueryParam("deviceName") String deviceName);
@Path("devices/generate_link")
@GET
Response generateSketchLink(@QueryParam("deviceName") String deviceName);
}

@ -1,251 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.api;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.api.util.APIUtil;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
@Path("enrollment")
public class DoorManagerManagerServiceImpl implements DoorManagerManagerService {
private static Log log = LogFactory.getLog(DoorManagerManagerServiceImpl.class);
private static ApiApplicationKey apiApplicationKey;
private static final String KEY_TYPE = "PRODUCTION";
@Path("devices/{device_id}")
@DELETE
public Response removeDevice(@PathParam("device_id") String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("devices/{device_id}")
@PUT
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DoorManagerConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getDevice(@PathParam("device_id") String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("devices/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response downloadSketch(@QueryParam("deviceName") String deviceName) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return response.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
@Path("devices/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName){
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String owner, String deviceName)
throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException,
UserStoreException {
if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
if (apiApplicationKey == null) {
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DoorManagerConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DoorManagerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + DoorManagerConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner,
scopes);
//create token
String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken();
//Register the device with CDMF
boolean status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
DoorManagerConstants.DEVICE_TYPE, deviceId,
deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
/**
* Generate UUID
*
* @return generated UUID
*/
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(DoorManagerConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
}
}
}

@ -1,38 +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.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@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;
}

@ -1,36 +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.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserInfo {
@XmlElement(required = true)
public String deviceId;
@XmlElement(required = true)
public String cardNumber;
@XmlElement(required = true)
public String userName;
}

@ -1,64 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.api.exception;
public class DoorManagerException extends Exception {
private static final long serialVersionUID = 2736466230451105441L;
private String errorMessage;
@SuppressWarnings("unused")
public DoorManagerException(String msg, DoorManagerException nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DoorManagerException(String message, Throwable cause) {
super(message, cause);
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;
}
}

@ -1,236 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.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.api.exception.DoorManagerException;
import org.homeautomation.doormanager.api.util.DoorManagerServiceUtils;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.device.mgt.analytics.data.publisher.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.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler;
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 String PUBLISHER_CONTEXT = "publisher";
private static String SUBCRIBER_TOPIC = "wso2/" + DoorManagerConstants.DEVICE_TYPE + "/+/publisher";
private static String PUBLISHER_TOPIC = "wso2/"+ DoorManagerConstants.DEVICE_TYPE + "/%s/subscriber";
private static String SUBSCRIBER = UUID.randomUUID().toString().substring(0, 5);
private DoorManagerMQTTConnector() {
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() {
public void run() {
while (!isConnected()) {
try {
String brokerUsername = MqttConfig.getInstance().getMqttQueueUsername();
String brokerPassword = MqttConfig.getInstance().getMqttQueuePassword();
setUsernameAndPassword(brokerUsername, brokerPassword);
connectToQueue();
} catch (TransportHandlerException e) {
log.error("Connection to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException ex) {
log.error("MQTT-Connector: Thread Sleep Interrupt Exception.", ex);
}
}
try {
subscribeToQueue();
} catch (TransportHandlerException e) {
log.warn("Subscription to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
}
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
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 + PUBLISHER_CONTEXT, "");
String owner = ownerAndId.split(":")[0];
String deviceId = ownerAndId.split(":")[1];
log.warn(deviceId);
String[] messageData = message.toString().split(":");
if (log.isDebugEnabled()) {
log.debug("Received MQTT message for: [OWNER-" + owner + "] & [DEVICE.ID-" + deviceId + "]");
}
if (messageData.length == 2) {
String lockerCurrentState = messageData[1];
float lockerStatus;
if (lockerCurrentState.equals("LOCKED")) {
lockerStatus = 0;
} else {
lockerStatus = 1;
}
try {
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);
}
}
}
/**
* 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()) {
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 topic = String.format(PUBLISHER_TOPIC, deviceOwner, deviceId);
String payload = operation + param;
try {
publishToAutomaticDoorLocker(topic, payload, 2, false);
if (param.toUpperCase().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 (param.toUpperCase().equals("UNLOCK")) {
if (!DoorManagerServiceUtils.publishToDASLockerStatus(deviceOwner, deviceId, 1)) {
log.warn("An error occurred 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() {
public void run() {
while (isConnected()) {
try {
closeConnection();
} catch (MqttException e) {
if (log.isDebugEnabled()) {
log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
log.error("MQTT-Terminator: Thread Sleep Interrupt Exception");
}
}
}
}
};
Thread terminatorThread = new Thread(stopConnection);
terminatorThread.setDaemon(true);
terminatorThread.start();
}
@Override
public void publishDeviceData() throws TransportHandlerException {
}
@Override
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
}
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
}
@Override
public void processIncomingMessage() {
}
@Override
public void processIncomingMessage(MqttMessage message) throws TransportHandlerException {
}
}

@ -1,81 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.api.util;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
/**
* 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 getTenantDomainOftheUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
return tenantDomain;
}
public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management service has not initialized.";
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
public static APIManagementProviderService getAPIManagementProviderService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
APIManagementProviderService apiManagementProviderService =
(APIManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (apiManagementProviderService == null) {
String msg = "API management provider service has not initialized.";
throw new IllegalStateException(msg);
}
return apiManagementProviderService;
}
public static JWTClientManagerService getJWTClientManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
JWTClientManagerService jwtClientManagerService =
(JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null);
if (jwtClientManagerService == null) {
String msg = "JWT Client manager service has not initialized.";
throw new IllegalStateException(msg);
}
return jwtClientManagerService;
}
}

@ -1,68 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
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";
/**
* 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);
}
private static boolean publishToDAS(String owner, String deviceId, Object[] payloadCurrent,
String definition) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setUsername(owner);
if (ctx.getTenantDomain(true) == null) {
ctx.setTenantDomain("carbon.super", true);
}
EventsPublisherService deviceAnalyticsService = (EventsPublisherService) ctx.getOSGiService(
EventsPublisherService.class, null);
Object metaData[] = {owner, DoorManagerConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
try {
deviceAnalyticsService.publishEvent(definition, STREAM_DEFINITION_VERSION, metaData,
new Object[0], payloadCurrent);
} catch (DataPublisherConfigurationException e) {
log.error(e);
return false;
}
return true;
}
}

@ -1,108 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.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;
}
}
}

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

@ -1,34 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -1,45 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2011-2012 WSO2, Inc. (http://wso2.com)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="DoorManagerController" address="/">
<jaxrs:serviceBeans>
<bean id="DoorManagerControllerService"
class="org.homeautomation.doormanager.api.DoorManagerControllerServiceImpl">
<property name="DoorManagerMQTTConnector" ref="communicationHandler"/>
</bean>
<bean id="DoorManagerManagerService"
class="org.homeautomation.doormanager.api.DoorManagerManagerServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
<bean id="communicationHandler"
class="org.homeautomation.doormanager.api.transport.DoorManagerMQTTConnector">
</bean>
</beans>

@ -1,61 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Sample-Webapp-Controller</display-name>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>providerTenantDomain</param-name>
<param-value>carbon.super</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
</web-app>

@ -1,183 +0,0 @@
<!--/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager-component</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>1.0.0-SNAPSHOT</version>
<artifactId>org.homeautomation.doormanager.plugin</artifactId>
<packaging>bundle</packaging>
<name>org.homeautomation.doormanager.plugin</name>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>${org.apache.felix.version}</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>org.homeautomation.doormanager.plugin</Bundle-SymbolicName>
<Bundle-Name>org.homeautomation.doormanager.plugin</Bundle-Name>
<Bundle-Version>1.0.0-SNAPSHOT</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.homeautomation.doormanager.plugin.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.naming,
javax.sql,
javax.xml.parsers,
javax.net,
javax.net.ssl,
org.w3c.dom,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common,
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.*
</Import-Package>
<Export-Package>
!org.homeautomation.doormanager.plugin.internal,
org.homeautomation.doormanager.plugin.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>

@ -1,34 +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.constants;
public class DoorManagerConstants {
public final static String DEVICE_TYPE = "doormanager";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "doormanager_DEVICE_ID";
public final static String DEVICE_PLUGIN_DEVICE_SERIAL_NUMBER = "SERIAL_NUMBER";
public final static String DEVICE_PLUGIN_DEVICE_UID_OF_USER = "UID_of_USER";
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";
}

@ -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.
*/
package org.homeautomation.doormanager.plugin.exception;
public class DoorManagerDeviceMgtPluginException extends Exception {
private String errorMessage;
public DoorManagerDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DoorManagerDeviceMgtPluginException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public DoorManagerDeviceMgtPluginException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DoorManagerDeviceMgtPluginException() {
super();
}
public DoorManagerDeviceMgtPluginException(Throwable cause) {
super(cause);
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -1,299 +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.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.DoorManagerDAOUtil;
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 DoorManager implements DeviceManager {
private static final Log log = LogFactory.getLog(DoorManager.class);
private static final DoorManagerDAOUtil DOOR_MANAGER_DAO = new DoorManagerDAOUtil();
private PrivilegedCarbonContext ctx;
@Override
public FeatureManager getFeatureManager() {
return null;
}
@Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration)
throws DeviceManagementException {
return false;
}
@Override
public TenantConfiguration getConfiguration() throws DeviceManagementException {
return null;
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new Automatic Door Locker device : " + device.getDeviceIdentifier());
}
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().addDevice(device);
DoorManagerDAOUtil.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAOUtil.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
e1.printStackTrace();
}
String msg = "Error while enrolling the Automatic Door Locker device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Automatic Door Locker device enrollment data");
}
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().updateDevice(device);
DoorManagerDAOUtil.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAOUtil.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
e1.printStackTrace();
}
String msg = "Error while updating the enrollment of the Automatic Door Locker device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling Automatic Door Locker device : " + deviceId);
}
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().deleteDevice(deviceId.getId());
DoorManagerDAOUtil.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAOUtil.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException e1) {
e1.printStackTrace();
}
String msg = "Error while removing the Automatic Door Locker device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Automatic Door Locker device : " + deviceId.getId());
}
Device iotDevice = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (DoorManagerDeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of Automatic Door Locker device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return isEnrolled;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return true;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Automatic Door Locker device : " + deviceId.getId());
}
device = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().getDevice(deviceId.getId());
} catch (DoorManagerDeviceMgtPluginException e) {
String msg = "Error while fetching the Automatic Door Locker device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return device;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
}
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
}
@Override
public License getLicense(String s) throws LicenseManagementException {
return null;
}
@Override
public void addLicense(License license) throws LicenseManagementException {
}
@Override
public boolean requireDeviceAuthorization() {
return false;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug(
"updating the details of Automatic Door Locker device : " + deviceIdentifier);
}
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().updateDevice(device);
DoorManagerDAOUtil.commitTransaction();
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAOUtil.rollbackTransaction();
} catch (DoorManagerDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg =
"Error while updating the Automatic Door Locker device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Automatic Door Locker devices");
}
devices = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().getAllDevices();
} catch (DoorManagerDeviceMgtPluginException e) {
String msg = "Error while fetching all Automatic Door Locker devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
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();
}
public boolean assignUserToLock(DoorLockSafe doorLockSafe) throws DoorManagerDeviceMgtPluginException {
boolean status;
try {
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().registerDoorLockSafe(doorLockSafe);
DoorManagerDAOUtil.commitTransaction();
return status;
} catch (DoorManagerDeviceMgtPluginException e) {
try {
DoorManagerDAOUtil.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;
DoorManagerDAOUtil.beginTransaction();
status = DOOR_MANAGER_DAO.getAutomaticDoorLockerDeviceDAO().checkCardDoorAssociation(cardNumber, deviceId);
DoorManagerDAOUtil.commitTransaction();
return status;
}
}

@ -1,108 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.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 void init() throws DeviceManagementException {
this.deviceManager = new DoorManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> deviceIds)
throws DeviceManagementException {
}
@Override
public Application[] getApplications(String domain, int pageNumber, int size)
throws ApplicationManagementException {
return new Application[0];
}
@Override
public void updateApplicationStatus(DeviceIdentifier deviceId, Application application,
String status) throws ApplicationManagementException {
}
@Override
public String getApplicationStatus(DeviceIdentifier deviceId, Application application)
throws ApplicationManagementException {
return null;
}
@Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> deviceIdentifiers)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUsers(Operation operation, List<String> userNameList)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUserRoles(Operation operation, List<String> userRoleList)
throws ApplicationManagementException {
}
}

@ -1,92 +0,0 @@
/*~ Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.*/
package org.homeautomation.doormanager.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;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getUIDofUser() {
return UIDofUser;
}
public void setUIDofUser(String UIDofUser) {
this.UIDofUser = UIDofUser;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public String getPolicy() {
return policy;
}
public void setPolicy(String policy) {
this.policy = policy;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
}

@ -1,132 +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.dao;
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.impl.DoorManagerDAO;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DoorManagerDAOUtil {
private static final Log log = LogFactory.getLog(DoorManagerDAOUtil.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public DoorManagerDAOUtil() {
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 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();
}
}
public DoorManagerDAO getAutomaticDoorLockerDeviceDAO() {
return new DoorManagerDAO();
}
}

@ -1,474 +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.dao.impl;
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.DoorLockSafe;
import org.homeautomation.doormanager.plugin.impl.dao.DoorManagerDAOUtil;
import org.homeautomation.doormanager.plugin.impl.dao.util.DoorManagerUtils;
import org.wso2.carbon.device.mgt.common.Device;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Device Dao for automatic door locker Devices.
*/
public class DoorManagerDAO {
private static final Log log = LogFactory.getLog(DoorManagerDAO.class);
public Device getDevice(String deviceId) throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
Device automaticDoorLockerDevice = null;
ResultSet resultSet = null;
try {
conn = DoorManagerDAOUtil.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<Device.Property> 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);
DoorManagerDAOUtil.closeConnection();
}
return automaticDoorLockerDevice;
}
public boolean addDevice(Device automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAOUtil.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;
}
public boolean registerDoorLockSafe(DoorLockSafe automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAOUtil.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 {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
conn = DoorManagerDAOUtil.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 {
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);
DoorManagerDAOUtil.closeConnection();
}
}
public boolean isUserAllowed(String serialNumber, String UIDofUser, String deviceId) throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
conn = DoorManagerDAOUtil.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()) {
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()) {
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);
DoorManagerDAOUtil.closeConnection();
}
}
public boolean shareDoorLockSafe(DoorLockSafe automaticDoorLOcker) throws DoorManagerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAOUtil.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 = DoorManagerDAOUtil.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 = DoorManagerDAOUtil.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<String> getUserCredentials(String deviceId, String UIDofUser) throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<String> userCredentials = new ArrayList<>();
try {
conn = DoorManagerDAOUtil.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);
DoorManagerDAOUtil.closeConnection();
}
}
public List<String> getRegisteredDoorLocks(String deviceId) throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<String> doorLockSafes = new ArrayList<>();
try {
conn = DoorManagerDAOUtil.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);
DoorManagerDAOUtil.closeConnection();
}
}
public boolean updateDevice(Device automaticDoorLocker) throws DoorManagerDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DoorManagerDAOUtil.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<Device.Property>());
}
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 = DoorManagerDAOUtil.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<Device> getAllDevices() throws DoorManagerDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device connectedCupDevice;
List<Device> iotDevices = new ArrayList<>();
try {
conn = DoorManagerDAOUtil.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);
DoorManagerDAOUtil.closeConnection();
}
}
}

@ -1,86 +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.dao.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Contains utility methods used by Automatic Door Locker
*/
public class DoorManagerUtils {
private static Log log = LogFactory.getLog(DoorManagerUtils.class);
public static String getDeviceProperty(List<Device.Property> deviceProperties, String propertyKey) {
String deviceProperty = "";
for (Device.Property property : deviceProperties) {
if (propertyKey.equals(property.getName())) {
deviceProperty = property.getValue();
}
}
return deviceProperty;
}
public static Device.Property getProperty(String property, String value) {
if (property != null) {
Device.Property prop = new Device.Property();
prop.setName(property);
prop.setValue(value);
return prop;
}
return null;
}
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}
}

@ -1,74 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.doormanager.plugin.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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;
/**
* @scr.component name="org.homeautomation.doormanager.plugin.internal.DoorManagerManagementServiceComponent"
* immediate="true"
*/
public class DoorManagerManagementServiceComponent {
private static final Log log = LogFactory.getLog(DoorManagerManagementServiceComponent.class);
private ServiceRegistration automaticDoorLocker;
protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("Activating Door Opener Device Management Service Component");
}
try {
BundleContext bundleContext = ctx.getBundleContext();
automaticDoorLocker =
bundleContext.registerService(DeviceManagementService.class.getName(),
new DoorManagerService(), null);
if (log.isDebugEnabled()) {
log.debug("DoorOpener Device Management Service Component has been successfully activated");
}
} catch (Throwable e) {
log.error("Error occurred while activating DoorOpener Device Management Service Component", e);
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating Door Opener Device Management Service Component");
}
try {
if (automaticDoorLocker != null) {
automaticDoorLocker.unregister();
}
if (log.isDebugEnabled()) {
log.debug(
"Door Opener Device Management Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error(
"Error occurred while de-activating Door Locker Device Management bundle", e);
}
}
}

@ -1,56 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>1.0.0-SNAPSHOT</version>
<artifactId>doormanager-component</artifactId>
<packaging>pom</packaging>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<version>${maven-scr-plugin.version}</version>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>plugin</module>
<module>api</module>
<module>analytics</module>
<module>ui</module>
</modules>
</project>

@ -1,56 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager-component</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.homeautomation.doormanager.ui</artifactId>
<name>org.homeautomation.doormanager.ui</name>
<packaging>pom</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<finalName>org.homeautomation.doormanager.ui-1.0.0-SNAPSHOT</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/src.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>create-archive</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,36 +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.
-->
<assembly
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>src</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<baseDirectory>${basedir}/src</baseDirectory>
<fileSets>
<fileSet>
<directory>${basedir}/src/main/resources/jaggeryapps/</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>
</assembly>

@ -1,94 +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.
*/-->
{{#zone "topCss"}}
<style>
.thumbnail.icon:before {
padding-top: 0;
}
</style>
{{/zone}}
{{#zone "device-thumbnail"}}
<img src="{{@unit.publicUri}}/images/doormanager-icon.png"/>
{{/zone}}
{{#zone "operation-status"}}
<div id="div-operation-status" class="hidden" align="center" style="padding: 10px; margin-bottom: 5px">
</div>
{{/zone}}
{{#zone "device-opetations"}}
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">
Operations
</div>
<div class="add-margin-top-4x">
{{unit "iot.unit.device.operation-bar" device=device}}
</div>
{{/zone}}
{{#zone "device-detail-properties"}}
<div class="media">
<div class="media-left col-xs-12 col-sm-2 col-md-2 col-lg-2">
<ul class="list-group" role="tablist">
<li class="active">
<a class="list-group-item" href="#device_statistics" role="tab" data-toggle="tab"
aria-controls="device_statistics">Device Statistics</a>
</li>
<li><a class="list-group-item" href="#event_log" role="tab" data-toggle="tab"
aria-controls="event_log">Operations Log</a></li>
</ul>
</div>
<div class="media-body add-padding-left-5x remove-padding-xs tab-content">
<div class="panel-group tab-content">
<div class="panel panel-default tab-pane active"
id="device_statistics" role="tabpanel" aria-labelledby="device_statistics">
<div class="panel-heading">Device Statistics</div>
{{unit "iot.unit.device.stats" device=device}}
</div>
<div class="panel panel-default tab-pane" id="event_log" role="tabpanel"
aria-labelledby="event_log">
<div class="panel-heading">Operations Log <span><a href="#"
id="refresh-operations"><i
class="fw fw-refresh"></i></a></span></div>
<div class="panel-body">
<div id="operations-spinner" class="wr-advance-operations-init hidden">
<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<i class="fw fw-settings fw-spin fw-2x"></i>
&nbsp;&nbsp;&nbsp;
Loading Operations Log . . .
<br>
<br>
</div>
<div id="operations-log-container">
<div class="panel-body">
Not available yet
</div>
<br class="c-both"/>
</div>
</div>
</div>
</div>
</div>
</div>
{{/zone}}

@ -1,37 +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.
*/
function onRequest(context) {
var log = new Log("device-view.js");
var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("id");
var getProperty = require("process").getProperty;
var port = getProperty("carbon.https.port");
var host = getProperty("carbon.local.ip");
var sessionId = session.getId();
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};
}
}
}

@ -1,242 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
var modalPopup = ".wr-modalpopup";
var modalPopupContainer = modalPopup + " .modalpopup-container";
var modalPopupContent = modalPopup + " .modalpopup-content";
var body = "body";
/*
* set popup maximum height function.
*/
function setPopupMaxHeight() {
$(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30)));
$(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2)));
}
/*
* show popup function.
*/
function showPopup() {
$(modalPopup).show();
setPopupMaxHeight();
$('#downloadForm').validate({
rules: {
deviceName: {
minlength: 4,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
$(element).closest('.control-group').removeClass('error').addClass('success');
$('label[for=deviceName]').remove();
}
});
var deviceType = "";
$('.deviceType').each(function () {
if (this.value != "") {
deviceType = this.value;
}
});
}
/*
* hide popup function.
*/
function hidePopup() {
$('label[for=deviceName]').remove();
$('.control-group').removeClass('success').removeClass('error');
$(modalPopupContent).html('');
$(modalPopup).hide();
}
/*
* DOM ready functions.
*/
$(document).ready(function () {
attachEvents();
});
function attachEvents() {
/**
* Following click function would execute
* when a user clicks on "Download" link
* on Device Management page in WSO2 DC Console.
*/
$("a.download-link").click(function () {
var sketchType = $(this).data("sketchtype");
var deviceType = $(this).data("devicetype");
var downloadDeviceAPI = "/devicemgt/api/devices/sketch/generate_link";
var payload = {"sketchType": sketchType, "deviceType": deviceType};
$(modalPopupContent).html($('#download-device-modal-content').html());
showPopup();
var deviceName;
$("a#download-device-download-link").click(function () {
$('.new-device-name').each(function () {
if (this.value != "") {
deviceName = this.value;
}
});
$('label[for=deviceName]').remove();
if (deviceName && deviceName.length >= 4) {
payload.deviceName = deviceName;
invokerUtil.post(
downloadDeviceAPI,
payload,
function (data, textStatus, jqxhr) {
doAction(data);
},
function (data) {
doAction(data);
}
);
} else if (deviceName) {
$('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">Please enter at least 4 ' +
'characters.</label>');
$('.control-group').removeClass('success').addClass('error');
} else {
$('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">This field is required.' +
'</label>');
$('.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 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;
$('.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;
}
});
var deviceType = "";
$('.deviceType').each(function () {
if (this.value != "") {
deviceType = this.value;
}
});
var sketchType = "";
$('.sketchType').each(function () {
if (this.value != "") {
sketchType = this.value;
}
});
/*var serialNumber = "";
$('.device-serial-number').each(function () {
if (this.value != "") {
serialNumber = this.value;
}
});*/
var deviceNameFormat = /^[^~?!#$:;%^*`+={}\[\]\\()|<>,'"]{1,30}$/;
if (deviceName && deviceNameFormat.test(deviceName)) {
$(modalPopupContent).html($('#device-agent-downloading-content').html());
var successCallback = function (data) {
data = JSON.parse(data);
hidePopup();
window.location = "/devicemgt/api/devices/sketch/download/" + data.responseContent;
};
var generateLink = "/" + deviceType + "_mgt/manager/device/" + sketchType
+ "/generate_link?deviceName=" + deviceName;
console.log("generated link"+ generateLink);
invokerUtil.get(generateLink, successCallback, function (message) {
console.log(message.content);
hidePopup();
doAction(data);
});
} else {
$("#invalid-username-error-msg span").text("Invalid device name");
$("#invalid-username-error-msg").removeClass("hidden");
}
}
function doAction(data) {
if (data.status == null) {
document.write(data);
}
if (data.status == "200") {
$(modalPopupContent).html($('#download-device-modal-content-links').html());
$("input#download-device-url").val(data.responseText);
$("input#download-device-url").focus(function () {
$(this).select();
});
showPopup();
} else if (data.status == "401") {
$(modalPopupContent).html($('#device-401-content').html());
$("#device-401-link").click(function () {
window.location = "/devicemgt/login";
});
showPopup();
} else if (data == "403") {
$(modalPopupContent).html($('#device-403-content').html());
$("#device-403-link").click(function () {
window.location = "/devicemgt/login";
});
showPopup();
} else {
$(modalPopupContent).html($('#device-unexpected-error-content').html());
$("a#device-unexpected-error-link").click(function () {
hidePopup();
});
}
}

@ -1,321 +0,0 @@
<div class="col-lg-12 margin-top-double">
<h1 class="grey ">Door Manager</h1>
<hr>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 padding-top">
<img src="{{@unit.publicUri}}/images/doormanager-icon.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 padding-top">
<!--todo need to change this url-->
<h4 class="doc-link">Click <a href="https://docs.wso2.com/pages/viewpage.action?pageId=48289181"
target="_blank">[ here ]</a> for latest instructions and troubleshooting.</h4>
</div>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 padding-top">
<h3 class="uppercase">What it Does</h3>
<hr>
<p class="grey margin-top">Connect an Automatic Door Locker to WSO2 IoT Server and control and view current state
of door locker.</p>
<br>
<h3 class="uppercase">What You Need</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double"><span class="circle">ITEM 01</span>&nbsp;&nbsp;&nbsp;Electronic solenoid door
lock - 2
</li>
<li class="padding-top-double"><span class="circle">ITEM 02</span>&nbsp;&nbsp;&nbsp;MFRC522 RFID Reader/Writer
</li>
<li class="padding-top-double"><span class="circle">ITEM 03</span>&nbsp;&nbsp;&nbsp;2 Channel 5V Relay Module
</li>
<li class="padding-top-double"><span class="circle">ITEM 04</span>&nbsp;&nbsp;&nbsp;12 Volt DC - 1 Amp (12V, 1A)
Power Supply
</li>
<li class="padding-top-double"><span class="circle">ITEM 05</span>&nbsp;&nbsp;&nbsp;LED Bulbs (Red and Green)
</li>
<li class="padding-top-double"><span class="circle">ITEM 06</span>&nbsp;&nbsp;&nbsp;Resistors (333ohms) -2
</li>
<li class="padding-top-double">&nbsp;&nbsp;&nbsp;Proceed to [Prepare] section.
</ul>
<br>
<a href="/api-store/apis/info?name={{@uriParams.deviceType}}&version=1.0.0&provider=admin" class="btn-operations"
target="_blank"><i class="fw fw-api"></i> View API</i> &nbsp;</a>
<a href="#" class="download-link btn-operations"><i class="fw fw-download"></i>Register New Lock Safe</a>
<div id="download-device-modal-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 center-container">
<h3>Enter your device name serial number and then register {{@uriParams.deviceType}} the agent
from following link.</h3>
<br/>
<form id="downloadForm" method="GET" action="#">
<div class="control-group">
<div class="controls">
Device Name: <input class="new-device-name" style="color:#3f3f3f;padding:5px"
type="text"
placeholder="Ex. drone"
name="deviceName" size="60" required></br>
Serial Number: <input style="color:#3f3f3f;padding:5px"
type="text"
placeholder="Ex. serial number"
name="serialNumber" size="60"
class="device-serial-number" required>
<br/>
<input type="hidden" class="deviceType" name="deviceType"
value="doormanager"/>
<input type="hidden" class="sketchType" name="sketchType"
value="doormanager"/>
</div>
</div>
<br/>
<div class="buttons">
<a class="btn-operations" onclick="downloadAgent()">Register Now</a>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="device-agent-downloading-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Agent will download shortly.</h3>
</div>
</div>
</div>
</div>
<div id="download-device-modal-content-links" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Please download the file from following link(Press CTRL+C).</h3>
<br/>
<div>
<input id="download-device-url" style="color:#3f3f3f;padding:5px"
type="text" value="" placeholder="Type here" size="60">
</div>
</div>
</div>
</div>
</div>
<div id="device-400-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Exception at backend. Try Later.</h3>
<div class="buttons">
<a href="#" id="device-400-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-401-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>You have to log in first.</h3><br/>
<div class="buttons">
<a href="#" id="device-401-link" class="blue-button">
Goto Login Page
</a>&nbsp;&nbsp;
<a href="#" onclick="hidePopup();" class="btn-operations">
Cancel
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-403-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Action not permitted.</h3><br/>
<div class="buttons">
<a href="#" id="device-403-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-409-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Sketch does not exist.</h3><br/>
<div class="buttons">
<a href="#" id="device-409-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-unexpected-error-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Unexpected error.</h3><br/>
<div class="buttons">
<a href="#" id="device-unexpected-error-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<br/><br/>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 padding-double grey-bg">
<h3 class="uppercase">Prepare</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double"><span class="circle">01</span>&nbsp;&nbsp;&nbsp;Get the basic setup done
according to schematic below
</li>
<li class="padding-top-double"><span class="circle">02</span>&nbsp;&nbsp;&nbsp;Ensure your RaspberryPi Board
can connect to Internet.
</li>
<li class="padding-top-double"><span class="circle">03</span>&nbsp;&nbsp;&nbsp;Click on
[Download Agent] button above to get Automatic Door Locker agent.
</li>
<li class="padding-top-double"><span class="circle">04</span>&nbsp;&nbsp;&nbsp;Copy downloaded Agent into your
RaspberryPi.
</li>
<li class="padding-top-double"><span class="circle">05</span>&nbsp;&nbsp;&nbsp; Run "Agent.sh" script with root
privileges.
</li>
</ul>
<br>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
<h3 class="uppercase">SCHEMATIC DIAGRAM</h3>
<hr>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@unit.publicUri}}/images/schematicsGuide.png" target="_blank">
<img src="{{@unit.publicUri}}/images/schematicsGuide.png" class="img-responsive">
</a>
</center>
<br/>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
<h3 class="uppercase">Try Out</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double"><span class="circle">01</span>&nbsp;&nbsp;&nbsp;You can view
all your connected
devices at <a
href="{{@app.context}}/devices">[Device
Management]</a>
page.
</li>
<li class="padding-top-double"><span class="circle">02</span>&nbsp;&nbsp;&nbsp;Select one of
connected devices and check for available control operations as well as current state of door locker
</li>
</ul>
<br/>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@unit.publicUri}}/images/myDevices_analytics.png" target="_blank">
<img src="{{@unit.publicUri}}/images/myDevices_analytics.png" class="img-responsive">
</a>
</center>
</div>
{{#zone "topCss"}}
<style type="text/css">
.circle {
background: none repeat scroll 0 0 #191919;
border-radius: 50px;
height: 50px;
padding: 10px;
width: 50px;
color: #fff;
}
.padding-top-double {
padding-top: 20px;
}
.padding-double {
padding: 20px;
}
.grey {
color: #333;
}
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #7f7f7f;
margin: 1em 0;
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;
}
</style>
{{/zone}}
{{#zone "bottomJs"}}
{{js "/js/download.js"}}
{{js "/js/jquery.validate.js"}}
{{/zone}}

@ -1,20 +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.
-->*/
{
"version": "1.0.0"
}

@ -1,209 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager-feature</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>1.0.0-SNAPSHOT</version>
<artifactId>org.homeautomation.doormanager.feature</artifactId>
<packaging>pom</packaging>
<name>${project.artifactId}</name>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.api</artifactId>
<version>1.0.0-SNAPSHOT</version>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
<version>1.2.140.wso2v3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.analytics</artifactId>
<version>1.0.0-SNAPSHOT</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/carbonapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
<artifactItem>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.ui
</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/jaggeryapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-api-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.api</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps/
</outputDirectory>
<destFileName>doormanager.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>${maven-antrun-plugin.version}</version>
<executions>
<execution>
<id>create-doormanager-plugin-mgt-schema</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<property name="db.dir"
value="src/main/resources/database"/>
<property name="userid" value="wso2carbon"/>
<property name="password" value="wso2carbon"/>
<property name="dbURL"
value="jdbc:h2:file:${basedir}/${db.dir}/doormanagerDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
<mkdir dir="${basedir}/${db.dir}"/>
<sql driver="org.h2.Driver" url="${dbURL}" userid="${userid}"
password="${password}"
autocommit="true" onerror="continue">
<classpath refid="maven.dependency.classpath"/>
<classpath refid="maven.compile.classpath"/>
<classpath refid="maven.runtime.classpath"/>
<fileset file="${basedir}/src/main/resources/dbscripts/h2.sql"/>
</sql>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon-p2-plugin.version}</version>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>${project-base-package}</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:true</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.homeautomation:${project-base-package}.plugin:1.0.0-SNAPSHOT
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -1,30 +0,0 @@
# Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
[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

@ -1,3 +0,0 @@
templates=deviceConfig.properties
zipfilename=doormanager.zip

@ -1,194 +0,0 @@
#!/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()

@ -1,396 +0,0 @@
#!/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<len(sendData)):
self.Write_MFRC522(self.FIFODataReg, sendData[i])
i = i+1
self.Write_MFRC522(self.CommandReg, command)
if command == self.PCD_TRANSCEIVE:
self.SetBitMask(self.BitFramingReg, 0x80)
i = 2000
while True:
n = self.Read_MFRC522(self.CommIrqReg)
i = i - 1
if ~((i!=0) and ~(n&0x01) and ~(n&waitIRq)):
break
self.ClearBitMask(self.BitFramingReg, 0x80)
if i != 0:
if (self.Read_MFRC522(self.ErrorReg) & 0x1B)==0x00:
status = self.MI_OK
if n & irqEn & 0x01:
status = self.MI_NOTAGERR
if command == self.PCD_TRANSCEIVE:
n = self.Read_MFRC522(self.FIFOLevelReg)
lastBits = self.Read_MFRC522(self.ControlReg) & 0x07
if lastBits != 0:
backLen = (n-1)*8 + lastBits
else:
backLen = n*8
if n == 0:
n = 1
if n > self.MAX_LEN:
n = self.MAX_LEN
i = 0
while i<n:
backData.append(self.Read_MFRC522(self.FIFODataReg))
i = i + 1;
else:
status = self.MI_ERR
return (status,backData,backLen)
def MFRC522_Request(self, reqMode):
status = None
backBits = None
TagType = []
self.Write_MFRC522(self.BitFramingReg, 0x07)
TagType.append(reqMode);
(status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)
if ((status != self.MI_OK) | (backBits != 0x10)):
status = self.MI_ERR
return (status,backBits)
def MFRC522_Anticoll(self):
backData = []
serNumCheck = 0
serNum = []
self.Write_MFRC522(self.BitFramingReg, 0x00)
serNum.append(self.PICC_ANTICOLL)
serNum.append(0x20)
(status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,serNum)
if(status == self.MI_OK):
i = 0
if len(backData)==5:
while i<4:
serNumCheck = serNumCheck ^ backData[i]
i = i + 1
if serNumCheck != backData[i]:
status = self.MI_ERR
else:
status = self.MI_ERR
return (status,backData)
def CalulateCRC(self, pIndata):
self.ClearBitMask(self.DivIrqReg, 0x04)
self.SetBitMask(self.FIFOLevelReg, 0x80);
i = 0
while i<len(pIndata):
self.Write_MFRC522(self.FIFODataReg, pIndata[i])
i = i + 1
self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC)
i = 0xFF
while True:
n = self.Read_MFRC522(self.DivIrqReg)
i = i - 1
if not ((i != 0) and not (n&0x04)):
break
pOutData = []
pOutData.append(self.Read_MFRC522(self.CRCResultRegL))
pOutData.append(self.Read_MFRC522(self.CRCResultRegM))
return pOutData
def MFRC522_SelectTag(self, serNum):
backData = []
buf = []
buf.append(self.PICC_SElECTTAG)
buf.append(0x70)
i = 0
while i<5:
buf.append(serNum[i])
i = i + 1
pOut = self.CalulateCRC(buf)
buf.append(pOut[0])
buf.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
if (status == self.MI_OK) and (backLen == 0x18):
print "Size: " + str(backData[0])
return backData[0]
else:
return 0
def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):
buff = []
# First byte should be the authMode (A or B)
buff.append(authMode)
# Second byte is the trailerBlock (usually 7)
buff.append(BlockAddr)
# Now we need to append the authKey which usually is 6 bytes of 0xFF
i = 0
while(i < len(Sectorkey)):
buff.append(Sectorkey[i])
i = i + 1
i = 0
# Next we append the first 4 bytes of the UID
while(i < 4):
buff.append(serNum[i])
i = i +1
# Now we start the authentication itself
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT,buff)
# Check if an error occurred
if not(status == self.MI_OK):
print "AUTH ERROR!!"
if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0:
print "AUTH ERROR(status2reg & 0x08) != 0"
# Return the status
return status
def MFRC522_StopCrypto1(self):
self.ClearBitMask(self.Status2Reg, 0x08)
def MFRC522_Read(self, blockAddr):
recvData = []
recvData.append(self.PICC_READ)
recvData.append(blockAddr)
pOut = self.CalulateCRC(recvData)
recvData.append(pOut[0])
recvData.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
if not(status == self.MI_OK):
print "Error while reading!"
i = 0
if len(backData) == 16:
print "Sector "+str(blockAddr)+" "+str(backData)
def MFRC522_Write(self, blockAddr, writeData):
buff = []
buff.append(self.PICC_WRITE)
buff.append(blockAddr)
crc = self.CalulateCRC(buff)
buff.append(crc[0])
buff.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
status = self.MI_ERR
print str(backLen)+" backdata &0x0F == 0x0A "+str(backData[0]&0x0F)
if status == self.MI_OK:
i = 0
buf = []
while i < 16:
buf.append(writeData[i])
i = i + 1
crc = self.CalulateCRC(buf)
buf.append(crc[0])
buf.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,buf)
if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
print "Error while writing"
if status == self.MI_OK:
print "Data written"
def MFRC522_DumpClassic1K(self, key, uid):
i = 0
while i < 64:
status = self.MFRC522_Auth(self.PICC_AUTHENT1A, i, key, uid)
# Check if authenticated
if status == self.MI_OK:
self.MFRC522_Read(i)
else:
print "Authentication error"
i = i+1
def MFRC522_Init(self):
GPIO.output(self.NRSTPD, 1)
self.MFRC522_Reset();
self.Write_MFRC522(self.TModeReg, 0x8D)
self.Write_MFRC522(self.TPrescalerReg, 0x3E)
self.Write_MFRC522(self.TReloadRegL, 30)
self.Write_MFRC522(self.TReloadRegH, 0)
self.Write_MFRC522(self.TxAutoReg, 0x40)
self.Write_MFRC522(self.ModeReg, 0x3D)
self.AntennaOn()

@ -1,131 +0,0 @@
#!/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 time
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
import iotUtils
global mqttClient
mqttClient = mqtt.Client()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The callback for when the client receives a CONNACK response from the server.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def on_connect(mqttClient, userdata, flags, rc):
print("MQTT_LISTENER: Connected with result code " + str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
print ("MQTT_LISTENER: Subscribing with topic " + TOPIC_TO_SUBSCRIBE)
mqttClient.subscribe(TOPIC_TO_SUBSCRIBE)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The callback for when a PUBLISH message is received from the server.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def on_message(mqttClient, userdata, msg):
print("MQTT_LISTENER: " + msg.topic + " " + str(msg.payload))
request = str(msg.payload)
resource = ""
if (len(request.split(":")) == 2):
resource = request.split(":")[0].upper()
state = request.split(":")[1].upper()
if state == "LOCK":
GPIO.output(iotUtils.DOOR_LOCKER_2_PORT, GPIO.HIGH)
GPIO.output(iotUtils.DOOR_LOCKER_1_PORT, GPIO.HIGH)
GPIO.output(iotUtils.LOCK_STATE_OFF_NOTIFY_PORT, GPIO.HIGH)
GPIO.output(iotUtils.LOCK_STATE_ON_NOTIFY_PORT, GPIO.LOW)
mqttClient.publish(TOPIC_TO_PUBLISH, "Locker:LOCKED")
print "Door is locked"
elif state == "UNLOCK":
GPIO.output(iotUtils.DOOR_LOCKER_2_PORT, GPIO.LOW)
GPIO.output(iotUtils.DOOR_LOCKER_1_PORT, GPIO.LOW)
GPIO.output(iotUtils.LOCK_STATE_OFF_NOTIFY_PORT, GPIO.LOW)
GPIO.output(iotUtils.LOCK_STATE_ON_NOTIFY_PORT, GPIO.HIGH)
mqttClient.publish(TOPIC_TO_PUBLISH, "Locker:UNLOCKED")
print "Door is unlocked"
else:
print "MQTT message in the wrong format"
print "MQTT_LISTENER: Resource- " + resource
else:
print "MQTT message in the wrong format"
print "MQTT_LISTENER: Resource- " + resource
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The callback for when a PUBLISH message to the server when door is open or close
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def on_publish(mqttClient, msg):
mqttClient.publish(TOPIC_TO_PUBLISH, msg)
def sendLockerStatus(msg):
global mqttClient
on_publish(mqttClient, msg)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The Main method of the server script
# This method is invoked from DoorLockerAgent.py on a new thread
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def main():
MQTT_ENDPOINT = iotUtils.MQTT_EP.split(":")
MQTT_IP = MQTT_ENDPOINT[1].replace('//', '')
MQTT_PORT = int(MQTT_ENDPOINT[2])
DEV_OWNER = iotUtils.DEVICE_OWNER
DEV_ID = iotUtils.DEVICE_ID
global TOPIC_TO_SUBSCRIBE
TOPIC_TO_SUBSCRIBE = "wso2/iot/" + DEV_OWNER + "/doormanager/" + DEV_ID + "/subscriber"
global TOPIC_TO_PUBLISH
TOPIC_TO_PUBLISH = "wso2/iot/" + DEV_OWNER + "/doormanager/" + DEV_ID + "/publisher"
print ("MQTT_LISTENER: MQTT_ENDPOINT is " + str(MQTT_ENDPOINT))
print ("MQTT_LISTENER: MQTT_TOPIC is " + TOPIC_TO_SUBSCRIBE)
global mqttClient
mqttClient.on_connect = on_connect
mqttClient.on_message = on_message
while True:
try:
mqttClient.connect(MQTT_IP, MQTT_PORT, 60)
print "MQTT_LISTENER: " + time.asctime(), "Connected to MQTT Broker - %s:%s" % (MQTT_IP, MQTT_PORT)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
mqttClient.loop_forever()
except (KeyboardInterrupt, Exception) as e:
print "MQTT_LISTENER: Exception in MQTTServerThread (either KeyboardInterrupt or Other)"
print ("MQTT_LISTENER: " + str(e))
mqttClient.disconnect()
print "MQTT_LISTENER: " + time.asctime(), "Connection to Broker closed - %s:%s" % (MQTT_IP, MQTT_PORT)
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
pass
if __name__ == '__main__':
main()

@ -1,170 +0,0 @@
#!/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 signal
import RPi.GPIO as GPIO
import MFRC522
import MQTTHandler
import iotUtils
import argparse
import httplib
import logging
import logging.handlers
import signal
import ssl
import sys
import threading
import time
from functools import wraps
CONTINUE_READING = True
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# 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
# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
global CONTINUE_READING
print "Ctrl+C captured, ending read."
CONTINUE_READING = False
GPIO.cleanup()
# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)
# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()
global RFID_CARD_UID
RFID_CARD_UID = ""
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Endpoint specific settings to connect with the IoT Server
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SERVER_ENDPOINT = iotUtils.HTTPS_EP.split(":")
SERVER_IP = SERVER_ENDPOINT[1].replace('//', '')
SERVER_PORT = int(SERVER_ENDPOINT[2])
API_ENDPOINT_CONTEXT = iotUtils.CONTROLLER_CONTEXT
REGISTER_ENDPOINT = str(API_ENDPOINT_CONTEXT) + '/register'
APIM_SERVER_ENDPOINT = iotUtils.API_EP.split(":")
APIM_SERVER_IP = APIM_SERVER_ENDPOINT[1].replace('//', '')
APIM_SERVER_PORT = int(APIM_SERVER_ENDPOINT[2])
MANAGER_API_CONTEXT = iotUtils.MANAGER_CONTEXT
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This method check whether the UID of RFID card is registered or not
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def isRFIDCardRegistered( RFID_CARD_UID ):
ssl.wrap_socket = sslwrap(ssl.wrap_socket) # using the overridden sslwrap that uses TLSv1
print "Waiting to get UID of RFID card..."
if sys.version_info<(2,7,9):
dcConncection = httplib.HTTPSConnection(host=SERVER_IP, port=SERVER_PORT)
else:
dcConncection = httplib.HTTPSConnection(host=SERVER_IP, port=SERVER_PORT, context=ssl._create_unverified_context())
dcConncection.set_debuglevel(1)
dcConncection.connect()
PUSH_DATA = iotUtils.DEVICE_INFO_WITH_OWNER + iotUtils.DEVICE_DATA + RFID_CARD_UID
PUSH_DATA += '"}'
print PUSH_DATA
APIURL = str(MANAGER_API_CONTEXT)
dcConncection.putrequest('POST', APIURL)
dcConncection.putheader('Content-Type', 'application/json')
dcConncection.putheader('Authorization', 'Bearer ' + iotUtils.AUTH_TOKEN)
dcConncection.putheader('Content-Length', len(PUSH_DATA))
dcConncection.endheaders()
dcConncection.send(PUSH_DATA)
dcResponse = dcConncection.getresponse()
if(dcResponse.status < 250):
print "You are allowed to open the door"
isRegisteredUser = True
else:
isRegisteredUser = False
print "You are not allowed to open the door"
print ('DoorManager: ' + str(dcResponse.status))
print ('DoorManager: ' + str(dcResponse.reason))
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print ('DoorManager: ' + str(APIURL))
print ('DoorManager: Response Message')
print str(dcResponse.msg)
dcConncection.close()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
return isRegisteredUser
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~------
# Read RFID card and if user is authorized to given RFID card, then open the lock
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~------
def readUIDofRFID():
print "-----------------------------------Starting MFRC522 chip reader---------------------------------------------"
# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while CONTINUE_READING:
# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
# If a card is found
# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()
# If we have the UID, continue
if status == MIFAREReader.MI_OK:
global RFID_CARD_UID
RFID_CARD_UID = str(uid[0])+":"+str(uid[1])+":"+str(uid[2])+":"+str(uid[3])
print "Card read UID: " + RFID_CARD_UID
# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)
# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)
# Check if authenticated
if status == MIFAREReader.MI_OK:
MIFAREReader.MFRC522_Read(8)
MIFAREReader.MFRC522_StopCrypto1()
if(isRFIDCardRegistered(RFID_CARD_UID)):
print "Authentication successful"
GPIO.output(iotUtils.LOCK_STATE_OFF_NOTIFY_PORT, GPIO.LOW)
GPIO.output(iotUtils.LOCK_STATE_ON_NOTIFY_PORT, GPIO.HIGH)
GPIO.output(iotUtils.DOOR_LOCKER_2_PORT, GPIO.LOW)
GPIO.output(iotUtils.DOOR_LOCKER_1_PORT, GPIO.LOW)
MQTTHandler.on_publish(MQTTHandler.mqttClient,"Locker:UNLOCKED")
return True
def main():
global RFID_CARD_UID
RFID_CARD_UID = ""
readUIDofRFID()
if __name__ == '__main__':
main()

@ -1,69 +0,0 @@
#!/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 ConfigParser
import os
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Device specific info when pushing data to server
# Read from a file "deviceConfig.properties" in the same folder level
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
configParser = ConfigParser.RawConfigParser()
configFilePath = os.path.join(os.path.dirname(__file__), './deviceConfig.properties')
configParser.read(configFilePath)
DEVICE_OWNER = configParser.get('Device-Configurations', 'owner')
DEVICE_ID = configParser.get('Device-Configurations', 'deviceId')
SERIAL_NUMBER = configParser.get('Device-Configurations', 'deviceId')
MQTT_EP = configParser.get('Device-Configurations', 'mqtt-ep')
AUTH_TOKEN = configParser.get('Device-Configurations', 'auth-token')
USER_NAME = configParser.get('Device-Configurations', 'username')
CONTROLLER_CONTEXT = configParser.get('Device-Configurations', 'controller-context')
DEVICE_INFO = '{"owner":"' + DEVICE_OWNER + '","deviceId":"' + DEVICE_ID + '",'
HTTPS_EP = configParser.get('Device-Configurations', 'https-ep')
HTTP_EP = configParser.get('Device-Configurations', 'http-ep')
DEVICE_INFO_WITH_OWNER = '{"serialNumber":"' + SERIAL_NUMBER + '", "userName":"'+ USER_NAME +'","deviceId":"' + SERIAL_NUMBER + '",'
API_EP = configParser.get('Device-Configurations', 'apim-ep')
MANAGER_CONTEXT = configParser.get('Device-Configurations', 'manager-context')
DEVICE_DATA = '"cardNumber":"'
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
global IS_REGISTERED
IS_REGISTERED = False
DOOR_LOCKER_1_PORT = 16
DOOR_LOCKER_2_PORT = 18
LOCK_STATE_ON_NOTIFY_PORT = 11
LOCK_STATE_OFF_NOTIFY_PORT = 13
def isEmpty (string):
if string and string.strip():
#string is not None AND string is not empty or blank
return False
#string is None OR string is empty or blank
return True

@ -1,59 +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.
#**/
#"""
#!/bin/bash
echo "----------------------------------------------------------------"
echo "| WSO2 IOT Door Manager "
echo "| Agent "
echo "| --------------------- "
echo "| ....initializing startup-script "
echo "----------------------------------------------------------------"
currentDir=$PWD
for f in ./deviceConfig.properties; do
## Check if the glob gets expanded to existing files.
## If not, f here will be exactly the pattern above
## and the exists test will evaluate to false.
if [ -e "$f" ]; then
echo "Configuration file found......"
else
echo "'deviceConfig.properties' file does not exist in current path. \nExiting installation...";
exit;
fi
## This is all we needed to know, so we can break after the first iteration
break
done
cd $currentDir
cp deviceConfig.properties ./src
chmod +x ./src/DoorManagerAgent.py
sudo python ./src/DoorManagerAgent.py
if [ $? -ne 0 ]; then
echo "Could not start the service..."
exit;
fi
echo "--------------------------------------"
echo "| Successfully Started "
echo "| -------------------------- "

@ -1,18 +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.
# -->
custom = true

@ -1,31 +0,0 @@
{
"deviceType": {
"label": "Door Manager",
"category": "iot"
},
"analyticStreams": [
{
"name": "smartLock",
"table": "DEVICE_smartLock_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data": [
{
"column": {
"name": "TIME",
"label": "time",
"ui-mapping": "x-axis"
}
},
{
"column": {
"name": "smartLock",
"label": "smartLock",
"ui-mapping": "y-axis"
}
}
]
}
}
]
}

@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<DeviceTypeConfigurations>
<DeviceTypeConfig type="doormanager">
<DatasourceName>jdbc/doormanagerDM_DB</DatasourceName>
</DeviceTypeConfig>
</DeviceTypeConfigurations>

@ -1,47 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<datasources-configuration>
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>
<datasources>
<datasource>
<name>doormanagerDM_DB</name>
<description>The datasource used for the this device type</description>
<jndiConfig>
<name>jdbc/doormanagerDM_DB</name>
</jndiConfig>
<definition type="RDBMS">
<configuration>
<url>jdbc:h2:repository/database/doormanagerDM_DB;DB_CLOSE_ON_EXIT=FALSE
</url>
<username>wso2carbon</username>
<password>wso2carbon</password>
<driverClassName>org.h2.Driver</driverClassName>
<maxActive>50</maxActive>
<maxWait>60000</maxWait>
<testOnBorrow>true</testOnBorrow>
<validationQuery>SELECT 1</validationQuery>
<validationInterval>30000</validationInterval>
</configuration>
</definition>
</datasource>
</datasources>
</datasources-configuration>

@ -1,29 +0,0 @@
-- -----------------------------------------------------
-- Agent Database
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `doormanager_DEVICE` (
`doormanager_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
`ACCESS_TOKEN` VARCHAR(200) NULL DEFAULT NULL,
`REFRESH_TOKEN` VARCHAR(200) NULL DEFAULT NULL);
CREATE TABLE IF NOT EXISTS `SHARED_DOORLOCK_SAFE` (
`doormanager_DEVICE_ID` VARCHAR(45) NOT NULL ,
`SERIAL_NUMBER` VARCHAR(45) NOT NULL ,
`UID_of_USER` VARCHAR(100) NULL DEFAULT NULL,
`POLICY` VARCHAR(100) NULL DEFAULT NULL);
CREATE TABLE IF NOT EXISTS `REGISTERED_DOORLOCK_SAFE` (
`doormanager_DEVICE_ID` VARCHAR(45) NOT NULL ,
`SERIAL_NUMBER` VARCHAR(100) NULL DEFAULT NULL,
`UID_of_USER` VARCHAR(100) NULL DEFAULT NULL,
`POLICY` VARCHAR(100) NULL DEFAULT NULL,
`EMAIL_ADDRESS` VARCHAR(100) NULL DEFAULT NULL,
`ACCESS_TOKEN` VARCHAR(200) NULL DEFAULT NULL,
`REFRESH_TOKEN` VARCHAR(200) NULL DEFAULT NULL);

@ -1,12 +0,0 @@
-- -----------------------------------------------------
-- Agent Database
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `doormanager_DEVICE` (
`doormanager_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`doormanager_DEVICE_ID`) )
ENGINE = InnoDB;

@ -1,28 +0,0 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../conf/device-types/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.doormanager_${feature.version}/configs/,target:${installFolder}/../../conf/device-types/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.doormanager_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/doormanager/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.doormanager_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/doormanager/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.doormanager_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/doormanager,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.doormanager_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.doormanager_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.doormanager_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/carbonapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.doormanager_${feature.version}/carbonapps/,target:${installFolder}/../../deployment/server/carbonapps/,overwrite:true);\
instructions.unconfigure = \
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/device-types/doormanager.json);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/device-types/doormanager.xml);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/doormanager.war);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/doormanager);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../dbscripts/cdm/plugins/doormanager);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../resources/sketches/doormanager);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/datasources/doormanager-datasources.xml);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../database/doormanagerDM_DB.h2.db);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.device-view);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.doormanager.type-view);\

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>doormanager-feature</artifactId>
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<version>1.0.0-SNAPSHOT</version>
<modules>
<module>feature</module>
</modules>
</project>

@ -1,518 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2</groupId>
<artifactId>wso2</artifactId>
<version>1</version>
</parent>
<groupId>org.homeautomation</groupId>
<artifactId>doormanager</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modelVersion>4.0.0</modelVersion>
<url>http://wso2.com</url>
<modules>
<module>component</module>
<module>feature</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
<version>${eclipse.osgi.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.equinox</groupId>
<artifactId>org.eclipse.equinox.common</artifactId>
<version>${eclipse.equinox.common.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
<exclusion>
<groupId>org.beanshell</groupId>
<artifactId>bsh</artifactId>
</exclusion>
<exclusion>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</exclusion>
</exclusions>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
<version>3.3.100.v20120522-1822</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
<version>${carbon.kernel.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.log4j.wso2</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.bootstrap</artifactId>
</exclusion>
</exclusions>
<scope>provided</scope>
</dependency>
<!-- CXF dependencies -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>${cxf.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>${paho.mqtt.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>${javax.ws.rs.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId>
<version>1.0.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.apimgt.webapp.publisher_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
<version>${carbon.kernel.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.ndatasource.core_${carbon.kernel.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<version>${carbon.iot.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.iot_${carbon.iot.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.core_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.common_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.certificate.mgt.core_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.apimgt.annotations_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.analytics.data.publisher_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
<version>${commons-httpclient.orbit.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/commons-httpclient_3.1.0.wso2v2.jar
</systemPath>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
<version>${commons-httpclient.orbit.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/commons-httpclient_3.1.0.wso2v2.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<version>${carbon.kernel.version}</version>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.utils_${carbon.kernel.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
<version>${smack.wso2.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/smack_3.0.4.wso2v1.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
<version>${smackx.wso2.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/smackx_3.0.4.wso2v1.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
<version>${commons-json.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/json_3.0.0.wso2v1.jar
</systemPath>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4.0.wso2v1</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/commons-codec_1.4.0.wso2v1.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.core</artifactId>
<version>${carbon.kernel.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.user.core_${carbon.kernel.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
<version>${carbon.kernel.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.user.api_${carbon.kernel.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.device.mgt.extensions_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.apimgt.application.extension_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
<version>${carbon.device.mgt.jar.version}</version>
<scope>system</scope>
<systemPath>
${basedir}/../../../../repository/components/plugins/org.wso2.carbon.identity.jwt.client.extension_${carbon.device.mgt.jar.version}.jar
</systemPath>
</dependency>
</dependencies>
</dependencyManagement>
<pluginRepositories>
<pluginRepository>
<id>wso2.releases</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</pluginRepository>
<pluginRepository>
<id>wso2.snapshots</id>
<name>Apache Snapshot Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
<pluginRepository>
<id>wso2-nexus</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<id>wso2-nexus</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</repository>
<repository>
<id>wso2.releases</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</repository>
<repository>
<id>wso2.snapshots</id>
<name>WSO2 Snapshot Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>gcm-server-repository</id>
<name>GCM Server repository - GitHub</name>
<url>https://github.com/slorber/gcm-server-repository/raw/master/releases/</url>
</repository>
<repository>
<id>wso2-staging</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/orgwso2carbonapimgt-174/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</repository>
</repositories>
<properties>
<carbon.kernel.version>4.4.3</carbon.kernel.version>
<carbon.device.mgt.version>1.1.0-SNAPSHOT</carbon.device.mgt.version>
<carbon.device.mgt.jar.version>1.1.0.SNAPSHOT</carbon.device.mgt.jar.version>
<carbon-p2-plugin.version>1.5.3</carbon-p2-plugin.version>
<paho.mqtt.version>1.0.2</paho.mqtt.version>
<commons-json.version>3.0.0.wso2v1</commons-json.version>
<eclipse.osgi.version>3.8.1.v20120830-144521</eclipse.osgi.version>
<carbon.iot.device.mgt.version>2.1.0-SNAPSHOT</carbon.iot.device.mgt.version>
<carbon.iot.device.mgt.jar.version>2.1.0.SNAPSHOT</carbon.iot.device.mgt.jar.version>
<javax.ws.rs.version>1.1.1</javax.ws.rs.version>
<commons-io.version>2.4</commons-io.version>
<smack.wso2.version>3.0.4.wso2v1</smack.wso2.version>
<smackx.wso2.version>3.0.4.wso2v1</smackx.wso2.version>
<cxf.version>2.6.1</cxf.version>
<jackson.version>1.9.0</jackson.version>
<commons-httpclient.orbit.version>3.1.0.wso2v2</commons-httpclient.orbit.version>
<eclipse.equinox.common.version>3.6.100.v20120522-1841</eclipse.equinox.common.version>
<wso2.maven.compiler.source>1.7</wso2.maven.compiler.source>
<wso2.maven.compiler.target>1.7</wso2.maven.compiler.target>
<project-base-package>org.homeautomation.doormanager</project-base-package>
<junit.version>3.8.1</junit.version>
<org.apache.felix.version>1.4.0</org.apache.felix.version>
<maven-clean-plugin.version>2.4.1</maven-clean-plugin.version>
<maven-compiler-plugin.version>2.3.2</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-antrun-plugin.version>1.8</maven-antrun-plugin.version>
<maven-scr-plugin.version>1.7.2</maven-scr-plugin.version>
</properties>
</project>
Loading…
Cancel
Save