commit
70483aacde
@ -0,0 +1,28 @@
|
||||
<?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="smartBulb_CAPP" version="1.0.0" type="carbon/application">
|
||||
<dependency artifact="smartBulb_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="smartBulb_store" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="smartBulb_mqtt_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="smartBulb_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="smartBulb_spark_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
|
||||
</artifact>
|
||||
</artifacts>
|
@ -0,0 +1,32 @@
|
||||
<?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="smartBulb-mqtt" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
|
||||
<from eventAdapterType="oauth-mqtt">
|
||||
<property name="topic">carbon.super/doormanager/+/smartBulb</property>
|
||||
<property name="username">admin</property>
|
||||
<property name="contentValidatorParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:2</property>
|
||||
<property name="contentValidator">org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTContentValidator</property>
|
||||
<property name="contentTransformer">default</property>
|
||||
<property name="dcrUrl">https://localhost:${carbon.https.port}/dynamic-client-web/register</property>
|
||||
<property name="url">tcp://${mqtt.broker.host}:${mqtt.broker.port}</property>
|
||||
<property name="cleanSession">true</property>
|
||||
</from>
|
||||
<mapping customMapping="disable" type="json"/>
|
||||
<to streamName="org.wso2.iot.devices.smartBulb" version="1.0.0"/>
|
||||
</eventReceiver>
|
@ -0,0 +1,22 @@
|
||||
<?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="smartBulb_publisher" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
|
||||
<file>smartBulb_publisher.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,25 @@
|
||||
<?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.
|
||||
-->
|
||||
|
||||
<eventPublisher name="EventPublisher_smartBulb" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
|
||||
<from streamName="org.wso2.iot.devices.smartBulb" version="1.0.0"/>
|
||||
<mapping customMapping="disable" type="wso2event"/>
|
||||
<to eventAdapterType="iot-ui"/>
|
||||
</eventPublisher>
|
||||
|
@ -0,0 +1,22 @@
|
||||
<?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="smartBulb_spark_script" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
|
||||
<file>smartBulb_spark_script.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,28 @@
|
||||
<?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>smartBulb_spark_script</Name>
|
||||
<Script>
|
||||
CREATE TEMPORARY TABLE DevicesmartBulbData USING CarbonAnalytics OPTIONS(tableName "ORG_WSO2_IOT_DEVICES_smartBulb");
|
||||
CREATE TEMPORARY TABLE DevicesmartBulbSummaryData USING CarbonAnalytics OPTIONS (tableName "DEVICE_smartBulb_SUMMARY", schema "smartBulb FLOAT, deviceType STRING -i, deviceId STRING -i, owner STRING -i, time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
|
||||
insert overwrite table DevicesmartBulbSummaryData select smartBulb, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DevicesmartBulbData group by smartBulb, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
|
||||
</Script>
|
||||
<CronExpression>0 * * * * ?</CronExpression>
|
||||
</Analytics>
|
@ -0,0 +1,22 @@
|
||||
<?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="smartBulb_store" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
|
||||
<file>org_wso2_iot_devices_smartBulb.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,62 @@
|
||||
<?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.smartBulb: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>smartBulb</Name>
|
||||
<EnableIndexing>false</EnableIndexing>
|
||||
<IsPrimaryKey>false</IsPrimaryKey>
|
||||
<EnableScoreParam>false</EnableScoreParam>
|
||||
<Type>FLOAT</Type>
|
||||
</ColumnDefinition>
|
||||
</TableSchema>
|
||||
</EventStoreConfiguration>
|
@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "org.wso2.iot.devices.smartBulb",
|
||||
"version": "1.0.0",
|
||||
"nickName": "smartBulb",
|
||||
"description": "smartBulb data received from the Device",
|
||||
"metaData": [
|
||||
{"name":"owner","type":"STRING"},
|
||||
{"name":"deviceType","type":"STRING"},
|
||||
{"name":"deviceId","type":"STRING"},
|
||||
{"name":"time","type":"LONG"}
|
||||
],
|
||||
"payloadData": [
|
||||
{
|
||||
"name": "smartBulb","type": "FLOAT"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
|
@ -0,0 +1,28 @@
|
||||
<?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="smartFan_CAPP" version="1.0.0" type="carbon/application">
|
||||
<dependency artifact="smartFan_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="smartFan_store" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="smartFan_mqtt_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="smartFan_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="smartFan_spark_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
|
||||
</artifact>
|
||||
</artifacts>
|
@ -0,0 +1,22 @@
|
||||
<?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="smartFan_mqtt_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
|
||||
<file>smartFan_mqtt_receiver.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,32 @@
|
||||
<?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="smartFan-mqtt" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
|
||||
<from eventAdapterType="oauth-mqtt">
|
||||
<property name="topic">carbon.super/doormanager/+/smartFan</property>
|
||||
<property name="username">admin</property>
|
||||
<property name="contentValidatorParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:2</property>
|
||||
<property name="contentValidator">org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTContentValidator</property>
|
||||
<property name="contentTransformer">default</property>
|
||||
<property name="dcrUrl">https://localhost:${carbon.https.port}/dynamic-client-web/register</property>
|
||||
<property name="url">tcp://${mqtt.broker.host}:${mqtt.broker.port}</property>
|
||||
<property name="cleanSession">true</property>
|
||||
</from>
|
||||
<mapping customMapping="disable" type="json"/>
|
||||
<to streamName="org.wso2.iot.devices.smartFan" version="1.0.0"/>
|
||||
</eventReceiver>
|
@ -0,0 +1,22 @@
|
||||
<?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="smartFan_publisher" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
|
||||
<file>smartFan_publisher.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,25 @@
|
||||
<?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.
|
||||
-->
|
||||
|
||||
<eventPublisher name="EventPublisher_smartFan" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
|
||||
<from streamName="org.wso2.iot.devices.smartFan" version="1.0.0"/>
|
||||
<mapping customMapping="disable" type="wso2event"/>
|
||||
<to eventAdapterType="iot-ui"/>
|
||||
</eventPublisher>
|
||||
|
@ -0,0 +1,22 @@
|
||||
<?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="smartFan_spark_script" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
|
||||
<file>smartFan_spark_script.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,28 @@
|
||||
<?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>smartFan_spark_script</Name>
|
||||
<Script>
|
||||
CREATE TEMPORARY TABLE DevicesmartFanData USING CarbonAnalytics OPTIONS(tableName "ORG_WSO2_IOT_DEVICES_smartFan");
|
||||
CREATE TEMPORARY TABLE DevicesmartFanSummaryData USING CarbonAnalytics OPTIONS (tableName "DEVICE_smartFan_SUMMARY", schema "smartFan FLOAT, deviceType STRING -i, deviceId STRING -i, owner STRING -i, time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
|
||||
insert overwrite table DevicesmartFanSummaryData select smartFan, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DevicesmartFanData group by smartFan, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
|
||||
</Script>
|
||||
<CronExpression>0 * * * * ?</CronExpression>
|
||||
</Analytics>
|
@ -0,0 +1,22 @@
|
||||
<?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="smartFan_store" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
|
||||
<file>org_wso2_iot_devices_smartFan.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,62 @@
|
||||
<?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.smartFan: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>smartFan</Name>
|
||||
<EnableIndexing>false</EnableIndexing>
|
||||
<IsPrimaryKey>false</IsPrimaryKey>
|
||||
<EnableScoreParam>false</EnableScoreParam>
|
||||
<Type>FLOAT</Type>
|
||||
</ColumnDefinition>
|
||||
</TableSchema>
|
||||
</EventStoreConfiguration>
|
@ -0,0 +1,23 @@
|
||||
<?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="smartFan_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
|
||||
<file>org.wso2.iot.devices.smartFan_1.0.0.json</file>
|
||||
</artifact>
|
||||
|
@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "org.wso2.iot.devices.smartFan",
|
||||
"version": "1.0.0",
|
||||
"nickName": "smartFan",
|
||||
"description": "smartFan data received from the Device",
|
||||
"metaData": [
|
||||
{"name":"owner","type":"STRING"},
|
||||
{"name":"deviceType","type":"STRING"},
|
||||
{"name":"deviceId","type":"STRING"},
|
||||
{"name":"time","type":"LONG"}
|
||||
],
|
||||
"payloadData": [
|
||||
{
|
||||
"name": "smartFan","type": "FLOAT"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
|
@ -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>
|
@ -0,0 +1,22 @@
|
||||
<?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="smartLock_mqtt_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
|
||||
<file>smartLock_mqtt_receiver.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,32 @@
|
||||
<?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="smartLock-mqtt" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
|
||||
<from eventAdapterType="oauth-mqtt">
|
||||
<property name="topic">carbon.super/doormanager/+/smartLock</property>
|
||||
<property name="username">admin</property>
|
||||
<property name="contentValidatorParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:2</property>
|
||||
<property name="contentValidator">org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTContentValidator</property>
|
||||
<property name="contentTransformer">default</property>
|
||||
<property name="dcrUrl">https://localhost:${carbon.https.port}/dynamic-client-web/register</property>
|
||||
<property name="url">tcp://${mqtt.broker.host}:${mqtt.broker.port}</property>
|
||||
<property name="cleanSession">true</property>
|
||||
</from>
|
||||
<mapping customMapping="disable" type="json"/>
|
||||
<to streamName="org.wso2.iot.devices.smartLock" version="1.0.0"/>
|
||||
</eventReceiver>
|
@ -0,0 +1,22 @@
|
||||
<?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="smartLock_publisher" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
|
||||
<file>smartLock_publisher.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,25 @@
|
||||
<?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.
|
||||
-->
|
||||
|
||||
<eventPublisher name="EventPublisher_smartLock" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
|
||||
<from streamName="org.wso2.iot.devices.smartLock" version="1.0.0"/>
|
||||
<mapping customMapping="disable" type="wso2event"/>
|
||||
<to eventAdapterType="iot-ui"/>
|
||||
</eventPublisher>
|
||||
|
@ -0,0 +1,22 @@
|
||||
<?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="smartLock_spark_script" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
|
||||
<file>smartLock_spark_script.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,28 @@
|
||||
<?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>smartLock_spark_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>
|
@ -0,0 +1,62 @@
|
||||
<?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>
|
@ -0,0 +1,23 @@
|
||||
<?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="smartLock_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
|
||||
<file>org.wso2.iot.devices.smartLock_1.0.0.json</file>
|
||||
</artifact>
|
||||
|
@ -0,0 +1,20 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
|
@ -0,0 +1,142 @@
|
||||
/*
|
||||
* 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.DeviceJSON;
|
||||
import org.homeautomation.doormanager.api.dto.UserInfo;
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Permission;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
|
||||
/**
|
||||
* This is the API which is used to control and manage device type functionality
|
||||
*/
|
||||
@SuppressWarnings("NonJaxWsWebServices")
|
||||
@API(name = "doormanager", version = "1.0.0", context = "/doormanager", tags = "doormanager")
|
||||
@DeviceType(value = "doormanager")
|
||||
public interface DoorManagerService {
|
||||
|
||||
/**
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param state change status of sensor: on/off
|
||||
*/
|
||||
@Path("device/{deviceId}/change-status")
|
||||
@POST
|
||||
@Feature(code = "change-status", name = "Change status of door lock: lock/unlock",
|
||||
description = "Change status of door lock: lock/unlock")
|
||||
Response changeStatusOfDoorLockSafe(@PathParam("deviceId") String deviceId,
|
||||
@QueryParam("state") String state,
|
||||
@Context HttpServletResponse response);
|
||||
|
||||
/**
|
||||
* Retrieve Sensor data for the given time period
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param from starting time
|
||||
* @param to ending time
|
||||
* @return response with List<SensorRecord> object which includes sensor data which is requested
|
||||
*/
|
||||
@Path("device/stats/{deviceId}")
|
||||
@GET
|
||||
@Consumes("application/json")
|
||||
@Produces("application/json")
|
||||
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/stats"})
|
||||
Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
|
||||
@QueryParam("to") long to, @QueryParam("sensorType") String sensorType);
|
||||
|
||||
/**
|
||||
* Remove device type instance using device id
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
*/
|
||||
@Path("/device/{device_id}")
|
||||
@DELETE
|
||||
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/removeDevice"})
|
||||
Response removeDevice(@PathParam("device_id") String deviceId);
|
||||
|
||||
/**
|
||||
* Update device instance name
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param name new name for the device type instance
|
||||
*/
|
||||
@Path("/device/{device_id}")
|
||||
@PUT
|
||||
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
|
||||
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
|
||||
|
||||
/**
|
||||
* To get device information
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @return Device object which carries all information related to a managed device
|
||||
*/
|
||||
@Path("/device/{device_id}")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
|
||||
Response getDevice(@PathParam("device_id") String deviceId);
|
||||
|
||||
/**
|
||||
* Get all device type instance which belongs to user
|
||||
* @return Array of devices which includes device's information
|
||||
*/
|
||||
@Path("/devices")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/devices"})
|
||||
Response getAllDevices();
|
||||
|
||||
/**
|
||||
* To download device type agent source code as zip file
|
||||
* @param deviceName name for the device type instance
|
||||
* @param sketchType folder name where device type agent was installed into server
|
||||
* @return Agent source code as zip file
|
||||
*/
|
||||
@Path("/device/download")
|
||||
@GET
|
||||
@Produces("application/zip")
|
||||
@Permission(scope = "doormanager_user", permissions = {"/permission/admin/device-mgt/download"})
|
||||
Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType);
|
||||
|
||||
@Path("device/assign-user/{deviceId}")
|
||||
@POST
|
||||
@Feature(code = "assign-user", name = "Assign new user to lock",
|
||||
description = "Add new access card to user to control the lock ")
|
||||
Response assignUserToLock(@QueryParam("cardNumber") String cardNumber,
|
||||
@QueryParam("userName") String userName,
|
||||
@QueryParam("emailAddress") String emailAddress,
|
||||
@PathParam("deviceId") String deviceId);
|
||||
|
||||
/**
|
||||
* @param userInfo user information which are required to test given user is authorized to open requested door
|
||||
* @return if user is authorized open the the door allow to open it
|
||||
*/
|
||||
@POST
|
||||
@Path("/device/is-user-authorized")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
Response isUserAuthorized(final UserInfo userInfo);
|
||||
}
|
@ -0,0 +1,629 @@
|
||||
/*
|
||||
* 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.dto.SensorRecord;
|
||||
import org.homeautomation.doormanager.api.dto.UserInfo;
|
||||
import org.homeautomation.doormanager.api.util.APIUtil;
|
||||
import org.homeautomation.doormanager.api.util.ZipUtil;
|
||||
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
|
||||
import org.homeautomation.doormanager.plugin.exception.DoorManagerDeviceMgtPluginException;
|
||||
import org.homeautomation.doormanager.plugin.impl.DoorManagerManager;
|
||||
import org.homeautomation.doormanager.plugin.impl.dao.DoorLockSafe;
|
||||
import org.wso2.carbon.analytics.dataservice.commons.SORT;
|
||||
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
|
||||
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
|
||||
import org.wso2.carbon.apimgt.annotations.api.API;
|
||||
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
|
||||
import org.wso2.carbon.apimgt.application.extension.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.common.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
|
||||
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
|
||||
import org.wso2.carbon.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.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
|
||||
/**
|
||||
* This is the API which is used to control and manage device type functionality
|
||||
*/
|
||||
@SuppressWarnings("NonJaxWsWebServices")
|
||||
@API(name = "doormanager", version = "1.0.0", context = "/doormanager", tags = "doormanager")
|
||||
@DeviceType(value = "doormanager")
|
||||
public class DoorManagerServiceImpl implements DoorManagerService {
|
||||
|
||||
private static final String KEY_TYPE = "PRODUCTION";
|
||||
private static Log log = LogFactory.getLog(DoorManagerService.class);
|
||||
private static volatile ApiApplicationKey apiApplicationKey;
|
||||
private DoorManagerManager doorManagerManager;
|
||||
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);
|
||||
}
|
||||
|
||||
DoorManagerServiceImpl(){
|
||||
doorManagerManager = new DoorManagerManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param state change status of sensor: on/off
|
||||
*/
|
||||
@Path("device/change-locker-status/{deviceId}")
|
||||
@POST
|
||||
@Feature(code = "change-locker-status", name = "Change status of door lock: lock/unlock",
|
||||
description = "Change status of door lock: lock/unlock")
|
||||
public Response changeStatusOfDoorLockSafe(@PathParam("deviceId") String deviceId,
|
||||
@QueryParam("state") String state,
|
||||
@Context HttpServletResponse response) {
|
||||
try {
|
||||
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
|
||||
DoorManagerConstants.DEVICE_TYPE))) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
String sensorState = state.toUpperCase();
|
||||
if (!sensorState.equals(DoorManagerConstants.STATE_LOCK) && !sensorState.equals(
|
||||
DoorManagerConstants.STATE_UNLOCK)) {
|
||||
log.error("The requested state change should be either - 'lock' or 'unlock'");
|
||||
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
|
||||
}
|
||||
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
|
||||
+ "/" + DoorManagerConstants.DEVICE_TYPE + "/" + deviceId + DoorManagerConstants.MQTT_TOPIC_FOR_LOCK;
|
||||
Operation commandOp = new CommandOperation();
|
||||
commandOp.setCode("change-locker-status");
|
||||
commandOp.setType(Operation.Type.COMMAND);
|
||||
commandOp.setEnabled(true);
|
||||
commandOp.setPayLoad(sensorState);
|
||||
Properties props = new Properties();
|
||||
props.setProperty(DoorManagerConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
|
||||
commandOp.setProperties(props);
|
||||
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
|
||||
deviceIdentifiers.add(new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE));
|
||||
APIUtil.getDeviceManagementService().addOperation(DoorManagerConstants.DEVICE_TYPE, commandOp, deviceIdentifiers);
|
||||
return Response.ok().build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (OperationManagementException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param currentValue change voltage
|
||||
*/
|
||||
@Path("device/change-light-intensity/{deviceId}")
|
||||
@POST
|
||||
@Feature(code = "change-light-intensity", name = "Change bulb intensity",
|
||||
description = "Change status of door lock: lock/unlock")
|
||||
public Response changeLightIntensity(@PathParam("deviceId") String deviceId,
|
||||
@QueryParam("currentValue") String currentValue,
|
||||
@Context HttpServletResponse response) {
|
||||
try {
|
||||
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
|
||||
DoorManagerConstants.DEVICE_TYPE))) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
|
||||
+ "/" + DoorManagerConstants.DEVICE_TYPE + "/" + deviceId + DoorManagerConstants.MQTT_TOPIC_FOR_BULB;
|
||||
Operation commandOp = new CommandOperation();
|
||||
commandOp.setCode("change-light-intensity");
|
||||
commandOp.setType(Operation.Type.COMMAND);
|
||||
commandOp.setEnabled(true);
|
||||
commandOp.setPayLoad(currentValue);
|
||||
Properties props = new Properties();
|
||||
props.setProperty(DoorManagerConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
|
||||
commandOp.setProperties(props);
|
||||
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
|
||||
deviceIdentifiers.add(new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE));
|
||||
APIUtil.getDeviceManagementService().addOperation(DoorManagerConstants.DEVICE_TYPE, commandOp, deviceIdentifiers);
|
||||
return Response.ok().build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (OperationManagementException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param state change status of sensor: on/off
|
||||
*/
|
||||
@Path("device/change-fan-status/{deviceId}")
|
||||
@POST
|
||||
@Feature(code = "change-fan-state", name = "Change status of door lock: lock/unlock",
|
||||
description = "Change status of door lock: lock/unlock")
|
||||
public Response changeFanState(@PathParam("deviceId") String deviceId,
|
||||
@QueryParam("state") String state,
|
||||
@Context HttpServletResponse response) {
|
||||
try {
|
||||
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
|
||||
DoorManagerConstants.DEVICE_TYPE))) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
String sensorState = state.toUpperCase();
|
||||
if (!sensorState.equals(DoorManagerConstants.STATE_BULB_ON) && !sensorState.equals(DoorManagerConstants.STATE_BULB_OFF)){
|
||||
log.error("The requested state change should be either - 'ON' or 'OFF'");
|
||||
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
|
||||
}
|
||||
|
||||
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
|
||||
+ "/" + DoorManagerConstants.DEVICE_TYPE + "/" + deviceId + DoorManagerConstants.MQTT_TOPIC_FOR_FAN;
|
||||
Operation commandOp = new CommandOperation();
|
||||
commandOp.setCode("change-fan-state");
|
||||
commandOp.setType(Operation.Type.COMMAND);
|
||||
commandOp.setEnabled(true);
|
||||
commandOp.setPayLoad(sensorState);
|
||||
Properties props = new Properties();
|
||||
props.setProperty(DoorManagerConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
|
||||
commandOp.setProperties(props);
|
||||
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
|
||||
deviceIdentifiers.add(new DeviceIdentifier(deviceId, DoorManagerConstants.DEVICE_TYPE));
|
||||
APIUtil.getDeviceManagementService().addOperation(DoorManagerConstants.DEVICE_TYPE, commandOp, deviceIdentifiers);
|
||||
return Response.ok().build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (OperationManagementException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Path("device/assign-user/{deviceId}")
|
||||
@POST
|
||||
@Feature(code = "assign-user", name = "Assign new user to lock",
|
||||
description = "Add new access card to user to control the lock ")
|
||||
public Response assignUserToLock(@QueryParam("cardNumber") String cardNumber,
|
||||
@QueryParam("userName") String userName,
|
||||
@QueryParam("emailAddress") String emailAddress,
|
||||
@PathParam("deviceId") String deviceId) {
|
||||
try {
|
||||
if (userName != null && cardNumber != null) {
|
||||
UserStoreManager userStoreManager = APIUtil.getUserStoreManager();
|
||||
DoorLockSafe doorLockSafe = new DoorLockSafe();
|
||||
String applicationUsername = null;
|
||||
if (userStoreManager.isExistingUser(userName)) {
|
||||
if (apiApplicationKey == null) {
|
||||
applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
|
||||
.getRealmConfiguration().getAdminUserName();
|
||||
applicationUsername = applicationUsername + "@" + APIUtil.getAuthenticatedUserTenantDomain();
|
||||
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 = DoorManagerConstants.DEVICE_SCOPE_INFO_DEVICE_TYPE
|
||||
+ DoorManagerConstants.DEVICE_TYPE + DoorManagerConstants.DEVICE_SCOPE_INFO_DEVICE_ID
|
||||
+ deviceId;
|
||||
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
|
||||
apiApplicationKey.getConsumerSecret(), APIUtil.getAuthenticatedUser() + "@"
|
||||
+ APIUtil.getAuthenticatedUserTenantDomain(), scopes);
|
||||
String accessToken = accessTokenInfo.getAccessToken();
|
||||
if (accessToken == null) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
doorLockSafe.setAccessToken(accessTokenInfo.getAccessToken());
|
||||
doorLockSafe.setRefreshToken(accessTokenInfo.getRefreshToken());
|
||||
doorLockSafe.setDeviceId(deviceId);
|
||||
doorLockSafe.setOwner(applicationUsername);
|
||||
doorLockSafe.setEmailAddress(emailAddress);
|
||||
doorLockSafe.setUIDofUser(cardNumber);
|
||||
doorLockSafe.setSerialNumber(deviceId);
|
||||
//DoorManagerManager doorManager = APIUtil.getDoorManagerManagerService();
|
||||
if (doorManagerManager.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();
|
||||
}
|
||||
} else {
|
||||
return Response.status(Response.Status.BAD_REQUEST.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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Retrieve Sensor data for the given time period
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param from starting time
|
||||
* @param to ending time
|
||||
* @return response with List<SensorRecord> object which includes sensor data which is requested
|
||||
*/
|
||||
@Path("device/stats/{deviceId}")
|
||||
@GET
|
||||
@Consumes("application/json")
|
||||
@Produces("application/json")
|
||||
public Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
|
||||
@QueryParam("to") long to, @QueryParam("sensorType") String sensorType) {
|
||||
String fromDate = String.valueOf(from);
|
||||
String toDate = String.valueOf(to);
|
||||
String query = DoorManagerConstants.DEVICE_META_INFO_DEVICE_ID + deviceId + " AND " + DoorManagerConstants.DEVICE_META_INFO_DEVICE_TYPE +
|
||||
DoorManagerConstants.DEVICE_TYPE + " AND "+ DoorManagerConstants.DEVICE_META_INFO_TIME +" : [" + fromDate + " TO " + toDate + "]";
|
||||
String sensorTableName = null;
|
||||
if(sensorType.equals(DoorManagerConstants.SENSOR_TYPE1)){
|
||||
sensorTableName = DoorManagerConstants.SENSOR_TYPE1_EVENT_TABLE;
|
||||
}else if(sensorType.equals(DoorManagerConstants.SENSOR_TYPE2)){
|
||||
sensorTableName = DoorManagerConstants.SENSOR_TYPE2_EVENT_TABLE;
|
||||
}
|
||||
try {
|
||||
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
|
||||
DoorManagerConstants.DEVICE_TYPE))) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
if (sensorTableName != null) {
|
||||
List<SortByField> sortByFields = new ArrayList<>();
|
||||
SortByField sortByField = new SortByField(DoorManagerConstants.DEVICE_META_INFO_TIME, SORT.ASC, false);
|
||||
sortByFields.add(sortByField);
|
||||
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
|
||||
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
|
||||
}
|
||||
} catch (AnalyticsException e) {
|
||||
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
|
||||
log.error(errorMsg);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove device type instance using device id
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
*/
|
||||
@Path("/device/{deviceId}")
|
||||
@DELETE
|
||||
public Response removeDevice(@PathParam("deviceId") String deviceId) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
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) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update device instance name
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param name new name for the device type instance
|
||||
*/
|
||||
@Path("/device/{deviceId}")
|
||||
@PUT
|
||||
public Response updateDevice(@PathParam("deviceId") String deviceId, @QueryParam("name") String name) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
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) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* To get device information
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @return return Device object which carries all information related to a managed device
|
||||
*/
|
||||
@Path("/device/{deviceId}")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getDevice(@PathParam("deviceId") String deviceId) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
return Response.ok().entity(device).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all device type instance which belongs to user
|
||||
* @return Array of devices which includes device's information
|
||||
*/
|
||||
@Path("/devices")
|
||||
@GET
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response getAllDevices() {
|
||||
try {
|
||||
List<Device> userDevices =
|
||||
APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser());
|
||||
ArrayList<Device> deviceList = new ArrayList<>();
|
||||
for (Device device : userDevices) {
|
||||
if (device.getType().equals(DoorManagerConstants.DEVICE_TYPE) &&
|
||||
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
|
||||
deviceList.add(device);
|
||||
}
|
||||
}
|
||||
Device[] devices = deviceList.toArray(new Device[]{});
|
||||
return Response.ok().entity(devices).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* To download device type agent source code as zip file
|
||||
* @param deviceName name for the device type instance
|
||||
* @param sketchType folder name where device type agent was installed into server
|
||||
* @return Agent source code as zip file
|
||||
*/
|
||||
@Path("/device/download")
|
||||
@GET
|
||||
@Produces("application/zip")
|
||||
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
|
||||
@QueryParam("sketchType") String sketchType) {
|
||||
try {
|
||||
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
|
||||
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
|
||||
response.status(Response.Status.OK);
|
||||
response.type("application/zip");
|
||||
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
|
||||
Response requestedFile = response.build();
|
||||
File file = zipFile.getZipFile();
|
||||
if (!file.delete()) {
|
||||
String message = file.exists() ? "is in use by another process" : "does not exist " + sketchType;
|
||||
throw new IOException("Cannot delete file, because file " + message + ".");
|
||||
} else {
|
||||
return requestedFile;
|
||||
}
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
|
||||
} catch (DeviceManagementException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
|
||||
} catch (JWTClientException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
|
||||
} catch (APIManagerException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
|
||||
} catch (IOException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
|
||||
} catch (UserStoreException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register device into device management service
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param name name for the device type instance
|
||||
* @return check whether device is installed into cdmf
|
||||
*/
|
||||
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);
|
||||
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
|
||||
device.setName(name);
|
||||
device.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
|
||||
if (added) {
|
||||
APIUtil.registerApiAccessRoles(APIUtil.getAuthenticatedUser());
|
||||
}
|
||||
return added;
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
|
||||
throws DeviceManagementException, JWTClientException, APIManagerException,
|
||||
UserStoreException {
|
||||
//create new device id
|
||||
String deviceId = shortUUID();
|
||||
if (apiApplicationKey == null) {
|
||||
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
|
||||
.getRealmConfiguration().getAdminUserName();
|
||||
applicationUsername = applicationUsername + "@" + APIUtil.getAuthenticatedUserTenantDomain();
|
||||
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 = DoorManagerConstants.DEVICE_SCOPE_INFO_DEVICE_TYPE
|
||||
+ DoorManagerConstants.DEVICE_TYPE + DoorManagerConstants.DEVICE_SCOPE_INFO_DEVICE_ID
|
||||
+ deviceId;
|
||||
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
|
||||
apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(), scopes);
|
||||
String accessToken = accessTokenInfo.getAccessToken();
|
||||
String refreshToken = accessTokenInfo.getRefreshToken();
|
||||
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();
|
||||
return ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
|
||||
deviceId, deviceName, accessToken, refreshToken, apiApplicationKey.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param userInfo user information which are required to test given user is authorized to open requested door
|
||||
* @return if user is authorized open the the door allow to open it
|
||||
*/
|
||||
@POST
|
||||
@Path("/device/is-user-authorized")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@SuppressWarnings("unchecked") //This is to avoid unchecked call to put(k, v) into jsonObject. org.json.simple
|
||||
// library uses raw type collections internally.
|
||||
public Response isUserAuthorized(final UserInfo userInfo) {
|
||||
if (userInfo.cardNumber != null && userInfo.deviceId != null) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(userInfo.deviceId);
|
||||
deviceIdentifier.setType(DoorManagerConstants.DEVICE_TYPE);
|
||||
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
if (doorManagerManager.checkCardDoorAssociation(userInfo.cardNumber, userInfo.deviceId)) {
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} else {
|
||||
return Response.status(Response.Status.UNAUTHORIZED).build();
|
||||
}
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED).build();
|
||||
} catch (DoorManagerDeviceMgtPluginException e) {
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
}
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
|
||||
|
||||
/* private void sendCEPEvent(String deviceId, String cardId, boolean accessStatus){
|
||||
String cepEventReciever = "http://localhost:9768/endpoints/LockEventReciever";
|
||||
|
||||
HttpClient httpClient = new SystemDefaultHttpClient();
|
||||
HttpPost method = new HttpPost(cepEventReciever);
|
||||
JsonObject event = new JsonObject();
|
||||
JsonObject metaData = new JsonObject();
|
||||
|
||||
metaData.addProperty("deviceID", deviceId);
|
||||
metaData.addProperty("cardID", cardId);
|
||||
|
||||
event.add("metaData", metaData);
|
||||
|
||||
String eventString = "{\"event\": " + event + "}";
|
||||
|
||||
try {
|
||||
StringEntity entity = new StringEntity(eventString);
|
||||
method.setEntity(entity);
|
||||
if (cepEventReciever.startsWith("https")) {
|
||||
method.setHeader("Authorization", "Basic " + Base64.encode(("admin" + ":" + "admin").getBytes()));
|
||||
}
|
||||
httpClient.execute(method).getEntity().getContent().close();
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
log.error("Error while constituting CEP event"+ e.getMessage());
|
||||
} catch (ClientProtocolException e) {
|
||||
log.error("Error while sending message to CEP "+ e.getMessage());
|
||||
} catch (IOException e) {
|
||||
log.error("Error while sending message to CEP "+ e.getMessage());
|
||||
}
|
||||
}*/
|
||||
}
|
@ -0,0 +1,88 @@
|
||||
/*
|
||||
* 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.dto;
|
||||
|
||||
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
|
||||
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlElementWrapper;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* This stores sensor event data for doormanager.
|
||||
*/
|
||||
@XmlRootElement
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class SensorRecord {
|
||||
|
||||
@XmlElementWrapper(required = true, name = "values")
|
||||
private Map<String, Object> values;
|
||||
|
||||
/**
|
||||
* Unique identifier for each recode
|
||||
*/
|
||||
@XmlElement(required = false, name = "id")
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* Gets the values.
|
||||
* @return the values
|
||||
*/
|
||||
public Map<String, Object> getValues() {
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the values.
|
||||
* @param values set corresponding values
|
||||
*/
|
||||
public void setValues(Map<String, Object> values) {
|
||||
this.values = values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the id.
|
||||
* @return the id
|
||||
*/
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the id.
|
||||
* @param id set unique identifier
|
||||
*/
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
List<String> valueList = new ArrayList<>();
|
||||
for (Map.Entry<String, Object> entry : values.entrySet()) {
|
||||
valueList.add(entry.getKey() + ":" + entry.getValue());
|
||||
}
|
||||
return valueList.toString();
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,271 @@
|
||||
/*
|
||||
* 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.api.dto.SensorRecord;
|
||||
import org.homeautomation.doormanager.plugin.impl.DoorManagerManager;
|
||||
import org.homeautomation.doormanager.plugin.impl.DoorManagerManagerService;
|
||||
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
|
||||
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
|
||||
import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry;
|
||||
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
|
||||
import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils;
|
||||
import org.wso2.carbon.analytics.datasource.commons.Record;
|
||||
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
|
||||
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
|
||||
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
|
||||
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.user.api.UserStoreManager;
|
||||
import org.wso2.carbon.user.core.Permission;
|
||||
import org.wso2.carbon.user.core.service.RealmService;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* This class provides utility functions used by REST-API.
|
||||
*/
|
||||
public class APIUtil {
|
||||
|
||||
private static Log log = LogFactory.getLog(APIUtil.class);
|
||||
|
||||
public static String getAuthenticatedUser() {
|
||||
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
String username = threadLocalCarbonContext.getUsername();
|
||||
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
|
||||
if (username.endsWith(tenantDomain)) {
|
||||
return username.substring(0, username.lastIndexOf("@"));
|
||||
}
|
||||
return username;
|
||||
}
|
||||
|
||||
public static DeviceManagementProviderService getDeviceManagementService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
DeviceManagementProviderService deviceManagementProviderService =
|
||||
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
|
||||
if (deviceManagementProviderService == null) {
|
||||
String msg = "Device Management service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return deviceManagementProviderService;
|
||||
}
|
||||
|
||||
public static APIManagementProviderService getAPIManagementProviderService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
APIManagementProviderService apiManagementProviderService =
|
||||
(APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null);
|
||||
if (apiManagementProviderService == null) {
|
||||
String msg = "API management provider service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return apiManagementProviderService;
|
||||
}
|
||||
|
||||
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.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return jwtClientManagerService;
|
||||
}
|
||||
|
||||
public static String getTenantDomainOftheUser() {
|
||||
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
return threadLocalCarbonContext.getTenantDomain();
|
||||
}
|
||||
|
||||
public static UserStoreManager getUserStoreManager() {
|
||||
RealmService realmService;
|
||||
UserStoreManager userStoreManager;
|
||||
try {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
|
||||
if (realmService == null) {
|
||||
String msg = "Realm service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
int tenantId = ctx.getTenantId();
|
||||
userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
|
||||
} catch (UserStoreException e) {
|
||||
String msg = "Error occurred while retrieving current user store manager";
|
||||
log.error(msg, e);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return userStoreManager;
|
||||
}
|
||||
|
||||
public static void registerApiAccessRoles(String user) {
|
||||
UserStoreManager userStoreManager;
|
||||
try {
|
||||
userStoreManager = getUserStoreManager();
|
||||
String[] userList = new String[]{user};
|
||||
if (userStoreManager != null) {
|
||||
String rolesOfUser[] = userStoreManager.getRoleListOfUser(user);
|
||||
if (!userStoreManager.isExistingRole(DoorManagerUtilConstants.DEFAULT_ROLE_NAME)) {
|
||||
userStoreManager.addRole(DoorManagerUtilConstants.DEFAULT_ROLE_NAME, userList, getDefaultPermissions());
|
||||
} else if (rolesOfUser == null) {
|
||||
userStoreManager.updateUserListOfRole(DoorManagerUtilConstants.DEFAULT_ROLE_NAME, new String[0], userList);
|
||||
}
|
||||
}
|
||||
} catch (UserStoreException e) {
|
||||
log.error("Error while creating a role and adding a user for virtual_firealarm.", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
|
||||
(DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null);
|
||||
if (deviceAccessAuthorizationService == null) {
|
||||
String msg = "Device Authorization service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return deviceAccessAuthorizationService;
|
||||
}
|
||||
|
||||
public static List<SensorRecord> getAllEventsForDevice(String tableName, String query,
|
||||
List<SortByField> sortByFields) throws AnalyticsException {
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI();
|
||||
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
|
||||
if (eventCount == 0) {
|
||||
return null;
|
||||
}
|
||||
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount,
|
||||
sortByFields);
|
||||
List<String> recordIds = getRecordIds(resultEntries);
|
||||
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
|
||||
Map<String, SensorRecord> sensorDatas = createSensorData(AnalyticsDataServiceUtils.listRecords(
|
||||
analyticsDataAPI, response));
|
||||
return getSortedSensorData(sensorDatas, resultEntries);
|
||||
}
|
||||
|
||||
public static List<SensorRecord> getSortedSensorData(Map<String, SensorRecord> sensorDatas,
|
||||
List<SearchResultEntry> searchResults) {
|
||||
List<SensorRecord> sortedRecords = new ArrayList<>();
|
||||
for (SearchResultEntry searchResultEntry : searchResults) {
|
||||
sortedRecords.add(sensorDatas.get(searchResultEntry.getId()));
|
||||
}
|
||||
return sortedRecords;
|
||||
}
|
||||
|
||||
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (SearchResultEntry searchResult : searchResults) {
|
||||
ids.add(searchResult.getId());
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
public static Map<String, SensorRecord> createSensorData(List<Record> records) {
|
||||
Map<String, SensorRecord> sensorDatas = new HashMap<>();
|
||||
for (Record record : records) {
|
||||
SensorRecord sensorData = createSensorData(record);
|
||||
sensorDatas.put(sensorData.getId(), sensorData);
|
||||
}
|
||||
return sensorDatas;
|
||||
}
|
||||
|
||||
public static SensorRecord createSensorData(Record record) {
|
||||
SensorRecord recordBean = new SensorRecord();
|
||||
recordBean.setId(record.getId());
|
||||
recordBean.setValues(record.getValues());
|
||||
return recordBean;
|
||||
}
|
||||
|
||||
public static AnalyticsDataAPI getAnalyticsDataAPI() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
AnalyticsDataAPI analyticsDataAPI =
|
||||
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
|
||||
if (analyticsDataAPI == null) {
|
||||
String msg = "Analytics api service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return analyticsDataAPI;
|
||||
}
|
||||
|
||||
public static String getAuthenticatedUserTenantDomain() {
|
||||
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
return threadLocalCarbonContext.getTenantDomain();
|
||||
}
|
||||
|
||||
public static OutputEventAdapterService getOutputEventAdapterService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
OutputEventAdapterService outputEventAdapterService =
|
||||
(OutputEventAdapterService) ctx.getOSGiService(OutputEventAdapterService.class, null);
|
||||
if (outputEventAdapterService == null) {
|
||||
String msg = "Device Authorization service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return outputEventAdapterService;
|
||||
}
|
||||
|
||||
public static Permission[] getDefaultPermissions() {
|
||||
return new Permission[]{new org.wso2.carbon.user.core
|
||||
.Permission(DoorManagerUtilConstants.DEFAULT_PERMISSION_RESOURCE, "ui.execute")};
|
||||
}
|
||||
|
||||
public static PlatformConfigurationManagementService getTenantConfigurationManagementService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
PlatformConfigurationManagementService tenantConfigurationManagementService =
|
||||
(PlatformConfigurationManagementService) ctx.getOSGiService(PlatformConfigurationManagementService.class, null);
|
||||
if (tenantConfigurationManagementService == null) {
|
||||
String msg = "Tenant configuration Management service not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return tenantConfigurationManagementService;
|
||||
}
|
||||
|
||||
public static DoorManagerManager getDoorManagerManagerService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
DeviceManagementService deviceManagementProviderService =
|
||||
(DeviceManagementService) ctx.getOSGiService(DoorManagerManagerService.class, null);
|
||||
if (deviceManagementProviderService == null) {
|
||||
String msg = "Device Management service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
|
||||
DoorManagerManager doorManagerManager = (DoorManagerManager)deviceManagementProviderService.getDeviceManager();
|
||||
|
||||
return doorManagerManager;
|
||||
}
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* This hold the constants related to the device type.
|
||||
*/
|
||||
public class DoorManagerUtilConstants {
|
||||
|
||||
public static final String DEFAULT_PERMISSION_RESOURCE = "/permission/admin/device-mgt/doormanager/user";
|
||||
public static final String DEFAULT_ROLE_NAME = "doormanager_user";
|
||||
public final static String APPLICATION_ZIP = "application/zip";
|
||||
public final static String CONTENT_DISPOSITION = "Content-Disposition";
|
||||
public final static String ATTACHMENT_FILENAME = "attachment; filename=\"";
|
||||
public static final String TENANT_DOMAIN = "TENANT_DOMAIN";
|
||||
public static final String DEVICE_OWNER = "DEVICE_OWNER";
|
||||
public static final String DEVICE_ID = "DEVICE_ID";
|
||||
public static final String DEVICE_NAME = "DEVICE_NAME";
|
||||
public static final String HTTPS_EP = "HTTPS_EP";
|
||||
public static final String HTTP_EP = "HTTP_EP";
|
||||
public static final String APIM_EP = "APIM_EP";
|
||||
public static final String MQTT_EP = "MQTT_EP";
|
||||
public static final String XMPP_EP = "XMPP_EP";
|
||||
public static final String DOORMANAGER_HTTPS_EP = "DOORMANAGER_HTTPS_EP";
|
||||
public static final String DOORMANAGER_HTTP_EP = "DOORMANAGER_HTTP_EP";
|
||||
public static final String DOORMANAGER_APIM_EP = "DOORMANAGER_APIM_EP";
|
||||
public static final String DOORMANAGER_MQTT_EP = "DOORMANAGER_MQTT_EP";
|
||||
public static final String DOORMANAGER_XMPP_EP = "DOORMANAGER_XMPP_EP";
|
||||
public static final String API_APPLICATION_KEY = "API_APPLICATION_KEY";
|
||||
public static final String DEVICE_TOKEN = "DEVICE_TOKEN";
|
||||
public static final String DEVICE_REFRESH_TOKEN = "DEVICE_REFRESH_TOKEN";
|
||||
public static final String SERVER_NAME = "SERVER_NAME";
|
||||
public static final String SERVER_JID = "SERVER_JID";
|
||||
}
|
@ -0,0 +1,123 @@
|
||||
/*
|
||||
* 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.codec.binary.Base64;
|
||||
import org.json.JSONObject;
|
||||
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
|
||||
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
|
||||
import org.wso2.carbon.device.mgt.iot.util.Utils;
|
||||
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* This is used to create a zip file that includes the necessary configuration required for the agent.
|
||||
*/
|
||||
public class ZipUtil {
|
||||
|
||||
private static final String HTTPS_PORT_PROPERTY = "httpsPort";
|
||||
private static final String HTTP_PORT_PROPERTY = "httpPort";
|
||||
|
||||
private static final String LOCALHOST = "localhost";
|
||||
private static final String HTTPS_PROTOCOL_APPENDER = "https://";
|
||||
private static final String HTTP_PROTOCOL_APPENDER = "http://";
|
||||
private static final String CONFIG_TYPE = "general";
|
||||
private static final String DEFAULT_MQTT_ENDPOINT = "tcp://localhost:1883";
|
||||
|
||||
public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType,
|
||||
String deviceId, String deviceName, String token,
|
||||
String refreshToken, String apiApplicationKey) throws DeviceManagementException {
|
||||
|
||||
String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches";
|
||||
String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" +
|
||||
File.separator + deviceId;
|
||||
String templateSketchPath = sketchFolder + File.separator + deviceType;
|
||||
String iotServerIP;
|
||||
try {
|
||||
iotServerIP = Utils.getServerUrl();
|
||||
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
|
||||
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
|
||||
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
|
||||
String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort;
|
||||
String mqttEndpoint = DEFAULT_MQTT_ENDPOINT;
|
||||
if (mqttEndpoint.contains(LOCALHOST)) {
|
||||
mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
|
||||
}
|
||||
|
||||
PlatformConfiguration configuration = APIUtil.getTenantConfigurationManagementService().getConfiguration(
|
||||
CONFIG_TYPE);
|
||||
if (configuration != null && configuration.getConfiguration() != null && configuration
|
||||
.getConfiguration().size() > 0) {
|
||||
List<ConfigurationEntry> configurations = configuration.getConfiguration();
|
||||
for (ConfigurationEntry configurationEntry : configurations) {
|
||||
switch (configurationEntry.getName()) {
|
||||
case DoorManagerUtilConstants.DOORMANAGER_HTTPS_EP:
|
||||
httpsServerEP = (String)configurationEntry.getValue();
|
||||
break;
|
||||
case DoorManagerUtilConstants.DOORMANAGER_HTTP_EP:
|
||||
httpServerEP = (String)configurationEntry.getValue();
|
||||
break;
|
||||
case DoorManagerUtilConstants.DOORMANAGER_MQTT_EP:
|
||||
mqttEndpoint = (String)configurationEntry.getValue();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
String base64EncodedApplicationKey = getBase64EncodedAPIAppKey(apiApplicationKey).trim();
|
||||
|
||||
Map<String, String> contextParams = new HashMap<>();
|
||||
contextParams.put(DoorManagerUtilConstants.TENANT_DOMAIN, APIUtil.getTenantDomainOftheUser());
|
||||
contextParams.put(DoorManagerUtilConstants.DEVICE_OWNER, owner);
|
||||
contextParams.put(DoorManagerUtilConstants.DEVICE_ID, deviceId);
|
||||
contextParams.put(DoorManagerUtilConstants.DEVICE_NAME, deviceName);
|
||||
contextParams.put(DoorManagerUtilConstants.HTTPS_EP, httpsServerEP);
|
||||
contextParams.put(DoorManagerUtilConstants.HTTP_EP, httpServerEP);
|
||||
contextParams.put(DoorManagerUtilConstants.APIM_EP, httpServerEP);
|
||||
contextParams.put(DoorManagerUtilConstants.MQTT_EP, mqttEndpoint);
|
||||
contextParams.put(DoorManagerUtilConstants.API_APPLICATION_KEY, base64EncodedApplicationKey);
|
||||
contextParams.put(DoorManagerUtilConstants.DEVICE_TOKEN, token);
|
||||
contextParams.put(DoorManagerUtilConstants.DEVICE_REFRESH_TOKEN, refreshToken);
|
||||
ZipArchive zipFile;
|
||||
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
|
||||
return zipFile;
|
||||
} catch (IOException e) {
|
||||
throw new DeviceManagementException("Zip File Creation Failed", e);
|
||||
} catch (ConfigurationManagementException e) {
|
||||
throw new DeviceManagementException("Failed to retrieve configuration", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String getBase64EncodedAPIAppKey(String apiAppCredentialsAsJSONString) {
|
||||
|
||||
JSONObject jsonObject = new JSONObject(apiAppCredentialsAsJSONString);
|
||||
String consumerKey = jsonObject.get(ApiApplicationConstants.OAUTH_CLIENT_ID).toString();
|
||||
String consumerSecret = jsonObject.get(ApiApplicationConstants.OAUTH_CLIENT_SECRET).toString();
|
||||
String stringToEncode = consumerKey + ":" + consumerSecret;
|
||||
return Base64.encodeBase64String(stringToEncode.getBytes());
|
||||
}
|
||||
}
|
@ -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,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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,91 @@
|
||||
/*
|
||||
* 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.homeautomation.doormanager.plugin.internal.DoorManagerManagementDataHolder;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManager;
|
||||
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
|
||||
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
|
||||
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class DoorManagerManagerService implements DeviceManagementService {
|
||||
private DeviceManager deviceManager;
|
||||
private PushNotificationConfig pushNotificationConfig;
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return DoorManagerConstants.DEVICE_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init() throws DeviceManagementException {
|
||||
this.deviceManager = new DoorManagerManager();
|
||||
this.pushNotificationConfig = this.populatePushNotificationConfig();
|
||||
|
||||
}
|
||||
|
||||
private PushNotificationConfig populatePushNotificationConfig() {
|
||||
DeviceManagementConfiguration deviceManagementConfiguration = DoorManagerManagementDataHolder.getInstance()
|
||||
.getDeviceTypeConfigService().getConfiguration(DoorManagerConstants.DEVICE_TYPE,
|
||||
DoorManagerConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
|
||||
org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig sourceConfig =
|
||||
deviceManagementConfiguration.getPushNotificationConfig();
|
||||
Map<String, String> staticProps = new HashMap<>();
|
||||
for (org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig.Property
|
||||
property : sourceConfig.getProperties()) {
|
||||
staticProps.put(property.getName(), property.getValue());
|
||||
}
|
||||
return new PushNotificationConfig(sourceConfig.getPushNotificationProvider(), staticProps);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public DeviceManager getDeviceManager() {
|
||||
return deviceManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationManager getApplicationManager() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProvisioningConfig getProvisioningConfig() {
|
||||
DeviceManagementConfiguration deviceManagementConfiguration = DoorManagerManagementDataHolder.getInstance()
|
||||
.getDeviceTypeConfigService().getConfiguration(DoorManagerConstants.DEVICE_TYPE,
|
||||
DoorManagerConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
|
||||
boolean sharedWithAllTenants = deviceManagementConfiguration.getDeviceManagementConfigRepository()
|
||||
.getProvisioningConfig().isSharedWithAllTenants();
|
||||
return new ProvisioningConfig(DoorManagerConstants.DEVICE_TYPE_PROVIDER_DOMAIN, sharedWithAllTenants);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public PushNotificationConfig getPushNotificationConfig() {
|
||||
return pushNotificationConfig;
|
||||
}
|
||||
|
||||
}
|
@ -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,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);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
package org.homeautomation.doormanager.plugin.impl.feature;
|
||||
|
||||
import org.homeautomation.doormanager.plugin.constants.DoorManagerConstants;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.Feature;
|
||||
import org.wso2.carbon.device.mgt.common.FeatureManager;
|
||||
import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Device type specific feature management server
|
||||
*/
|
||||
public class DoorManagerFeatureManager implements FeatureManager {
|
||||
@Override
|
||||
public boolean addFeature(Feature feature) throws DeviceManagementException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Feature getFeature(String name) throws DeviceManagementException {
|
||||
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
|
||||
return genericFeatureManager.getFeature(DoorManagerConstants.DEVICE_TYPE, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Feature> getFeatures() throws DeviceManagementException {
|
||||
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
|
||||
return genericFeatureManager.getFeatures(DoorManagerConstants.DEVICE_TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeFeature(String name) throws DeviceManagementException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
|
||||
return false;
|
||||
}
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Provides methods for initializing the database script.
|
||||
*/
|
||||
public class DeviceSchemaInitializer extends DatabaseCreator{
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
|
||||
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
|
||||
+ File.separator + "cdm" + File.separator + "plugins" + File.separator;
|
||||
|
||||
public DeviceSchemaInitializer(DataSource dataSource) {
|
||||
super(dataSource);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getDbScriptLocation(String databaseType) {
|
||||
String scriptName = databaseType + ".sql";
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Loading database script from :" + scriptName);
|
||||
}
|
||||
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
|
||||
}
|
||||
}
|
@ -0,0 +1,103 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
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.internal.DoorManagerManagementDataHolder;
|
||||
import org.wso2.carbon.base.ServerConfiguration;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.core.util.Utils;
|
||||
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
|
||||
import org.wso2.carbon.event.output.adapter.core.MessageType;
|
||||
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
|
||||
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.sql.DataSource;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* Contains utility methods used by doormanager plugin.
|
||||
*/
|
||||
public class DoorManagerUtils {
|
||||
|
||||
private static Log log = LogFactory.getLog(org.homeautomation.doormanager.plugin.impl.util.DoorManagerUtils.class);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public static void setupDeviceManagementSchema() throws DoorManagerDeviceMgtPluginException {
|
||||
DeviceManagementConfiguration deviceManagementConfiguration = DoorManagerManagementDataHolder.getInstance()
|
||||
.getDeviceTypeConfigService().getConfiguration(DoorManagerConstants.DEVICE_TYPE,
|
||||
DoorManagerConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
|
||||
String datasource = deviceManagementConfiguration.getDeviceManagementConfigRepository().getDataSourceConfig()
|
||||
.getJndiLookupDefinition().getJndiName();
|
||||
try {
|
||||
Context ctx = new InitialContext();
|
||||
DataSource dataSource = (DataSource) ctx.lookup(datasource);
|
||||
DeviceSchemaInitializer initializer = new DeviceSchemaInitializer(dataSource);
|
||||
log.info("Initializing device management repository database schema");
|
||||
initializer.createRegistryDatabase();
|
||||
} catch (NamingException e) {
|
||||
log.error("Error while looking up the data source: " + datasource, e);
|
||||
} catch (Exception e) {
|
||||
throw new DoorManagerDeviceMgtPluginException("Error occurred while initializing Iot Device " +
|
||||
"Management database schema", e);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
/*
|
||||
* 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.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
|
||||
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
|
||||
|
||||
/**
|
||||
* DataHolder class of doormanager plugins component.
|
||||
*/
|
||||
public class DoorManagerManagementDataHolder {
|
||||
|
||||
private DeviceTypeConfigService deviceTypeConfigService;
|
||||
private static DoorManagerManagementDataHolder thisInstance = new DoorManagerManagementDataHolder();
|
||||
|
||||
|
||||
private DoorManagerManagementDataHolder() {
|
||||
}
|
||||
|
||||
public static DoorManagerManagementDataHolder getInstance() {
|
||||
return thisInstance;
|
||||
}
|
||||
|
||||
public DeviceTypeConfigService getDeviceTypeConfigService() {
|
||||
return deviceTypeConfigService;
|
||||
}
|
||||
|
||||
public void setDeviceTypeConfigService(
|
||||
DeviceTypeConfigService deviceTypeConfigService) {
|
||||
this.deviceTypeConfigService = deviceTypeConfigService;
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,121 @@
|
||||
/*
|
||||
* 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.exception.DoorManagerDeviceMgtPluginException;
|
||||
import org.homeautomation.doormanager.plugin.impl.DoorManagerManagerService;
|
||||
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
|
||||
import org.homeautomation.doormanager.plugin.impl.util.DoorManagerUtils;
|
||||
import org.osgi.framework.BundleContext;
|
||||
import org.osgi.framework.ServiceRegistration;
|
||||
import org.osgi.service.component.ComponentContext;
|
||||
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
|
||||
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
|
||||
import org.wso2.carbon.ndatasource.core.DataSourceService;
|
||||
|
||||
/**
|
||||
* @scr.component name="org.homeautomation.doormanager.plugin.internal.ServiceComponent"
|
||||
* immediate="true"
|
||||
* @scr.reference name="org.wso2.carbon.ndatasource"
|
||||
* interface="org.wso2.carbon.ndatasource.core.DataSourceService"
|
||||
* cardinality="1..1"
|
||||
* policy="dynamic"
|
||||
* bind="setDataSourceService"
|
||||
* unbind="unsetDataSourceService"
|
||||
* @scr.reference name="devicetype.configuration.service"
|
||||
* interface="org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService"
|
||||
* cardinality="1..1"
|
||||
* policy="dynamic"
|
||||
* bind="setDeviceTypeConfigService"
|
||||
* unbind="unsetDeviceTypeConfigService"
|
||||
*/
|
||||
|
||||
public class ServiceComponent {
|
||||
private static final Log log = LogFactory.getLog(ServiceComponent.class);
|
||||
private ServiceRegistration serviceRegistration;
|
||||
|
||||
protected void activate(ComponentContext ctx) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Activating b Management Service Component");
|
||||
}
|
||||
try {
|
||||
DoorManagerManagerService deviceTypeManagerService = new DoorManagerManagerService();
|
||||
BundleContext bundleContext = ctx.getBundleContext();
|
||||
serviceRegistration =
|
||||
bundleContext.registerService(DeviceManagementService.class.getName(),
|
||||
deviceTypeManagerService, null);
|
||||
|
||||
String setupOption = System.getProperty("setup");
|
||||
if (setupOption != null) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("-Dsetup is enabled. Iot Device management repository schema initialization is about " +
|
||||
"to begin");
|
||||
}
|
||||
try {
|
||||
DoorManagerUtils.setupDeviceManagementSchema();
|
||||
} catch (DoorManagerDeviceMgtPluginException e) {
|
||||
log.error("Exception occurred while initializing device management database schema", e);
|
||||
}
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("b Management Service Component has been successfully activated");
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log.error("Error occurred while activating Current Sensor Management Service Component", e);
|
||||
}
|
||||
}
|
||||
|
||||
protected void deactivate(ComponentContext ctx) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("De-activating b Management Service Component");
|
||||
}
|
||||
try {
|
||||
if (serviceRegistration != null) {
|
||||
serviceRegistration.unregister();
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Current Sensor Management Service Component has been successfully de-activated");
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log.error("Error occurred while de-activating Iot Device Management bundle", e);
|
||||
}
|
||||
}
|
||||
|
||||
protected void setDataSourceService(DataSourceService dataSourceService) {
|
||||
/* This is to avoid mobile device management component getting initialized before the underlying datasources
|
||||
are registered */
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Data source service set to service component");
|
||||
}
|
||||
}
|
||||
|
||||
protected void unsetDataSourceService(DataSourceService dataSourceService) {
|
||||
//do nothing
|
||||
}
|
||||
|
||||
protected void setDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
|
||||
DoorManagerManagementDataHolder.getInstance().setDeviceTypeConfigService(deviceTypeConfigService);
|
||||
}
|
||||
|
||||
protected void unsetDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
|
||||
DoorManagerManagementDataHolder.getInstance().setDeviceTypeConfigService(null);
|
||||
}
|
||||
}
|
@ -0,0 +1,37 @@
|
||||
{{#zone "topCss"}}
|
||||
{{css "css/graph.css"}}
|
||||
{{/zone}}
|
||||
<span id="details" data-devicename="{{device.name}}" data-deviceid="{{device.deviceIdentifier}}"
|
||||
data-appcontext="{{@app.context}}"></span>
|
||||
<div id="chartDivSensorType1">
|
||||
<div class="chartWrapper" id="chartWrapper">
|
||||
<span id="sensorType1Title">smartLock</span>
|
||||
<div id="sensorType1yAxis" class="custom_y_axis"></div>
|
||||
<div class="legend_container">
|
||||
<div id="smoother" title="Smoothing"></div>
|
||||
<div id="sensorType1Legend"></div>
|
||||
</div>
|
||||
<div id="chartSensorType1" class="custom_rickshaw_graph" data-backend-api-url = {{backendApiUri}}></div>
|
||||
<div id="sensorType1xAxis" class="custom_x_axis"></div>
|
||||
<div id="sensorType1Slider" class="custom_slider"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="chartDivSensorType2">
|
||||
<div class="chartWrapper" id="chartWrapper">
|
||||
<span id="sensorType2Title">smartFan</span>
|
||||
<div id="sensorType2yAxis" class="custom_y_axis"></div>
|
||||
<div class="legend_container">
|
||||
<div id="smoother" title="Smoothing"></div>
|
||||
<div id="sensorType2Legend"></div>
|
||||
</div>
|
||||
<div id="chartSensorType2" class="custom_rickshaw_graph" data-backend-api-url = {{backendApiUri}}></div>
|
||||
<div id="sensorType2xAxis" class="custom_x_axis"></div>
|
||||
<div id="sensorType2Slider" class="custom_slider"></div>
|
||||
</div>
|
||||
</div>
|
||||
{{#zone "bottomJs"}}
|
||||
{{js "js/d3.min.js"}}
|
||||
{{js "js/rickshaw.min.js"}}
|
||||
{{js "js/moment.min.js"}}
|
||||
{{js "js/devicetype-graph.js"}}
|
||||
{{/zone}}
|
@ -0,0 +1,42 @@
|
||||
/*
|
||||
* 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 devices = context.unit.params.devices;
|
||||
var deviceType = context.uriParams.deviceType;
|
||||
var deviceId = request.getParameter("deviceId");
|
||||
|
||||
if (devices) {
|
||||
return {
|
||||
"devices": stringify(devices),
|
||||
"backendApiUri": devicemgtProps["httpsURL"] + "/"+deviceType+"/device/stats/"
|
||||
};
|
||||
} else 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") {
|
||||
return {
|
||||
"device": device,
|
||||
"backendApiUri": devicemgtProps["httpsURL"] + "/"+deviceType+"/device/stats/" + deviceId
|
||||
};
|
||||
} else {
|
||||
response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!");
|
||||
exit();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"version": "1.0.0"
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue