diff --git a/components/analytics/iot-analytics/org.wso2.carbon.device.mgt.iot.analytics/pom.xml b/components/analytics/iot-analytics/org.wso2.carbon.device.mgt.iot.analytics/pom.xml index bbb867dacf..de0b0b0c2d 100644 --- a/components/analytics/iot-analytics/org.wso2.carbon.device.mgt.iot.analytics/pom.xml +++ b/components/analytics/iot-analytics/org.wso2.carbon.device.mgt.iot.analytics/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt-plugins iot-analytics - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/analytics/iot-analytics/org.wso2.carbon.iot.device.statistics.dashboard/pom.xml b/components/analytics/iot-analytics/org.wso2.carbon.iot.device.statistics.dashboard/pom.xml index ed31c04bab..a20dfa538b 100644 --- a/components/analytics/iot-analytics/org.wso2.carbon.iot.device.statistics.dashboard/pom.xml +++ b/components/analytics/iot-analytics/org.wso2.carbon.iot.device.statistics.dashboard/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt-plugins iot-analytics - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/pom.xml b/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/pom.xml index 6869eeae7d..5299503532 100644 --- a/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/pom.xml +++ b/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt-plugins iot-analytics - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/css/bootstrap-datepicker.min.css b/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/css/bootstrap-datepicker.min.css new file mode 100644 index 0000000000..679e25cc45 --- /dev/null +++ b/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/css/bootstrap-datepicker.min.css @@ -0,0 +1,8 @@ +/*! + * Datepicker for Bootstrap v1.4.0 (https://github.com/eternicode/bootstrap-datepicker) + * + * Copyright 2012 Stefan Petre + * Improvements by Andrew Rowls + * Licensed under the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0) + */ +.datepicker{padding:4px;border-radius:4px;direction:ltr}.datepicker-inline{width:220px}.datepicker.datepicker-rtl{direction:rtl}.datepicker.datepicker-rtl table tr td span{float:right}.datepicker-dropdown{top:0;left:0}.datepicker-dropdown:before{content:'';display:inline-block;border-left:7px solid transparent;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-top:0;border-bottom-color:rgba(0,0,0,.2);position:absolute}.datepicker-dropdown:after{content:'';display:inline-block;border-left:6px solid transparent;border-right:6px solid transparent;border-bottom:6px solid #fff;border-top:0;position:absolute}.datepicker-dropdown.datepicker-orient-left:before{left:6px}.datepicker-dropdown.datepicker-orient-left:after{left:7px}.datepicker-dropdown.datepicker-orient-right:before{right:6px}.datepicker-dropdown.datepicker-orient-right:after{right:7px}.datepicker-dropdown.datepicker-orient-top:before{top:-7px}.datepicker-dropdown.datepicker-orient-top:after{top:-6px}.datepicker-dropdown.datepicker-orient-bottom:before{bottom:-7px;border-bottom:0;border-top:7px solid #999}.datepicker-dropdown.datepicker-orient-bottom:after{bottom:-6px;border-bottom:0;border-top:6px solid #fff}.datepicker>div{display:none}.datepicker.days .datepicker-days,.datepicker.months .datepicker-months,.datepicker.years .datepicker-years{display:block}.datepicker table{margin:0;-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.datepicker table tr td,.datepicker table tr th{text-align:center;width:30px;height:30px;border-radius:4px;border:none}.table-striped .datepicker table tr td,.table-striped .datepicker table tr th{background-color:transparent}.datepicker table tr td.day:hover,.datepicker table tr td.day.focused{background:#eee;cursor:pointer}.datepicker table tr td.old,.datepicker table tr td.new{color:#999}.datepicker table tr td.disabled,.datepicker table tr td.disabled:hover{background:0 0;color:#999;cursor:default}.datepicker table tr td.today,.datepicker table tr td.today:hover,.datepicker table tr td.today.disabled,.datepicker table tr td.today.disabled:hover{color:#000;background-color:#ffdb99;border-color:#ffb733}.datepicker table tr td.today:hover,.datepicker table tr td.today:hover:hover,.datepicker table tr td.today.disabled:hover,.datepicker table tr td.today.disabled:hover:hover,.datepicker table tr td.today:focus,.datepicker table tr td.today:hover:focus,.datepicker table tr td.today.disabled:focus,.datepicker table tr td.today.disabled:hover:focus,.datepicker table tr td.today:active,.datepicker table tr td.today:hover:active,.datepicker table tr td.today.disabled:active,.datepicker table tr td.today.disabled:hover:active,.datepicker table tr td.today.active,.datepicker table tr td.today:hover.active,.datepicker table tr td.today.disabled.active,.datepicker table tr td.today.disabled:hover.active,.open .dropdown-toggle.datepicker table tr td.today,.open .dropdown-toggle.datepicker table tr td.today:hover,.open .dropdown-toggle.datepicker table tr td.today.disabled,.open .dropdown-toggle.datepicker table tr td.today.disabled:hover{color:#000;background-color:#ffcd70;border-color:#f59e00}.datepicker table tr td.today:active,.datepicker table tr td.today:hover:active,.datepicker table tr td.today.disabled:active,.datepicker table tr td.today.disabled:hover:active,.datepicker table tr td.today.active,.datepicker table tr td.today:hover.active,.datepicker table tr td.today.disabled.active,.datepicker table tr td.today.disabled:hover.active,.open .dropdown-toggle.datepicker table tr td.today,.open .dropdown-toggle.datepicker table tr td.today:hover,.open .dropdown-toggle.datepicker table tr td.today.disabled,.open .dropdown-toggle.datepicker table tr td.today.disabled:hover{background-image:none}.datepicker table tr td.today.disabled,.datepicker table tr td.today:hover.disabled,.datepicker table tr td.today.disabled.disabled,.datepicker table tr td.today.disabled:hover.disabled,.datepicker table tr td.today[disabled],.datepicker table tr td.today:hover[disabled],.datepicker table tr td.today.disabled[disabled],.datepicker table tr td.today.disabled:hover[disabled],fieldset[disabled] .datepicker table tr td.today,fieldset[disabled] .datepicker table tr td.today:hover,fieldset[disabled] .datepicker table tr td.today.disabled,fieldset[disabled] .datepicker table tr td.today.disabled:hover,.datepicker table tr td.today.disabled:hover,.datepicker table tr td.today:hover.disabled:hover,.datepicker table tr td.today.disabled.disabled:hover,.datepicker table tr td.today.disabled:hover.disabled:hover,.datepicker table tr td.today[disabled]:hover,.datepicker table tr td.today:hover[disabled]:hover,.datepicker table tr td.today.disabled[disabled]:hover,.datepicker table tr td.today.disabled:hover[disabled]:hover,fieldset[disabled] .datepicker table tr td.today:hover,fieldset[disabled] .datepicker table tr td.today:hover:hover,fieldset[disabled] .datepicker table tr td.today.disabled:hover,fieldset[disabled] .datepicker table tr td.today.disabled:hover:hover,.datepicker table tr td.today.disabled:focus,.datepicker table tr td.today:hover.disabled:focus,.datepicker table tr td.today.disabled.disabled:focus,.datepicker table tr td.today.disabled:hover.disabled:focus,.datepicker table tr td.today[disabled]:focus,.datepicker table tr td.today:hover[disabled]:focus,.datepicker table tr td.today.disabled[disabled]:focus,.datepicker table tr td.today.disabled:hover[disabled]:focus,fieldset[disabled] .datepicker table tr td.today:focus,fieldset[disabled] .datepicker table tr td.today:hover:focus,fieldset[disabled] .datepicker table tr td.today.disabled:focus,fieldset[disabled] .datepicker table tr td.today.disabled:hover:focus,.datepicker table tr td.today.disabled:active,.datepicker table tr td.today:hover.disabled:active,.datepicker table tr td.today.disabled.disabled:active,.datepicker table tr td.today.disabled:hover.disabled:active,.datepicker table tr td.today[disabled]:active,.datepicker table tr td.today:hover[disabled]:active,.datepicker table tr td.today.disabled[disabled]:active,.datepicker table tr td.today.disabled:hover[disabled]:active,fieldset[disabled] .datepicker table tr td.today:active,fieldset[disabled] .datepicker table tr td.today:hover:active,fieldset[disabled] .datepicker table tr td.today.disabled:active,fieldset[disabled] .datepicker table tr td.today.disabled:hover:active,.datepicker table tr td.today.disabled.active,.datepicker table tr td.today:hover.disabled.active,.datepicker table tr td.today.disabled.disabled.active,.datepicker table tr td.today.disabled:hover.disabled.active,.datepicker table tr td.today[disabled].active,.datepicker table tr td.today:hover[disabled].active,.datepicker table tr td.today.disabled[disabled].active,.datepicker table tr td.today.disabled:hover[disabled].active,fieldset[disabled] .datepicker table tr td.today.active,fieldset[disabled] .datepicker table tr td.today:hover.active,fieldset[disabled] .datepicker table tr td.today.disabled.active,fieldset[disabled] .datepicker table tr td.today.disabled:hover.active{background-color:#ffdb99;border-color:#ffb733}.datepicker table tr td.today:hover:hover{color:#000}.datepicker table tr td.today.active:hover{color:#fff}.datepicker table tr td.range,.datepicker table tr td.range:hover,.datepicker table tr td.range.disabled,.datepicker table tr td.range.disabled:hover{background:#eee;border-radius:0}.datepicker table tr td.range.today,.datepicker table tr td.range.today:hover,.datepicker table tr td.range.today.disabled,.datepicker table tr td.range.today.disabled:hover{color:#000;background-color:#f7ca77;border-color:#f1a417;border-radius:0}.datepicker table tr td.range.today:hover,.datepicker table tr td.range.today:hover:hover,.datepicker table tr td.range.today.disabled:hover,.datepicker table tr td.range.today.disabled:hover:hover,.datepicker table tr td.range.today:focus,.datepicker table tr td.range.today:hover:focus,.datepicker table tr td.range.today.disabled:focus,.datepicker table tr td.range.today.disabled:hover:focus,.datepicker table tr td.range.today:active,.datepicker table tr td.range.today:hover:active,.datepicker table tr td.range.today.disabled:active,.datepicker table tr td.range.today.disabled:hover:active,.datepicker table tr td.range.today.active,.datepicker table tr td.range.today:hover.active,.datepicker table tr td.range.today.disabled.active,.datepicker table tr td.range.today.disabled:hover.active,.open .dropdown-toggle.datepicker table tr td.range.today,.open .dropdown-toggle.datepicker table tr td.range.today:hover,.open .dropdown-toggle.datepicker table tr td.range.today.disabled,.open .dropdown-toggle.datepicker table tr td.range.today.disabled:hover{color:#000;background-color:#f4bb51;border-color:#bf800c}.datepicker table tr td.range.today:active,.datepicker table tr td.range.today:hover:active,.datepicker table tr td.range.today.disabled:active,.datepicker table tr td.range.today.disabled:hover:active,.datepicker table tr td.range.today.active,.datepicker table tr td.range.today:hover.active,.datepicker table tr td.range.today.disabled.active,.datepicker table tr td.range.today.disabled:hover.active,.open .dropdown-toggle.datepicker table tr td.range.today,.open .dropdown-toggle.datepicker table tr td.range.today:hover,.open .dropdown-toggle.datepicker table tr td.range.today.disabled,.open .dropdown-toggle.datepicker table tr td.range.today.disabled:hover{background-image:none}.datepicker table tr td.range.today.disabled,.datepicker table tr td.range.today:hover.disabled,.datepicker table tr td.range.today.disabled.disabled,.datepicker table tr td.range.today.disabled:hover.disabled,.datepicker table tr td.range.today[disabled],.datepicker table tr td.range.today:hover[disabled],.datepicker table tr td.range.today.disabled[disabled],.datepicker table tr td.range.today.disabled:hover[disabled],fieldset[disabled] .datepicker table tr td.range.today,fieldset[disabled] .datepicker table tr td.range.today:hover,fieldset[disabled] .datepicker table tr td.range.today.disabled,fieldset[disabled] .datepicker table tr td.range.today.disabled:hover,.datepicker table tr td.range.today.disabled:hover,.datepicker table tr td.range.today:hover.disabled:hover,.datepicker table tr td.range.today.disabled.disabled:hover,.datepicker table tr td.range.today.disabled:hover.disabled:hover,.datepicker table tr td.range.today[disabled]:hover,.datepicker table tr td.range.today:hover[disabled]:hover,.datepicker table tr td.range.today.disabled[disabled]:hover,.datepicker table tr td.range.today.disabled:hover[disabled]:hover,fieldset[disabled] .datepicker table tr td.range.today:hover,fieldset[disabled] .datepicker table tr td.range.today:hover:hover,fieldset[disabled] .datepicker table tr td.range.today.disabled:hover,fieldset[disabled] .datepicker table tr td.range.today.disabled:hover:hover,.datepicker table tr td.range.today.disabled:focus,.datepicker table tr td.range.today:hover.disabled:focus,.datepicker table tr td.range.today.disabled.disabled:focus,.datepicker table tr td.range.today.disabled:hover.disabled:focus,.datepicker table tr td.range.today[disabled]:focus,.datepicker table tr td.range.today:hover[disabled]:focus,.datepicker table tr td.range.today.disabled[disabled]:focus,.datepicker table tr td.range.today.disabled:hover[disabled]:focus,fieldset[disabled] .datepicker table tr td.range.today:focus,fieldset[disabled] .datepicker table tr td.range.today:hover:focus,fieldset[disabled] .datepicker table tr td.range.today.disabled:focus,fieldset[disabled] .datepicker table tr td.range.today.disabled:hover:focus,.datepicker table tr td.range.today.disabled:active,.datepicker table tr td.range.today:hover.disabled:active,.datepicker table tr td.range.today.disabled.disabled:active,.datepicker table tr td.range.today.disabled:hover.disabled:active,.datepicker table tr td.range.today[disabled]:active,.datepicker table tr td.range.today:hover[disabled]:active,.datepicker table tr td.range.today.disabled[disabled]:active,.datepicker table tr td.range.today.disabled:hover[disabled]:active,fieldset[disabled] .datepicker table tr td.range.today:active,fieldset[disabled] .datepicker table tr td.range.today:hover:active,fieldset[disabled] .datepicker table tr td.range.today.disabled:active,fieldset[disabled] .datepicker table tr td.range.today.disabled:hover:active,.datepicker table tr td.range.today.disabled.active,.datepicker table tr td.range.today:hover.disabled.active,.datepicker table tr td.range.today.disabled.disabled.active,.datepicker table tr td.range.today.disabled:hover.disabled.active,.datepicker table tr td.range.today[disabled].active,.datepicker table tr td.range.today:hover[disabled].active,.datepicker table tr td.range.today.disabled[disabled].active,.datepicker table tr td.range.today.disabled:hover[disabled].active,fieldset[disabled] .datepicker table tr td.range.today.active,fieldset[disabled] .datepicker table tr td.range.today:hover.active,fieldset[disabled] .datepicker table tr td.range.today.disabled.active,fieldset[disabled] .datepicker table tr td.range.today.disabled:hover.active{background-color:#f7ca77;border-color:#f1a417}.datepicker table tr td.selected,.datepicker table tr td.selected:hover,.datepicker table tr td.selected.disabled,.datepicker table tr td.selected.disabled:hover{color:#fff;background-color:#999;border-color:#555;text-shadow:0 -1px 0 rgba(0,0,0,.25)}.datepicker table tr td.selected:hover,.datepicker table tr td.selected:hover:hover,.datepicker table tr td.selected.disabled:hover,.datepicker table tr td.selected.disabled:hover:hover,.datepicker table tr td.selected:focus,.datepicker table tr td.selected:hover:focus,.datepicker table tr td.selected.disabled:focus,.datepicker table tr td.selected.disabled:hover:focus,.datepicker table tr td.selected:active,.datepicker table tr td.selected:hover:active,.datepicker table tr td.selected.disabled:active,.datepicker table tr td.selected.disabled:hover:active,.datepicker table tr td.selected.active,.datepicker table tr td.selected:hover.active,.datepicker table tr td.selected.disabled.active,.datepicker table tr td.selected.disabled:hover.active,.open .dropdown-toggle.datepicker table tr td.selected,.open .dropdown-toggle.datepicker table tr td.selected:hover,.open .dropdown-toggle.datepicker table tr td.selected.disabled,.open .dropdown-toggle.datepicker table tr td.selected.disabled:hover{color:#fff;background-color:#858585;border-color:#373737}.datepicker table tr td.selected:active,.datepicker table tr td.selected:hover:active,.datepicker table tr td.selected.disabled:active,.datepicker table tr td.selected.disabled:hover:active,.datepicker table tr td.selected.active,.datepicker table tr td.selected:hover.active,.datepicker table tr td.selected.disabled.active,.datepicker table tr td.selected.disabled:hover.active,.open .dropdown-toggle.datepicker table tr td.selected,.open .dropdown-toggle.datepicker table tr td.selected:hover,.open .dropdown-toggle.datepicker table tr td.selected.disabled,.open .dropdown-toggle.datepicker table tr td.selected.disabled:hover{background-image:none}.datepicker table tr td.selected.disabled,.datepicker table tr td.selected:hover.disabled,.datepicker table tr td.selected.disabled.disabled,.datepicker table tr td.selected.disabled:hover.disabled,.datepicker table tr td.selected[disabled],.datepicker table tr td.selected:hover[disabled],.datepicker table tr td.selected.disabled[disabled],.datepicker table tr td.selected.disabled:hover[disabled],fieldset[disabled] .datepicker table tr td.selected,fieldset[disabled] .datepicker table tr td.selected:hover,fieldset[disabled] .datepicker table tr td.selected.disabled,fieldset[disabled] .datepicker table tr td.selected.disabled:hover,.datepicker table tr td.selected.disabled:hover,.datepicker table tr td.selected:hover.disabled:hover,.datepicker table tr td.selected.disabled.disabled:hover,.datepicker table tr td.selected.disabled:hover.disabled:hover,.datepicker table tr td.selected[disabled]:hover,.datepicker table tr td.selected:hover[disabled]:hover,.datepicker table tr td.selected.disabled[disabled]:hover,.datepicker table tr td.selected.disabled:hover[disabled]:hover,fieldset[disabled] .datepicker table tr td.selected:hover,fieldset[disabled] .datepicker table tr td.selected:hover:hover,fieldset[disabled] .datepicker table tr td.selected.disabled:hover,fieldset[disabled] .datepicker table tr td.selected.disabled:hover:hover,.datepicker table tr td.selected.disabled:focus,.datepicker table tr td.selected:hover.disabled:focus,.datepicker table tr td.selected.disabled.disabled:focus,.datepicker table tr td.selected.disabled:hover.disabled:focus,.datepicker table tr td.selected[disabled]:focus,.datepicker table tr td.selected:hover[disabled]:focus,.datepicker table tr td.selected.disabled[disabled]:focus,.datepicker table tr td.selected.disabled:hover[disabled]:focus,fieldset[disabled] .datepicker table tr td.selected:focus,fieldset[disabled] .datepicker table tr td.selected:hover:focus,fieldset[disabled] .datepicker table tr td.selected.disabled:focus,fieldset[disabled] .datepicker table tr td.selected.disabled:hover:focus,.datepicker table tr td.selected.disabled:active,.datepicker table tr td.selected:hover.disabled:active,.datepicker table tr td.selected.disabled.disabled:active,.datepicker table tr td.selected.disabled:hover.disabled:active,.datepicker table tr td.selected[disabled]:active,.datepicker table tr td.selected:hover[disabled]:active,.datepicker table tr td.selected.disabled[disabled]:active,.datepicker table tr td.selected.disabled:hover[disabled]:active,fieldset[disabled] .datepicker table tr td.selected:active,fieldset[disabled] .datepicker table tr td.selected:hover:active,fieldset[disabled] .datepicker table tr td.selected.disabled:active,fieldset[disabled] .datepicker table tr td.selected.disabled:hover:active,.datepicker table tr td.selected.disabled.active,.datepicker table tr td.selected:hover.disabled.active,.datepicker table tr td.selected.disabled.disabled.active,.datepicker table tr td.selected.disabled:hover.disabled.active,.datepicker table tr td.selected[disabled].active,.datepicker table tr td.selected:hover[disabled].active,.datepicker table tr td.selected.disabled[disabled].active,.datepicker table tr td.selected.disabled:hover[disabled].active,fieldset[disabled] .datepicker table tr td.selected.active,fieldset[disabled] .datepicker table tr td.selected:hover.active,fieldset[disabled] .datepicker table tr td.selected.disabled.active,fieldset[disabled] .datepicker table tr td.selected.disabled:hover.active{background-color:#999;border-color:#555}.datepicker table tr td.active,.datepicker table tr td.active:hover,.datepicker table tr td.active.disabled,.datepicker table tr td.active.disabled:hover{color:#fff;background-color:#428bca;border-color:#357ebd;text-shadow:0 -1px 0 rgba(0,0,0,.25)}.datepicker table tr td.active:hover,.datepicker table tr td.active:hover:hover,.datepicker table tr td.active.disabled:hover,.datepicker table tr td.active.disabled:hover:hover,.datepicker table tr td.active:focus,.datepicker table tr td.active:hover:focus,.datepicker table tr td.active.disabled:focus,.datepicker table tr td.active.disabled:hover:focus,.datepicker table tr td.active:active,.datepicker table tr td.active:hover:active,.datepicker table tr td.active.disabled:active,.datepicker table tr td.active.disabled:hover:active,.datepicker table tr td.active.active,.datepicker table tr td.active:hover.active,.datepicker table tr td.active.disabled.active,.datepicker table tr td.active.disabled:hover.active,.open .dropdown-toggle.datepicker table tr td.active,.open .dropdown-toggle.datepicker table tr td.active:hover,.open .dropdown-toggle.datepicker table tr td.active.disabled,.open .dropdown-toggle.datepicker table tr td.active.disabled:hover{color:#fff;background-color:#3276b1;border-color:#285e8e}.datepicker table tr td.active:active,.datepicker table tr td.active:hover:active,.datepicker table tr td.active.disabled:active,.datepicker table tr td.active.disabled:hover:active,.datepicker table tr td.active.active,.datepicker table tr td.active:hover.active,.datepicker table tr td.active.disabled.active,.datepicker table tr td.active.disabled:hover.active,.open .dropdown-toggle.datepicker table tr td.active,.open .dropdown-toggle.datepicker table tr td.active:hover,.open .dropdown-toggle.datepicker table tr td.active.disabled,.open .dropdown-toggle.datepicker table tr td.active.disabled:hover{background-image:none}.datepicker table tr td.active.disabled,.datepicker table tr td.active:hover.disabled,.datepicker table tr td.active.disabled.disabled,.datepicker table tr td.active.disabled:hover.disabled,.datepicker table tr td.active[disabled],.datepicker table tr td.active:hover[disabled],.datepicker table tr td.active.disabled[disabled],.datepicker table tr td.active.disabled:hover[disabled],fieldset[disabled] .datepicker table tr td.active,fieldset[disabled] .datepicker table tr td.active:hover,fieldset[disabled] .datepicker table tr td.active.disabled,fieldset[disabled] .datepicker table tr td.active.disabled:hover,.datepicker table tr td.active.disabled:hover,.datepicker table tr td.active:hover.disabled:hover,.datepicker table tr td.active.disabled.disabled:hover,.datepicker table tr td.active.disabled:hover.disabled:hover,.datepicker table tr td.active[disabled]:hover,.datepicker table tr td.active:hover[disabled]:hover,.datepicker table tr td.active.disabled[disabled]:hover,.datepicker table tr td.active.disabled:hover[disabled]:hover,fieldset[disabled] .datepicker table tr td.active:hover,fieldset[disabled] .datepicker table tr td.active:hover:hover,fieldset[disabled] .datepicker table tr td.active.disabled:hover,fieldset[disabled] .datepicker table tr td.active.disabled:hover:hover,.datepicker table tr td.active.disabled:focus,.datepicker table tr td.active:hover.disabled:focus,.datepicker table tr td.active.disabled.disabled:focus,.datepicker table tr td.active.disabled:hover.disabled:focus,.datepicker table tr td.active[disabled]:focus,.datepicker table tr td.active:hover[disabled]:focus,.datepicker table tr td.active.disabled[disabled]:focus,.datepicker table tr td.active.disabled:hover[disabled]:focus,fieldset[disabled] .datepicker table tr td.active:focus,fieldset[disabled] .datepicker table tr td.active:hover:focus,fieldset[disabled] .datepicker table tr td.active.disabled:focus,fieldset[disabled] .datepicker table tr td.active.disabled:hover:focus,.datepicker table tr td.active.disabled:active,.datepicker table tr td.active:hover.disabled:active,.datepicker table tr td.active.disabled.disabled:active,.datepicker table tr td.active.disabled:hover.disabled:active,.datepicker table tr td.active[disabled]:active,.datepicker table tr td.active:hover[disabled]:active,.datepicker table tr td.active.disabled[disabled]:active,.datepicker table tr td.active.disabled:hover[disabled]:active,fieldset[disabled] .datepicker table tr td.active:active,fieldset[disabled] .datepicker table tr td.active:hover:active,fieldset[disabled] .datepicker table tr td.active.disabled:active,fieldset[disabled] .datepicker table tr td.active.disabled:hover:active,.datepicker table tr td.active.disabled.active,.datepicker table tr td.active:hover.disabled.active,.datepicker table tr td.active.disabled.disabled.active,.datepicker table tr td.active.disabled:hover.disabled.active,.datepicker table tr td.active[disabled].active,.datepicker table tr td.active:hover[disabled].active,.datepicker table tr td.active.disabled[disabled].active,.datepicker table tr td.active.disabled:hover[disabled].active,fieldset[disabled] .datepicker table tr td.active.active,fieldset[disabled] .datepicker table tr td.active:hover.active,fieldset[disabled] .datepicker table tr td.active.disabled.active,fieldset[disabled] .datepicker table tr td.active.disabled:hover.active{background-color:#428bca;border-color:#357ebd}.datepicker table tr td span{display:block;width:23%;height:54px;line-height:54px;float:left;margin:1%;cursor:pointer;border-radius:4px}.datepicker table tr td span:hover{background:#eee}.datepicker table tr td span.disabled,.datepicker table tr td span.disabled:hover{background:0 0;color:#999;cursor:default}.datepicker table tr td span.active,.datepicker table tr td span.active:hover,.datepicker table tr td span.active.disabled,.datepicker table tr td span.active.disabled:hover{color:#fff;background-color:#428bca;border-color:#357ebd;text-shadow:0 -1px 0 rgba(0,0,0,.25)}.datepicker table tr td span.active:hover,.datepicker table tr td span.active:hover:hover,.datepicker table tr td span.active.disabled:hover,.datepicker table tr td span.active.disabled:hover:hover,.datepicker table tr td span.active:focus,.datepicker table tr td span.active:hover:focus,.datepicker table tr td span.active.disabled:focus,.datepicker table tr td span.active.disabled:hover:focus,.datepicker table tr td span.active:active,.datepicker table tr td span.active:hover:active,.datepicker table tr td span.active.disabled:active,.datepicker table tr td span.active.disabled:hover:active,.datepicker table tr td span.active.active,.datepicker table tr td span.active:hover.active,.datepicker table tr td span.active.disabled.active,.datepicker table tr td span.active.disabled:hover.active,.open .dropdown-toggle.datepicker table tr td span.active,.open .dropdown-toggle.datepicker table tr td span.active:hover,.open .dropdown-toggle.datepicker table tr td span.active.disabled,.open .dropdown-toggle.datepicker table tr td span.active.disabled:hover{color:#fff;background-color:#3276b1;border-color:#285e8e}.datepicker table tr td span.active:active,.datepicker table tr td span.active:hover:active,.datepicker table tr td span.active.disabled:active,.datepicker table tr td span.active.disabled:hover:active,.datepicker table tr td span.active.active,.datepicker table tr td span.active:hover.active,.datepicker table tr td span.active.disabled.active,.datepicker table tr td span.active.disabled:hover.active,.open .dropdown-toggle.datepicker table tr td span.active,.open .dropdown-toggle.datepicker table tr td span.active:hover,.open .dropdown-toggle.datepicker table tr td span.active.disabled,.open .dropdown-toggle.datepicker table tr td span.active.disabled:hover{background-image:none}.datepicker table tr td span.active.disabled,.datepicker table tr td span.active:hover.disabled,.datepicker table tr td span.active.disabled.disabled,.datepicker table tr td span.active.disabled:hover.disabled,.datepicker table tr td span.active[disabled],.datepicker table tr td span.active:hover[disabled],.datepicker table tr td span.active.disabled[disabled],.datepicker table tr td span.active.disabled:hover[disabled],fieldset[disabled] .datepicker table tr td span.active,fieldset[disabled] .datepicker table tr td span.active:hover,fieldset[disabled] .datepicker table tr td span.active.disabled,fieldset[disabled] .datepicker table tr td span.active.disabled:hover,.datepicker table tr td span.active.disabled:hover,.datepicker table tr td span.active:hover.disabled:hover,.datepicker table tr td span.active.disabled.disabled:hover,.datepicker table tr td span.active.disabled:hover.disabled:hover,.datepicker table tr td span.active[disabled]:hover,.datepicker table tr td span.active:hover[disabled]:hover,.datepicker table tr td span.active.disabled[disabled]:hover,.datepicker table tr td span.active.disabled:hover[disabled]:hover,fieldset[disabled] .datepicker table tr td span.active:hover,fieldset[disabled] .datepicker table tr td span.active:hover:hover,fieldset[disabled] .datepicker table tr td span.active.disabled:hover,fieldset[disabled] .datepicker table tr td span.active.disabled:hover:hover,.datepicker table tr td span.active.disabled:focus,.datepicker table tr td span.active:hover.disabled:focus,.datepicker table tr td span.active.disabled.disabled:focus,.datepicker table tr td span.active.disabled:hover.disabled:focus,.datepicker table tr td span.active[disabled]:focus,.datepicker table tr td span.active:hover[disabled]:focus,.datepicker table tr td span.active.disabled[disabled]:focus,.datepicker table tr td span.active.disabled:hover[disabled]:focus,fieldset[disabled] .datepicker table tr td span.active:focus,fieldset[disabled] .datepicker table tr td span.active:hover:focus,fieldset[disabled] .datepicker table tr td span.active.disabled:focus,fieldset[disabled] .datepicker table tr td span.active.disabled:hover:focus,.datepicker table tr td span.active.disabled:active,.datepicker table tr td span.active:hover.disabled:active,.datepicker table tr td span.active.disabled.disabled:active,.datepicker table tr td span.active.disabled:hover.disabled:active,.datepicker table tr td span.active[disabled]:active,.datepicker table tr td span.active:hover[disabled]:active,.datepicker table tr td span.active.disabled[disabled]:active,.datepicker table tr td span.active.disabled:hover[disabled]:active,fieldset[disabled] .datepicker table tr td span.active:active,fieldset[disabled] .datepicker table tr td span.active:hover:active,fieldset[disabled] .datepicker table tr td span.active.disabled:active,fieldset[disabled] .datepicker table tr td span.active.disabled:hover:active,.datepicker table tr td span.active.disabled.active,.datepicker table tr td span.active:hover.disabled.active,.datepicker table tr td span.active.disabled.disabled.active,.datepicker table tr td span.active.disabled:hover.disabled.active,.datepicker table tr td span.active[disabled].active,.datepicker table tr td span.active:hover[disabled].active,.datepicker table tr td span.active.disabled[disabled].active,.datepicker table tr td span.active.disabled:hover[disabled].active,fieldset[disabled] .datepicker table tr td span.active.active,fieldset[disabled] .datepicker table tr td span.active:hover.active,fieldset[disabled] .datepicker table tr td span.active.disabled.active,fieldset[disabled] .datepicker table tr td span.active.disabled:hover.active{background-color:#428bca;border-color:#357ebd}.datepicker table tr td span.old,.datepicker table tr td span.new{color:#999}.datepicker .datepicker-switch{width:145px}.datepicker thead tr:first-child th,.datepicker tfoot tr th{cursor:pointer}.datepicker thead tr:first-child th:hover,.datepicker tfoot tr th:hover{background:#eee}.datepicker .cw{font-size:10px;width:12px;padding:0 2px 0 5px;vertical-align:middle}.datepicker thead tr:first-child .cw{cursor:default;background-color:transparent}.input-group.date .input-group-addon{cursor:pointer}.input-daterange{width:100%}.input-daterange input{text-align:center}.input-daterange input:first-child{border-radius:3px 0 0 3px}.input-daterange input:last-child{border-radius:0 3px 3px 0}.input-daterange .input-group-addon{width:auto;min-width:16px;padding:4px 5px;font-weight:400;line-height:1.42857143;text-align:center;text-shadow:0 1px 0 #fff;vertical-align:middle;background-color:#eee;border:solid #ccc;border-width:1px 0;margin-left:-5px;margin-right:-5px} \ No newline at end of file diff --git a/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/index.xml b/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/index.xml index 35449da599..6f1ca09064 100644 --- a/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/index.xml +++ b/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/index.xml @@ -69,6 +69,12 @@ + + @@ -85,7 +91,17 @@ - + + diff --git a/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/js/app.js b/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/js/app.js index 9ea1b8d4e2..5d4bfab3d5 100644 --- a/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/js/app.js +++ b/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/js/app.js @@ -327,25 +327,31 @@ function notifyError(message) { function enableRealTime() { document.getElementById('realTimeShow').style.display = 'none'; spatialObject = currentSpatialObjects[selectedSpatialObject]; - spatialObject.removePath(); - spatialObject.marker.closePopup(); + if (spatialObject) { + spatialObject.removePath(); + spatialObject.marker.closePopup(); + } selectedSpatialObject = null; clearFocus(); clearMap(); document.getElementById('objectInfo').style.display = 'none'; isBatchModeOn = false; } + function focusOnHistorySpatialObject(objectId, timeFrom, timeTo) { if (!timeFrom) { notifyError('No start time provided to show history. Please provide a suitable value' + timeFrom); } else if (!timeTo) { notifyError('No end time provided to show history. Please provide a suitable value' + timeTo); } else { + $('#dateRangePopup').dialog('close'); document.getElementById('realTimeShow').style.display = 'block'; isBatchModeOn = true; clearFocus(); // Clear current focus if any clearMap(); - var tableData = getProviderData(timeFrom, timeTo); + var fromDate = new Date(timeFrom); + var toDate = new Date(timeTo); + var tableData = getProviderData(fromDate.valueOf() / 1000, toDate.valueOf() / 1000); for (var i = 0; i < tableData.length; i++) { var data = tableData[i]; var geoMessage = { @@ -401,7 +407,6 @@ function focusOnHistorySpatialObject(objectId, timeFrom, timeTo) { createChart(); chart.load({columns: [spatialObject.speedHistory.getArray()]}); }, 100); - $('#dateRangePopup').dialog('close'); } } diff --git a/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/js/jquery/bootstrap-datepicker.min.js b/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/js/jquery/bootstrap-datepicker.min.js new file mode 100644 index 0000000000..f26d0d8674 --- /dev/null +++ b/components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/src/main/resources/carbonapps/GadgetGeoDashboard_1.0.0/geo-dashboard/js/jquery/bootstrap-datepicker.min.js @@ -0,0 +1,8 @@ +/*! + * Datepicker for Bootstrap v1.4.0 (https://github.com/eternicode/bootstrap-datepicker) + * + * Copyright 2012 Stefan Petre + * Improvements by Andrew Rowls + * Licensed under the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0) + */ +!function(a,b){function c(){return new Date(Date.UTC.apply(Date,arguments))}function d(){var a=new Date;return c(a.getFullYear(),a.getMonth(),a.getDate())}function e(a,b){return a.getUTCFullYear()===b.getUTCFullYear()&&a.getUTCMonth()===b.getUTCMonth()&&a.getUTCDate()===b.getUTCDate()}function f(a){return function(){return this[a].apply(this,arguments)}}function g(b,c){function d(a,b){return b.toLowerCase()}var e,f=a(b).data(),g={},h=new RegExp("^"+c.toLowerCase()+"([A-Z])");c=new RegExp("^"+c.toLowerCase());for(var i in f)c.test(i)&&(e=i.replace(h,d),g[e]=f[i]);return g}function h(b){var c={};if(p[b]||(b=b.split("-")[0],p[b])){var d=p[b];return a.each(o,function(a,b){b in d&&(c[b]=d[b])}),c}}var i=function(){var b={get:function(a){return this.slice(a)[0]},contains:function(a){for(var b=a&&a.valueOf(),c=0,d=this.length;d>c;c++)if(this[c].valueOf()===b)return c;return-1},remove:function(a){this.splice(a,1)},replace:function(b){b&&(a.isArray(b)||(b=[b]),this.clear(),this.push.apply(this,b))},clear:function(){this.length=0},copy:function(){var a=new i;return a.replace(this),a}};return function(){var c=[];return c.push.apply(c,arguments),a.extend(c,b),c}}(),j=function(b,c){this._process_options(c),this.dates=new i,this.viewDate=this.o.defaultViewDate,this.focusDate=null,this.element=a(b),this.isInline=!1,this.isInput=this.element.is("input"),this.component=this.element.hasClass("date")?this.element.find(".add-on, .input-group-addon, .btn"):!1,this.hasInput=this.component&&this.element.find("input").length,this.component&&0===this.component.length&&(this.component=!1),this.picker=a(q.template),this._buildEvents(),this._attachEvents(),this.isInline?this.picker.addClass("datepicker-inline").appendTo(this.element):this.picker.addClass("datepicker-dropdown dropdown-menu"),this.o.rtl&&this.picker.addClass("datepicker-rtl"),this.viewMode=this.o.startView,this.o.calendarWeeks&&this.picker.find("tfoot .today, tfoot .clear").attr("colspan",function(a,b){return parseInt(b)+1}),this._allow_update=!1,this.setStartDate(this._o.startDate),this.setEndDate(this._o.endDate),this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled),this.setDatesDisabled(this.o.datesDisabled),this.fillDow(),this.fillMonths(),this._allow_update=!0,this.update(),this.showMode(),this.isInline&&this.show()};j.prototype={constructor:j,_process_options:function(e){this._o=a.extend({},this._o,e);var f=this.o=a.extend({},this._o),g=f.language;switch(p[g]||(g=g.split("-")[0],p[g]||(g=n.language)),f.language=g,f.startView){case 2:case"decade":f.startView=2;break;case 1:case"year":f.startView=1;break;default:f.startView=0}switch(f.minViewMode){case 1:case"months":f.minViewMode=1;break;case 2:case"years":f.minViewMode=2;break;default:f.minViewMode=0}f.startView=Math.max(f.startView,f.minViewMode),f.multidate!==!0&&(f.multidate=Number(f.multidate)||!1,f.multidate!==!1&&(f.multidate=Math.max(0,f.multidate))),f.multidateSeparator=String(f.multidateSeparator),f.weekStart%=7,f.weekEnd=(f.weekStart+6)%7;var h=q.parseFormat(f.format);if(f.startDate!==-1/0&&(f.startDate=f.startDate?f.startDate instanceof Date?this._local_to_utc(this._zero_time(f.startDate)):q.parseDate(f.startDate,h,f.language):-1/0),1/0!==f.endDate&&(f.endDate=f.endDate?f.endDate instanceof Date?this._local_to_utc(this._zero_time(f.endDate)):q.parseDate(f.endDate,h,f.language):1/0),f.daysOfWeekDisabled=f.daysOfWeekDisabled||[],a.isArray(f.daysOfWeekDisabled)||(f.daysOfWeekDisabled=f.daysOfWeekDisabled.split(/[,\s]*/)),f.daysOfWeekDisabled=a.map(f.daysOfWeekDisabled,function(a){return parseInt(a,10)}),f.datesDisabled=f.datesDisabled||[],!a.isArray(f.datesDisabled)){var i=[];i.push(q.parseDate(f.datesDisabled,h,f.language)),f.datesDisabled=i}f.datesDisabled=a.map(f.datesDisabled,function(a){return q.parseDate(a,h,f.language)});var j=String(f.orientation).toLowerCase().split(/\s+/g),k=f.orientation.toLowerCase();if(j=a.grep(j,function(a){return/^auto|left|right|top|bottom$/.test(a)}),f.orientation={x:"auto",y:"auto"},k&&"auto"!==k)if(1===j.length)switch(j[0]){case"top":case"bottom":f.orientation.y=j[0];break;case"left":case"right":f.orientation.x=j[0]}else k=a.grep(j,function(a){return/^left|right$/.test(a)}),f.orientation.x=k[0]||"auto",k=a.grep(j,function(a){return/^top|bottom$/.test(a)}),f.orientation.y=k[0]||"auto";else;if(f.defaultViewDate){var l=f.defaultViewDate.year||(new Date).getFullYear(),m=f.defaultViewDate.month||0,o=f.defaultViewDate.day||1;f.defaultViewDate=c(l,m,o)}else f.defaultViewDate=d();f.showOnFocus=f.showOnFocus!==b?f.showOnFocus:!0},_events:[],_secondaryEvents:[],_applyEvents:function(a){for(var c,d,e,f=0;fe?(this.picker.addClass("datepicker-orient-right"),n=k.left+m-b):this.picker.addClass("datepicker-orient-left");var p,q,r=this.o.orientation.y;if("auto"===r&&(p=-g+o-c,q=g+f-(o+l+c),r=Math.max(p,q)===q?"top":"bottom"),this.picker.addClass("datepicker-orient-"+r),"top"===r?o+=l:o-=c+parseInt(this.picker.css("padding-top")),this.o.rtl){var s=e-(n+m);this.picker.css({top:o,right:s,zIndex:j})}else this.picker.css({top:o,left:n,zIndex:j});return this},_allow_update:!0,update:function(){if(!this._allow_update)return this;var b=this.dates.copy(),c=[],d=!1;return arguments.length?(a.each(arguments,a.proxy(function(a,b){b instanceof Date&&(b=this._local_to_utc(b)),c.push(b)},this)),d=!0):(c=this.isInput?this.element.val():this.element.data("date")||this.element.find("input").val(),c=c&&this.o.multidate?c.split(this.o.multidateSeparator):[c],delete this.element.data().date),c=a.map(c,a.proxy(function(a){return q.parseDate(a,this.o.format,this.o.language)},this)),c=a.grep(c,a.proxy(function(a){return athis.o.endDate||!a},this),!0),this.dates.replace(c),this.dates.length?this.viewDate=new Date(this.dates.get(-1)):this.viewDatethis.o.endDate&&(this.viewDate=new Date(this.o.endDate)),d?this.setValue():c.length&&String(b)!==String(this.dates)&&this._trigger("changeDate"),!this.dates.length&&b.length&&this._trigger("clearDate"),this.fill(),this},fillDow:function(){var a=this.o.weekStart,b="";if(this.o.calendarWeeks){this.picker.find(".datepicker-days thead tr:first-child .datepicker-switch").attr("colspan",function(a,b){return parseInt(b)+1});var c=' ';b+=c}for(;a'+p[this.o.language].daysMin[a++%7]+"";b+="",this.picker.find(".datepicker-days thead").append(b)},fillMonths:function(){for(var a="",b=0;12>b;)a+=''+p[this.o.language].monthsShort[b++]+"";this.picker.find(".datepicker-months td").html(a)},setRange:function(b){b&&b.length?this.range=a.map(b,function(a){return a.valueOf()}):delete this.range,this.fill()},getClassNames:function(b){var c=[],d=this.viewDate.getUTCFullYear(),f=this.viewDate.getUTCMonth(),g=new Date;return b.getUTCFullYear()d||b.getUTCFullYear()===d&&b.getUTCMonth()>f)&&c.push("new"),this.focusDate&&b.valueOf()===this.focusDate.valueOf()&&c.push("focused"),this.o.todayHighlight&&b.getUTCFullYear()===g.getFullYear()&&b.getUTCMonth()===g.getMonth()&&b.getUTCDate()===g.getDate()&&c.push("today"),-1!==this.dates.contains(b)&&c.push("active"),(b.valueOf()this.o.endDate||-1!==a.inArray(b.getUTCDay(),this.o.daysOfWeekDisabled))&&c.push("disabled"),this.o.datesDisabled.length>0&&a.grep(this.o.datesDisabled,function(a){return e(b,a)}).length>0&&c.push("disabled","disabled-date"),this.range&&(b>this.range[0]&&b"),this.o.calendarWeeks)){var u=new Date(+n+(this.o.weekStart-n.getUTCDay()-7)%7*864e5),v=new Date(Number(u)+(11-u.getUTCDay())%7*864e5),w=new Date(Number(w=c(v.getUTCFullYear(),0,1))+(11-w.getUTCDay())%7*864e5),x=(v-w)/864e5/7+1;t.push(''+x+"")}if(s=this.getClassNames(n),s.push("day"),this.o.beforeShowDay!==a.noop){var y=this.o.beforeShowDay(this._utc_to_local(n));y===b?y={}:"boolean"==typeof y?y={enabled:y}:"string"==typeof y&&(y={classes:y}),y.enabled===!1&&s.push("disabled"),y.classes&&(s=s.concat(y.classes.split(/\s+/))),y.tooltip&&(d=y.tooltip)}s=a.unique(s),t.push('"+n.getUTCDate()+""),d=null,n.getUTCDay()===this.o.weekEnd&&t.push(""),n.setUTCDate(n.getUTCDate()+1)}this.picker.find(".datepicker-days tbody").empty().append(t.join(""));var z=this.picker.find(".datepicker-months").find("th:eq(1)").text(f).end().find("span").removeClass("active");if(a.each(this.dates,function(a,b){b.getUTCFullYear()===f&&z.eq(b.getUTCMonth()).addClass("active")}),(h>f||f>j)&&z.addClass("disabled"),f===h&&z.slice(0,i).addClass("disabled"),f===j&&z.slice(k+1).addClass("disabled"),this.o.beforeShowMonth!==a.noop){var A=this;a.each(z,function(b,c){if(!a(c).hasClass("disabled")){var d=new Date(f,b,1),e=A.o.beforeShowMonth(d);e===!1&&a(c).addClass("disabled")}})}t="",f=10*parseInt(f/10,10);var B=this.picker.find(".datepicker-years").find("th:eq(1)").text(f+"-"+(f+9)).end().find("td");f-=1;for(var C,D=a.map(this.dates,function(a){return a.getUTCFullYear()}),E=-1;11>E;E++)C=["year"],-1===E?C.push("old"):10===E&&C.push("new"),-1!==a.inArray(f,D)&&C.push("active"),(h>f||f>j)&&C.push("disabled"),t+=''+f+"",f+=1;B.html(t)}},updateNavArrows:function(){if(this._allow_update){var a=new Date(this.viewDate),b=a.getUTCFullYear(),c=a.getUTCMonth();switch(this.viewMode){case 0:this.picker.find(".prev").css(this.o.startDate!==-1/0&&b<=this.o.startDate.getUTCFullYear()&&c<=this.o.startDate.getUTCMonth()?{visibility:"hidden"}:{visibility:"visible"}),this.picker.find(".next").css(1/0!==this.o.endDate&&b>=this.o.endDate.getUTCFullYear()&&c>=this.o.endDate.getUTCMonth()?{visibility:"hidden"}:{visibility:"visible"});break;case 1:case 2:this.picker.find(".prev").css(this.o.startDate!==-1/0&&b<=this.o.startDate.getUTCFullYear()?{visibility:"hidden"}:{visibility:"visible"}),this.picker.find(".next").css(1/0!==this.o.endDate&&b>=this.o.endDate.getUTCFullYear()?{visibility:"hidden"}:{visibility:"visible"})}}},click:function(b){b.preventDefault();var d,e,f,g=a(b.target).closest("span, td, th");if(1===g.length)switch(g[0].nodeName.toLowerCase()){case"th":switch(g[0].className){case"datepicker-switch":this.showMode(1);break;case"prev":case"next":var h=q.modes[this.viewMode].navStep*("prev"===g[0].className?-1:1);switch(this.viewMode){case 0:this.viewDate=this.moveMonth(this.viewDate,h),this._trigger("changeMonth",this.viewDate);break;case 1:case 2:this.viewDate=this.moveYear(this.viewDate,h),1===this.viewMode&&this._trigger("changeYear",this.viewDate)}this.fill();break;case"today":var i=new Date;i=c(i.getFullYear(),i.getMonth(),i.getDate(),0,0,0),this.showMode(-2);var j="linked"===this.o.todayBtn?null:"view";this._setDate(i,j);break;case"clear":this.clearDates()}break;case"span":g.hasClass("disabled")||(this.viewDate.setUTCDate(1),g.hasClass("month")?(f=1,e=g.parent().find("span").index(g),d=this.viewDate.getUTCFullYear(),this.viewDate.setUTCMonth(e),this._trigger("changeMonth",this.viewDate),1===this.o.minViewMode&&this._setDate(c(d,e,f))):(f=1,e=0,d=parseInt(g.text(),10)||0,this.viewDate.setUTCFullYear(d),this._trigger("changeYear",this.viewDate),2===this.o.minViewMode&&this._setDate(c(d,e,f))),this.showMode(-1),this.fill());break;case"td":g.hasClass("day")&&!g.hasClass("disabled")&&(f=parseInt(g.text(),10)||1,d=this.viewDate.getUTCFullYear(),e=this.viewDate.getUTCMonth(),g.hasClass("old")?0===e?(e=11,d-=1):e-=1:g.hasClass("new")&&(11===e?(e=0,d+=1):e+=1),this._setDate(c(d,e,f)))}this.picker.is(":visible")&&this._focused_from&&a(this._focused_from).focus(),delete this._focused_from},_toggle_multidate:function(a){var b=this.dates.contains(a);if(a||this.dates.clear(),-1!==b?(this.o.multidate===!0||this.o.multidate>1||this.o.toggleActive)&&this.dates.remove(b):this.o.multidate===!1?(this.dates.clear(),this.dates.push(a)):this.dates.push(a),"number"==typeof this.o.multidate)for(;this.dates.length>this.o.multidate;)this.dates.remove(0)},_setDate:function(a,b){b&&"date"!==b||this._toggle_multidate(a&&new Date(a)),b&&"view"!==b||(this.viewDate=a&&new Date(a)),this.fill(),this.setValue(),b&&"view"===b||this._trigger("changeDate");var c;this.isInput?c=this.element:this.component&&(c=this.element.find("input")),c&&c.change(),!this.o.autoclose||b&&"date"!==b||this.hide()},moveMonth:function(a,c){if(!a)return b;if(!c)return a;var d,e,f=new Date(a.valueOf()),g=f.getUTCDate(),h=f.getUTCMonth(),i=Math.abs(c);if(c=c>0?1:-1,1===i)e=-1===c?function(){return f.getUTCMonth()===h}:function(){return f.getUTCMonth()!==d},d=h+c,f.setUTCMonth(d),(0>d||d>11)&&(d=(d+12)%12);else{for(var j=0;i>j;j++)f=this.moveMonth(f,c);d=f.getUTCMonth(),f.setUTCDate(g),e=function(){return d!==f.getUTCMonth()}}for(;e();)f.setUTCDate(--g),f.setUTCMonth(d);return f},moveYear:function(a,b){return this.moveMonth(a,12*b)},dateWithinRange:function(a){return a>=this.o.startDate&&a<=this.o.endDate},keydown:function(a){if(!this.picker.is(":visible"))return void(27===a.keyCode&&this.show());var b,c,e,f=!1,g=this.focusDate||this.viewDate;switch(a.keyCode){case 27:this.focusDate?(this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.fill()):this.hide(),a.preventDefault();break;case 37:case 39:if(!this.o.keyboardNavigation)break;b=37===a.keyCode?-1:1,a.ctrlKey?(c=this.moveYear(this.dates.get(-1)||d(),b),e=this.moveYear(g,b),this._trigger("changeYear",this.viewDate)):a.shiftKey?(c=this.moveMonth(this.dates.get(-1)||d(),b),e=this.moveMonth(g,b),this._trigger("changeMonth",this.viewDate)):(c=new Date(this.dates.get(-1)||d()),c.setUTCDate(c.getUTCDate()+b),e=new Date(g),e.setUTCDate(g.getUTCDate()+b)),this.dateWithinRange(e)&&(this.focusDate=this.viewDate=e,this.setValue(),this.fill(),a.preventDefault());break;case 38:case 40:if(!this.o.keyboardNavigation)break;b=38===a.keyCode?-1:1,a.ctrlKey?(c=this.moveYear(this.dates.get(-1)||d(),b),e=this.moveYear(g,b),this._trigger("changeYear",this.viewDate)):a.shiftKey?(c=this.moveMonth(this.dates.get(-1)||d(),b),e=this.moveMonth(g,b),this._trigger("changeMonth",this.viewDate)):(c=new Date(this.dates.get(-1)||d()),c.setUTCDate(c.getUTCDate()+7*b),e=new Date(g),e.setUTCDate(g.getUTCDate()+7*b)),this.dateWithinRange(e)&&(this.focusDate=this.viewDate=e,this.setValue(),this.fill(),a.preventDefault());break;case 32:break;case 13:g=this.focusDate||this.dates.get(-1)||this.viewDate,this.o.keyboardNavigation&&(this._toggle_multidate(g),f=!0),this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.setValue(),this.fill(),this.picker.is(":visible")&&(a.preventDefault(),"function"==typeof a.stopPropagation?a.stopPropagation():a.cancelBubble=!0,this.o.autoclose&&this.hide());break;case 9:this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.fill(),this.hide()}if(f){this._trigger(this.dates.length?"changeDate":"clearDate");var h;this.isInput?h=this.element:this.component&&(h=this.element.find("input")),h&&h.change()}},showMode:function(a){a&&(this.viewMode=Math.max(this.o.minViewMode,Math.min(2,this.viewMode+a))),this.picker.children("div").hide().filter(".datepicker-"+q.modes[this.viewMode].clsName).css("display","block"),this.updateNavArrows()}};var k=function(b,c){this.element=a(b),this.inputs=a.map(c.inputs,function(a){return a.jquery?a[0]:a}),delete c.inputs,m.call(a(this.inputs),c).bind("changeDate",a.proxy(this.dateUpdated,this)),this.pickers=a.map(this.inputs,function(b){return a(b).data("datepicker")}),this.updateDates()};k.prototype={updateDates:function(){this.dates=a.map(this.pickers,function(a){return a.getUTCDate()}),this.updateRanges()},updateRanges:function(){var b=a.map(this.dates,function(a){return a.valueOf()});a.each(this.pickers,function(a,c){c.setRange(b)})},dateUpdated:function(b){if(!this.updating){this.updating=!0;var c=a(b.target).data("datepicker"),d=c.getUTCDate(),e=a.inArray(b.target,this.inputs),f=e-1,g=e+1,h=this.inputs.length;if(-1!==e){if(a.each(this.pickers,function(a,b){b.getUTCDate()||b.setUTCDate(d)}),d=0&&dthis.dates[g])for(;h>g&&d>this.dates[g];)this.pickers[g++].setUTCDate(d);this.updateDates(),delete this.updating}}},remove:function(){a.map(this.pickers,function(a){a.remove()}),delete this.element.data().datepicker}};var l=a.fn.datepicker,m=function(c){var d=Array.apply(null,arguments);d.shift();var e;return this.each(function(){var f=a(this),i=f.data("datepicker"),l="object"==typeof c&&c;if(!i){var m=g(this,"date"),o=a.extend({},n,m,l),p=h(o.language),q=a.extend({},n,p,m,l);if(f.hasClass("input-daterange")||q.inputs){var r={inputs:q.inputs||f.find("input").toArray()};f.data("datepicker",i=new k(this,a.extend(q,r)))}else f.data("datepicker",i=new j(this,q))}return"string"==typeof c&&"function"==typeof i[c]&&(e=i[c].apply(i,d),e!==b)?!1:void 0}),e!==b?e:this};a.fn.datepicker=m;var n=a.fn.datepicker.defaults={autoclose:!1,beforeShowDay:a.noop,beforeShowMonth:a.noop,calendarWeeks:!1,clearBtn:!1,toggleActive:!1,daysOfWeekDisabled:[],datesDisabled:[],endDate:1/0,forceParse:!0,format:"mm/dd/yyyy",keyboardNavigation:!0,language:"en",minViewMode:0,multidate:!1,multidateSeparator:",",orientation:"auto",rtl:!1,startDate:-1/0,startView:0,todayBtn:!1,todayHighlight:!1,weekStart:0,disableTouchKeyboard:!1,enableOnReadonly:!0,container:"body"},o=a.fn.datepicker.locale_opts=["format","rtl","weekStart"];a.fn.datepicker.Constructor=j;var p=a.fn.datepicker.dates={en:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],daysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sun"],daysMin:["Su","Mo","Tu","We","Th","Fr","Sa","Su"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],today:"Today",clear:"Clear"}},q={modes:[{clsName:"days",navFnc:"Month",navStep:1},{clsName:"months",navFnc:"FullYear",navStep:1},{clsName:"years",navFnc:"FullYear",navStep:10}],isLeapYear:function(a){return a%4===0&&a%100!==0||a%400===0},getDaysInMonth:function(a,b){return[31,q.isLeapYear(a)?29:28,31,30,31,30,31,31,30,31,30,31][b]},validParts:/dd?|DD?|mm?|MM?|yy(?:yy)?/g,nonpunctuation:/[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,parseFormat:function(a){var b=a.replace(this.validParts,"\x00").split("\x00"),c=a.match(this.validParts);if(!b||!b.length||!c||0===c.length)throw new Error("Invalid date format.");return{separators:b,parts:c}},parseDate:function(d,e,f){function g(){var a=this.slice(0,m[k].length),b=m[k].slice(0,a.length);return a.toLowerCase()===b.toLowerCase()}if(!d)return b;if(d instanceof Date)return d;"string"==typeof e&&(e=q.parseFormat(e));var h,i,k,l=/([\-+]\d+)([dmwy])/,m=d.match(/([\-+]\d+)([dmwy])/g);if(/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(d)){for(d=new Date,k=0;kb;)b+=12;for(b%=12,a.setUTCMonth(b);a.getUTCMonth()!==b;)a.setUTCDate(a.getUTCDate()-1);return a},d:function(a,b){return a.setUTCDate(b)}};t.M=t.MM=t.mm=t.m,t.dd=t.d,d=c(d.getFullYear(),d.getMonth(),d.getDate(),0,0,0);var u=e.parts.slice();if(m.length!==u.length&&(u=a(u).filter(function(b,c){return-1!==a.inArray(c,s)}).toArray()),m.length===u.length){var v;for(k=0,v=u.length;v>k;k++){if(n=parseInt(m[k],10),h=u[k],isNaN(n))switch(h){case"MM":o=a(p[f].months).filter(g),n=a.inArray(o[0],p[f].months)+1;break;case"M":o=a(p[f].monthsShort).filter(g),n=a.inArray(o[0],p[f].monthsShort)+1}r[h]=n}var w,x;for(k=0;k=g;g++)f.length&&b.push(f.shift()),b.push(e[c.parts[g]]);return b.join("")},headTemplate:'«»',contTemplate:'',footTemplate:''};q.template='
'+q.headTemplate+""+q.footTemplate+'
'+q.headTemplate+q.contTemplate+q.footTemplate+'
'+q.headTemplate+q.contTemplate+q.footTemplate+"
",a.fn.datepicker.DPGlobal=q,a.fn.datepicker.noConflict=function(){return a.fn.datepicker=l,this},a.fn.datepicker.version="1.4.0",a(document).on("focus.datepicker.data-api click.datepicker.data-api",'[data-provide="datepicker"]',function(b){var c=a(this);c.data("datepicker")||(b.preventDefault(),m.call(c,"show"))}),a(function(){m.call(a('[data-provide="datepicker-inline"]'))})}(window.jQuery); \ No newline at end of file diff --git a/components/analytics/iot-analytics/pom.xml b/components/analytics/iot-analytics/pom.xml index 43b0bb55cb..5f5d269d2d 100644 --- a/components/analytics/iot-analytics/pom.xml +++ b/components/analytics/iot-analytics/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins analytics - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/analytics/pom.xml b/components/analytics/pom.xml index 6b4bf19083..ce6574f96d 100644 --- a/components/analytics/pom.xml +++ b/components/analytics/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins carbon-device-mgt-plugins-parent - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../../pom.xml diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/SenseClientAsyncExecutor.java b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/SenseClientAsyncExecutor.java index 8a31fdf9c7..9289a29a80 100755 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/SenseClientAsyncExecutor.java +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/SenseClientAsyncExecutor.java @@ -116,7 +116,7 @@ public class SenseClientAsyncExecutor extends AsyncTask diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/res/values/strings.xml b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/res/values/strings.xml index 62002d6055..e3cf8a1e12 100755 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/res/values/strings.xml +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/res/values/strings.xml @@ -1,7 +1,7 @@ WSO2-SenseAgent Sense Settings - Server URL https://host:9443 + Server URL https://host:8243 Speakup to capture the words DeEnroll ActivitySelectSensor diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.analytics/pom.xml b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.analytics/pom.xml index 4a94f15922..ff84765e63 100644 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.analytics/pom.xml +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.analytics/pom.xml @@ -21,7 +21,7 @@ androidsense-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.analytics/src/main/resources/carbonapps/androidsense/android_sense_receiver/android_sense_receiver.xml b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.analytics/src/main/resources/carbonapps/androidsense/android_sense_receiver/android_sense_receiver.xml index 48bb1f9194..e94bf47ca4 100644 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.analytics/src/main/resources/carbonapps/androidsense/android_sense_receiver/android_sense_receiver.xml +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.analytics/src/main/resources/carbonapps/androidsense/android_sense_receiver/android_sense_receiver.xml @@ -21,10 +21,8 @@ carbon.super/android_sense/+/data admin + admin org.wso2.carbon.device.mgt.input.adapter.mqtt.util.MQTTContentValidator - default - https://${iot.core.host}:${iot.core.https.port}/dynamic-client-web/register - tcp://${mqtt.broker.host}:${mqtt.broker.port} true diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/pom.xml b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/pom.xml index 1cf3ce06ad..b747d2f5df 100644 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/pom.xml +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/pom.xml @@ -3,7 +3,7 @@ androidsense-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml @@ -153,6 +153,11 @@ org.wso2.carbon.device.mgt.extensions provided + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + provided + diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseService.java b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseService.java index 2c60c0b4df..b259eb6b59 100644 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseService.java +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/AndroidSenseService.java @@ -19,14 +19,29 @@ package org.wso2.carbon.device.mgt.iot.androidsense.service.impl; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Info; -import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.*; +import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; +import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.constants.AndroidSenseConstants; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; import io.swagger.annotations.Extension; +import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.Info; +import io.swagger.annotations.ResponseHeader; +import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; -import org.wso2.carbon.apimgt.annotations.api.Scope; import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; @SwaggerDefinition( @@ -44,6 +59,16 @@ import javax.ws.rs.core.Response; @Tag(name = "android_sense", description = "") } ) +@Scopes( + scopes = { + @Scope( + name = "Enroll device", + description = "", + key = "perm:android-sense:enroll", + permissions = {"/device-mgt/devices/enroll/android-sense"} + ) + } +) public interface AndroidSenseService { /** @@ -52,10 +77,57 @@ public interface AndroidSenseService { * @param deviceId The registered device Id. * @param keywords The key words to be sent. (Comma separated values) */ - @Path("device/{deviceId}/words") @POST - @Scope(key = "device:android-sense:enroll", name = "", description = "") - Response sendKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("keywords") String keywords); + @Path("device/{deviceId}/words") + @ApiOperation( + httpMethod = "POST", + value = "End point to send the key words to the device", + notes = "", + tags = "android_sense", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidSenseConstants.SCOPE, value = "perm:android-sense:enroll") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid Device Identifiers found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while executing command operation to" + + " send keywords", + response = Response.class) + }) + Response sendKeyWords( + @ApiParam( + name = "deviceId", + value = "The registered device Id.", + required = true) + @PathParam("deviceId") String deviceId, + @ApiParam( + name = "keywords", + value = "The key words to be sent. (Comma separated values)", + required = true) + @QueryParam("keywords") String keywords); /** * End point to send the key words to the device @@ -63,34 +135,222 @@ public interface AndroidSenseService { * @param deviceId The registered device Id. * @param threshold The key words to be sent. (Comma separated values) */ - @Path("device/{deviceId}/words/threshold") @POST - @Scope(key = "device:android-sense:enroll", name = "", description = "") - Response sendThreshold(@PathParam("deviceId") String deviceId, @QueryParam("threshold") String threshold); + @Path("device/{deviceId}/words/threshold") + @ApiOperation( + httpMethod = "POST", + value = "End point to send threshold value to the device", + notes = "", + tags = "android_sense", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidSenseConstants.SCOPE, value = "perm:android-sense:enroll") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid Device Identifiers found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while executing command operation to" + + " send threashold", + response = Response.class) + }) + Response sendThreshold( + @ApiParam( + name = "deviceId", + value = "The registered device Id.", + required = true) + @PathParam("deviceId") String deviceId, + @ApiParam( + name = "threshold", + value = "Threshold to be sent.", + required = true) + @QueryParam("threshold") String threshold); - @Path("device/{deviceId}/words") + /** + * End point to remove key words from the device + */ @DELETE - @Scope(key = "device:android-sense:enroll", name = "", description = "") - Response removeKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("words") String words); + @Path("device/{deviceId}/words") + @ApiOperation( + httpMethod = "DELETE", + value = "Remove key words from the device", + notes = "", + response = Response.class, + tags = "android_sense", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidSenseConstants.SCOPE, value = "perm:android-sense:enroll") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid Device Identifiers found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while executing command operation to" + + " send threashold", + response = Response.class) + }) + Response removeKeyWords( + @ApiParam( + name = "deviceId", + value = "The registered device Id.", + required = true) + @PathParam("deviceId") String deviceId, + @ApiParam( + name = "words", + value = "The key words to be sent. (Comma separated values)", + required = true) + @QueryParam("words") String words); /** * Retrieve Sensor data for the device type */ - @Path("stats/{deviceId}/sensors/{sensorName}") @GET - @Consumes("application/json") - @Scope(key = "device:android-sense:enroll", name = "", description = "") - @Produces("application/json") - Response getAndroidSenseDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor, - @QueryParam("from") long from, @QueryParam("to") long to); + @Path("stats/{deviceId}/sensors/{sensorName}") + @ApiOperation( + consumes = "application/json", + produces = "application/json", + httpMethod = "GET", + value = "Retrieve Sensor data for the device type", + notes = "", + response = Response.class, + tags = "android_sense", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidSenseConstants.SCOPE, value = "perm:android-sense:enroll") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK.", + response = Response.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid Device Identifiers found.", + response = Response.class), + @ApiResponse( + code = 401, + message = "Unauthorized. \n Unauthorized request."), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response getAndroidSenseDeviceStats( + @ApiParam( + name = "deviceId", + value = "The registered device Id.", + required = true) + @PathParam("deviceId") String deviceId, + @ApiParam( + name = "sensorName", + value = "Name of the sensor", + required = true) + @PathParam("sensorName") String sensor, + @ApiParam( + name = "from", + value = "Get stats from what time", + required = true) + @QueryParam("from") long from, + @ApiParam( + name = "to", + value = "Get stats up to what time", + required = true) + @QueryParam("to") long to); /** * Enroll devices. */ - @Path("device/{device_id}/register") @POST - @Scope(key = "device:android-sense:enroll", name = "", description = "") - Response register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName); + @Path("device/{device_id}/register") + @ApiOperation( + httpMethod = "POST", + value = "Enroll device", + notes = "", + response = Response.class, + tags = "android_sense", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidSenseConstants.SCOPE, value = "perm:android-sense:enroll") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 202, + message = "Accepted.", + response = Response.class), + @ApiResponse( + code = 406, + message = "Not Acceptable"), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error on retrieving stats", + response = Response.class) + }) + Response register( + @ApiParam( + name = "deviceId", + value = "Device identifier id of the device to be added", + required = true) + @PathParam("device_id") String deviceId, + @ApiParam( + name = "deviceName", + value = "Device name of the device to be added", + required = true) + @QueryParam("deviceName") String deviceName); } diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/constants/AndroidSenseConstants.java b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/constants/AndroidSenseConstants.java index e1419844c7..68678d0006 100644 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/constants/AndroidSenseConstants.java +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/java/org/wso2/carbon/device/mgt/iot/androidsense/service/impl/constants/AndroidSenseConstants.java @@ -42,4 +42,6 @@ public class AndroidSenseConstants { public static final String CONFIG_TYPE = "general"; public static final String DEFAULT_ENDPOINT = "tcp://localhost:1886"; + public static final String SCOPE = "scope"; + } diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/webapp/WEB-INF/web.xml b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/webapp/WEB-INF/web.xml index 3908d86c60..be0eee231f 100644 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/webapp/WEB-INF/web.xml +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/src/main/webapp/WEB-INF/web.xml @@ -28,18 +28,10 @@ isSharedWithAllTenants true - - providerTenantDomain - carbon.super - managed-api-enabled true - - managed-api-owner - admin - diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/pom.xml b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/pom.xml index f362df4d4b..7f8bb2dc12 100644 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/pom.xml +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/pom.xml @@ -22,7 +22,7 @@ androidsense-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.device-view/device-view.hbs b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.device-view/device-view.hbs index ba9322aca0..952d78878e 100644 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.device-view/device-view.hbs +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.device-view/device-view.hbs @@ -43,6 +43,8 @@
  • Operations Log
  • +
  • Map
  • {{/zone}} {{#zone "device-view-tab-contents"}} @@ -73,4 +75,20 @@ + {{/zone}} diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.device-view/device-view.js b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.device-view/device-view.js index 32d8c813e1..a3ef93ec7b 100644 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.device-view/device-view.js +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.device-view/device-view.js @@ -20,6 +20,7 @@ function onRequest(context) { var log = new Log("device-view.js"); var deviceType = context.uriParams.deviceType; var deviceId = request.getParameter("id"); + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var autoCompleteParams = [ {"name" : "deviceId", "value" : deviceId} ]; @@ -28,10 +29,13 @@ function onRequest(context) { var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var device = deviceModule.viewDevice(deviceType, deviceId); if (device && device.status != "error") { + var anchor = { "device" : { "id" : device.content.deviceIdentifier, "type" : device.content.type}}; return { "device": device.content, "autoCompleteParams": autoCompleteParams, - "encodedFeaturePayloads": "" + "encodedFeaturePayloads": "", + "portalUrl" : devicemgtProps['portalURL'], + "anchor" : JSON.stringify(anchor) }; } else { response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!"); diff --git a/components/device-types/androidsense-plugin/pom.xml b/components/device-types/androidsense-plugin/pom.xml index 43386b1f8b..cba450b580 100644 --- a/components/device-types/androidsense-plugin/pom.xml +++ b/components/device-types/androidsense-plugin/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins device-types - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.analytics/pom.xml b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.analytics/pom.xml index f04ebe19bd..5584f230a0 100644 --- a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.analytics/pom.xml +++ b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.analytics/pom.xml @@ -21,7 +21,7 @@ arduino-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.analytics/src/main/resources/carbonapps/Arduino/arduino_receiver/arduino_receiver.xml b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.analytics/src/main/resources/carbonapps/Arduino/arduino_receiver/arduino_receiver.xml index a12cae6801..c8c306ef98 100644 --- a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.analytics/src/main/resources/carbonapps/Arduino/arduino_receiver/arduino_receiver.xml +++ b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.analytics/src/main/resources/carbonapps/Arduino/arduino_receiver/arduino_receiver.xml @@ -18,14 +18,7 @@ --> - 2 - admin org.wso2.carbon.device.mgt.input.adapter.http.util.HTTPContentValidator - default - all - 100 - https://localhost:${dcr.endpoint.port}/services/OAuth2TokenValidationService - admin diff --git a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/pom.xml b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/pom.xml index 55154f46a7..cfabc64c72 100644 --- a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/pom.xml +++ b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/pom.xml @@ -21,7 +21,7 @@ arduino-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml @@ -141,6 +141,11 @@ org.wso2.carbon.analytics.api provided + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + provided + diff --git a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/impl/ArduinoService.java b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/impl/ArduinoService.java index cd0ef710b5..3ed382479a 100644 --- a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/impl/ArduinoService.java +++ b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/impl/ArduinoService.java @@ -18,15 +18,14 @@ package org.wso2.carbon.device.mgt.iot.arduino.service.impl; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Info; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Extension; -import io.swagger.annotations.Tag; +import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; +import org.wso2.carbon.device.mgt.iot.arduino.service.impl.constants.ArduinoConstants; import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @SwaggerDefinition( @@ -44,26 +43,72 @@ import javax.ws.rs.core.Response; @Tag(name = "arduino", description = "") } ) +@Scopes( + scopes = { + @Scope( + name = "Enroll device", + description = "", + key = "perm:arduino:enroll", + permissions = {"/device-mgt/devices/enroll/arduino"} + ) + } +) public interface ArduinoService { @Path("device/{deviceId}/bulb") @POST - @Scope(key = "device:arduino:enroll", name = "", description = "") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Switch bulb", + notes = "", + response = Response.class, + tags = "arduino", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = ArduinoConstants.SCOPE, value = "perm:arduino:enroll") + }) + } + ) Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state); @Path("device/{deviceId}/controls") @GET - @Scope(key = "device:arduino:enroll", name = "", description = "") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Read controls", + notes = "", + response = Response.class, + tags = "arduino", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = ArduinoConstants.SCOPE, value = "perm:arduino:enroll") + }) + } + ) Response readControls(@PathParam("deviceId") String deviceId); /** - * Retreive Sensor data for the device type + * Retrieve Sensor data for the device type */ @Path("device/stats/{deviceId}") @GET @Consumes("application/json") @Produces("application/json") - @Scope(key = "device:arduino:enroll", name = "", description = "") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Retrieve Sensor data for the device type", + notes = "", + response = Response.class, + tags = "arduino", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = ArduinoConstants.SCOPE, value = "perm:arduino:enroll") + }) + } + ) Response getArduinoTemperatureStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, @QueryParam("to") long to); @@ -73,7 +118,19 @@ public interface ArduinoService { @Path("device/download") @GET @Produces("application/octet-stream") - @Scope(key = "device:arduino:enroll", name = "", description = "") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Download device agent", + notes = "", + response = Response.class, + tags = "arduino", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = ArduinoConstants.SCOPE, value = "perm:arduino:enroll") + }) + } + ) Response downloadSketch(@QueryParam("deviceName") String customDeviceName); } diff --git a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/impl/constants/ArduinoConstants.java b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/impl/constants/ArduinoConstants.java index ebf84d9ea9..4f3a042c9a 100644 --- a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/impl/constants/ArduinoConstants.java +++ b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/java/org/wso2/carbon/device/mgt/iot/arduino/service/impl/constants/ArduinoConstants.java @@ -27,4 +27,6 @@ public class ArduinoConstants { public static final String APIM_APPLICATION_TOKEN_VALIDITY_PERIOD = "3600"; + public static final String SCOPE = "scope"; + } diff --git a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/webapp/WEB-INF/web.xml b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/webapp/WEB-INF/web.xml index 4c38553526..a137eb9cc7 100644 --- a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/webapp/WEB-INF/web.xml +++ b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/src/main/webapp/WEB-INF/web.xml @@ -28,19 +28,11 @@ isSharedWithAllTenants true - - providerTenantDomain - carbon.super - managed-api-enabled true - - managed-api-owner - admin - \ No newline at end of file diff --git a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/pom.xml b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/pom.xml index 5bed062800..55167c5211 100644 --- a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/pom.xml +++ b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/pom.xml @@ -23,7 +23,7 @@ arduino-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.arduino.device-view/device-view.hbs b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.arduino.device-view/device-view.hbs index 182c043a13..23aaa135e4 100644 --- a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.arduino.device-view/device-view.hbs +++ b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.arduino.device-view/device-view.hbs @@ -44,6 +44,8 @@
  • Operations Log
  • +
  • Map
  • {{/zone}} {{#zone "device-view-tab-contents"}} @@ -75,4 +77,20 @@ + {{/zone}} \ No newline at end of file diff --git a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.arduino.device-view/device-view.js b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.arduino.device-view/device-view.js index c3863813b2..9ea752caaf 100644 --- a/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.arduino.device-view/device-view.js +++ b/components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.arduino.device-view/device-view.js @@ -20,6 +20,7 @@ function onRequest(context) { var log = new Log("device-view.js"); var deviceType = context.uriParams.deviceType; var deviceId = request.getParameter("id"); + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var autoCompleteParams = [ {"name" : "deviceId", "value" : deviceId} ]; @@ -28,7 +29,14 @@ function onRequest(context) { var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var device = deviceModule.viewDevice(deviceType, deviceId); if (device && device.status != "error") { - return {"device": device.content, "autoCompleteParams" : autoCompleteParams, "encodedFeaturePayloads": ""}; + var anchor = { "device" : { "id" : device.content.deviceIdentifier, "type" : device.content.type}}; + return { + "device": device.content, + "autoCompleteParams" : autoCompleteParams, + "encodedFeaturePayloads": "", + "portalUrl" : devicemgtProps['portalURL'], + "anchor" : JSON.stringify(anchor) + }; } else { response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!"); exit(); diff --git a/components/device-types/arduino-plugin/pom.xml b/components/device-types/arduino-plugin/pom.xml index ff196368b9..460dd3127b 100644 --- a/components/device-types/arduino-plugin/pom.xml +++ b/components/device-types/arduino-plugin/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins device-types - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/pom.xml b/components/device-types/pom.xml index f4e7c9ab6c..5cc40ae831 100644 --- a/components/device-types/pom.xml +++ b/components/device-types/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins carbon-device-mgt-plugins-parent - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../../pom.xml diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.analytics/pom.xml b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.analytics/pom.xml index ccca11f189..6dd2008d49 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.analytics/pom.xml +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.analytics/pom.xml @@ -21,7 +21,7 @@ raspberrypi-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.analytics/src/main/resources/carbonapps/raspberrypi/raspberrypi_receiver/raspberrypi_receiver.xml b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.analytics/src/main/resources/carbonapps/raspberrypi/raspberrypi_receiver/raspberrypi_receiver.xml index 60d130514e..9cd4a9eb46 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.analytics/src/main/resources/carbonapps/raspberrypi/raspberrypi_receiver/raspberrypi_receiver.xml +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.analytics/src/main/resources/carbonapps/raspberrypi/raspberrypi_receiver/raspberrypi_receiver.xml @@ -20,10 +20,8 @@ carbon.super/raspberrypi/+/temperature admin + admin org.wso2.carbon.device.mgt.input.adapter.mqtt.util.MQTTContentValidator - default - https://${iot.core.host}:${iot.core.https.port}/dynamic-client-web/register - tcp://${mqtt.broker.host}:${mqtt.broker.port} true diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/pom.xml b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/pom.xml index 8df74b2f26..f13a7ab09c 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/pom.xml +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/pom.xml @@ -21,7 +21,7 @@ raspberrypi-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml @@ -121,7 +121,11 @@ org.wso2.carbon.device.mgt.extensions provided - + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + + diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/RaspberryPiService.java b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/RaspberryPiService.java index 812c584394..1f227e630e 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/RaspberryPiService.java +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/RaspberryPiService.java @@ -18,12 +18,10 @@ package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Info; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Extension; -import io.swagger.annotations.Tag; +import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; +import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.constants.RaspberrypiConstants; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -44,11 +42,33 @@ import javax.ws.rs.core.Response; @Tag(name = "raspberrypi", description = "") } ) +@Scopes( + scopes = { + @Scope( + name = "Enroll device", + description = "", + key = "perm:raspberrypi:enroll", + permissions = {"/device-mgt/devices/enroll/raspberrypi"} + ) + } +) public interface RaspberryPiService { @Path("device/{deviceId}/bulb") @POST - @Scope(key = "device:raspberrypi:enroll", name = "", description = "") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Switch bulb", + notes = "", + response = Response.class, + tags = "raspberrypi", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = RaspberrypiConstants.SCOPE, value = "perm:raspberrypi:enroll") + }) + } + ) Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state); /** @@ -58,7 +78,19 @@ public interface RaspberryPiService { @GET @Consumes("application/json") @Produces("application/json") - @Scope(key = "device:raspberrypi:enroll", name = "", description = "") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Retreive Sensor data for the device type", + notes = "", + response = Response.class, + tags = "raspberrypi", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = RaspberrypiConstants.SCOPE, value = "perm:raspberrypi:enroll") + }) + } + ) Response getRaspberryPiTemperatureStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, @QueryParam("to") long to); @@ -68,7 +100,19 @@ public interface RaspberryPiService { @Path("device/download") @GET @Produces(MediaType.APPLICATION_JSON) - @Scope(key = "device:raspberrypi:enroll", name = "", description = "") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Download the agent.", + notes = "", + response = Response.class, + tags = "raspberrypi", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = RaspberrypiConstants.SCOPE, value = "perm:raspberrypi:enroll") + }) + } + ) Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketch_type") String sketchType); } diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/constants/RaspberrypiConstants.java b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/constants/RaspberrypiConstants.java index 168cb7d6d3..00919d6f6b 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/constants/RaspberrypiConstants.java +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/constants/RaspberrypiConstants.java @@ -33,4 +33,6 @@ public class RaspberrypiConstants { public static final String APIM_APPLICATION_TOKEN_VALIDITY_PERIOD = "3600"; + public static final String SCOPE = "scope"; + } diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/webapp/WEB-INF/web.xml b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/webapp/WEB-INF/web.xml index 623d182b7a..975eb808a0 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/webapp/WEB-INF/web.xml +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/webapp/WEB-INF/web.xml @@ -28,19 +28,11 @@ isSharedWithAllTenants true - - providerTenantDomain - carbon.super - managed-api-enabled true - - managed-api-owner - admin - \ No newline at end of file diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/pom.xml b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/pom.xml index 77b68621c2..c03a3c9f2c 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/pom.xml +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/pom.xml @@ -23,7 +23,7 @@ raspberrypi-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.device-view/device-view.hbs b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.device-view/device-view.hbs index 9c12567b1d..42ad0d173f 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.device-view/device-view.hbs +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.device-view/device-view.hbs @@ -44,6 +44,8 @@
  • Operations Log
  • +
  • Map
  • {{/zone}} {{#zone "device-view-tab-contents"}} @@ -75,4 +77,20 @@ + {{/zone}} \ No newline at end of file diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.device-view/device-view.js b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.device-view/device-view.js index c3863813b2..9ea752caaf 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.device-view/device-view.js +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.raspberrypi.device-view/device-view.js @@ -20,6 +20,7 @@ function onRequest(context) { var log = new Log("device-view.js"); var deviceType = context.uriParams.deviceType; var deviceId = request.getParameter("id"); + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var autoCompleteParams = [ {"name" : "deviceId", "value" : deviceId} ]; @@ -28,7 +29,14 @@ function onRequest(context) { var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var device = deviceModule.viewDevice(deviceType, deviceId); if (device && device.status != "error") { - return {"device": device.content, "autoCompleteParams" : autoCompleteParams, "encodedFeaturePayloads": ""}; + var anchor = { "device" : { "id" : device.content.deviceIdentifier, "type" : device.content.type}}; + return { + "device": device.content, + "autoCompleteParams" : autoCompleteParams, + "encodedFeaturePayloads": "", + "portalUrl" : devicemgtProps['portalURL'], + "anchor" : JSON.stringify(anchor) + }; } else { response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!"); exit(); diff --git a/components/device-types/raspberrypi-plugin/pom.xml b/components/device-types/raspberrypi-plugin/pom.xml index d42d8d5676..584a4a2888 100644 --- a/components/device-types/raspberrypi-plugin/pom.xml +++ b/components/device-types/raspberrypi-plugin/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins device-types - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/pom.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/pom.xml index e4ec55de6f..0b1805d433 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/pom.xml +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/pom.xml @@ -23,7 +23,7 @@ virtual-fire-alarm-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java index f9e6bd6d38..cd5c25571b 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/mqtt/FireAlarmMQTTCommunicator.java @@ -191,7 +191,10 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler { @Override public void run() { int currentTemperature = agentManager.getTemperature(); - String message = "PUBLISHER:" + AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature; + String message = "{\"event\": {\"metaData\": {\"owner\": \"" + AgentManager + .getInstance().getAgentConfigs().getDeviceOwner() + "\",\"deviceId\": \"" + AgentManager + .getInstance().getAgentConfigs().getDeviceId() + "\",\"time\": " + + "0},\"payloadData\": { \"temperature\": " + currentTemperature + "} }}"; try { String payLoad = AgentUtilOperations.prepareSecurePayLoad(message); diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/xmpp/FireAlarmXMPPCommunicator.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/xmpp/FireAlarmXMPPCommunicator.java index 668b0e16df..8ba82906f5 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/xmpp/FireAlarmXMPPCommunicator.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/communication/xmpp/FireAlarmXMPPCommunicator.java @@ -189,7 +189,10 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler { try { int currentTemperature = agentManager.getTemperature(); - String message = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature; + String message = "{\"event\": {\"metaData\": {\"owner\": \"" + AgentManager + .getInstance().getAgentConfigs().getDeviceOwner() + "\",\"deviceId\": \"" + AgentManager + .getInstance().getAgentConfigs().getDeviceId() + "\",\"time\": " + + "0},\"payloadData\": { \"temperature\": " + currentTemperature + "} }}"; String payLoad = AgentUtilOperations.prepareSecurePayLoad(message); xmppMessage.setTo(xmppAdminJID); diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java index 7c02e675d2..c3c2f77da1 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentConstants.java @@ -58,7 +58,7 @@ public class AgentConstants { public static final int DEFAULT_MQTT_RECONNECTION_INTERVAL = 2; // time in seconds public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; public static final String MQTT_SUBSCRIBE_TOPIC = "%s/" + DEVICE_TYPE + "/%s"; - public static final String MQTT_PUBLISH_TOPIC = "%s/" + DEVICE_TYPE + "/%s/publisher"; + public static final String MQTT_PUBLISH_TOPIC = "%s/" + DEVICE_TYPE + "/%s/temperature"; /* --------------------------------------------------------------------------------------- XMPP Connection specific information --------------------------------------------------------------------------------------- */ diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java index 30a4fe0b98..e3b83a4c4a 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentManager.java @@ -168,13 +168,13 @@ public class AgentManager { } } - try { - EnrollmentManager.getInstance().beginEnrollmentFlow(); - } catch (AgentCoreOperationException e) { - log.error("Device Enrollment Failed:\n"); - e.printStackTrace(); - System.exit(0); - } +// try { +// EnrollmentManager.getInstance().beginEnrollmentFlow(); +// } catch (AgentCoreOperationException e) { +// log.error("Device Enrollment Failed:\n"); +// e.printStackTrace(); +// System.exit(0); +// } //Start agent communication agentCommunicator.get(protocol).connect(); diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java index 15e15c1be3..9123c5fac7 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/core/AgentUtilOperations.java @@ -241,59 +241,67 @@ public class AgentUtilOperations { public static String prepareSecurePayLoad(String message) throws AgentCoreOperationException { - PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey(); - String encodedMessage = Base64.encodeBase64String(message.getBytes()); - String signedPayload; - try { - signedPayload = CommunicationUtils.signMessage(encodedMessage, devicePrivateKey); - } catch (TransportHandlerException e) { - String errorMsg = "Error occurred whilst trying to sign encrypted message of: [" + message + "]"; - log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg, e); - } + if (EnrollmentManager.getInstance().isEnrolled()) { + PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey(); + String encodedMessage = Base64.encodeBase64String(message.getBytes()); + String signedPayload; + try { + signedPayload = CommunicationUtils.signMessage(encodedMessage, devicePrivateKey); + } catch (TransportHandlerException e) { + String errorMsg = "Error occurred whilst trying to sign encrypted message of: [" + message + "]"; + log.error(errorMsg); + throw new AgentCoreOperationException(errorMsg, e); + } - JSONObject jsonPayload = new JSONObject(); - jsonPayload.put(JSON_MESSAGE_KEY, encodedMessage); - jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload); - //below statements are temporary fix. - jsonPayload.put(JSON_SERIAL_KEY, EnrollmentManager.getInstance().getSCEPCertificate().getSerialNumber()); + JSONObject jsonPayload = new JSONObject(); + jsonPayload.put(JSON_MESSAGE_KEY, encodedMessage); + jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload); + //below statements are temporary fix. + jsonPayload.put(JSON_SERIAL_KEY, EnrollmentManager.getInstance().getSCEPCertificate().getSerialNumber()); - return jsonPayload.toString(); + return jsonPayload.toString(); + } else { + return message; + } } public static String extractMessageFromPayload(String message) throws AgentCoreOperationException { - String actualMessage; + if (EnrollmentManager.getInstance().isEnrolled()) { + String actualMessage; - PublicKey serverPublicKey = EnrollmentManager.getInstance().getServerPublicKey(); - JSONObject jsonPayload = new JSONObject(message); - Object encodedMessage = jsonPayload.get(JSON_MESSAGE_KEY); - Object signedPayload = jsonPayload.get(JSON_SIGNATURE_KEY); - boolean verification; + PublicKey serverPublicKey = EnrollmentManager.getInstance().getServerPublicKey(); + JSONObject jsonPayload = new JSONObject(message); + Object encodedMessage = jsonPayload.get(JSON_MESSAGE_KEY); + Object signedPayload = jsonPayload.get(JSON_SIGNATURE_KEY); + boolean verification; - if (encodedMessage != null && signedPayload != null) { - try { - verification = CommunicationUtils.verifySignature( - encodedMessage.toString(), signedPayload.toString(), serverPublicKey); - } catch (TransportHandlerException e) { - String errorMsg = - "Error occurred whilst trying to verify signature on received message: [" + message + "]"; + if (encodedMessage != null && signedPayload != null) { + try { + verification = CommunicationUtils.verifySignature( + encodedMessage.toString(), signedPayload.toString(), serverPublicKey); + } catch (TransportHandlerException e) { + String errorMsg = + "Error occurred whilst trying to verify signature on received message: [" + message + "]"; + log.error(errorMsg); + throw new AgentCoreOperationException(errorMsg, e); + } + } else { + String errorMsg = "The received message is in an INVALID format. " + + "Need to be JSON - {\"Msg\":\"\", \"Sig\":\"\"}."; + throw new AgentCoreOperationException(errorMsg); + } + if (verification) { + actualMessage = new String(Base64.decodeBase64(encodedMessage.toString()), StandardCharsets.UTF_8); + } else { + String errorMsg = "Could not verify payload signature. The message was not signed by a valid client"; log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg, e); + throw new AgentCoreOperationException(errorMsg); } + return actualMessage; } else { - String errorMsg = "The received message is in an INVALID format. " + - "Need to be JSON - {\"Msg\":\"\", \"Sig\":\"\"}."; - throw new AgentCoreOperationException(errorMsg); - } - if (verification) { - actualMessage = new String(Base64.decodeBase64(encodedMessage.toString()), StandardCharsets.UTF_8); - } else { - String errorMsg = "Could not verify payload signature. The message was not signed by a valid client"; - log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg); + return message; } - return actualMessage; } public static String formatMessage(String message) { diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/enrollment/EnrollmentManager.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/enrollment/EnrollmentManager.java index a60f25f031..d6d6954d7b 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/enrollment/EnrollmentManager.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/advanced/enrollment/EnrollmentManager.java @@ -96,6 +96,7 @@ public class EnrollmentManager { private PublicKey publicKey; private PublicKey serverPublicKey; private X509Certificate SCEPCertificate; + private boolean isEnrolled = false; /** @@ -443,4 +444,13 @@ public class EnrollmentManager { public PublicKey getServerPublicKey() { return serverPublicKey; } + + /** + * Checks whether the device has already been enrolled with the SCEP Server. + * + * @return the enrollment status; 'TRUE' if already enrolled else 'FALSE'. + */ + public boolean isEnrolled() { + return isEnrolled; + } } diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/pom.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/pom.xml index 4e3e506153..bc54bbb8f6 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/pom.xml +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/pom.xml @@ -23,7 +23,7 @@ virtual-fire-alarm-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/http/FireAlarmHTTPCommunicator.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/http/FireAlarmHTTPCommunicator.java index 98dbc6dc73..ead68c5285 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/http/FireAlarmHTTPCommunicator.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/http/FireAlarmHTTPCommunicator.java @@ -111,7 +111,7 @@ public class FireAlarmHTTPCommunicator extends HTTPTransportHandler { AgentManager agentManager = AgentManager.getInstance(); String pathContext = request.getPathInfo(); - String separator = File.separator; + String separator = File.separatorChar=='\\' ? "\\\\" : File.separator ; if (pathContext.toUpperCase().contains( separator + AgentConstants.TEMPERATURE_CONTROL)) { diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java index 5b24783e7c..8f89750fde 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/mqtt/FireAlarmMQTTCommunicator.java @@ -208,7 +208,10 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler { @Override public void run() { int currentTemperature = agentManager.getTemperature(); - String message = "PUBLISHER:" + AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature; + String message = "{\"event\": {\"metaData\": {\"owner\": \"" + AgentManager + .getInstance().getAgentConfigs().getDeviceOwner() + "\",\"deviceId\": \"" + AgentManager + .getInstance().getAgentConfigs().getDeviceId() + "\",\"time\": " + + "0},\"payloadData\": { \"temperature\": " + currentTemperature + "} }}"; try { String payLoad = AgentUtilOperations.prepareSecurePayLoad(message); diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/xmpp/FireAlarmXMPPCommunicator.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/xmpp/FireAlarmXMPPCommunicator.java index abb8d7965d..0780f2d847 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/xmpp/FireAlarmXMPPCommunicator.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/communication/xmpp/FireAlarmXMPPCommunicator.java @@ -189,8 +189,10 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler { try { int currentTemperature = agentManager.getTemperature(); - - String message = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature; + String message = "{\"event\": {\"metaData\": {\"owner\": \"" + AgentManager + .getInstance().getAgentConfigs().getDeviceOwner() + "\",\"deviceId\": \"" + AgentManager + .getInstance().getAgentConfigs().getDeviceId() + "\",\"time\": " + + "0},\"payloadData\": { \"temperature\": " + currentTemperature + "} }}"; String payLoad = AgentUtilOperations.prepareSecurePayLoad(message); xmppMessage.setTo(xmppAdminJID); diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java index 566e5cfc01..f1372b25a0 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentConstants.java @@ -62,7 +62,7 @@ public class AgentConstants { public static final int DEFAULT_MQTT_RECONNECTION_INTERVAL = 2; // time in seconds public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; public static final String MQTT_SUBSCRIBE_TOPIC = "%s/" + DEVICE_TYPE + "/%s"; - public static final String MQTT_PUBLISH_TOPIC = "%s/" + DEVICE_TYPE + "/%s/publisher"; + public static final String MQTT_PUBLISH_TOPIC = "%s/" + DEVICE_TYPE + "/%s/temperature"; /* --------------------------------------------------------------------------------------- Device/Agent specific properties to be read from the 'deviceConfig.properties' file diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java index 2e7634054f..6ee95dceb9 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentManager.java @@ -153,15 +153,15 @@ public class AgentManager { } } - try { - if (!EnrollmentManager.getInstance().isEnrolled()) { - EnrollmentManager.getInstance().beginEnrollmentFlow(); - } - } catch (AgentCoreOperationException e) { - log.error("Device Enrollment Failed:\n"); - log.error(e); - System.exit(0); - } +// try { +// if (!EnrollmentManager.getInstance().isEnrolled()) { +// EnrollmentManager.getInstance().beginEnrollmentFlow(); +// } +// } catch (AgentCoreOperationException e) { +// log.error("Device Enrollment Failed:\n"); +// log.error(e); +// System.exit(0); +// } //Start agent communication agentCommunicator.get(protocol).connect(); diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentUtilOperations.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentUtilOperations.java index 60c3941b8d..7a365174b5 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentUtilOperations.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/core/AgentUtilOperations.java @@ -250,57 +250,65 @@ public class AgentUtilOperations { } public static String prepareSecurePayLoad(String message) throws AgentCoreOperationException { - PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey(); - String encodedMessage = Base64.encodeBase64String(message.getBytes()); - String signedPayload; - try { - signedPayload = CommunicationUtils.signMessage(encodedMessage, devicePrivateKey); - } catch (TransportHandlerException e) { - String errorMsg = "Error occurred whilst trying to sign encrypted message of: [" + message + "]"; - log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg, e); - } + if (EnrollmentManager.getInstance().isEnrolled()) { + PrivateKey devicePrivateKey = EnrollmentManager.getInstance().getPrivateKey(); + String encodedMessage = Base64.encodeBase64String(message.getBytes()); + String signedPayload; + try { + signedPayload = CommunicationUtils.signMessage(encodedMessage, devicePrivateKey); + } catch (TransportHandlerException e) { + String errorMsg = "Error occurred whilst trying to sign encrypted message of: [" + message + "]"; + log.error(errorMsg); + throw new AgentCoreOperationException(errorMsg, e); + } - JSONObject jsonPayload = new JSONObject(); - jsonPayload.put(JSON_MESSAGE_KEY, encodedMessage); - jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload); - //below statements are temporary fix. - jsonPayload.put(JSON_SERIAL_KEY, EnrollmentManager.getInstance().getSCEPCertificate().getSerialNumber()); - return jsonPayload.toString(); + JSONObject jsonPayload = new JSONObject(); + jsonPayload.put(JSON_MESSAGE_KEY, encodedMessage); + jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload); + //below statements are temporary fix. + jsonPayload.put(JSON_SERIAL_KEY, EnrollmentManager.getInstance().getSCEPCertificate().getSerialNumber()); + return jsonPayload.toString(); + } else { + return message; + } } public static String extractMessageFromPayload(String message) throws AgentCoreOperationException { - String actualMessage; + if (EnrollmentManager.getInstance().isEnrolled()) { + String actualMessage; - PublicKey serverPublicKey = EnrollmentManager.getInstance().getServerPublicKey(); - JSONObject jsonPayload = new JSONObject(message); - Object encodedMessage = jsonPayload.get(JSON_MESSAGE_KEY); - Object signedPayload = jsonPayload.get(JSON_SIGNATURE_KEY); - boolean verification; + PublicKey serverPublicKey = EnrollmentManager.getInstance().getServerPublicKey(); + JSONObject jsonPayload = new JSONObject(message); + Object encodedMessage = jsonPayload.get(JSON_MESSAGE_KEY); + Object signedPayload = jsonPayload.get(JSON_SIGNATURE_KEY); + boolean verification; - if (encodedMessage != null && signedPayload != null) { - try { - verification = CommunicationUtils.verifySignature( - encodedMessage.toString(), signedPayload.toString(), serverPublicKey); - } catch (TransportHandlerException e) { - String errorMsg = - "Error occurred whilst trying to verify signature on received message: [" + message + "]"; + if (encodedMessage != null && signedPayload != null) { + try { + verification = CommunicationUtils.verifySignature( + encodedMessage.toString(), signedPayload.toString(), serverPublicKey); + } catch (TransportHandlerException e) { + String errorMsg = + "Error occurred whilst trying to verify signature on received message: [" + message + "]"; + log.error(errorMsg); + throw new AgentCoreOperationException(errorMsg, e); + } + } else { + String errorMsg = "The received message is in an INVALID format. " + + "Need to be JSON - {\"Msg\":\"\", \"Sig\":\"\"}."; + throw new AgentCoreOperationException(errorMsg); + } + if (verification) { + actualMessage = new String(Base64.decodeBase64(encodedMessage.toString()), StandardCharsets.UTF_8); + } else { + String errorMsg = "Could not verify payload signature. The message was not signed by a valid client"; log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg, e); + throw new AgentCoreOperationException(errorMsg); } + return actualMessage; } else { - String errorMsg = "The received message is in an INVALID format. " + - "Need to be JSON - {\"Msg\":\"\", \"Sig\":\"\"}."; - throw new AgentCoreOperationException(errorMsg); - } - if (verification) { - actualMessage = new String(Base64.decodeBase64(encodedMessage.toString()), StandardCharsets.UTF_8); - } else { - String errorMsg = "Could not verify payload signature. The message was not signed by a valid client"; - log.error(errorMsg); - throw new AgentCoreOperationException(errorMsg); + return message; } - return actualMessage; } public static String getAuthenticationMethod() { diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/enrollment/EnrollmentManager.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/enrollment/EnrollmentManager.java index 6059483bc9..deaa5ac241 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/enrollment/EnrollmentManager.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/agent/enrollment/EnrollmentManager.java @@ -111,7 +111,7 @@ public class EnrollmentManager { */ private EnrollmentManager() { this.SCEPUrl = AgentManager.getInstance().getEnrollmentEP(); - setEnrollmentStatus(); + //setEnrollmentStatus(); } /** diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/build.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/build.xml new file mode 100644 index 0000000000..90687661e5 --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/build.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/pom.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/pom.xml new file mode 100644 index 0000000000..d4b7524f36 --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/pom.xml @@ -0,0 +1,75 @@ + + + + + + virtual-fire-alarm-plugin + org.wso2.carbon.devicemgt-plugins + 3.0.6-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics + WSO2 Carbon - IoT Server Virtual Firealarm Analytics capp + pom + + + + + maven-antrun-plugin + 1.7 + + + process-resources + + + + + + + run + + + + + + maven-assembly-plugin + 2.5.5 + + ${project.artifactId}-${carbon.devicemgt.plugins.version} + false + + src/assembly/src.xml + + + + + create-archive + package + + single + + + + + + + + \ No newline at end of file diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/assembly/src.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/assembly/src.xml new file mode 100644 index 0000000000..a5a375010e --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/assembly/src.xml @@ -0,0 +1,36 @@ + + + + src + + zip + + false + ${basedir}/src + + + ${basedir}/target/carbonapps + / + true + + + \ No newline at end of file diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/artifacts.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/artifacts.xml new file mode 100644 index 0000000000..fbd1362af3 --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/artifacts.xml @@ -0,0 +1,26 @@ + + + + + + + + + + diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_execution/artifact.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_execution/artifact.xml new file mode 100644 index 0000000000..b23fa50d7d --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_execution/artifact.xml @@ -0,0 +1,23 @@ + + + + + virtualfirealarm_execution.siddhiql + + diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_execution/virtualfirealarm_execution.siddhiql b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_execution/virtualfirealarm_execution.siddhiql new file mode 100644 index 0000000000..4346a61991 --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_execution/virtualfirealarm_execution.siddhiql @@ -0,0 +1,20 @@ +/* Enter a unique ExecutionPlan */ +@Plan:name('virtualfirealarm_execution') + +/* Enter a unique description for ExecutionPlan */ +-- @Plan:description('virtualfirealarm_execution') + +/* define streams/tables and write queries here ... */ + +@Import('org.wso2.iot.virtualfirealarm:1.0.0') +define stream virtualfirealarm (meta_owner string, meta_deviceId string, meta_time long, temperature float); + +@Export('org.wso2.iot.devices.temperature:1.0.0') +define stream temperature (meta_owner string, meta_deviceType string, meta_deviceId string, meta_time long, temperature float); + +from virtualfirealarm +select meta_owner, 'virtual_firealarm' as meta_deviceType, meta_deviceId, time:timestampInMilliseconds() as meta_time, temperature +insert into temperature; + + + diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_receiver/artifact.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_receiver/artifact.xml new file mode 100644 index 0000000000..14141e7da5 --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_receiver/artifact.xml @@ -0,0 +1,22 @@ + + + + + virtualfirealarm_receiver.xml + diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_receiver/virtualfirealarm_receiver.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_receiver/virtualfirealarm_receiver.xml new file mode 100644 index 0000000000..7f7b3cf7f6 --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_receiver/virtualfirealarm_receiver.xml @@ -0,0 +1,29 @@ + + + + + carbon.super/virtual_firealarm/+/temperature + admin + admin + org.wso2.carbon.device.mgt.input.adapter.mqtt.util.MQTTContentValidator + true + + + + diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_stream/artifact.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_stream/artifact.xml new file mode 100644 index 0000000000..d14485b3b2 --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_stream/artifact.xml @@ -0,0 +1,23 @@ + + + + + org.wso2.iot.virtualfirealarm_1.0.0.json + + diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_stream/org.wso2.iot.virtualfirealarm_1.0.0.json b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_stream/org.wso2.iot.virtualfirealarm_1.0.0.json new file mode 100644 index 0000000000..0ba70911ef --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/src/main/resources/carbonapps/virtualfirealarm/virtualfirealarm_stream/org.wso2.iot.virtualfirealarm_1.0.0.json @@ -0,0 +1,16 @@ +{ + "name": "org.wso2.iot.virtualfirealarm", + "version": "1.0.0", + "nickName": "virtual_firealarm", + "description": "Temperature data received from the virtual_firealarm", + "metaData": [ + {"name":"owner","type":"STRING"}, + {"name":"deviceId","type":"STRING"}, + {"name":"time","type":"LONG"} + ], + "payloadData": [ + { + "name": "temperature","type": "FLOAT" + } + ] +} \ No newline at end of file diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/pom.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/pom.xml index 59ccc4a793..ab9ed68ede 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/pom.xml +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/pom.xml @@ -21,7 +21,7 @@ virtual-fire-alarm-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml @@ -235,12 +235,12 @@ org.wso2.carbon.device.mgt.extensions provided - - org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations provided - - + + diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmService.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmService.java index 75db835b7b..6585280f0e 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmService.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmService.java @@ -18,14 +18,12 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Info; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Extension; -import io.swagger.annotations.Tag; +import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** @@ -50,8 +48,20 @@ import javax.ws.rs.core.Response; @Tag(name = "virtual_firealarm", description = "") } ) +@Scopes( + scopes = { + @Scope( + name = "Enroll device", + description = "", + key = "perm:firealarm:enroll", + permissions = {"/device-mgt/devices/enroll/firealarm"} + ) + } +) public interface VirtualFireAlarmService { + String SCOPE = "scope"; + /** * This is an API called/used from within the Server(Front-End) or by a device Owner. It sends a control command to * the VirtualFirealarm device to switch `ON` or `OFF` its buzzer. The method also takes in the protocol to be used @@ -63,7 +73,19 @@ public interface VirtualFireAlarmService { */ @POST @Path("device/{deviceId}/buzz") - @Scope(key = "device:firealarm:enroll", name = "", description = "") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Switch Buzzer", + notes = "", + response = Response.class, + tags = "virtual_firealarm", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:firealarm:enroll") + }) + } + ) Response switchBuzzer(@PathParam("deviceId") String deviceId, @FormParam("state") String state); @@ -72,7 +94,19 @@ public interface VirtualFireAlarmService { */ @Path("device/stats/{deviceId}") @GET - @Scope(key = "device:firealarm:enroll", name = "", description = "") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Retrieve Sensor data for the device type", + notes = "", + response = Response.class, + tags = "virtual_firealarm", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:firealarm:enroll") + }) + } + ) @Consumes("application/json") @Produces("application/json") Response getVirtualFirealarmStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, @@ -81,7 +115,19 @@ public interface VirtualFireAlarmService { @Path("device/download") @GET @Produces("application/zip") - @Scope(key = "device:firealarm:enroll", name = "", description = "") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Download agent", + notes = "", + response = Response.class, + tags = "virtual_firealarm", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:firealarm:enroll") + }) + } + ) Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType); } diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmServiceImpl.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmServiceImpl.java index c00dd6ab79..f5bb1d84b1 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmServiceImpl.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmServiceImpl.java @@ -18,7 +18,6 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl; -import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -35,18 +34,15 @@ import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; 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.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.VirtualFirealarmSecurityManager; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppAccount; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppConfig; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppServerClient; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.constants.VirtualFireAlarmConstants; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.APIUtil; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.VirtualFireAlarmServiceUtils; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipArchive; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipUtil; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp.VirtualFirealarmXMPPException; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp.XmppAccount; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp.XmppConfig; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp.XmppServerClient; 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; @@ -76,11 +72,8 @@ import java.util.UUID; public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService { - private static final String XMPP_PROTOCOL = "XMPP"; - private static final String MQTT_PROTOCOL = "MQTT"; private static final String KEY_TYPE = "PRODUCTION"; private static ApiApplicationKey apiApplicationKey; - private static final String DEVICE_MGT_SCOPE_IDENTIFIER = "device-mgt"; private static Log log = LogFactory.getLog(VirtualFireAlarmServiceImpl.class); @POST @@ -103,10 +96,7 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService { return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); } String resource = VirtualFireAlarmConstants.BULB_CONTEXT.replace("/", ""); - PrivateKey serverPrivateKey = VirtualFirealarmSecurityManager.getServerPrivateKey(); String actualMessage = resource + ":" + switchToState; - String encryptedMsg = VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage, - serverPrivateKey); String publishTopic = APIUtil.getTenantDomainOftheUser() + "/" + VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId; @@ -114,7 +104,7 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService { commandOp.setCode("buzz"); commandOp.setType(Operation.Type.COMMAND); commandOp.setEnabled(true); - commandOp.setPayLoad(encryptedMsg); + commandOp.setPayLoad(actualMessage); Properties props = new Properties(); props.setProperty(VirtualFireAlarmConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic); @@ -137,10 +127,6 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService { } catch (DeviceAccessAuthorizationException e) { log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (VirtualFireAlarmException e) { - String errorMsg = "Preparing Secure payload failed for device - [" + deviceId + "]"; - log.error(errorMsg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } catch (OperationManagementException e) { String msg = "Error occurred while executing command operation upon ringing the buzzer"; log.error(msg, e); @@ -162,37 +148,22 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService { DeviceGroupConstants.Permissions.DEFAULT_MANAGE_POLICIES_PERMISSIONS)) { return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); } - PrivateKey serverPrivateKey = VirtualFirealarmSecurityManager.getServerPrivateKey(); String actualMessage = VirtualFireAlarmConstants.POLICY_CONTEXT + ":" + policy; - String encryptedMsg = VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage, - serverPrivateKey); Map dynamicProperties = new HashMap<>(); - switch (protocolString) { - case XMPP_PROTOCOL: - dynamicProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY, - deviceId + "@" + XmppConfig.getInstance().getServerName()); - dynamicProperties.put(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "POLICTY-REQUEST"); - dynamicProperties.put(VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY, - VirtualFireAlarmConstants.CHAT_PROPERTY_KEY); - APIUtil.getOutputEventAdapterService().publish(VirtualFireAlarmConstants.XMPP_ADAPTER_NAME, - dynamicProperties, encryptedMsg); - break; - default: - - String publishTopic = APIUtil.getTenantDomainOftheUser() + "/" - + VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId; - dynamicProperties.put(VirtualFireAlarmConstants.ADAPTER_TOPIC_PROPERTY, publishTopic); - APIUtil.getOutputEventAdapterService().publish(VirtualFireAlarmConstants.MQTT_ADAPTER_NAME, - dynamicProperties, encryptedMsg); - break; - } + String publishTopic = APIUtil.getTenantDomainOftheUser() + "/" + + VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId; + dynamicProperties.put(VirtualFireAlarmConstants.ADAPTER_TOPIC_PROPERTY, publishTopic); + dynamicProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY, + deviceId + "@" + XmppConfig.getInstance().getServerName()); + dynamicProperties.put(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "POLICTY-REQUEST"); + dynamicProperties.put(VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY, + VirtualFireAlarmConstants.CHAT_PROPERTY_KEY); + APIUtil.getOutputEventAdapterService().publish(VirtualFireAlarmConstants.XMPP_ADAPTER_NAME, + dynamicProperties, actualMessage); return Response.ok().build(); } catch (DeviceAccessAuthorizationException e) { log.error(e.getErrorMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } catch (VirtualFireAlarmException e) { - log.error(e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } @@ -260,7 +231,7 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService { } catch (UserStoreException ex) { log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); - } catch (VirtualFirealarmDeviceMgtPluginException ex) { + } catch (VirtualFirealarmXMPPException ex) { log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); } @@ -294,7 +265,7 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService { private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) throws DeviceManagementException, APIManagerException, JWTClientException, - UserStoreException, VirtualFirealarmDeviceMgtPluginException { + UserStoreException, VirtualFirealarmXMPPException { //create new device id String deviceId = shortUUID(); boolean status = register(deviceId, deviceName); diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/constants/VirtualFireAlarmConstants.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/constants/VirtualFireAlarmConstants.java new file mode 100644 index 0000000000..204ede0040 --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/constants/VirtualFireAlarmConstants.java @@ -0,0 +1,84 @@ +/* + * 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.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.constants; + +public class VirtualFireAlarmConstants { + public final static String DEVICE_TYPE = "virtual_firealarm"; + public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; + public final static String DEVICE_PLUGIN_DEVICE_ID = "VIRTUAL_FIREALARM_DEVICE_ID"; + public final static String STATE_ON = "ON"; + public final static String STATE_OFF = "OFF"; + + public static final String URL_PREFIX = "http://"; + public static final String BULB_CONTEXT = "BULB"; + public static final String POLICY_CONTEXT = "POLICY"; + + //sensor events sumerized table name for temperature + public static final String TEMPERATURE_EVENT_TABLE = "DEVICE_TEMPERATURE_SUMMARY"; + public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super"; + + //mqtt tranport related constants + public static final String MQTT_ADAPTER_NAME = "virtual_firealarm_mqtt"; + public static final String MQTT_ADAPTER_TYPE = "oauth-mqtt"; + public static final String ADAPTER_TOPIC_PROPERTY = "topic"; + public static final String MQTT_PORT = "\\$\\{mqtt.broker.port\\}"; + public static final String MQTT_BROKER_HOST = "\\$\\{mqtt.broker.host\\}"; + public static final String CARBON_CONFIG_PORT_OFFSET = "Ports.Offset"; + public static final String DEFAULT_CARBON_LOCAL_IP_PROPERTY = "carbon.local.ip"; + public static final int CARBON_DEFAULT_PORT_OFFSET = 0; + public static final int DEFAULT_MQTT_PORT = 1886; + + //xmpp transport related constants + public static final String XMPP_ADAPTER_NAME = "virtual_firealarm_xmpp"; + public static final String XMPP_ADAPTER_TYPE = "xmpp"; + public static final String PASSWORD_PROPERTY_KEY = "password"; + public static final String JID_PROPERTY_KEY = "jid"; + public static final String CLIENT_JID_PROPERTY_KEY = "xmpp.client.jid"; + public static final String SUBJECT_PROPERTY_KEY = "xmpp.client.subject"; + public static final String MESSAGE_TYPE_PROPERTY_KEY = "xmpp.client.messageType"; + public static final String CHAT_PROPERTY_KEY = "chat"; + + public static final String USERNAME_PROPERTY_KEY = "username"; + public static final String DCR_PROPERTY_KEY = "dcrUrl"; + public static final String BROKER_URL_PROPERTY_KEY = "url"; + public static final String SCOPES_PROPERTY_KEY = "scopes"; + public static final String QOS_PROPERTY_KEY = "qos"; + public static final String CLIENT_ID_PROPERTY_KEY = "qos"; + public static final String CLEAR_SESSION_PROPERTY_KEY = "clearSession"; + public static final String TOPIC = "topic"; + public static final String SUBSCRIBED_TOPIC = "carbon.super/virtual_firealarm/+/publisher"; + + public static final String CONTENT_VALIDATION = "contentValidator"; + public static final String CONTENT_TRANSFORMATION = "contentTransformer"; + public static final String RESOURCE = "resource"; + + public static final String JSON_SERIAL_KEY = "SerialNumber"; + public static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature"; + public static final String JSON_MESSAGE_KEY = "Msg"; + public static final String JSON_SIGNATURE_KEY = "Sig"; + + public static final String HOST_KEY = "host"; + public static final String PORT_KEY = "port"; + + public static final String SERVER_NAME = "serverName"; + + public static final String MQTT_ADAPTER_TOPIC_PROPERTY_NAME = "mqtt.adapter.topic"; + + public static final String APIM_APPLICATION_TOKEN_VALIDITY_PERIOD = "3600"; +} diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/VirtualFireAlarmServiceUtils.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/VirtualFireAlarmServiceUtils.java deleted file mode 100644 index 277000e0f0..0000000000 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/VirtualFireAlarmServiceUtils.java +++ /dev/null @@ -1,51 +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.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util; - -import org.apache.commons.codec.binary.Base64; -import org.json.JSONObject; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.VirtualFirealarmSecurityManager; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException; - -import java.lang.*; -import java.security.PrivateKey; - -/** - * - */ -public class VirtualFireAlarmServiceUtils { - - private static final String JSON_MESSAGE_KEY = "Msg"; - private static final String JSON_SIGNATURE_KEY = "Sig"; - - public static String prepareSecurePayLoad(String message, PrivateKey signatureKey) throws VirtualFireAlarmException { - try { - message = Base64.encodeBase64String(message.getBytes()); - String signedPayload = VirtualFirealarmSecurityManager.signMessage(message, signatureKey); - JSONObject jsonPayload = new JSONObject(); - jsonPayload.put(JSON_MESSAGE_KEY, message); - jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload); - return jsonPayload.toString(); - } catch (VirtualFirealarmDeviceMgtPluginException e) { - throw new VirtualFireAlarmException(e); - } - - } -} diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/VirtualFireAlarmUtilConstants.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/VirtualFireAlarmUtilConstants.java index fae96848d3..a255b9537f 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/VirtualFireAlarmUtilConstants.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/VirtualFireAlarmUtilConstants.java @@ -1,6 +1,5 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppConfig; public class VirtualFireAlarmUtilConstants { diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipUtil.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipUtil.java index 2c6cd28407..39e938f2b8 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipUtil.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipUtil.java @@ -30,7 +30,7 @@ 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.virtualfirealarm.plugin.xmpp.XmppConfig; +import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp.XmppConfig; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.NetworkUtils; diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/VirtualFirealarmXMPPException.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/VirtualFirealarmXMPPException.java new file mode 100644 index 0000000000..57d0b8a0bd --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/VirtualFirealarmXMPPException.java @@ -0,0 +1,56 @@ +/* + * 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.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp; + + +public class VirtualFirealarmXMPPException extends Exception{ + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public VirtualFirealarmXMPPException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public VirtualFirealarmXMPPException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public VirtualFirealarmXMPPException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public VirtualFirealarmXMPPException() { + super(); + } + + public VirtualFirealarmXMPPException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/XmppAccount.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/XmppAccount.java new file mode 100644 index 0000000000..162ea957f9 --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/XmppAccount.java @@ -0,0 +1,63 @@ +/* + * 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.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp; + +/** + * holds the information related to account that needs to be created on xmpp server. + */ +public class XmppAccount { + + private String username; + private String password; + private String accountName; + private String email; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/XmppConfig.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/XmppConfig.java new file mode 100644 index 0000000000..d96f14c6e5 --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/XmppConfig.java @@ -0,0 +1,124 @@ +/* + * 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.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class XmppConfig { + + private String host; + private int port; + private String username; + private String password; + private String serverName; + private boolean enabled; + private String jid; + private static XmppConfig xmppConfig = new XmppConfig(); + private static final Log log = LogFactory.getLog(XmppConfig.class); + private static final String ENABLED = "enabled"; + private static final String USERNAME = "username"; + private static final String PASSWORD = "password"; + private static final String HOST = "host"; + private static final String PORT = "port"; + private static final String SERVERNAME = "serverName"; + private static final String JID = "jid"; + + private XmppConfig() { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + InputStream input = classLoader.getResourceAsStream("../xmpp.properties"); + Properties properties = new Properties(); + try { + properties.load(input); + enabled = Boolean.parseBoolean(properties.getProperty(ENABLED, "false")); + host = properties.getProperty(HOST); + port = Integer.parseInt(properties.getProperty(PORT)); + username = properties.getProperty(USERNAME); + password = properties.getProperty(PASSWORD); + serverName = properties.getProperty(SERVERNAME); + jid = properties.getProperty(JID); + } catch (IOException e) { + log.error("Failed to load xmpp config properties."); + } + } + + public static XmppConfig getInstance() { + return xmppConfig; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getServerName() { + return serverName; + } + + public void setServerName(String serverName) { + this.serverName = serverName; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getJid() { + return jid; + } + + public void setJid(String jid) { + this.jid = jid; + } +} diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/XmppServerClient.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/XmppServerClient.java new file mode 100644 index 0000000000..7369f90a4f --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/xmpp/XmppServerClient.java @@ -0,0 +1,66 @@ +/* + * 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.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp; + +import org.jivesoftware.smack.AccountManager; +import org.jivesoftware.smack.ConnectionConfiguration; +import org.jivesoftware.smack.XMPPConnection; +import org.jivesoftware.smack.XMPPException; + +import java.util.HashMap; +import java.util.Map; + +public class XmppServerClient { + + public static boolean createAccount(XmppAccount xmppAccount) throws VirtualFirealarmXMPPException { + if (XmppConfig.getInstance().isEnabled()) { + if (xmppAccount != null) { + try { + ConnectionConfiguration config = new ConnectionConfiguration(XmppConfig.getInstance().getHost(), + XmppConfig.getInstance().getPort(), + "Accounts"); + XMPPConnection xmppConnection = new XMPPConnection(config); + xmppConnection.connect(); + xmppConnection.login(XmppConfig.getInstance().getUsername(), XmppConfig.getInstance().getPassword()); + AccountManager accountManager = xmppConnection.getAccountManager(); + Map attributes = new HashMap<>(); + attributes.put("username", xmppAccount.getUsername()); + attributes.put("password", xmppAccount.getPassword()); + attributes.put("email", xmppAccount.getEmail()); + attributes.put("name", xmppAccount.getAccountName()); + accountManager.createAccount(xmppAccount.getUsername(), xmppAccount.getPassword(), attributes); + xmppConnection.disconnect(); + return true; + } catch (XMPPException e) { + if (e.getXMPPError().getCode() == 409) { + //AccountAlreadyExist + return true; + } else { + throw new VirtualFirealarmXMPPException( + "XMPP account creation failed. Error: " + e.getLocalizedMessage(), e); + } + } + } else { + throw new VirtualFirealarmXMPPException("Invalid XMPP attributes"); + } + } else { + return true; + } + } +} diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/webapp/WEB-INF/web.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/webapp/WEB-INF/web.xml index 2d1c6e26b9..eb4a397bf7 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/webapp/WEB-INF/web.xml +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/webapp/WEB-INF/web.xml @@ -34,9 +34,7 @@ managed-api-enabled true - - managed-api-owner - admin - + + \ No newline at end of file diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/webapp/WEB-INF/xmpp.properties b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/webapp/WEB-INF/xmpp.properties new file mode 100644 index 0000000000..3a173cb920 --- /dev/null +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/webapp/WEB-INF/xmpp.properties @@ -0,0 +1,25 @@ +# +# 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. +# +# + +#[XMPP-Configurations] +enabled=false +username=admin +password=admin +host=localhost +port=5222 +serverName=localhost +jid=admin@localhost \ No newline at end of file diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin/pom.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin/pom.xml index 40eba7c2ee..40fe1a347e 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin/pom.xml +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin/pom.xml @@ -23,7 +23,7 @@ virtual-fire-alarm-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml @@ -77,12 +77,12 @@ org.apache.commons.codec.binary, org.json.*;version="${commons-json.version.range}", org.wso2.carbon.certificate.mgt.core.*, - org.wso2.carbon.certificate.mgt.core.util, org.wso2.carbon.device.mgt.analytics.data.publisher.exception, org.wso2.carbon.device.mgt.analytics.data.publisher.service, org.wso2.carbon.event.input.adapter.core, org.wso2.carbon.event.input.adapter.core.exception, org.jivesoftware.smack.*, + javax.xml, javax.xml.bind, javax.xml.bind.annotation, javax.xml.parsers; version="${javax.xml.parsers.import.pkg.version}", diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/plugin/config/VirtualFirealarmConfig.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/plugin/config/VirtualFirealarmConfig.java index a5a75611ea..9bb1380e52 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/plugin/config/VirtualFirealarmConfig.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/plugin/config/VirtualFirealarmConfig.java @@ -6,6 +6,7 @@ import org.w3c.dom.Document; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.config.exception.VirtualFirealarmConfigurationException; import org.wso2.carbon.utils.CarbonUtils; +import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; @@ -50,6 +51,7 @@ public class VirtualFirealarmConfig { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); return docBuilder.parse(file); } catch (Exception e) { diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/pom.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/pom.xml index 3c71c1b282..ea477f5ebb 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/pom.xml +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/pom.xml @@ -21,7 +21,7 @@ virtual-fire-alarm-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServer.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServer.java deleted file mode 100644 index c5b4676bc8..0000000000 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServer.java +++ /dev/null @@ -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.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; -import java.io.InputStream; - - -public interface VirtualFireAlarmScepServer { - - /** - * This is an API called/used by the SCEP Client of the VirtualFirealarm device in its SCEP enrollment process. - * This acts as the endpoint exposed as part of the SCEP-Server for use by a SCEP Client. This is one of the two - * method-signatures that takes different parameters according to the SCEP-Operation executed by the SCEP-Client - * of the enrolling device. The API supports 2 SCEP Operations [GetCACert] and [GetCACaps]. - *

    - * Operation [GetCACert] returns the CA cert of the SCEP-Server for the device to verify its authenticity. - * Operation [GetCACaps] returns the CA Capabilities of the SCEP-Server. - * - * @param operation the SCEP operation requested by the client. [GetCACert] or [GetCACaps] - * @param message any messages pertaining to the requested SCEP Operation. - * @return an HTTP Response object with either the CA-Cert or the CA-Capabilities according to the operation. - */ - @GET - @Path("scep") - Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message); - - - /** - * This is an API called/used by the SCEP Client of the VirtualFirealarm device in its SCEP enrollment process. - * This acts as the endpoint exposed as part of the SCEP-Server for use by a SCEP Client. This is one of the two - * method-signatures that takes different parameters according to the SCEP-Operation executed by the SCEP-Client - * of the enrolling device. This API supports the SCEP Operation [PKIOperation]. - *

    - * Operation [PKIOperation] returns a certificate generated by the SCEP-Server for the enrolling device. - * - * @param operation the final SCEP operation executed in the enrollment process - which is [PKIOperation] - * @param inputStream an input stream consisting of the Certificate-Signing-Request (CSR) from the device. - * @return an HTTP Response object with the signed certificate for the device by the CA of the SCEP Server. - */ - @POST - @Path("scep") - Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream); - -} diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServerImpl.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServerImpl.java deleted file mode 100644 index c2f7a17e61..0000000000 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/VirtualFireAlarmScepServerImpl.java +++ /dev/null @@ -1,136 +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.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse; -import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; -import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.exception.VirtualFireAlarmException; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util.scep.ContentType; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util.scep.SCEPOperation; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util.VirtualFireAlarmServiceUtils; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.InputStream; - -@SuppressWarnings("Non-Annoted WebService") -public class VirtualFireAlarmScepServerImpl implements VirtualFireAlarmScepServer { - - private static Log log = LogFactory.getLog(VirtualFireAlarmScepServerImpl.class); - - @GET - @Path("scep") - public Response scepRequest(@QueryParam("operation") String operation, @QueryParam("message") String message) { - if (log.isDebugEnabled()) { - log.debug("Invoking SCEP operation " + operation); - } - if (SCEPOperation.GET_CA_CERT.getValue().equals(operation)) { - if (log.isDebugEnabled()) { - log.debug("Invoking GetCACert"); - } - try { - CertificateManagementService certificateManagementService = - VirtualFireAlarmServiceUtils.getCertificateManagementService(); - SCEPResponse scepResponse = certificateManagementService.getCACertSCEP(); - Response.ResponseBuilder responseBuilder; - switch (scepResponse.getResultCriteria()) { - case CA_CERT_FAILED: - log.error("CA cert failed"); - responseBuilder = Response.serverError(); - break; - case CA_CERT_RECEIVED: - if (log.isDebugEnabled()) { - log.debug("CA certificate received in GetCACert"); - } - responseBuilder = Response.ok(scepResponse.getEncodedResponse(), - ContentType.X_X509_CA_CERT); - break; - case CA_RA_CERT_RECEIVED: - if (log.isDebugEnabled()) { - log.debug("CA and RA certificates received in GetCACert"); - } - responseBuilder = Response.ok(scepResponse.getEncodedResponse(), - ContentType.X_X509_CA_RA_CERT); - break; - default: - log.error("Invalid SCEP request"); - responseBuilder = Response.serverError(); - break; - } - - return responseBuilder.build(); - } catch (VirtualFireAlarmException e) { - log.error("Error occurred while enrolling the VirtualFireAlarm device", e); - } catch (KeystoreException e) { - log.error("Keystore error occurred while enrolling the VirtualFireAlarm device", e); - } - - } else if (SCEPOperation.GET_CA_CAPS.getValue().equals(operation)) { - - if (log.isDebugEnabled()) { - log.debug("Invoking GetCACaps"); - } - try { - CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils. - getCertificateManagementService(); - byte caCaps[] = certificateManagementService.getCACapsSCEP(); - - return Response.ok(caCaps, MediaType.TEXT_PLAIN).build(); - - } catch (VirtualFireAlarmException e) { - log.error("Error occurred while enrolling the device", e); - } - } else { - log.error("Invalid SCEP operation " + operation); - } - return Response.serverError().build(); - } - - @POST - @Path("scep") - public Response scepRequestPost(@QueryParam("operation") String operation, InputStream inputStream) { - if (log.isDebugEnabled()) { - log.debug("Invoking SCEP operation " + operation); - } - if (SCEPOperation.PKI_OPERATION.getValue().equals(operation)) { - if (log.isDebugEnabled()) { - log.debug("Invoking PKIOperation"); - } - try { - CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils. - getCertificateManagementService(); - byte pkiMessage[] = certificateManagementService.getPKIMessageSCEP(inputStream); - return Response.ok(pkiMessage, ContentType.X_PKI_MESSAGE).build(); - } catch (VirtualFireAlarmException e) { - log.error("Error occurred while enrolling the device", e); - } catch (KeystoreException e) { - log.error("Keystore error occurred while enrolling the device", e); - } - } - return Response.serverError().build(); - } - -} diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/exception/VirtualFireAlarmException.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/exception/VirtualFireAlarmException.java deleted file mode 100644 index 4a81ec6d51..0000000000 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/exception/VirtualFireAlarmException.java +++ /dev/null @@ -1,31 +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.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.exception; - -public class VirtualFireAlarmException extends Exception { - private static final long serialVersionUID = 118512086957330189L; - - public VirtualFireAlarmException(String errorMessage) { - super(errorMessage); - } - - public VirtualFireAlarmException(String errorMessage, Throwable throwable) { - super(errorMessage, throwable); - } -} diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/VirtualFireAlarmServiceUtils.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/VirtualFireAlarmServiceUtils.java deleted file mode 100644 index de3d1e6a2b..0000000000 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/VirtualFireAlarmServiceUtils.java +++ /dev/null @@ -1,103 +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.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; -import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.exception.VirtualFireAlarmException; - -import java.lang.*; -import java.security.PublicKey; -import java.security.cert.X509Certificate; - -/** - * - */ -public class VirtualFireAlarmServiceUtils { - private static final Log log = LogFactory.getLog(VirtualFireAlarmServiceUtils.class); - - /** - * - * @return - * @throws VirtualFireAlarmException - */ - public static CertificateManagementService getCertificateManagementService() throws VirtualFireAlarmException { - - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - CertificateManagementService certificateManagementService = (CertificateManagementService) - ctx.getOSGiService(CertificateManagementService.class, null); - - if (certificateManagementService == null) { - String msg = "EnrollmentService is not initialized"; - log.error(msg); - throw new VirtualFireAlarmException(msg); - } - - return certificateManagementService; - } - - /** - * - * @param deviceId - * @return - * @throws VirtualFireAlarmException - */ - public static PublicKey getDevicePublicKey(String deviceId) throws VirtualFireAlarmException { - PublicKey clientPublicKey; - String alias = ""; - - try { - alias += deviceId.hashCode(); - - CertificateManagementService certificateManagementService = - VirtualFireAlarmServiceUtils.getCertificateManagementService(); - X509Certificate clientCertificate = (X509Certificate) certificateManagementService.getCertificateByAlias( - alias); - clientPublicKey = clientCertificate.getPublicKey(); - - } catch (VirtualFireAlarmException e) { - String errorMsg = "Could not retrieve CertificateManagementService from the runtime."; - if(log.isDebugEnabled()){ - log.debug(errorMsg); - } - throw new VirtualFireAlarmException(errorMsg, e); - } catch (KeystoreException e) { - String errorMsg; - if (e.getMessage().contains("NULL_CERT")) { - errorMsg = "The Device-View page might have been accessed prior to the device being started."; - if(log.isDebugEnabled()){ - log.debug(errorMsg); - } - throw new VirtualFireAlarmException(errorMsg, e); - } else { - errorMsg = "An error occurred whilst trying to retrieve certificate for deviceId [" + deviceId + - "] with alias: [" + alias + "]"; - if(log.isDebugEnabled()){ - log.debug(errorMsg); - } - throw new VirtualFireAlarmException(errorMsg, e); - } - } - return clientPublicKey; - } - -} diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/ContentType.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/ContentType.java deleted file mode 100644 index 707ca75fdf..0000000000 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/ContentType.java +++ /dev/null @@ -1,26 +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.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util.scep; - -public class ContentType { - public static final String X_PKI_MESSAGE = "application/x-pki-message"; - public static final String X_X509_CA_CERT = "application/x-x509-ca-cert"; - public static final String X_X509_CA_RA_CERT = "application/x-x509-ca-ra-cert"; -} - diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/SCEPOperation.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/SCEPOperation.java deleted file mode 100644 index b93a990164..0000000000 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/scep/service/impl/util/scep/SCEPOperation.java +++ /dev/null @@ -1,39 +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.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util.scep; - -public enum SCEPOperation { - GET_CA_CERT("GetCACert"), - GET_CA_CAPS("GetCACaps"), - PKI_OPERATION("PKIOperation"); - - private String value; - - private SCEPOperation(String value) { - this.setValue(value); - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100644 index fa44619195..0000000000 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - false - - - CXF,Carbon - diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/cxf-servlet.xml deleted file mode 100644 index 23280d4369..0000000000 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/web.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 1daeeb516c..0000000000 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - WSO2 IoT Server - WSO2 IoT Server - - - CXFServlet - org.apache.cxf.transport.servlet.CXFServlet - 1 - - - CXFServlet - /* - - - isAdminService - false - - - doAuthentication - false - - - isSharedWithAllTenants - true - - - providerTenantDomain - carbon.super - - - - - managed-api-enabled - false - - - managed-api-owner - admin - - - \ No newline at end of file diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/pom.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/pom.xml index 1022c15ad3..25f13368a7 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/pom.xml +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/pom.xml @@ -23,7 +23,7 @@ virtual-fire-alarm-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/device-types/virtual-fire-alarm-plugin/pom.xml b/components/device-types/virtual-fire-alarm-plugin/pom.xml index 17832867ae..e1f5fb87d0 100644 --- a/components/device-types/virtual-fire-alarm-plugin/pom.xml +++ b/components/device-types/virtual-fire-alarm-plugin/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins device-types - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml @@ -38,7 +38,7 @@ org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl org.wso2.carbon.device.mgt.iot.virtualfirealarm.api - org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.api + org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics diff --git a/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.osgiconnector/pom.xml b/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.osgiconnector/pom.xml index 7351fa82c0..a4d5e38795 100644 --- a/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.osgiconnector/pom.xml +++ b/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.osgiconnector/pom.xml @@ -18,7 +18,7 @@ org.wso2.carbon.devicemgt-plugins appm-connector - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/extensions/appm-connector/pom.xml b/components/extensions/appm-connector/pom.xml index 3e8801d59a..d1132e33b4 100644 --- a/components/extensions/appm-connector/pom.xml +++ b/components/extensions/appm-connector/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins extensions - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.extension/pom.xml b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.extension/pom.xml index f47feca209..82ac225384 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.extension/pom.xml +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.extension/pom.xml @@ -20,7 +20,7 @@ org.wso2.carbon.devicemgt-plugins cdmf-transport-adapters - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/pom.xml b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/pom.xml index 1d972eb97c..0f03141f2c 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/pom.xml +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/pom.xml @@ -20,7 +20,7 @@ org.wso2.carbon.devicemgt-plugins cdmf-transport-adapters - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../../pom.xml diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPEventAdapter.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPEventAdapter.java index 009db280f2..b85cef4d02 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPEventAdapter.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPEventAdapter.java @@ -186,7 +186,7 @@ public final class HTTPEventAdapter implements InputEventAdapter { "HttpService not available, Error in registering endpoint " + endpoint); } httpService.registerServlet(endpoint, new HTTPMessageServlet(eventAdaptorListener, tenantId, - eventAdapterConfiguration), + eventAdapterConfiguration, globalProperties), new Hashtable(), httpService.createDefaultHttpContext()); } catch (ServletException | NamespaceException e) { throw new InputEventAdapterRuntimeException("Error in registering endpoint " + endpoint, e); diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPEventAdapterFactory.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPEventAdapterFactory.java index 6ac043edd1..b46117f654 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPEventAdapterFactory.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPEventAdapterFactory.java @@ -66,7 +66,7 @@ public class HTTPEventAdapterFactory extends InputEventAdapterFactory { // Transport Exposed Property exposedTransportsProperty = new Property(HTTPEventAdapterConstants.EXPOSED_TRANSPORTS); - exposedTransportsProperty.setRequired(true); + exposedTransportsProperty.setRequired(false); exposedTransportsProperty.setDisplayName( resourceBundle.getString(HTTPEventAdapterConstants.EXPOSED_TRANSPORTS)); exposedTransportsProperty.setOptions( @@ -75,45 +75,6 @@ public class HTTPEventAdapterFactory extends InputEventAdapterFactory { exposedTransportsProperty.setDefaultValue(HTTPEventAdapterConstants.ALL); propertyList.add(exposedTransportsProperty); - // OAUTH validation endpoint admin service username - Property username = new Property(HTTPEventAdapterConstants.USERNAME); - username.setRequired(true); - username.setDisplayName(resourceBundle.getString(HTTPEventAdapterConstants.USERNAME)); - username.setHint(resourceBundle.getString(HTTPEventAdapterConstants.USERNAME_HINT)); - propertyList.add(username); - - // OAUTH validation endpoint admin service password - Property password = new Property(HTTPEventAdapterConstants.PASSWORD); - password.setRequired(true); - password.setDisplayName(resourceBundle.getString(HTTPEventAdapterConstants.PASSWORD)); - password.setHint(resourceBundle.getString(HTTPEventAdapterConstants.PASSWORD_HINT)); - propertyList.add(password); - - // OAUTH validation endpoint - Property tokenValidationEndpoint = new Property(HTTPEventAdapterConstants.TOKEN_VALIDATION_ENDPOINT_URL); - tokenValidationEndpoint.setRequired(true); - tokenValidationEndpoint.setDisplayName(resourceBundle.getString(HTTPEventAdapterConstants.TOKEN_VALIDATION_ENDPOINT_URL)); - tokenValidationEndpoint.setHint(resourceBundle.getString(HTTPEventAdapterConstants.TOKEN_VALIDATION_ENDPOINT_URL_HINT)); - propertyList.add(tokenValidationEndpoint); - - Property maximumHttpConnectionPerHost = new Property(HTTPEventAdapterConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST); - maximumHttpConnectionPerHost.setRequired(true); - maximumHttpConnectionPerHost.setDisplayName(resourceBundle.getString( - HTTPEventAdapterConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST)); - maximumHttpConnectionPerHost.setHint(resourceBundle.getString( - HTTPEventAdapterConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST_HINT)); - maximumHttpConnectionPerHost.setDefaultValue(HTTPEventAdapterConstants.MAX_HTTP_CONNECTION); - propertyList.add(maximumHttpConnectionPerHost); - - Property maxTotalHttpConnection = new Property(HTTPEventAdapterConstants.MAXIMUM_TOTAL_HTTP_CONNECTION); - maxTotalHttpConnection.setRequired(true); - maxTotalHttpConnection.setDisplayName(resourceBundle.getString( - HTTPEventAdapterConstants.MAXIMUM_TOTAL_HTTP_CONNECTION)); - maxTotalHttpConnection.setHint(resourceBundle.getString( - HTTPEventAdapterConstants.MAXIMUM_TOTAL_HTTP_CONNECTION_HINT)); - maxTotalHttpConnection.setDefaultValue(HTTPEventAdapterConstants.MAX_TOTAL_HTTP_CONNECTION); - propertyList.add(maxTotalHttpConnection); - //Content Validator details Property contentValidator = new Property(HTTPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME); contentValidator.setDisplayName( diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPMessageServlet.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPMessageServlet.java index 8538ef3a26..3d5351b30e 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPMessageServlet.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/HTTPMessageServlet.java @@ -60,7 +60,8 @@ public class HTTPMessageServlet extends HttpServlet { private static OAuthAuthenticator oAuthAuthenticator; public HTTPMessageServlet(InputEventAdapterListener eventAdaptorListener, int tenantId, - InputEventAdapterConfiguration eventAdapterConfiguration) { + InputEventAdapterConfiguration eventAdapterConfiguration, + Map globalProperties) { this.eventAdaptorListener = eventAdaptorListener; this.tenantId = tenantId; this.exposedTransports = eventAdapterConfiguration.getProperties().get( @@ -107,7 +108,7 @@ public class HTTPMessageServlet extends HttpServlet { } jwtAuthenticator = new JWTAuthenticator(); - oAuthAuthenticator = new OAuthAuthenticator(eventAdapterConfiguration); + oAuthAuthenticator = new OAuthAuthenticator(globalProperties); } @Override diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/oauth/OAuthAuthenticator.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/oauth/OAuthAuthenticator.java index 408cb745a7..7ccd3c98c9 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/oauth/OAuthAuthenticator.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/oauth/OAuthAuthenticator.java @@ -36,6 +36,7 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.servlet.http.HttpServletRequest; import java.rmi.RemoteException; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -51,8 +52,8 @@ public class OAuthAuthenticator { private static final String AUTHORIZATION_HEADER = "Authorization"; private static Log log = LogFactory.getLog(OAuthAuthenticator.class); - public OAuthAuthenticator(InputEventAdapterConfiguration eventAdapterConfiguration) { - this.stubs = new GenericObjectPool(new OAuthTokenValidaterStubFactory(eventAdapterConfiguration)); + public OAuthAuthenticator(Map globalProperties) { + this.stubs = new GenericObjectPool(new OAuthTokenValidaterStubFactory(globalProperties)); } public AuthenticationInfo authenticate(HttpServletRequest req) { diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/oauth/OAuthTokenValidaterStubFactory.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/oauth/OAuthTokenValidaterStubFactory.java index ee2d7eb875..38a75f0c15 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/oauth/OAuthTokenValidaterStubFactory.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/oauth/OAuthTokenValidaterStubFactory.java @@ -34,7 +34,6 @@ import org.apache.commons.pool.BasePoolableObjectFactory; import org.apache.log4j.Logger; import org.wso2.carbon.core.util.Utils; import org.wso2.carbon.device.mgt.input.adapter.http.oauth.exception.OAuthTokenValidationException; -import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration; import org.wso2.carbon.device.mgt.input.adapter.http.util.HTTPEventAdapterConstants; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; @@ -42,6 +41,7 @@ import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; +import java.util.Map; /** * This follows object pool pattern to manage the stub for oauth validation service. @@ -49,11 +49,11 @@ import java.security.GeneralSecurityException; public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory { private static final Logger log = Logger.getLogger(OAuthTokenValidaterStubFactory.class); private HttpClient httpClient; - InputEventAdapterConfiguration eventAdapterConfiguration; + Map globalProperties; - public OAuthTokenValidaterStubFactory(InputEventAdapterConfiguration eventAdapterConfiguration) { - this.eventAdapterConfiguration = eventAdapterConfiguration; + public OAuthTokenValidaterStubFactory(Map globalProperties) { + this.globalProperties = globalProperties; this.httpClient = createHttpClient(); } @@ -92,9 +92,10 @@ public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory { private OAuth2TokenValidationServiceStub generateStub() throws OAuthTokenValidationException { OAuth2TokenValidationServiceStub stub; try { - URL hostURL = new URL(Utils.replaceSystemProperty(eventAdapterConfiguration.getProperties().get( - HTTPEventAdapterConstants.TOKEN_VALIDATION_ENDPOINT_URL))); - if (hostURL != null) { + URL hostURL = new URL(Utils.replaceSystemProperty(globalProperties.get( + HTTPEventAdapterConstants.TOKEN_VALIDATION_ENDPOINT_URL) + + HTTPEventAdapterConstants.TOKEN_VALIDATION_POST_FIX)); + if (hostURL != null) { stub = new OAuth2TokenValidationServiceStub(hostURL.toString()); if (stub != null) { ServiceClient client = stub._getServiceClient(); @@ -104,10 +105,8 @@ public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory { HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator(); auth.setPreemptiveAuthentication(true); - String username = eventAdapterConfiguration.getProperties().get(HTTPEventAdapterConstants - .USERNAME); - String password = eventAdapterConfiguration.getProperties().get(HTTPEventAdapterConstants - .PASSWORD); + String username = globalProperties.get(HTTPEventAdapterConstants.USERNAME); + String password = globalProperties.get(HTTPEventAdapterConstants.PASSWORD); auth.setPassword(username); auth.setUsername(password); Options options = client.getOptions(); @@ -151,8 +150,7 @@ public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory { */ private EasySSLProtocolSocketFactory createProtocolSocketFactory() throws OAuthTokenValidationException { try { - EasySSLProtocolSocketFactory easySSLPSFactory = new EasySSLProtocolSocketFactory(); - return easySSLPSFactory; + return new EasySSLProtocolSocketFactory(); } catch (IOException e) { String errorMsg = "Failed to initiate EasySSLProtocolSocketFactory."; throw new OAuthTokenValidationException(errorMsg, e); @@ -170,9 +168,9 @@ public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory { */ private HttpClient createHttpClient() { HttpConnectionManagerParams params = new HttpConnectionManagerParams(); - params.setDefaultMaxConnectionsPerHost(Integer.parseInt(eventAdapterConfiguration.getProperties().get( - HTTPEventAdapterConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST))); - params.setMaxTotalConnections(Integer.parseInt(eventAdapterConfiguration.getProperties().get( + params.setDefaultMaxConnectionsPerHost(Integer.parseInt(globalProperties.get( + HTTPEventAdapterConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST))); + params.setMaxTotalConnections(Integer.parseInt(globalProperties.get( HTTPEventAdapterConstants.MAXIMUM_TOTAL_HTTP_CONNECTION))); HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.setParams(params); diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/util/HTTPEventAdapterConstants.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/util/HTTPEventAdapterConstants.java index b2e4e02f2f..c5d88a9752 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/util/HTTPEventAdapterConstants.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/util/HTTPEventAdapterConstants.java @@ -51,8 +51,8 @@ public final class HTTPEventAdapterConstants { public static final String MAXIMUM_TOTAL_HTTP_CONNECTION_HINT = "maximumTotalHttpConnection.hint"; public static final String MAXIMUM_HTTP_CONNECTION_PER_HOST = "maximumHttpConnectionPerHost"; public static final String MAXIMUM_HTTP_CONNECTION_PER_HOST_HINT = "maximumHttpConnectionPerHost.hint"; - public static final String TOKEN_VALIDATION_ENDPOINT_URL = "tokenValidationEndpointUrl"; - public static final String TOKEN_VALIDATION_ENDPOINT_URL_HINT = "tokenValidationEndpointUrl.hint"; + public static final String TOKEN_VALIDATION_ENDPOINT_URL = "keymanagerUrl"; + public static final String TOKEN_VALIDATION_POST_FIX = "/services/OAuth2TokenValidationService"; public static final String USERNAME = "username"; public static final String USERNAME_HINT = "username.hint"; public static final String PASSWORD = "password"; diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/resources/org/wso2/carbon/device/mgt/input/adapter/http/i18n/Resources.properties b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/resources/org/wso2/carbon/device/mgt/input/adapter/http/i18n/Resources.properties index ccdfbfa7b4..d21d209178 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/resources/org/wso2/carbon/device/mgt/input/adapter/http/i18n/Resources.properties +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/resources/org/wso2/carbon/device/mgt/input/adapter/http/i18n/Resources.properties @@ -22,16 +22,6 @@ http.usage.tips_mid1=/endpoints/<event_receiver_name>
      < http.usage.tips_mid2=/endpoints/<event_receiver_name>

    For other tenants:
      http://localhost: http.usage.tips_mid3=/endpoints/t/<tenant_domain>/<event_receiver_name>
      https://localhost: http.usage.tips_postfix=/endpoints/t/<tenant_domain>/<event_receiver_name> -tokenValidationEndpointUrl=tokenEndpointUrl -tokenValidationEndpointUrl.hint=OAUTH Token Validation Endpoint -username=username -username.hint=username of the user to connect to the admin services -password=password -password.hint=password of the user to connect to the admin services. -maximumTotalHttpConnection=maximumTotalHttpConnection -maximumTotalHttpConnection.hint=Maximum Total connection to be made with the endpoint -maximumHttpConnectionPerHost=maximumHttpConnectionPerHost -maximumHttpConnectionPerHost.hint=Maximum Http connection per host. contentValidator=contentValidator contentValidator.hint=Class Name of the content Validation or 'default' to set default class, required to implement (if required) contentTransformer=contentTransformer diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/pom.xml b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/pom.xml index c217dd92ae..9539dc4c2f 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/pom.xml +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/pom.xml @@ -20,7 +20,7 @@ org.wso2.carbon.devicemgt-plugins cdmf-transport-adapters - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../../pom.xml 4.0.0 @@ -60,10 +60,6 @@ com.googlecode.json-simple.wso2 json-simple - - org.wso2.carbon.devicemgt - org.wso2.carbon.identity.jwt.client.extension - com.jayway.jsonpath json-path @@ -128,7 +124,6 @@ org.apache.http.client.methods;version="${httpclient.version.range}", org.apache.http.impl.client;version="${httpclient.version.range}", org.json.simple.*, - org.wso2.carbon.identity.jwt.client.extension.*, com.jayway.jsonpath.* * diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/MQTTEventAdapter.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/MQTTEventAdapter.java index ce148c6a41..a2ddfd4461 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/MQTTEventAdapter.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/MQTTEventAdapter.java @@ -53,29 +53,13 @@ public class MQTTEventAdapter implements InputEventAdapter { public void init(InputEventAdapterListener eventAdapterListener) throws InputEventAdapterException { this.eventAdapterListener = eventAdapterListener; try { - int keepAlive; - - //If global properties are available those will be assigned else constant values will be assigned - if (globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE) != null) { - keepAlive = Integer.parseInt((globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE))); - } else { - keepAlive = MQTTEventAdapterConstants.ADAPTER_CONF_DEFAULT_KEEP_ALIVE; - } - mqttBrokerConnectionConfiguration = new MQTTBrokerConnectionConfiguration( - eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_URL), - eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME), - eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES), - eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL), - eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION), - keepAlive, - eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME), - eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_TRANSFORMER_CLASSNAME) - ); - mqttAdapterListener = new MQTTAdapterListener(mqttBrokerConnectionConfiguration, - eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_MESSAGE_TOPIC), - eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID), - eventAdapterListener, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + mqttBrokerConnectionConfiguration = new MQTTBrokerConnectionConfiguration(eventAdapterConfiguration + ,globalProperties); + mqttAdapterListener = new MQTTAdapterListener(mqttBrokerConnectionConfiguration + ,eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_MESSAGE_TOPIC) + ,eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID) + ,eventAdapterListener, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); } catch (Throwable t) { throw new InputEventAdapterException(t.getMessage(), t); } diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/MQTTEventAdapterFactory.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/MQTTEventAdapterFactory.java index 643bce4fbe..5212b029dc 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/MQTTEventAdapterFactory.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/MQTTEventAdapterFactory.java @@ -59,16 +59,10 @@ public class MQTTEventAdapterFactory extends InputEventAdapterFactory { //Broker Url Property brokerUrl = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_URL); brokerUrl.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_URL)); - brokerUrl.setRequired(true); + brokerUrl.setRequired(false); brokerUrl.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_URL_HINT)); propertyList.add(brokerUrl); - //DCR endpoint details - Property dcrUrl = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL); - dcrUrl.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL)); - dcrUrl.setRequired(false); - dcrUrl.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL_HINT)); - propertyList.add(dcrUrl); //Content Validator details Property contentValidator = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME); @@ -84,10 +78,18 @@ public class MQTTEventAdapterFactory extends InputEventAdapterFactory { Property userName = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME); userName.setDisplayName( resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME)); - userName.setRequired(false); + userName.setRequired(true); userName.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME_HINT)); propertyList.add(userName); + //Broker Password + Property password = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD); + userName.setDisplayName( + resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD)); + userName.setRequired(true); + userName.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD_HINT)); + propertyList.add(password); + //Broker Required Scopes. Property scopes = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES); scopes.setDisplayName( diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/internal/InputAdapterServiceComponent.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/internal/InputAdapterServiceComponent.java index 4a39cf4f70..d02b8d356a 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/internal/InputAdapterServiceComponent.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/internal/InputAdapterServiceComponent.java @@ -23,13 +23,9 @@ import org.osgi.service.component.ComponentContext; import org.osgi.service.http.HttpService; import org.wso2.carbon.device.mgt.input.adapter.mqtt.MQTTEventAdapterFactory; import org.wso2.carbon.event.input.adapter.core.InputEventAdapterFactory; -import org.wso2.carbon.user.core.service.RealmService; /** * @scr.component name="input.iot.mqtt.AdapterService.component" immediate="true" - * @scr.reference name="user.realmservice.default" - * interface="org.wso2.carbon.user.core.service.RealmService" cardinality="1..1" - * policy="dynamic" bind="setRealmService" unbind="unsetRealmService" */ public class InputAdapterServiceComponent { @@ -48,14 +44,6 @@ public class InputAdapterServiceComponent { } } - protected void setRealmService(RealmService realmService) { - InputAdapterServiceDataHolder.registerRealmService(realmService); - } - - protected void unsetRealmService(RealmService realmService) { - InputAdapterServiceDataHolder.registerRealmService(null); - } - protected void setHttpService(HttpService httpService) { InputAdapterServiceDataHolder.registerHTTPService(httpService); } diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/internal/InputAdapterServiceDataHolder.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/internal/InputAdapterServiceDataHolder.java index 77053f6581..5335ddfb40 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/internal/InputAdapterServiceDataHolder.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/internal/InputAdapterServiceDataHolder.java @@ -15,28 +15,17 @@ package org.wso2.carbon.device.mgt.input.adapter.mqtt.internal; import org.osgi.service.http.HttpService; -import org.wso2.carbon.user.core.service.RealmService; /** * common place to hold some OSGI service references. */ public final class InputAdapterServiceDataHolder { - private static RealmService realmService; private static HttpService httpService; private InputAdapterServiceDataHolder() { } - public static void registerRealmService( - RealmService realmService) { - InputAdapterServiceDataHolder.realmService = realmService; - } - - public static RealmService getRealmService() { - return realmService; - } - public static void registerHTTPService( HttpService httpService) { InputAdapterServiceDataHolder.httpService = httpService; diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTAdapterListener.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTAdapterListener.java index cf864d5838..96546c3ada 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTAdapterListener.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTAdapterListener.java @@ -17,13 +17,18 @@ */ package org.wso2.carbon.device.mgt.input.adapter.mqtt.util; +import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence; import org.json.simple.JSONObject; @@ -39,9 +44,6 @@ import org.wso2.carbon.device.mgt.input.adapter.extension.DefaultContentValidato import org.wso2.carbon.event.input.adapter.core.InputEventAdapterListener; import org.wso2.carbon.event.input.adapter.core.exception.InputEventAdapterRuntimeException; import org.wso2.carbon.device.mgt.input.adapter.mqtt.exception.MQTTContentInitializationException; -import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; -import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; -import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import java.io.IOException; import java.net.MalformedURLException; @@ -49,7 +51,9 @@ import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; public class MQTTAdapterListener implements MqttCallback, Runnable { @@ -144,16 +148,14 @@ public class MQTTAdapterListener implements MqttCallback, Runnable { } public void startListener() throws MqttException { - if (this.mqttBrokerConnectionConfiguration.getBrokerUsername() != null && + if (this.mqttBrokerConnectionConfiguration.getUsername() != null && this.mqttBrokerConnectionConfiguration.getDcrUrl() != null) { - String username = this.mqttBrokerConnectionConfiguration.getBrokerUsername(); + String username = this.mqttBrokerConnectionConfiguration.getUsername(); + String password = this.mqttBrokerConnectionConfiguration.getPassword(); String dcrUrlString = this.mqttBrokerConnectionConfiguration.getDcrUrl(); String scopes = this.mqttBrokerConnectionConfiguration.getBrokerScopes(); //getJWT Client Parameters. if (dcrUrlString != null && !dcrUrlString.isEmpty()) { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); try { URL dcrUrl = new URL(dcrUrlString); HttpClient httpClient = MQTTUtil.getHttpClient(dcrUrl.getProtocol()); @@ -163,11 +165,15 @@ public class MQTTAdapterListener implements MqttCallback, Runnable { registrationProfile.setGrantType(MQTTEventAdapterConstants.GRANT_TYPE); registrationProfile.setOwner(username); registrationProfile.setTokenScope(MQTTEventAdapterConstants.TOKEN_SCOPE); - registrationProfile.setApplicationType(MQTTEventAdapterConstants.APPLICATION_TYPE); - registrationProfile.setClientName(username + "_" + tenantId); + registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX + + mqttBrokerConnectionConfiguration.getAdapterName() + "_" + tenantId); String jsonString = registrationProfile.toJSON(); StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); postMethod.setEntity(requestEntity); + String basicAuth = getBase64Encode(username, password); + postMethod.setHeader(new BasicHeader(MQTTEventAdapterConstants.AUTHORIZATION_HEADER_NAME, + MQTTEventAdapterConstants.AUTHORIZATION_HEADER_VALUE_PREFIX + + basicAuth)); HttpResponse httpResponse = httpClient.execute(postMethod); if (httpResponse != null) { String response = MQTTUtil.getResponseString(httpResponse); @@ -177,16 +183,10 @@ public class MQTTAdapterListener implements MqttCallback, Runnable { JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); String clientId = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_ID); String clientSecret = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_SECRET); - JWTClientManagerService jwtClientManagerService = MQTTUtil.getJWTClientManagerService(); - AccessTokenInfo accessTokenInfo = jwtClientManagerService.getJWTClient().getAccessToken( - clientId, clientSecret, username, scopes); - connectionOptions.setUserName(accessTokenInfo.getAccessToken()); + connectionOptions.setUserName(getToken(clientId, clientSecret)); } } catch (ParseException e) { - String msg = "error occurred while parsing client credential payload"; - log.error(msg, e); - } catch (JWTClientException e) { - String msg = "error occurred while parsing the response from JWT Client"; + String msg = "error occurred while parsing generating token for the adapter"; log.error(msg, e); } } @@ -194,8 +194,6 @@ public class MQTTAdapterListener implements MqttCallback, Runnable { log.error("Invalid dcrUrl : " + dcrUrlString); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException e) { log.error("Failed to create an https connection.", e); - } finally { - PrivilegedCarbonContext.endTenantFlow(); } } } @@ -287,4 +285,39 @@ public class MQTTAdapterListener implements MqttCallback, Runnable { public boolean isConnectionInitialized() { return connectionInitialized; } + + private String getToken(String clientId, String clientSecret) + throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, ParseException { + URL tokenEndpoint = new URL(mqttBrokerConnectionConfiguration.getTokenUrl()); + HttpClient httpClient = MQTTUtil.getHttpClient(tokenEndpoint.getProtocol()); + HttpPost postMethod = new HttpPost(tokenEndpoint.toString()); + + List nameValuePairs = new ArrayList<>(); + nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.GRANT_TYPE_PARAM_NAME, + MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE)); + nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE_USERNAME, + mqttBrokerConnectionConfiguration.getUsername())); + nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE_PASSWORD, + mqttBrokerConnectionConfiguration.getPassword())); + String scopes = mqttBrokerConnectionConfiguration.getBrokerScopes(); + if (scopes != null && !scopes.isEmpty()) { + nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE_SCOPES, scopes)); + } + + postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs)); + postMethod.addHeader("Authorization", "Basic " + getBase64Encode(clientId, clientSecret)); + postMethod.addHeader("Content-Type", "application/x-www-form-urlencoded"); + HttpResponse httpResponse = httpClient.execute(postMethod); + String response = MQTTUtil.getResponseString(httpResponse); + if (log.isDebugEnabled()) { + log.debug(response); + } + JSONParser jsonParser = new JSONParser(); + JSONObject jsonObject = (JSONObject) jsonParser.parse(response); + return (String) jsonObject.get(MQTTEventAdapterConstants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME); + } + + private String getBase64Encode(String key, String value) { + return new String(Base64.encodeBase64((key + ":" + value).getBytes())); + } } diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTBrokerConnectionConfiguration.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTBrokerConnectionConfiguration.java index 0724937799..59ef8a3b41 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTBrokerConnectionConfiguration.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTBrokerConnectionConfiguration.java @@ -17,28 +17,38 @@ */ package org.wso2.carbon.device.mgt.input.adapter.mqtt.util; +import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration; import org.wso2.carbon.event.input.adapter.core.exception.InputEventAdapterException; +import java.util.Map; + /** * This holds the configurations related to MQTT Broker. */ public class MQTTBrokerConnectionConfiguration { - private String brokerUsername = null; + private String username = null; + private String password = null; private String brokerScopes = null; private boolean cleanSession = true; private int keepAlive; private String brokerUrl; private String dcrUrl; + private String tokenUrl; private String contentValidatorClassName; private String contentTransformerClassName; + private String adapterName; public String getBrokerScopes() { return brokerScopes; } - public String getBrokerUsername() { - return brokerUsername; + public String getUsername() { + return username; + } + + public String getPassword() { + return password; } public boolean isCleanSession() { @@ -65,21 +75,44 @@ public class MQTTBrokerConnectionConfiguration { return contentTransformerClassName; } - public MQTTBrokerConnectionConfiguration(String brokerUrl, String brokerUsername, String brokerScopes, - String dcrUrl, String cleanSession, int keepAlive, - String contentValidatorClassName, String contentTransformerClassName) throws InputEventAdapterException { - this.brokerUsername = brokerUsername; - this.brokerScopes = brokerScopes; + public String getTokenUrl() { + return tokenUrl; + } + + public String getAdapterName() { + return adapterName; + } + + public MQTTBrokerConnectionConfiguration(InputEventAdapterConfiguration eventAdapterConfiguration, + Map globalProperties) throws InputEventAdapterException { + + adapterName = eventAdapterConfiguration.getName(); + this.username = eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME); + this.password = eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD); + this.brokerScopes = eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES); if (brokerScopes == null) { this.brokerScopes = MQTTEventAdapterConstants.EMPTY_STRING; } - this.brokerUrl = PropertyUtils.replaceMqttProperty(brokerUrl); - this.dcrUrl = PropertyUtils.replaceMqttProperty(dcrUrl); - this.contentValidatorClassName = contentValidatorClassName; - if (cleanSession != null) { - this.cleanSession = Boolean.parseBoolean(cleanSession); + String url = eventAdapterConfiguration .getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_URL); + if (url == null || url.isEmpty()) { + url = globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_URL); + } + this.brokerUrl = PropertyUtils.replaceMqttProperty(url); + this.dcrUrl = PropertyUtils + .replaceMqttProperty(globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL)); + this.tokenUrl = PropertyUtils + .replaceMqttProperty(globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_TOKEN_URL)); + this.contentValidatorClassName = eventAdapterConfiguration.getProperties() + .get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME); + this.cleanSession = Boolean.parseBoolean(eventAdapterConfiguration.getProperties() + .get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION)); + //If global properties are available those will be assigned else constant values will be assigned + if (globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE) != null) { + keepAlive = Integer.parseInt((globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE))); + } else { + keepAlive = MQTTEventAdapterConstants.ADAPTER_CONF_DEFAULT_KEEP_ALIVE; } - this.keepAlive = keepAlive; - this.contentTransformerClassName = contentTransformerClassName; + this.contentTransformerClassName = eventAdapterConfiguration.getProperties() + .get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_TRANSFORMER_CLASSNAME); } } diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTEventAdapterConstants.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTEventAdapterConstants.java index d02d5624fe..f21abd29bc 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTEventAdapterConstants.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTEventAdapterConstants.java @@ -27,10 +27,13 @@ public class MQTTEventAdapterConstants { public static final String ADAPTER_CONF_URL = "url"; public static final String ADAPTER_CONF_USERNAME = "username"; public static final String ADAPTER_CONF_USERNAME_HINT = "username.hint"; + public static final String ADAPTER_CONF_PASSWORD = "password"; + public static final String ADAPTER_CONF_PASSWORD_HINT = "password.hint"; public static final String ADAPTER_CONF_SCOPES = "scopes"; public static final String ADAPTER_CONF_SCOPES_HINT = "scopes.hint"; public static final String ADAPTER_CONF_URL_HINT = "url.hint"; public static final String ADAPTER_CONF_DCR_URL = "dcrUrl"; + public static final String ADAPTER_CONF_TOKEN_URL = "tokenUrl"; public static final String ADAPTER_CONF_DCR_URL_HINT = "dcrUrl.hint"; public static final String ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME = "contentValidator"; public static final String ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME_HINT = "contentValidator.hint"; @@ -49,11 +52,12 @@ public class MQTTEventAdapterConstants { public static final int RECONNECTION_PROGRESS_FACTOR = 2; public static final String EMPTY_STRING = ""; - public static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer refresh_token"; + public static final String GRANT_TYPE_PARAM_NAME = "grant_type"; + public static final String GRANT_TYPE = "password refresh_token"; public static final String TOKEN_SCOPE = "production"; - public static final String APPLICATION_TYPE = "device"; - public static final String CLIENT_ID = "client_id"; - public static final String CLIENT_SECRET = "client_secret"; + public static final String APPLICATION_NAME_PREFIX = "InputAdapter_"; + public static final String CLIENT_ID = "clientId"; + public static final String CLIENT_SECRET = "clientSecret"; public static final String CLIENT_NAME = "client_name"; public static final String DEFAULT = "default"; public static final String MQTT_CONTENT_VALIDATION_DEFAULT_PARAMETERS = ""; @@ -62,4 +66,12 @@ public class MQTTEventAdapterConstants { public static final String DEVICE_ID_JSON_PATH = "event.metaData.deviceId"; public static final String DEVICE_TYPE_JSON_PATH = "event.metaData.deviceId"; public static final int DEVICE_ID_TOPIC_HIERARCHY_INDEX = 2; + public static final String AUTHORIZATION_HEADER_NAME = "Authorization"; + public static final String AUTHORIZATION_HEADER_VALUE_PREFIX = "Basic "; + public static final String PASSWORD_GRANT_TYPE = "password"; + public static final String PASSWORD_GRANT_TYPE_USERNAME = "username"; + public static final String PASSWORD_GRANT_TYPE_PASSWORD = "password"; + public static final String PASSWORD_GRANT_TYPE_SCOPES = "scopes"; + public static final String ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME = "access_token"; + } diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTUtil.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTUtil.java index ca01b75b6f..2a5f71a10d 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTUtil.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/input/adapter/mqtt/util/MQTTUtil.java @@ -27,8 +27,6 @@ import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import java.io.BufferedReader; import java.io.IOException; @@ -84,16 +82,4 @@ public class MQTTUtil { } } } - - public static JWTClientManagerService getJWTClientManagerService() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - JWTClientManagerService jwtClientManagerService = - (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null); - if (jwtClientManagerService == null) { - String msg = "JWT management service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return jwtClientManagerService; - } } diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/resources/org/wso2/carbon/device/mgt/input/adapter/mqtt/i18n/Resources.properties b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/resources/org/wso2/carbon/device/mgt/input/adapter/mqtt/i18n/Resources.properties index f75e4075c8..a2d8774193 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/resources/org/wso2/carbon/device/mgt/input/adapter/mqtt/i18n/Resources.properties +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/src/main/resources/org/wso2/carbon/device/mgt/input/adapter/mqtt/i18n/Resources.properties @@ -20,9 +20,11 @@ topic=Topic topic.hint=Topic subscribed clientId=Client Id clientId.hint=client identifier is used by the server to identify a client when it reconnects, It used for durable subscriptions or reliable delivery of messages is required. -url=Broker Url +url=Broker Url (Not required), If it is not provided then it will connect to the default broker. username=Username username.hint=Username of the broker (if required) +password=Password +password.hint=Password of the user for the broker (if required) scopes=Scopes scopes.hint=Scopes required to connect to broker (if required) dcrUrl=dcrUrl diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.xmpp/pom.xml b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.xmpp/pom.xml index 34f3a24d90..b721416e87 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.xmpp/pom.xml +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.xmpp/pom.xml @@ -20,7 +20,7 @@ org.wso2.carbon.devicemgt-plugins cdmf-transport-adapters - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/pom.xml b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/pom.xml index f6af28854d..14bb28576d 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/pom.xml +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/pom.xml @@ -20,7 +20,7 @@ org.wso2.carbon.devicemgt-plugins cdmf-transport-adapters - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../../pom.xml 4.0.0 @@ -61,10 +61,6 @@ com.googlecode.json-simple.wso2 json-simple - - org.wso2.carbon.devicemgt - org.wso2.carbon.identity.jwt.client.extension - @@ -122,7 +118,10 @@ org.osgi.framework, org.osgi.service.component, org.wso2.carbon.context, - org.wso2.carbon.identity.jwt.client.extension.* + org.apache.commons.codec.binary, + org.apache.http.client.entity, + org.apache.http.message, + org.apache.commons.ssl diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/MQTTEventAdapter.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/MQTTEventAdapter.java index ca7b33393e..a87fddf588 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/MQTTEventAdapter.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/MQTTEventAdapter.java @@ -118,19 +118,7 @@ public class MQTTEventAdapter implements OutputEventAdapter { @Override public void connect() { MQTTBrokerConnectionConfiguration mqttBrokerConnectionConfiguration = - new MQTTBrokerConnectionConfiguration(eventAdapterConfiguration.getStaticProperties() - .get(MQTTEventAdapterConstants.ADAPTER_CONF_URL), - eventAdapterConfiguration.getStaticProperties() - .get(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME), - eventAdapterConfiguration.getStaticProperties() - .get(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL), - eventAdapterConfiguration.getStaticProperties() - .get(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES), - connectionKeepAliveInterval, - eventAdapterConfiguration.getStaticProperties() - .get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION) - ); - + new MQTTBrokerConnectionConfiguration(eventAdapterConfiguration, globalProperties); String clientId = eventAdapterConfiguration.getStaticProperties().get( MQTTEventAdapterConstants.ADAPTER_CONF_CLIENTID); qos = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_MESSAGE_QOS); diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/MQTTEventAdapterFactory.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/MQTTEventAdapterFactory.java index d2f7ff3be8..9275ec20dc 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/MQTTEventAdapterFactory.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/MQTTEventAdapterFactory.java @@ -50,7 +50,7 @@ public class MQTTEventAdapterFactory extends OutputEventAdapterFactory { //Broker Url Property brokerUrl = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_URL); brokerUrl.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_URL)); - brokerUrl.setRequired(true); + brokerUrl.setRequired(false); brokerUrl.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_URL_HINT)); //Broker Username @@ -59,11 +59,11 @@ public class MQTTEventAdapterFactory extends OutputEventAdapterFactory { userName.setRequired(true); userName.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME_HINT)); - //Broker dcr URL - Property dcrUrl = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL); - dcrUrl.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL)); - dcrUrl.setRequired(true); - dcrUrl.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL_HINT)); + //Broker Password + Property password = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD); + password.setDisplayName(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD)); + password.setRequired(true); + password.setHint(resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD_HINT)); //Broker Connection Scopes Property scopes = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES); @@ -95,10 +95,10 @@ public class MQTTEventAdapterFactory extends OutputEventAdapterFactory { staticPropertyList.add(brokerUrl); staticPropertyList.add(userName); - staticPropertyList.add(dcrUrl); staticPropertyList.add(scopes); staticPropertyList.add(clearSession); staticPropertyList.add(qos); + staticPropertyList.add(password); return staticPropertyList; } diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTAdapterPublisher.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTAdapterPublisher.java index eee4d60845..79188e840b 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTAdapterPublisher.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTAdapterPublisher.java @@ -19,11 +19,16 @@ package org.wso2.carbon.device.mgt.output.adapter.mqtt.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.commons.ssl.Base64; import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; @@ -36,9 +41,6 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.event.output.adapter.core.exception.ConnectionUnavailableException; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterRuntimeException; -import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; -import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; -import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import java.io.IOException; import java.net.MalformedURLException; @@ -46,6 +48,8 @@ import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.List; /** * MQTT publisher related configuration initialization and publishing capabilties are implemented here. @@ -77,10 +81,8 @@ public class MQTTAdapterPublisher { MqttConnectOptions connectionOptions = new MqttConnectOptions(); connectionOptions.setCleanSession(cleanSession); connectionOptions.setKeepAliveInterval(keepAlive); - if (mqttBrokerConnectionConfiguration.getBrokerUsername() != null) { - connectionOptions.setUserName(getToken(mqttBrokerConnectionConfiguration.getBrokerUsername(), - mqttBrokerConnectionConfiguration.getDcrUrl(), - mqttBrokerConnectionConfiguration.getScopes())); + if (mqttBrokerConnectionConfiguration.getUsername() != null) { + connectionOptions.setUserName(getToken()); connectionOptions.setPassword(MQTTEventAdapterConstants.DEFAULT_PASSWORD.toCharArray()); } // Construct an MQTT blocking mode client @@ -139,7 +141,11 @@ public class MQTTAdapterPublisher { } } - private String getToken(String username, String dcrUrlString, String scopes) { + private String getToken() { + String username = this.mqttBrokerConnectionConfiguration.getUsername(); + String password = this.mqttBrokerConnectionConfiguration.getPassword(); + String dcrUrlString = this.mqttBrokerConnectionConfiguration.getDcrUrl(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); if (dcrUrlString != null && !dcrUrlString.isEmpty()) { try { @@ -147,32 +153,34 @@ public class MQTTAdapterPublisher { HttpClient httpClient = MQTTUtil.getHttpClient(dcrUrl.getProtocol()); HttpPost postMethod = new HttpPost(dcrUrlString); RegistrationProfile registrationProfile = new RegistrationProfile(); - registrationProfile.setCallbackUrl(MQTTEventAdapterConstants.DEFAULT_CALLBACK); + registrationProfile.setCallbackUrl(MQTTEventAdapterConstants.EMPTY_STRING); registrationProfile.setGrantType(MQTTEventAdapterConstants.GRANT_TYPE); registrationProfile.setOwner(username); registrationProfile.setTokenScope(MQTTEventAdapterConstants.TOKEN_SCOPE); - registrationProfile.setApplicationType(MQTTEventAdapterConstants.APPLICATION_TYPE); - registrationProfile.setClientName(username + "_" + tenantId); + registrationProfile.setClientName(MQTTEventAdapterConstants.APPLICATION_NAME_PREFIX + + mqttBrokerConnectionConfiguration.getAdapterName() + "_" + tenantId); String jsonString = registrationProfile.toJSON(); StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON); postMethod.setEntity(requestEntity); + String basicAuth = getBase64Encode(username, password); + postMethod.setHeader(new BasicHeader(MQTTEventAdapterConstants.AUTHORIZATION_HEADER_NAME, + MQTTEventAdapterConstants.AUTHORIZATION_HEADER_VALUE_PREFIX + + basicAuth)); HttpResponse httpResponse = httpClient.execute(postMethod); - String response = MQTTUtil.getResponseString(httpResponse); - try { - JSONParser jsonParser = new JSONParser(); - JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); - String clientId = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_ID); - String clientSecret = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_SECRET); - JWTClientManagerService jwtClientManagerService = MQTTUtil.getJWTClientManagerService(); - AccessTokenInfo accessTokenInfo = jwtClientManagerService.getJWTClient().getAccessToken( - clientId, clientSecret, username, scopes); - return accessTokenInfo.getAccessToken(); - } catch (ParseException e) { - String msg = "error occurred while parsing client credential payload"; - throw new OutputEventAdapterRuntimeException(msg, e); - } catch (JWTClientException e) { - String msg = "error occurred while parsing the response from JWT Client"; - throw new OutputEventAdapterRuntimeException(msg, e); + if (httpResponse != null) { + String response = MQTTUtil.getResponseString(httpResponse); + try { + if (response != null) { + JSONParser jsonParser = new JSONParser(); + JSONObject jsonPayload = (JSONObject) jsonParser.parse(response); + String clientId = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_ID); + String clientSecret = (String) jsonPayload.get(MQTTEventAdapterConstants.CLIENT_SECRET); + return getToken(clientId, clientSecret); + } + } catch (ParseException e) { + String msg = "error occurred while parsing generating token for the adapter"; + log.error(msg, e); + } } } catch (MalformedURLException e) { throw new OutputEventAdapterRuntimeException("Invalid dcrUrl : " + dcrUrlString); @@ -183,4 +191,39 @@ public class MQTTAdapterPublisher { throw new OutputEventAdapterRuntimeException("Invalid configuration for mqtt publisher"); } + private String getToken(String clientId, String clientSecret) + throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, ParseException { + URL tokenEndpoint = new URL(mqttBrokerConnectionConfiguration.getTokenUrl()); + HttpClient httpClient = MQTTUtil.getHttpClient(tokenEndpoint.getProtocol()); + HttpPost postMethod = new HttpPost(tokenEndpoint.toString()); + + List nameValuePairs = new ArrayList<>(); + nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.GRANT_TYPE_PARAM_NAME, + MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE)); + nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE_USERNAME, + mqttBrokerConnectionConfiguration.getUsername())); + nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE_PASSWORD, + mqttBrokerConnectionConfiguration.getPassword())); + String scopes = mqttBrokerConnectionConfiguration.getScopes(); + if (scopes != null && !scopes.isEmpty()) { + nameValuePairs.add(new BasicNameValuePair(MQTTEventAdapterConstants.PASSWORD_GRANT_TYPE_SCOPES, scopes)); + } + + postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs)); + postMethod.addHeader("Authorization", "Basic " + getBase64Encode(clientId, clientSecret)); + postMethod.addHeader("Content-Type", "application/x-www-form-urlencoded"); + HttpResponse httpResponse = httpClient.execute(postMethod); + String response = MQTTUtil.getResponseString(httpResponse); + if (log.isDebugEnabled()) { + log.debug(response); + } + JSONParser jsonParser = new JSONParser(); + JSONObject jsonObject = (JSONObject) jsonParser.parse(response); + return (String) jsonObject.get(MQTTEventAdapterConstants.ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME); + } + + private String getBase64Encode(String key, String value) { + return new String(Base64.encodeBase64((key + ":" + value).getBytes())); + } + } diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTBrokerConnectionConfiguration.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTBrokerConnectionConfiguration.java index 83a8460b87..b88d9d18ba 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTBrokerConnectionConfiguration.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTBrokerConnectionConfiguration.java @@ -17,14 +17,25 @@ */ package org.wso2.carbon.device.mgt.output.adapter.mqtt.util; +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration; +import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; + +import java.util.Map; + public class MQTTBrokerConnectionConfiguration { - private String brokerUsername; + private String adapterName; + private String username; + private String password; private String dcrUrl; private String scopes; private String brokerUrl; + private String tokenUrl; private boolean cleanSession = true; private int keepAlive; + public String getTokenUrl() { + return tokenUrl; + } public String getDcrUrl() { return dcrUrl; @@ -34,8 +45,12 @@ public class MQTTBrokerConnectionConfiguration { return scopes; } - public String getBrokerUsername() { - return brokerUsername; + public String getUsername() { + return username; + } + + public String getPassword() { + return password; } public boolean isCleanSession() { @@ -50,15 +65,35 @@ public class MQTTBrokerConnectionConfiguration { return keepAlive; } - public MQTTBrokerConnectionConfiguration(String brokerUrl, String brokerUsername, - String dcrUrl, String scopes, int keepAlive, String cleanSession) { - this.brokerUsername = brokerUsername; - this.dcrUrl = dcrUrl; - this.scopes = scopes; - this.brokerUrl = brokerUrl; - this.keepAlive = keepAlive; - if (cleanSession != null) { - this.cleanSession = Boolean.parseBoolean(cleanSession); + public String getAdapterName() { + return adapterName; + } + + public MQTTBrokerConnectionConfiguration(OutputEventAdapterConfiguration eventAdapterConfiguration, + Map globalProperties) { + adapterName = eventAdapterConfiguration.getName(); + this.username = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME); + this.password = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_PASSWORD); + String url = eventAdapterConfiguration .getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_URL); + if (url == null || url.isEmpty()) { + url = globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_URL); + } + this.brokerUrl = PropertyUtils.replaceMqttProperty(url); + this.dcrUrl = PropertyUtils + .replaceMqttProperty(globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_DCR_URL)); + this.tokenUrl = PropertyUtils + .replaceMqttProperty(globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_TOKEN_URL)); + this.scopes = eventAdapterConfiguration.getStaticProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_SCOPES); + if (scopes == null) { + this.scopes = MQTTEventAdapterConstants.EMPTY_STRING; + } + this.cleanSession = Boolean.parseBoolean(eventAdapterConfiguration.getStaticProperties() + .get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION)); + //If global properties are available those will be assigned else constant values will be assigned + if (globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE) != null) { + keepAlive = Integer.parseInt((globalProperties.get(MQTTEventAdapterConstants.ADAPTER_CONF_KEEP_ALIVE))); + } else { + keepAlive = MQTTEventAdapterConstants.ADAPTER_CONF_DEFAULT_KEEP_ALIVE; } } diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTEventAdapterConstants.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTEventAdapterConstants.java index 228a8c6b4a..732af141c4 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTEventAdapterConstants.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTEventAdapterConstants.java @@ -27,8 +27,10 @@ public final class MQTTEventAdapterConstants { public static final String ADAPTER_CONF_URL = "url"; public static final String ADAPTER_CONF_USERNAME = "username"; public static final String ADAPTER_CONF_USERNAME_HINT = "username.hint"; + public static final String ADAPTER_CONF_PASSWORD = "password"; + public static final String ADAPTER_CONF_PASSWORD_HINT = "password.hint"; public static final String ADAPTER_CONF_DCR_URL = "dcrUrl"; - public static final String ADAPTER_CONF_DCR_URL_HINT = "dcrUrl.hint"; + public static final String ADAPTER_CONF_TOKEN_URL = "tokenUrl"; public static final String ADAPTER_CONF_SCOPES = "scopes"; public static final String ADAPTER_CONF_SCOPES_HINT = "scopes.hint"; public static final String ADAPTER_CONF_URL_HINT = "url.hint"; @@ -41,6 +43,9 @@ public final class MQTTEventAdapterConstants { public static final String ADAPTER_TEMP_DIRECTORY_NAME = "java.io.tmpdir"; public static final String ADAPTER_CONF_CLIENTID = "clientId"; public static final String ADAPTER_CONF_CLIENTID_HINT = "clientId.hint"; + public static final String EMPTY_STRING = ""; + public static final String ADAPTER_CONF_KEEP_ALIVE = "keepAlive"; + public static final int ADAPTER_CONF_DEFAULT_KEEP_ALIVE = 60000; public static final int DEFAULT_MIN_THREAD_POOL_SIZE = 8; public static final int DEFAULT_MAX_THREAD_POOL_SIZE = 100; @@ -53,9 +58,19 @@ public final class MQTTEventAdapterConstants { public static final String DEFAULT_CALLBACK = ""; public static final String DEFAULT_PASSWORD = ""; - public static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer refresh_token"; + public static final String GRANT_TYPE = "password"; public static final String TOKEN_SCOPE = "production"; - public static final String APPLICATION_TYPE = "device"; - public static final String CLIENT_ID = "client_id"; - public static final String CLIENT_SECRET = "client_secret"; + public static final String APPLICATION_NAME_PREFIX = "OutputAdapter_"; + public static final String CLIENT_ID = "clientId"; + public static final String CLIENT_SECRET = "clientSecret"; + + + public static final String AUTHORIZATION_HEADER_NAME = "Authorization"; + public static final String AUTHORIZATION_HEADER_VALUE_PREFIX = "Basic "; + public static final String PASSWORD_GRANT_TYPE = "password"; + public static final String PASSWORD_GRANT_TYPE_USERNAME = "username"; + public static final String PASSWORD_GRANT_TYPE_PASSWORD = "password"; + public static final String PASSWORD_GRANT_TYPE_SCOPES = "scopes"; + public static final String ACCESS_TOKEN_GRANT_TYPE_PARAM_NAME = "access_token"; + public static final String GRANT_TYPE_PARAM_NAME = "grant_type"; } diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTUtil.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTUtil.java index 0cb4639918..fcc8558144 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTUtil.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/MQTTUtil.java @@ -28,7 +28,6 @@ import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import java.io.BufferedReader; import java.io.IOException; @@ -85,15 +84,4 @@ public class MQTTUtil { } } - public static JWTClientManagerService getJWTClientManagerService() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - JWTClientManagerService jwtClientManagerService = - (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null); - if (jwtClientManagerService == null) { - String msg = "JWT management service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return jwtClientManagerService; - } } diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/PropertyUtils.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/PropertyUtils.java new file mode 100644 index 0000000000..deda48085b --- /dev/null +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/java/org/wso2/carbon/device/mgt/output/adapter/mqtt/util/PropertyUtils.java @@ -0,0 +1,40 @@ +/* +* 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.wso2.carbon.device.mgt.output.adapter.mqtt.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class PropertyUtils { + + //This method is only used if the mb features are within DAS. + static String replaceMqttProperty(String urlWithPlaceholders) { + String regex = "\\$\\{(.*?)\\}"; + Pattern pattern = Pattern.compile(regex); + Matcher matchPattern = pattern.matcher(urlWithPlaceholders); + while (matchPattern.find()) { + String sysPropertyName = matchPattern.group(1); + String sysPropertyValue = System.getProperty(sysPropertyName); + if (sysPropertyValue != null && !sysPropertyName.isEmpty()) { + urlWithPlaceholders = urlWithPlaceholders.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue); + } + } + return urlWithPlaceholders; + } +} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/resources/org/wso2/carbon/device/mgt/output/adapter/mqtt/i18n/Resources.properties b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/resources/org/wso2/carbon/device/mgt/output/adapter/mqtt/i18n/Resources.properties index c73a259ef5..8ffee08746 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/resources/org/wso2/carbon/device/mgt/output/adapter/mqtt/i18n/Resources.properties +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/src/main/resources/org/wso2/carbon/device/mgt/output/adapter/mqtt/i18n/Resources.properties @@ -18,13 +18,13 @@ topic=Topic url=Broker Url +url.hint=MQTT broker url username=Username username.hint=Username of the broker -dcrUrl=dcrUrl -dcrUrl.hint=Dynamic Client Registration Url +password=Password +password.hint=Password to connect to the server. scopes=scopes scopes.hint=Scopes that required to connect with the broker. -url.hint=MQTT broker url cleanSession=Clean Session cleanSession.hint=Persist topic subscriptions and ack positions across client sessions keepAlive=Keep Alive (In seconds) diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/pom.xml b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/pom.xml index 1c2f0a48ef..390264d2ec 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/pom.xml +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins cdmf-transport-adapters - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../../pom.xml diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/SubscriptionEndpoint.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/SubscriptionEndpoint.java index fc92f9cb1a..0afe5ebe2c 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/SubscriptionEndpoint.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/SubscriptionEndpoint.java @@ -52,7 +52,7 @@ public class SubscriptionEndpoint { () + ", for request URI - " + session.getRequestURI()); } - ServiceHolder.getInstance().getUiOutputCallbackControllerService().unsubscribeWebsocket(streamName, version, + ServiceHolder.getInstance().getWebsocketOutputCallbackControllerService().unsubscribeWebsocket(streamName, version, session); } @@ -68,7 +68,7 @@ public class SubscriptionEndpoint { log.error( "Error occurred in session ID: " + session.getId() + ", for request URI - " + session.getRequestURI() + ", " + throwable.getMessage(), throwable); - ServiceHolder.getInstance().getUiOutputCallbackControllerService().unsubscribeWebsocket(streamName, version, + ServiceHolder.getInstance().getWebsocketOutputCallbackControllerService().unsubscribeWebsocket(streamName, version, session); } } diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/SuperTenantSubscriptionEndpoint.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/SuperTenantSubscriptionEndpoint.java index 5eac9280eb..672e9aedfe 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/SuperTenantSubscriptionEndpoint.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/SuperTenantSubscriptionEndpoint.java @@ -75,7 +75,7 @@ public class SuperTenantSubscriptionEndpoint extends SubscriptionEndpoint { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId( MultitenantConstants.SUPER_TENANT_ID); - ServiceHolder.getInstance().getUiOutputCallbackControllerService().subscribeWebsocket(streamName, + ServiceHolder.getInstance().getWebsocketOutputCallbackControllerService().subscribeWebsocket(streamName, version, session); } finally { diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/TenantSubscriptionEndpoint.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/TenantSubscriptionEndpoint.java index 9243498a1b..6203f8888d 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/TenantSubscriptionEndpoint.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/TenantSubscriptionEndpoint.java @@ -74,7 +74,7 @@ public class TenantSubscriptionEndpoint extends SubscriptionEndpoint { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tdomain, true); - ServiceHolder.getInstance().getUiOutputCallbackControllerService().subscribeWebsocket(streamName + ServiceHolder.getInstance().getWebsocketOutputCallbackControllerService().subscribeWebsocket(streamName , version, session); } finally { PrivilegedCarbonContext.endTenantFlow(); diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/util/ServiceHolder.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/util/ServiceHolder.java index c6ddc49149..7bd8f06d01 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/util/ServiceHolder.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/endpoint/util/ServiceHolder.java @@ -21,18 +21,18 @@ package org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.output.adapter.websocket.UIOutputCallbackControllerService; +import org.wso2.carbon.device.mgt.output.adapter.websocket.WebsocketOutputCallbackControllerService; import org.wso2.carbon.device.mgt.output.adapter.websocket.service.WebsocketValidationService; public class ServiceHolder { private static ServiceHolder instance; - private UIOutputCallbackControllerService uiOutputCallbackControllerService; + private WebsocketOutputCallbackControllerService websocketOutputCallbackControllerService; private static final Log log = LogFactory.getLog(ServiceHolder.class); private ServiceHolder(){ - uiOutputCallbackControllerService = (UIOutputCallbackControllerService) PrivilegedCarbonContext - .getThreadLocalCarbonContext().getOSGiService(UIOutputCallbackControllerService.class, null); + websocketOutputCallbackControllerService = (WebsocketOutputCallbackControllerService) PrivilegedCarbonContext + .getThreadLocalCarbonContext().getOSGiService(WebsocketOutputCallbackControllerService.class, null); } public synchronized static ServiceHolder getInstance() { @@ -42,8 +42,8 @@ public class ServiceHolder { return instance; } - public UIOutputCallbackControllerService getUiOutputCallbackControllerService() { - return uiOutputCallbackControllerService; + public WebsocketOutputCallbackControllerService getWebsocketOutputCallbackControllerService() { + return websocketOutputCallbackControllerService; } public static WebsocketValidationService getWebsocketValidationService() { diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/pom.xml b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/pom.xml index 6400c6f34f..862dcd3a9f 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/pom.xml +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt-plugins cdmf-transport-adapters - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../../pom.xml @@ -134,6 +134,7 @@ org.wso2.carbon.event.output.adapter.core.*, + javax.xml, javax.xml.namespace; version=0.0.0, org.apache.axis2, org.apache.axis2.client, diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIEventAdapterFactory.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIEventAdapterFactory.java deleted file mode 100644 index 6233f6eaa5..0000000000 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIEventAdapterFactory.java +++ /dev/null @@ -1,80 +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.wso2.carbon.device.mgt.output.adapter.websocket; - -import org.wso2.carbon.device.mgt.output.adapter.websocket.util.UIEventAdapterConstants; -import org.wso2.carbon.event.output.adapter.core.MessageType; -import org.wso2.carbon.event.output.adapter.core.OutputEventAdapter; -import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration; -import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterFactory; -import org.wso2.carbon.event.output.adapter.core.Property; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.ResourceBundle; - -/** - * The UI event adapter factory class to create a UI output adapter - */ -public class UIEventAdapterFactory extends OutputEventAdapterFactory { - - private ResourceBundle resourceBundle = ResourceBundle.getBundle("org.wso2.carbon.device.mgt.output.adapter.websocket.i18n" + - ".Resources", Locale.getDefault()); - - public UIEventAdapterFactory() { - } - - @Override - public String getType() { - return UIEventAdapterConstants.ADAPTER_TYPE_UI; - } - - @Override - public List getSupportedMessageFormats() { - List supportedMessageFormats = new ArrayList(); - supportedMessageFormats.add(MessageType.WSO2EVENT); - supportedMessageFormats.add(MessageType.JSON); - return supportedMessageFormats; - } - - @Override - public List getStaticPropertyList() { - return null; - } - - @Override - public List getDynamicPropertyList() { - return null; - } - - @Override - public String getUsageTips() { - return resourceBundle.getString(UIEventAdapterConstants.ADAPTER_USAGE_TIPS_PREFIX) + " " - + resourceBundle.getString(UIEventAdapterConstants.ADAPTER_USAGE_TIPS_POSTFIX); - } - - @Override - public OutputEventAdapter createEventAdapter(OutputEventAdapterConfiguration eventAdapterConfiguration, - Map globalProperties) { - return new UIEventAdapter(eventAdapterConfiguration, globalProperties); - } - -} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIEventAdapter.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketEventAdapter.java similarity index 87% rename from components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIEventAdapter.java rename to components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketEventAdapter.java index 4d622d8e74..edf39993a0 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIEventAdapter.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketEventAdapter.java @@ -28,8 +28,8 @@ import org.wso2.carbon.databridge.commons.Attribute; import org.wso2.carbon.databridge.commons.Event; import org.wso2.carbon.databridge.commons.StreamDefinition; import org.wso2.carbon.device.mgt.output.adapter.websocket.constants.WebsocketConstants; -import org.wso2.carbon.device.mgt.output.adapter.websocket.internal.UIEventAdaptorServiceDataHolder; -import org.wso2.carbon.device.mgt.output.adapter.websocket.util.UIEventAdapterConstants; +import org.wso2.carbon.device.mgt.output.adapter.websocket.internal.WebsocketEventAdaptorServiceDataHolder; +import org.wso2.carbon.device.mgt.output.adapter.websocket.util.WebsocketEventAdapterConstants; import org.wso2.carbon.device.mgt.output.adapter.websocket.util.WebSocketSessionRequest; import org.wso2.carbon.event.output.adapter.core.EventAdapterUtil; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapter; @@ -56,9 +56,9 @@ import java.util.concurrent.TimeUnit; * Contains the life cycle of executions regarding the UI Adapter */ -public class UIEventAdapter implements OutputEventAdapter { +public class WebsocketEventAdapter implements OutputEventAdapter { - private static final Log log = LogFactory.getLog(UIEventAdapter.class); + private static final Log log = LogFactory.getLog(WebsocketEventAdapter.class); private OutputEventAdapterConfiguration eventAdapterConfiguration; private Map globalProperties; private int queueSize; @@ -72,7 +72,7 @@ public class UIEventAdapter implements OutputEventAdapter { private List streamCorrelationAttributes; private List streamPayloadAttributes; - public UIEventAdapter(OutputEventAdapterConfiguration eventAdapterConfiguration, Map globalProperties) { this.eventAdapterConfiguration = eventAdapterConfiguration; this.globalProperties = globalProperties; @@ -91,32 +91,32 @@ public class UIEventAdapter implements OutputEventAdapter { int jobQueSize; //If global properties are available those will be assigned else constant values will be assigned - if (globalProperties.get(UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME) != null) { + if (globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME) != null) { minThread = Integer.parseInt(globalProperties.get( - UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME)); + WebsocketEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME)); } else { - minThread = UIEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE; + minThread = WebsocketEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE; } - if (globalProperties.get(UIEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME) != null) { + if (globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME) != null) { maxThread = Integer.parseInt(globalProperties.get( - UIEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME)); + WebsocketEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME)); } else { - maxThread = UIEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE; + maxThread = WebsocketEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE; } - if (globalProperties.get(UIEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME) != null) { + if (globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME) != null) { defaultKeepAliveTime = Integer.parseInt(globalProperties.get( - UIEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME)); + WebsocketEventAdapterConstants.ADAPTER_KEEP_ALIVE_TIME_NAME)); } else { - defaultKeepAliveTime = UIEventAdapterConstants.DEFAULT_KEEP_ALIVE_TIME_IN_MILLIS; + defaultKeepAliveTime = WebsocketEventAdapterConstants.DEFAULT_KEEP_ALIVE_TIME_IN_MILLIS; } - if (globalProperties.get(UIEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME) != null) { + if (globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME) != null) { jobQueSize = Integer.parseInt(globalProperties.get( - UIEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME)); + WebsocketEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME)); } else { - jobQueSize = UIEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE; + jobQueSize = WebsocketEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE; } executorService = new ThreadPoolExecutor(minThread, maxThread, defaultKeepAliveTime, TimeUnit.MILLISECONDS, @@ -137,7 +137,7 @@ public class UIEventAdapter implements OutputEventAdapter { streamPayloadAttributes = streamDefinition.getPayloadData(); ConcurrentHashMap> tenantSpecifcEventOutputAdapterMap = - UIEventAdaptorServiceDataHolder.getTenantSpecificOutputEventStreamAdapterMap(); + WebsocketEventAdaptorServiceDataHolder.getTenantSpecificOutputEventStreamAdapterMap(); ConcurrentHashMap streamSpecifAdapterMap = tenantSpecifcEventOutputAdapterMap.get(tenantId); @@ -157,7 +157,7 @@ public class UIEventAdapter implements OutputEventAdapter { streamSpecifAdapterMap.put(streamId, eventAdapterConfiguration.getName()); ConcurrentHashMap>> tenantSpecificStreamMap = - UIEventAdaptorServiceDataHolder.getTenantSpecificStreamEventMap(); + WebsocketEventAdaptorServiceDataHolder.getTenantSpecificStreamEventMap(); ConcurrentHashMap> streamSpecificEventsMap = tenantSpecificStreamMap.get(tenantId); if (streamSpecificEventsMap == null) { @@ -175,16 +175,16 @@ public class UIEventAdapter implements OutputEventAdapter { } } - if (globalProperties.get(UIEventAdapterConstants.ADAPTER_EVENT_QUEUE_SIZE_NAME) != null) { + if (globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_EVENT_QUEUE_SIZE_NAME) != null) { try { queueSize = Integer.parseInt( - globalProperties.get(UIEventAdapterConstants.ADAPTER_EVENT_QUEUE_SIZE_NAME)); + globalProperties.get(WebsocketEventAdapterConstants.ADAPTER_EVENT_QUEUE_SIZE_NAME)); } catch (NumberFormatException e) { log.error("String does not have the appropriate format for conversion." + e.getMessage()); - queueSize = UIEventAdapterConstants.EVENTS_QUEUE_SIZE; + queueSize = WebsocketEventAdapterConstants.EVENTS_QUEUE_SIZE; } } else { - queueSize = UIEventAdapterConstants.EVENTS_QUEUE_SIZE; + queueSize = WebsocketEventAdapterConstants.EVENTS_QUEUE_SIZE; } } @@ -256,9 +256,9 @@ public class UIEventAdapter implements OutputEventAdapter { eventString = message.toString(); } - Object[] eventValues = new Object[UIEventAdapterConstants.INDEX_TWO]; - eventValues[UIEventAdapterConstants.INDEX_ZERO] = eventString; - eventValues[UIEventAdapterConstants.INDEX_ONE] = System.currentTimeMillis(); + Object[] eventValues = new Object[WebsocketEventAdapterConstants.INDEX_TWO]; + eventValues[WebsocketEventAdapterConstants.INDEX_ZERO] = eventString; + eventValues[WebsocketEventAdapterConstants.INDEX_ONE] = System.currentTimeMillis(); streamSpecificEvents.add(eventValues); // fetch all valid sessions checked against any queryParameters provided when subscribing. @@ -282,14 +282,14 @@ public class UIEventAdapter implements OutputEventAdapter { public void destroy() { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - ConcurrentHashMap tenantSpecificAdapterMap = UIEventAdaptorServiceDataHolder + ConcurrentHashMap tenantSpecificAdapterMap = WebsocketEventAdaptorServiceDataHolder .getTenantSpecificOutputEventStreamAdapterMap().get(tenantId); if (tenantSpecificAdapterMap != null && streamId != null) { tenantSpecificAdapterMap.remove(streamId); //Removing outputadapter and streamId } ConcurrentHashMap> tenantSpecificStreamEventMap = - UIEventAdaptorServiceDataHolder.getTenantSpecificStreamEventMap().get(tenantId); + WebsocketEventAdaptorServiceDataHolder.getTenantSpecificStreamEventMap().get(tenantId); if (tenantSpecificStreamEventMap != null && streamId != null) { //Removing the streamId and events registered for the output adapter tenantSpecificStreamEventMap.remove(streamId); @@ -310,7 +310,7 @@ public class UIEventAdapter implements OutputEventAdapter { * the matching Steam-Definition for the given StreamId cannot be retrieved. */ private StreamDefinition getStreamDefinition(String streamId) throws OutputEventAdapterException { - EventStreamService eventStreamService = UIEventAdaptorServiceDataHolder.getEventStreamService(); + EventStreamService eventStreamService = WebsocketEventAdaptorServiceDataHolder.getEventStreamService(); if (eventStreamService != null) { try { return eventStreamService.getStreamDefinition(streamId); @@ -337,11 +337,11 @@ public class UIEventAdapter implements OutputEventAdapter { */ private CopyOnWriteArrayList getValidSessions(Object event) { CopyOnWriteArrayList validSessions = new CopyOnWriteArrayList<>(); - UIOutputCallbackControllerServiceImpl uiOutputCallbackControllerServiceImpl = - UIEventAdaptorServiceDataHolder.getUIOutputCallbackRegisterServiceImpl(); + WebsocketOutputCallbackControllerServiceImpl websocketOutputCallbackControllerServiceImpl = + WebsocketEventAdaptorServiceDataHolder.getUIOutputCallbackRegisterServiceImpl(); // get all subscribed web-socket sessions. CopyOnWriteArrayList webSocketSessionUtils = - uiOutputCallbackControllerServiceImpl.getSessions(tenantId, streamId); + websocketOutputCallbackControllerServiceImpl.getSessions(tenantId, streamId); if (webSocketSessionUtils != null) { for (WebSocketSessionRequest webSocketSessionUtil : webSocketSessionUtils) { boolean isValidSession; diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketEventAdapterFactory.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketEventAdapterFactory.java new file mode 100644 index 0000000000..d06baa9087 --- /dev/null +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketEventAdapterFactory.java @@ -0,0 +1,138 @@ +/* + * 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.wso2.carbon.device.mgt.output.adapter.websocket; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +import org.wso2.carbon.device.mgt.output.adapter.websocket.authentication.Authenticator; +import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.Authorizer; +import org.wso2.carbon.device.mgt.output.adapter.websocket.service.WebsocketValidationService; +import org.wso2.carbon.device.mgt.output.adapter.websocket.service.WebsocketValidationServiceImpl; +import org.wso2.carbon.device.mgt.output.adapter.websocket.util.WebsocketEventAdapterConstants; +import org.wso2.carbon.event.output.adapter.core.MessageType; +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapter; +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration; +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterFactory; +import org.wso2.carbon.event.output.adapter.core.Property; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.ResourceBundle; + +/** + * The UI event adapter factory class to create a UI output adapter + */ +public class WebsocketEventAdapterFactory extends OutputEventAdapterFactory { + + private ResourceBundle resourceBundle = ResourceBundle.getBundle("org.wso2.carbon.device.mgt.output.adapter.websocket.i18n" + + ".Resources", Locale.getDefault()); + private BundleContext bundleContext; + private boolean isAuthInitialized = false; + private static final Log log = LogFactory.getLog(WebsocketEventAdapter.class); + + public WebsocketEventAdapterFactory() { + } + + @Override + public String getType() { + return WebsocketEventAdapterConstants.ADAPTER_TYPE_UI; + } + + @Override + public List getSupportedMessageFormats() { + List supportedMessageFormats = new ArrayList(); + supportedMessageFormats.add(MessageType.WSO2EVENT); + supportedMessageFormats.add(MessageType.JSON); + return supportedMessageFormats; + } + + @Override + public List getStaticPropertyList() { + return null; + } + + @Override + public List getDynamicPropertyList() { + return null; + } + + @Override + public String getUsageTips() { + return resourceBundle.getString(WebsocketEventAdapterConstants.ADAPTER_USAGE_TIPS_PREFIX) + " " + + resourceBundle.getString(WebsocketEventAdapterConstants.ADAPTER_USAGE_TIPS_POSTFIX); + } + + @Override + public OutputEventAdapter createEventAdapter(OutputEventAdapterConfiguration eventAdapterConfiguration, + Map globalProperties) { + if (!isAuthInitialized) { + initializeAuthenticatorAndAuthorizor(globalProperties); + } + return new WebsocketEventAdapter(eventAdapterConfiguration, globalProperties); + } + + public BundleContext getBundleContext() { + return bundleContext; + } + + public void setBundleContext(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } + + private void initializeAuthenticatorAndAuthorizor (Map globalProperties) { + if (!isAuthInitialized) { + synchronized (WebsocketEventAdapterFactory.class) { + if (!isAuthInitialized) { + try { + WebsocketValidationServiceImpl websocketValidationService = + new WebsocketValidationServiceImpl(); + String authenticatorClassName = globalProperties.get( + WebsocketEventAdapterConstants.AUTHENTICATOR_CLASS); + String authorizerClassName = globalProperties.get(WebsocketEventAdapterConstants.AUTHORIZER_CLASS); + if (authenticatorClassName != null && !authenticatorClassName.isEmpty()) { + Class authenticatorClass = Class.forName(authenticatorClassName) + .asSubclass(Authenticator.class); + Authenticator authenticator = authenticatorClass.newInstance(); + authenticator.init(globalProperties); + websocketValidationService.setAuthenticator(authenticator); + } + if (authorizerClassName != null && !authorizerClassName.isEmpty()) { + Class authorizerClass = Class.forName(authorizerClassName) + .asSubclass(Authorizer.class); + Authorizer authorizer = authorizerClass.newInstance(); + authorizer.init(globalProperties); + websocketValidationService.setAuthorizer(authorizer); + } + bundleContext.registerService( + WebsocketValidationService.class.getName(), websocketValidationService, null); + isAuthInitialized = true; + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { + log.error("Failed to initialize the class authentication and authorization given " + + "in the websocket validation configuration.", e); + } + } + } + } + + } + +} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIOutputCallbackControllerService.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketOutputCallbackControllerService.java similarity index 96% rename from components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIOutputCallbackControllerService.java rename to components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketOutputCallbackControllerService.java index ffcfb72a46..8d1858380c 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIOutputCallbackControllerService.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketOutputCallbackControllerService.java @@ -24,7 +24,7 @@ import javax.websocket.Session; /** * This interface is exposed as an OSGI service, which will be invoked by the local websocket endpoint to inform new subscriptions; and do un-subscriptions.. */ -public interface UIOutputCallbackControllerService { +public interface WebsocketOutputCallbackControllerService { /** * Used to subscribe the session id and stream id for later web socket connectivity diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIOutputCallbackControllerServiceImpl.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketOutputCallbackControllerServiceImpl.java similarity index 87% rename from components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIOutputCallbackControllerServiceImpl.java rename to components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketOutputCallbackControllerServiceImpl.java index b71a6fc78f..d1566795dc 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/UIOutputCallbackControllerServiceImpl.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/WebsocketOutputCallbackControllerServiceImpl.java @@ -19,9 +19,9 @@ package org.wso2.carbon.device.mgt.output.adapter.websocket; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.output.adapter.websocket.internal.UIEventAdaptorServiceDataHolder; +import org.wso2.carbon.device.mgt.output.adapter.websocket.internal.WebsocketEventAdaptorServiceDataHolder; import org.wso2.carbon.device.mgt.output.adapter.websocket.util.WebSocketSessionRequest; -import org.wso2.carbon.device.mgt.output.adapter.websocket.util.UIEventAdapterConstants; +import org.wso2.carbon.device.mgt.output.adapter.websocket.util.WebsocketEventAdapterConstants; import javax.websocket.Session; import java.util.Iterator; @@ -32,12 +32,12 @@ import java.util.concurrent.LinkedBlockingDeque; /** * Service implementation class which exposes to front end */ -public class UIOutputCallbackControllerServiceImpl implements UIOutputCallbackControllerService { +public class WebsocketOutputCallbackControllerServiceImpl implements WebsocketOutputCallbackControllerService { private ConcurrentHashMap>> outputEventAdaptorSessionMap; - public UIOutputCallbackControllerServiceImpl() { + public WebsocketOutputCallbackControllerServiceImpl() { outputEventAdaptorSessionMap = new ConcurrentHashMap<>(); } @@ -53,9 +53,9 @@ public class UIOutputCallbackControllerServiceImpl implements UIOutputCallbackCo int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); if (version == null || " ".equals(version)) { - version = UIEventAdapterConstants.ADAPTER_UI_DEFAULT_OUTPUT_STREAM_VERSION; + version = WebsocketEventAdapterConstants.ADAPTER_UI_DEFAULT_OUTPUT_STREAM_VERSION; } - String streamId = streamName + UIEventAdapterConstants.ADAPTER_UI_COLON + version; + String streamId = streamName + WebsocketEventAdapterConstants.ADAPTER_UI_COLON + version; ConcurrentHashMap> tenantSpecificAdaptorMap = outputEventAdaptorSessionMap.get(tenantId); if (tenantSpecificAdaptorMap == null) { @@ -102,9 +102,9 @@ public class UIOutputCallbackControllerServiceImpl implements UIOutputCallbackCo */ public LinkedBlockingDeque getEvents(int tenanId, String streamName, String version) { ConcurrentHashMap> tenantSpecificStreamMap = - UIEventAdaptorServiceDataHolder.getTenantSpecificStreamEventMap().get(tenanId); + WebsocketEventAdaptorServiceDataHolder.getTenantSpecificStreamEventMap().get(tenanId); if (tenantSpecificStreamMap != null) { - String streamId = streamName + UIEventAdapterConstants.ADAPTER_UI_COLON + version; + String streamId = streamName + WebsocketEventAdapterConstants.ADAPTER_UI_COLON + version; return tenantSpecificStreamMap.get(streamId); } return null; @@ -120,9 +120,9 @@ public class UIOutputCallbackControllerServiceImpl implements UIOutputCallbackCo public void unsubscribeWebsocket(String streamName, String version, Session session) { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); if (version == null || " ".equals(version)) { - version = UIEventAdapterConstants.ADAPTER_UI_DEFAULT_OUTPUT_STREAM_VERSION; + version = WebsocketEventAdapterConstants.ADAPTER_UI_DEFAULT_OUTPUT_STREAM_VERSION; } - String id = streamName + UIEventAdapterConstants.ADAPTER_UI_COLON + version; + String id = streamName + WebsocketEventAdapterConstants.ADAPTER_UI_COLON + version; ConcurrentHashMap> tenantSpecificAdaptorMap = outputEventAdaptorSessionMap.get(tenantId); if (tenantSpecificAdaptorMap != null) { diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/Authenticator.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/Authenticator.java index d1d06cc5c9..fc3a85f794 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/Authenticator.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/Authenticator.java @@ -22,9 +22,14 @@ import java.util.Map; */ public interface Authenticator { + /** + * This is used to initialize the authenticator + * @param globalProperties related to the output adapter + */ + void init(Map globalProperties); + /** * Check whether the client is authenticated to connect. - * @param session user object. * @return AuthenticationInfo which contains authentication client information. */ AuthenticationInfo isAuthenticated(Map> webSocketConnectionProperties); diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/OAuthAuthenticator.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/OAuthAuthenticator.java index 698f4f8261..da5d751442 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/OAuthAuthenticator.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/OAuthAuthenticator.java @@ -20,8 +20,13 @@ import java.util.List; import java.util.Map; public class OAuthAuthenticator implements Authenticator { + OAuthTokenValdiator oAuthTokenValdiator; + @Override + public void init(Map globalProperties) { + oAuthTokenValdiator = new OAuthTokenValdiator(globalProperties); + } public AuthenticationInfo isAuthenticated(Map> webSocketConnectionProperties) { - return OAuthTokenValdiator.getInstance().validateToken(webSocketConnectionProperties); + return oAuthTokenValdiator.validateToken(webSocketConnectionProperties); } } diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/oauth/OAuthTokenValdiator.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/oauth/OAuthTokenValdiator.java index b92f08ae09..55566963ca 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/oauth/OAuthTokenValdiator.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/oauth/OAuthTokenValdiator.java @@ -20,24 +20,18 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.pool.impl.GenericObjectPool; import org.wso2.carbon.device.mgt.output.adapter.websocket.authentication.AuthenticationInfo; -import org.wso2.carbon.device.mgt.output.adapter.websocket.config.Property; -import org.wso2.carbon.device.mgt.output.adapter.websocket.config.WebsocketConfig; import org.wso2.carbon.device.mgt.output.adapter.websocket.constants.WebsocketConstants; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import java.io.File; -import java.io.IOException; import java.rmi.RemoteException; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Properties; /** * This acts as a contract point for OAuth token validation. @@ -47,8 +41,6 @@ public class OAuthTokenValdiator { private static String cookie; private GenericObjectPool stubs; private static Log log = LogFactory.getLog(OAuthTokenValdiator.class); - private static final String WEBSOCKET_CONFIG_LOCATION = - CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "websocket-validation.properties"; private static final String COOKIE_KEY_VALUE_SEPERATOR = "="; private static final String COOKIE_KEYPAIR_SEPERATOR = ";"; private static final String COOKIE = "cookie"; @@ -56,25 +48,9 @@ public class OAuthTokenValdiator { private static final String TOKEN_IDENTIFIER = "websocket-token"; private static OAuthTokenValdiator oAuthTokenValdiator; - public static OAuthTokenValdiator getInstance() { - if (oAuthTokenValdiator == null) { - synchronized (OAuthTokenValdiator.class) { - if (oAuthTokenValdiator == null) { - oAuthTokenValdiator = new OAuthTokenValdiator(); - } - } - } - return oAuthTokenValdiator; - } - private OAuthTokenValdiator() { - try { - Properties properties = getWebSocketConfig(); - this.stubs = new GenericObjectPool(new OAuthTokenValidaterStubFactory(properties)); - } catch (IOException e) { - log.error("Failed to parse the web socket org.wso2.carbon.device.mgt.output.adapter.websocket.config file " + - WEBSOCKET_CONFIG_LOCATION, e); - } + public OAuthTokenValdiator(Map globalProperties) { + this.stubs = new GenericObjectPool(new OAuthTokenValidaterStubFactory(globalProperties)); } /** @@ -174,19 +150,6 @@ public class OAuthTokenValdiator { return authenticationInfo; } - /** - * Retrieve JWT configs from registry. - */ - private Properties getWebSocketConfig() throws IOException { - Properties properties = new Properties(); - List propertyList = WebsocketConfig.getInstance().getWebsocketValidationConfigs().getAuthenticator() - .getProperties().getProperty(); - for (Property property : propertyList) { - properties.put(property.getName(), property.getValue()); - } - return properties; - } - /** * Retrieving the token from the http header * @param webSocketConnectionProperties WebSocket connection information including http headers diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/oauth/OAuthTokenValidaterStubFactory.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/oauth/OAuthTokenValidaterStubFactory.java index 50ce3f5847..637787c68f 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/oauth/OAuthTokenValidaterStubFactory.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authentication/oauth/OAuthTokenValidaterStubFactory.java @@ -35,13 +35,15 @@ import org.apache.commons.logging.LogFactory; import org.apache.commons.pool.BasePoolableObjectFactory; import org.wso2.carbon.device.mgt.output.adapter.websocket.authentication.oauth.exception.OAuthTokenValidationException; import org.wso2.carbon.device.mgt.output.adapter.websocket.constants.WebsocketConstants; +import org.wso2.carbon.device.mgt.output.adapter.websocket.util.PropertyUtils; +import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; -import java.util.Properties; +import java.util.Map; /** * This follows object pool pattern to manage the stub for oauth validation service. @@ -49,11 +51,11 @@ import java.util.Properties; public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory { private static final Log log = LogFactory.getLog(OAuthTokenValidaterStubFactory.class); private HttpClient httpClient; - Properties tokenValidationProperties; + Map tokenValidationProperties; - public OAuthTokenValidaterStubFactory(Properties tokenValidationProperties) { - this.tokenValidationProperties = tokenValidationProperties; + public OAuthTokenValidaterStubFactory(Map globalProperties) { + this.tokenValidationProperties = globalProperties; this.httpClient = createHttpClient(); } @@ -91,51 +93,46 @@ public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory { */ private OAuth2TokenValidationServiceStub generateStub() throws OAuthTokenValidationException { OAuth2TokenValidationServiceStub stub; - try { - URL hostURL = new URL(tokenValidationProperties.getProperty((WebsocketConstants.TOKEN_VALIDATION_ENDPOINT_URL))); - if (hostURL != null) { - stub = new OAuth2TokenValidationServiceStub(hostURL.toString()); - if (stub != null) { - ServiceClient client = stub._getServiceClient(); - client.getServiceContext().getConfigurationContext().setProperty( - HTTPConstants.CACHED_HTTP_CLIENT, httpClient); + try { + URL hostURL = new URL(PropertyUtils.replaceProperty(tokenValidationProperties.get( + (WebsocketConstants.TOKEN_VALIDATION_ENDPOINT_URL))) + + WebsocketConstants.TOKEN_VALIDATION_CONTEX); + stub = new OAuth2TokenValidationServiceStub(hostURL.toString()); + ServiceClient client = stub._getServiceClient(); + client.getServiceContext().getConfigurationContext().setProperty( + HTTPConstants.CACHED_HTTP_CLIENT, httpClient); - HttpTransportProperties.Authenticator auth = - new HttpTransportProperties.Authenticator(); - auth.setPreemptiveAuthentication(true); - String username = tokenValidationProperties.getProperty(WebsocketConstants.USERNAME); - String password = tokenValidationProperties.getProperty(WebsocketConstants.PASSWORD); - auth.setPassword(username); - auth.setUsername(password); - Options options = client.getOptions(); - options.setProperty(HTTPConstants.AUTHENTICATE, auth); - options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE); - client.setOptions(options); - if (hostURL.getProtocol().equals("https")) { - // set up ssl factory since axis2 https transport is used. - EasySSLProtocolSocketFactory sslProtocolSocketFactory = createProtocolSocketFactory(); - Protocol authhttps = new Protocol(hostURL.getProtocol() - , (ProtocolSocketFactory) sslProtocolSocketFactory, hostURL.getPort()); - Protocol.registerProtocol(hostURL.getProtocol(), authhttps); - options.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER, authhttps); - } - } else { - String errorMsg = "OAuth Validation instanization failed."; - throw new OAuthTokenValidationException(errorMsg); - } - } else { - String errorMsg = "host url is invalid"; - throw new OAuthTokenValidationException(errorMsg); - } - } catch (AxisFault axisFault) { - throw new OAuthTokenValidationException( - "Error occurred while creating the OAuth2TokenValidationServiceStub.", axisFault); - } catch (MalformedURLException e) { - throw new OAuthTokenValidationException( - "Error occurred while parsing token endpoint URL", e); - } + HttpTransportProperties.Authenticator auth = + new HttpTransportProperties.Authenticator(); + auth.setPreemptiveAuthentication(true); + String username = tokenValidationProperties.get(WebsocketConstants.USERNAME); + String password = tokenValidationProperties.get(WebsocketConstants.PASSWORD); + auth.setPassword(username); + auth.setUsername(password); + Options options = client.getOptions(); + options.setProperty(HTTPConstants.AUTHENTICATE, auth); + options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE); + client.setOptions(options); + if (hostURL.getProtocol().equals("https")) { + // set up ssl factory since axis2 https transport is used. + EasySSLProtocolSocketFactory sslProtocolSocketFactory = createProtocolSocketFactory(); + Protocol authhttps = new Protocol(hostURL.getProtocol() + , (ProtocolSocketFactory) sslProtocolSocketFactory, hostURL.getPort()); + Protocol.registerProtocol(hostURL.getProtocol(), authhttps); + options.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER, authhttps); + } + + } catch (AxisFault axisFault) { + throw new OAuthTokenValidationException( + "Error occurred while creating the OAuth2TokenValidationServiceStub.", axisFault); + } catch (MalformedURLException e) { + throw new OAuthTokenValidationException( + "Error occurred while parsing token endpoint URL", e); + } catch (OutputEventAdapterException e) { + throw new OAuthTokenValidationException("Invalid token endpoint url", e); + } - return stub; + return stub; } /** @@ -165,9 +162,9 @@ public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory { */ private HttpClient createHttpClient() { HttpConnectionManagerParams params = new HttpConnectionManagerParams(); - params.setDefaultMaxConnectionsPerHost(Integer.parseInt(tokenValidationProperties.getProperty( - WebsocketConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST))); - params.setMaxTotalConnections(Integer.parseInt(tokenValidationProperties.getProperty( + params.setDefaultMaxConnectionsPerHost(Integer.parseInt(tokenValidationProperties.get( + WebsocketConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST))); + params.setMaxTotalConnections(Integer.parseInt(tokenValidationProperties.get( WebsocketConstants.MAXIMUM_TOTAL_HTTP_CONNECTION))); HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.setParams(params); diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/Authorizer.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/Authorizer.java index 65809a3588..e64f11dca7 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/Authorizer.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/Authorizer.java @@ -21,12 +21,19 @@ package org.wso2.carbon.device.mgt.output.adapter.websocket.authorization; import org.wso2.carbon.device.mgt.output.adapter.websocket.authentication.AuthenticationInfo; import javax.websocket.Session; +import java.util.Map; /** * Check whether the client is authorized to connect. */ public interface Authorizer { + /** + * This is used to initialize the authenticator + * @param globalProperties related to the output adapter + */ + void init(Map globalProperties); + /** * Check whether the client is authorized to connect with the stream. * @param authenticationInfo authenticated client information. diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/DeviceAuthorizer.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/DeviceAuthorizer.java index f024706256..d8e779491d 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/DeviceAuthorizer.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/DeviceAuthorizer.java @@ -31,13 +31,13 @@ import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client. .DeviceAccessAuthorizationAdminService; import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client.dto.DeviceAuthorizationResult; import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client.dto.DeviceIdentifier; -import org.wso2.carbon.device.mgt.output.adapter.websocket.config.Properties; -import org.wso2.carbon.device.mgt.output.adapter.websocket.config.Property; -import org.wso2.carbon.device.mgt.output.adapter.websocket.config.WebsocketConfig; +import org.wso2.carbon.device.mgt.output.adapter.websocket.util.PropertyUtils; import org.wso2.carbon.device.mgt.output.adapter.websocket.util.WebSocketSessionRequest; +import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; import javax.websocket.Session; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; @@ -50,26 +50,34 @@ public class DeviceAuthorizer implements Authorizer { private static final String CDMF_SERVER_BASE_CONTEXT = "/api/device-mgt/v1.0"; private static final String DEVICE_MGT_SERVER_URL = "deviceMgtServerUrl"; private static final String STAT_PERMISSION = "statsPermission"; + private static final String DEVICE_ID = "deviceId"; + private static final String DEVICE_TYPE = "deviceType"; private static Log logger = LogFactory.getLog(DeviceAuthorizer.class); private static List statPermissions; public DeviceAuthorizer() { - Properties properties = - WebsocketConfig.getInstance().getWebsocketValidationConfigs().getAuthorizer().getProperties(); - statPermissions = getPermissions(properties); - deviceAccessAuthorizationAdminService = Feign.builder() - .requestInterceptor(new OAuthRequestInterceptor()) - .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) - .target(DeviceAccessAuthorizationAdminService.class, getDeviceMgtServerUrl(properties) - + CDMF_SERVER_BASE_CONTEXT); + } + + @Override + public void init(Map globalProperties) { + statPermissions = getPermissions(globalProperties); + try { + deviceAccessAuthorizationAdminService = Feign.builder() + .requestInterceptor(new OAuthRequestInterceptor(globalProperties)) + .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) + .target(DeviceAccessAuthorizationAdminService.class, getDeviceMgtServerUrl(globalProperties) + + CDMF_SERVER_BASE_CONTEXT); + } catch (OutputEventAdapterException e) { + logger.error("Invalid value for deviceMgtServerUrl in globalProperties."); + } } @Override public boolean isAuthorized(AuthenticationInfo authenticationInfo, Session session, String stream) { WebSocketSessionRequest webSocketSessionRequest = new WebSocketSessionRequest(session); Map queryParams = webSocketSessionRequest.getQueryParamValuePairs(); - String deviceId = queryParams.get("deviceId"); - String deviceType = queryParams.get("deviceType"); + String deviceId = queryParams.get(DEVICE_ID); + String deviceType = queryParams.get(DEVICE_TYPE); if (deviceId != null && !deviceId.isEmpty() && deviceType != null && !deviceType.isEmpty()) { @@ -102,27 +110,19 @@ public class DeviceAuthorizer implements Authorizer { return false; } - private String getDeviceMgtServerUrl(Properties properties) { - String deviceMgtServerUrl = null; - for (Property property : properties.getProperty()) { - if (property.getName().equals(DEVICE_MGT_SERVER_URL)) { - deviceMgtServerUrl = property.getValue(); - break; - } - } + private String getDeviceMgtServerUrl(Map properties) throws OutputEventAdapterException { + String deviceMgtServerUrl = PropertyUtils.replaceProperty(properties.get(DEVICE_MGT_SERVER_URL)); if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) { logger.error("deviceMgtServerUrl can't be empty "); } return deviceMgtServerUrl; } - private List getPermissions(Properties properties) { - List permission = new ArrayList<>(); - for (Property property : properties.getProperty()) { - if (property.getName().equals(STAT_PERMISSION)) { - permission.add(property.getValue()); - } + private List getPermissions(Map properties) { + String stats = properties.get(STAT_PERMISSION); + if (stats != null && !stats.isEmpty()) { + return Arrays.asList(stats.replace("\n", "").split(" ")); } - return permission; + return null; } } \ No newline at end of file diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/OAuthRequestInterceptor.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/OAuthRequestInterceptor.java index 76466b09d1..8ab7db9384 100755 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/OAuthRequestInterceptor.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/OAuthRequestInterceptor.java @@ -28,9 +28,10 @@ import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client. import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client.dto.ApiApplicationRegistrationService; import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client.dto.ApiRegistrationProfile; import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client.dto.TokenIssuerService; -import org.wso2.carbon.device.mgt.output.adapter.websocket.config.Properties; -import org.wso2.carbon.device.mgt.output.adapter.websocket.config.Property; -import org.wso2.carbon.device.mgt.output.adapter.websocket.config.WebsocketConfig; +import org.wso2.carbon.device.mgt.output.adapter.websocket.util.PropertyUtils; +import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; + +import java.util.Map; /** * This is a request interceptor to add oauth token header. @@ -51,30 +52,40 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private static final String CONNECTION_USERNAME = "username"; private static final String CONNECTION_PASSWORD = "password"; - private static final String TOKEN_ENDPOINT = "tokenEndpoint"; + private static final String TOKEN_ENDPOINT = "tokenUrl"; private static final String TOKEN_REFRESH_TIME_OFFSET = "tokenRefreshTimeOffset"; + private static final String TOKEN_SCOPES = "scopes"; private static final String DEVICE_MGT_SERVER_URL = "deviceMgtServerUrl"; + private static final String TOKEN_ENDPOINT_CONTEXT = "tokenUrl"; private static String username; private static String password; private static String tokenEndpoint; private static String deviceMgtServerUrl; + private static String scopes; + private static Map globalProperties; + /** * Creates an interceptor that authenticates all requests. */ - public OAuthRequestInterceptor() { - Properties properties = - WebsocketConfig.getInstance().getWebsocketValidationConfigs().getAuthorizer().getProperties(); - deviceMgtServerUrl = getDeviceMgtServerUrl(properties); - refreshTimeOffset = getRefreshTimeOffset(properties); - username = getUsername(properties); - password = getPassword(properties); - tokenEndpoint = getTokenEndpoint(properties); - apiApplicationRegistrationService = Feign.builder().requestInterceptor( - new BasicAuthRequestInterceptor(username, password)) - .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) - .target(ApiApplicationRegistrationService.class, - deviceMgtServerUrl + API_APPLICATION_REGISTRATION_CONTEXT); + public OAuthRequestInterceptor(Map globalProperties) { + this.globalProperties = globalProperties; + try { + deviceMgtServerUrl = getDeviceMgtServerUrl(globalProperties); + refreshTimeOffset = getRefreshTimeOffset(globalProperties); + username = getUsername(globalProperties); + password = getPassword(globalProperties); + tokenEndpoint = getTokenEndpoint(globalProperties); + scopes = getScopes(globalProperties); + apiApplicationRegistrationService = Feign.builder().requestInterceptor( + new BasicAuthRequestInterceptor(username, password)) + .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) + .target(ApiApplicationRegistrationService.class, + deviceMgtServerUrl + API_APPLICATION_REGISTRATION_CONTEXT); + } catch (OutputEventAdapterException e) { + logger.error("Invalid url: deviceMgtServerUrl" + deviceMgtServerUrl + " or tokenEndpoint:" + tokenEndpoint, + e); + } } @Override @@ -93,7 +104,11 @@ public class OAuthRequestInterceptor implements RequestInterceptor { new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(TokenIssuerService.class, tokenEndpoint); - tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password); + if (scopes == null || scopes.isEmpty()) { + tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password); + } else { + tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password, scopes); + } tokenInfo.setExpires_in(System.currentTimeMillis() + tokenInfo.getExpires_in()); } synchronized(this) { @@ -106,76 +121,51 @@ public class OAuthRequestInterceptor implements RequestInterceptor { template.header("Authorization", headerValue); } - private String getUsername(Properties properties) { - String username = null; - for (Property property : properties.getProperty()) { - if (property.getName().equals(CONNECTION_USERNAME)) { - username = property.getValue(); - break; - } - } + private String getUsername(Map globalProperties) { + String username = globalProperties.get(CONNECTION_USERNAME); if (username == null || username.isEmpty()) { logger.error("username can't be empty "); } return username; } - private String getPassword(Properties properties) { - String password = null; - for (Property property : properties.getProperty()) { - if (property.getName().equals(CONNECTION_PASSWORD)) { - password = property.getValue(); - break; - } - } + private String getPassword(Map globalProperties) { + String password = globalProperties.get(CONNECTION_PASSWORD);; if (password == null || password.isEmpty()) { logger.error("password can't be empty "); } return password; } - private String getDeviceMgtServerUrl(Properties properties) { - String deviceMgtServerUrl = null; - for (Property property : properties.getProperty()) { - if (property.getName().equals(DEVICE_MGT_SERVER_URL)) { - deviceMgtServerUrl = property.getValue(); - break; - } - } + private String getDeviceMgtServerUrl(Map globalProperties) throws OutputEventAdapterException { + String deviceMgtServerUrl = globalProperties.get(DEVICE_MGT_SERVER_URL); if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) { logger.error("deviceMgtServerUrl can't be empty "); } - return deviceMgtServerUrl; + return PropertyUtils.replaceProperty(deviceMgtServerUrl); } - private String getTokenEndpoint(Properties properties) { - String tokenEndpoint = null; - for (Property property : properties.getProperty()) { - if (property.getName().equals(TOKEN_ENDPOINT)) { - tokenEndpoint = property.getValue(); - break; - } - } - if (tokenEndpoint == null || tokenEndpoint.isEmpty()) { + private String getTokenEndpoint(Map globalProperties) throws OutputEventAdapterException { + String tokenEndpoint = globalProperties.get(TOKEN_ENDPOINT_CONTEXT); + if ( tokenEndpoint.isEmpty()) { logger.error("tokenEndpoint can't be empty "); } - return tokenEndpoint; + return PropertyUtils.replaceProperty(tokenEndpoint); } - private long getRefreshTimeOffset(Properties properties) { - long refreshTimeOffset = 0; + private long getRefreshTimeOffset(Map globalProperties) { + long refreshTimeOffset = 100; try { - for (Property property : properties.getProperty()) { - if (property.getName().equals(TOKEN_REFRESH_TIME_OFFSET)) { - refreshTimeOffset = Long.parseLong(property.getValue()); - break; - } - } + refreshTimeOffset = Long.parseLong(globalProperties.get(TOKEN_REFRESH_TIME_OFFSET)); } catch (NumberFormatException e) { logger.error("refreshTimeOffset should be a number", e); } return refreshTimeOffset; } + private String getScopes(Map globalProperties) { + return globalProperties.get(TOKEN_SCOPES); + } + } diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/dto/TokenIssuerService.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/dto/TokenIssuerService.java index 9680d50f92..046184559b 100755 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/dto/TokenIssuerService.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/dto/TokenIssuerService.java @@ -36,7 +36,6 @@ import javax.ws.rs.core.MediaType; /** * This hold the api defintion that is used as a contract with netflix feign. */ -@Path("/token") public interface TokenIssuerService { @POST @@ -45,6 +44,12 @@ public interface TokenIssuerService { AccessTokenInfo getToken(@QueryParam("grant_type") String grant, @QueryParam("username") String username, @QueryParam("password") String password); + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + AccessTokenInfo getToken(@QueryParam("grant_type") String grant, @QueryParam("username") String username, + @QueryParam("password") String password, @QueryParam("scopes") String scopes); + @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Authenticator.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Authenticator.java deleted file mode 100644 index 25c0794ea0..0000000000 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Authenticator.java +++ /dev/null @@ -1,107 +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.wso2.carbon.device.mgt.output.adapter.websocket.config; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for Authenticator complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="Authenticator">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="Properties" type="{}Properties"/>
    - *       </sequence>
    - *       <attribute name="class" type="{http://www.w3.org/2001/XMLSchema}string" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Authenticator", propOrder = { - "properties" -}) -public class Authenticator { - - @XmlElement(name = "Properties", required = false) - protected Properties properties; - @XmlAttribute(name = "class") - protected String clazz; - - /** - * Gets the value of the properties property. - * - * @return - * possible object is - * {@link Properties } - * - */ - public Properties getProperties() { - return properties; - } - - /** - * Sets the value of the properties property. - * - * @param value - * allowed object is - * {@link Properties } - * - */ - public void setProperties(Properties value) { - this.properties = value; - } - - /** - * Gets the value of the clazz property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getClazz() { - return clazz; - } - - /** - * Sets the value of the clazz property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setClazz(String value) { - this.clazz = value; - } - -} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Authorizer.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Authorizer.java deleted file mode 100644 index 03cc6b9fd7..0000000000 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Authorizer.java +++ /dev/null @@ -1,107 +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.wso2.carbon.device.mgt.output.adapter.websocket.config; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for Authorizer complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="Authorizer">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="Properties" type="{}Properties"/>
    - *       </sequence>
    - *       <attribute name="class" type="{http://www.w3.org/2001/XMLSchema}string" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Authorizer", propOrder = { - "properties" -}) -public class Authorizer { - - @XmlElement(name = "Properties", required = false) - protected Properties properties; - @XmlAttribute(name = "class") - protected String clazz; - - /** - * Gets the value of the properties property. - * - * @return - * possible object is - * {@link Properties } - * - */ - public Properties getProperties() { - return properties; - } - - /** - * Sets the value of the properties property. - * - * @param value - * allowed object is - * {@link Properties } - * - */ - public void setProperties(Properties value) { - this.properties = value; - } - - /** - * Gets the value of the clazz property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getClazz() { - return clazz; - } - - /** - * Sets the value of the clazz property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setClazz(String value) { - this.clazz = value; - } - -} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Properties.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Properties.java deleted file mode 100644 index 9620f46a44..0000000000 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Properties.java +++ /dev/null @@ -1,86 +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.wso2.carbon.device.mgt.output.adapter.websocket.config; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; -import java.util.ArrayList; -import java.util.List; - - -/** - *

    Java class for Properties complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="Properties">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="Property" type="{}Property" maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Properties", propOrder = { - "property" -}) -public class Properties { - - @XmlElement(name = "Property") - protected List property; - - /** - * Gets the value of the property property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the property property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getProperty().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link Property } - * - * - */ - public List getProperty() { - if (property == null) { - property = new ArrayList(); - } - return this.property; - } - -} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Property.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Property.java deleted file mode 100644 index 7b14dbbe64..0000000000 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/Property.java +++ /dev/null @@ -1,104 +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.wso2.carbon.device.mgt.output.adapter.websocket.config; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlValue; - - -/** - *

    Java class for Property complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="Property">
    - *   <simpleContent>
    - *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
    - *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
    - *     </extension>
    - *   </simpleContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "Property", propOrder = { - "value" -}) -public class Property { - - @XmlValue - protected String value; - @XmlAttribute(name = "name") - protected String name; - - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } - - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } - -} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/WebsocketConfig.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/WebsocketConfig.java deleted file mode 100644 index 3499cd5e66..0000000000 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/WebsocketConfig.java +++ /dev/null @@ -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.wso2.carbon.device.mgt.output.adapter.websocket.config; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.wso2.carbon.device.mgt.output.adapter.websocket.util.WebsocketUtils; -import org.wso2.carbon.utils.CarbonUtils; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import java.io.File; - -/** - * This class represents the configuration that are needed for scopes to permission map. - */ -public class WebsocketConfig { - - private static WebsocketConfig config = new WebsocketConfig(); - private WebsocketValidationConfigs websocketValidationConfigs; - private static final Log log = LogFactory.getLog(WebsocketConfig.class); - - private static final String WEBSOCKET_VALIDATION_CONFIG_PATH = - CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "websocket-validation.xml"; - - private WebsocketConfig() { - } - - public static WebsocketConfig getInstance() { - return config; - } - - public void init() throws WebsocketValidationConfigurationFailedException { - try { - File deviceMgtConfig = new File(WEBSOCKET_VALIDATION_CONFIG_PATH); - Document doc = WebsocketUtils.convertToDocument(deviceMgtConfig); - - /* Un-marshaling DeviceMGtScope configuration */ - JAXBContext ctx = JAXBContext.newInstance(WebsocketValidationConfigs.class); - Unmarshaller unmarshaller = ctx.createUnmarshaller(); - //unmarshaller.setSchema(getSchema()); - websocketValidationConfigs = (WebsocketValidationConfigs) unmarshaller.unmarshal(doc); - } catch (JAXBException e) { - throw new WebsocketValidationConfigurationFailedException("Error occurred while un-marshalling Websocket" + - " Config", e); - } - } - - public WebsocketValidationConfigs getWebsocketValidationConfigs() { - if (websocketValidationConfigs == null) { - try { - init(); - } catch (WebsocketValidationConfigurationFailedException e) { - log.error("failed to initialize the config", e); - } - } - return websocketValidationConfigs; - } - - public void setWebsocketValidationConfigs(WebsocketValidationConfigs websocketValidationConfigs) { - websocketValidationConfigs = websocketValidationConfigs; - } -} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/WebsocketValidationConfigs.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/WebsocketValidationConfigs.java deleted file mode 100644 index 020cfd2cef..0000000000 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/WebsocketValidationConfigs.java +++ /dev/null @@ -1,105 +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.wso2.carbon.device.mgt.output.adapter.websocket.config; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - - -/** - *

    Java class for WebsocketValidationConfigs complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="WebsocketValidationConfigs">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="Authenticator" type="{}Authenticator"/>
    - *         <element name="Authorizer" type="{}Authorizer"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ - -@XmlRootElement(name = "WebsocketValidationConfigs") -@XmlAccessorType(XmlAccessType.FIELD) -public class WebsocketValidationConfigs { - - @XmlElement(name = "Authenticator", required = true) - protected Authenticator authenticator; - @XmlElement(name = "Authorizer", required = true) - protected Authorizer authorizer; - - /** - * Gets the value of the authenticator property. - * - * @return - * possible object is - * {@link Authenticator } - * - */ - public Authenticator getAuthenticator() { - return authenticator; - } - - /** - * Sets the value of the authenticator property. - * - * @param value - * allowed object is - * {@link Authenticator } - * - */ - public void setAuthenticator(Authenticator value) { - this.authenticator = value; - } - - /** - * Gets the value of the authorizer property. - * - * @return - * possible object is - * {@link Authorizer } - * - */ - public Authorizer getAuthorizer() { - return authorizer; - } - - /** - * Sets the value of the authorizer property. - * - * @param value - * allowed object is - * {@link Authorizer } - * - */ - public void setAuthorizer(Authorizer value) { - this.authorizer = value; - } - -} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/WebsocketValidationConfigurationFailedException.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/WebsocketValidationConfigurationFailedException.java deleted file mode 100644 index cc1eb08c5b..0000000000 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/config/WebsocketValidationConfigurationFailedException.java +++ /dev/null @@ -1,44 +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.wso2.carbon.device.mgt.output.adapter.websocket.config; - -public class WebsocketValidationConfigurationFailedException extends Exception { - - private static final long serialVersionUID = -3151279329290703928L; - - public WebsocketValidationConfigurationFailedException(String msg, Exception nestedEx) { - super(msg, nestedEx); - } - - public WebsocketValidationConfigurationFailedException(String message, Throwable cause) { - super(message, cause); - } - - public WebsocketValidationConfigurationFailedException(String msg) { - super(msg); - } - - public WebsocketValidationConfigurationFailedException() { - super(); - } - - public WebsocketValidationConfigurationFailedException(Throwable cause) { - super(cause); - } -} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/constants/WebsocketConstants.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/constants/WebsocketConstants.java index 5d459cd2ee..6391fa07d1 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/constants/WebsocketConstants.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/constants/WebsocketConstants.java @@ -29,7 +29,8 @@ public class WebsocketConstants { public static final String SCOPE_IDENTIFIER = "scopes"; public static final String MAXIMUM_TOTAL_HTTP_CONNECTION = "maximumTotalHttpConnection"; public static final String MAXIMUM_HTTP_CONNECTION_PER_HOST = "maximumHttpConnectionPerHost"; - public static final String TOKEN_VALIDATION_ENDPOINT_URL = "tokenValidationEndpoint"; + public static final String TOKEN_VALIDATION_ENDPOINT_URL = "keymanagerUrl"; + public static final String TOKEN_VALIDATION_CONTEX = "/services/OAuth2TokenValidationService"; public static final String USERNAME = "username"; public static final String PASSWORD = "password"; public static final String TOKEN_PARAM = "token"; diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/UILocalEventAdapterServiceComponent.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/UILocalEventAdapterServiceComponent.java deleted file mode 100644 index ce5aa792b6..0000000000 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/UILocalEventAdapterServiceComponent.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.output.adapter.websocket.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.device.mgt.output.adapter.websocket.UIEventAdapterFactory; -import org.wso2.carbon.device.mgt.output.adapter.websocket.UIOutputCallbackControllerServiceImpl; -import org.wso2.carbon.device.mgt.output.adapter.websocket.authentication.Authenticator; -import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.Authorizer; -import org.wso2.carbon.device.mgt.output.adapter.websocket.config.WebsocketConfig; -import org.wso2.carbon.device.mgt.output.adapter.websocket.config.WebsocketValidationConfigurationFailedException; -import org.wso2.carbon.device.mgt.output.adapter.websocket.service.WebsocketValidationService; -import org.wso2.carbon.device.mgt.output.adapter.websocket.service.WebsocketValidationServiceImpl; -import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterFactory; -import org.wso2.carbon.device.mgt.output.adapter.websocket.UIOutputCallbackControllerService; -import org.wso2.carbon.event.stream.core.EventStreamService; - -/** - * @scr.component component.name="output.extensions.Ui.AdapterService.component" immediate="true" - * @scr.reference name="eventStreamService.service" - * interface="org.wso2.carbon.event.stream.core.EventStreamService" cardinality="1..1" - * policy="dynamic" bind="setEventStreamService" unbind="unsetEventStreamService" - */ -public class UILocalEventAdapterServiceComponent { - - private static final Log log = LogFactory.getLog(UILocalEventAdapterServiceComponent.class); - - /** - * initialize the websocket adapter service here service here. - * - * @param context - */ - protected void activate(ComponentContext context) { - - try { - OutputEventAdapterFactory uiEventAdapterFactory = new UIEventAdapterFactory(); - context.getBundleContext().registerService(OutputEventAdapterFactory.class.getName(), uiEventAdapterFactory, null); - UIOutputCallbackControllerServiceImpl UIOutputCallbackRegisterServiceImpl = - new UIOutputCallbackControllerServiceImpl(); - context.getBundleContext().registerService(UIOutputCallbackControllerService.class.getName(), - UIOutputCallbackRegisterServiceImpl, null); - - UIEventAdaptorServiceDataHolder.registerUIOutputCallbackRegisterServiceInternal( - UIOutputCallbackRegisterServiceImpl); - if (log.isDebugEnabled()) { - log.debug("Successfully deployed the output websocket adapter service"); - } - try { - WebsocketConfig.getInstance().init(); - WebsocketValidationServiceImpl websocketValidationService = new WebsocketValidationServiceImpl(); - String authenticatorClassName = WebsocketConfig.getInstance().getWebsocketValidationConfigs() - .getAuthenticator().getClazz(); - String authorizerClassName = WebsocketConfig.getInstance().getWebsocketValidationConfigs() - .getAuthorizer().getClazz(); - if (authenticatorClassName != null && !authenticatorClassName.isEmpty()) { - Class authenticatorClass = Class.forName(authenticatorClassName) - .asSubclass(Authenticator.class); - Authenticator authenticator = authenticatorClass.newInstance(); - websocketValidationService.setAuthenticator(authenticator); - } - if (authorizerClassName != null && !authorizerClassName.isEmpty()) { - Class authorizerClass = Class.forName(authorizerClassName) - .asSubclass(Authorizer.class); - Authorizer authorizer = authorizerClass.newInstance(); - websocketValidationService.setAuthorizer(authorizer); - } - context.getBundleContext().registerService( - WebsocketValidationService.class.getName(), websocketValidationService, null); - } catch (WebsocketValidationConfigurationFailedException e) { - log.error("Failed to initialize configuration for websocket.", e); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { - log.error("Failed to initialize the class authentication and authorization given " + - "in the websocket validation configuration.", e); - } - } catch (RuntimeException e) { - log.error("Can not create the output websocket adapter service ", e); - } catch (Throwable e) { - log.error("Error occurred while activating UI Event Adapter Service Component", e); - } - } - - protected void setEventStreamService(EventStreamService eventStreamService) { - if (log.isDebugEnabled()) { - log.debug("Setting the EventStreamService reference for the UILocalEventAdaptor Service"); - } - UIEventAdaptorServiceDataHolder.registerEventStreamService(eventStreamService); - } - - protected void unsetEventStreamService(EventStreamService eventStreamService) { - if (log.isDebugEnabled()) { - log.debug("Un-Setting the EventStreamService reference for the UILocalEventAdaptor Service"); - } - UIEventAdaptorServiceDataHolder.registerEventStreamService(null); - } -} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/UIEventAdaptorServiceDataHolder.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/WebsocketEventAdaptorServiceDataHolder.java similarity index 72% rename from components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/UIEventAdaptorServiceDataHolder.java rename to components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/WebsocketEventAdaptorServiceDataHolder.java index ec3c322177..0485b07103 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/UIEventAdaptorServiceDataHolder.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/WebsocketEventAdaptorServiceDataHolder.java @@ -18,7 +18,7 @@ */ package org.wso2.carbon.device.mgt.output.adapter.websocket.internal; -import org.wso2.carbon.device.mgt.output.adapter.websocket.UIOutputCallbackControllerServiceImpl; +import org.wso2.carbon.device.mgt.output.adapter.websocket.WebsocketOutputCallbackControllerServiceImpl; import org.wso2.carbon.event.stream.core.EventStreamService; import java.util.concurrent.ConcurrentHashMap; @@ -27,9 +27,9 @@ import java.util.concurrent.LinkedBlockingDeque; /** * Creates a holder of type UIOutputCallbackRegisterServiceImpl. */ -public final class UIEventAdaptorServiceDataHolder { +public final class WebsocketEventAdaptorServiceDataHolder { - private static UIOutputCallbackControllerServiceImpl UIOutputCallbackRegisterServiceImpl; + private static WebsocketOutputCallbackControllerServiceImpl UIOutputCallbackRegisterServiceImpl; private static ConcurrentHashMap> tenantSpecificOutputEventStreamAdapterMap = new ConcurrentHashMap<>(); private static ConcurrentHashMap>> @@ -37,21 +37,21 @@ public final class UIEventAdaptorServiceDataHolder { private static EventStreamService eventStreamService; public static void registerEventStreamService(EventStreamService eventBuilderService) { - UIEventAdaptorServiceDataHolder.eventStreamService = eventBuilderService; + WebsocketEventAdaptorServiceDataHolder.eventStreamService = eventBuilderService; } public static EventStreamService getEventStreamService() { - return UIEventAdaptorServiceDataHolder.eventStreamService; + return WebsocketEventAdaptorServiceDataHolder.eventStreamService; } public static void registerUIOutputCallbackRegisterServiceInternal( - UIOutputCallbackControllerServiceImpl UIOutputCallbackRegisterServiceImpl) { - UIEventAdaptorServiceDataHolder.UIOutputCallbackRegisterServiceImpl = + WebsocketOutputCallbackControllerServiceImpl UIOutputCallbackRegisterServiceImpl) { + WebsocketEventAdaptorServiceDataHolder.UIOutputCallbackRegisterServiceImpl = UIOutputCallbackRegisterServiceImpl; } - public static UIOutputCallbackControllerServiceImpl getUIOutputCallbackRegisterServiceImpl() { - return UIEventAdaptorServiceDataHolder.UIOutputCallbackRegisterServiceImpl; + public static WebsocketOutputCallbackControllerServiceImpl getUIOutputCallbackRegisterServiceImpl() { + return WebsocketEventAdaptorServiceDataHolder.UIOutputCallbackRegisterServiceImpl; } public static ConcurrentHashMap> diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/WebsocketLocalEventAdapterServiceComponent.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/WebsocketLocalEventAdapterServiceComponent.java new file mode 100644 index 0000000000..4820d46e61 --- /dev/null +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/internal/WebsocketLocalEventAdapterServiceComponent.java @@ -0,0 +1,83 @@ +/* + * 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.wso2.carbon.device.mgt.output.adapter.websocket.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.device.mgt.output.adapter.websocket.WebsocketEventAdapterFactory; +import org.wso2.carbon.device.mgt.output.adapter.websocket.WebsocketOutputCallbackControllerServiceImpl; +import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterFactory; +import org.wso2.carbon.device.mgt.output.adapter.websocket.WebsocketOutputCallbackControllerService; +import org.wso2.carbon.event.stream.core.EventStreamService; + +/** + * @scr.component component.name="output.extensions.secured.websocket.AdapterService.component" immediate="true" + * @scr.reference name="eventStreamService.service" + * interface="org.wso2.carbon.event.stream.core.EventStreamService" cardinality="1..1" + * policy="dynamic" bind="setEventStreamService" unbind="unsetEventStreamService" + */ +public class WebsocketLocalEventAdapterServiceComponent { + + private static final Log log = LogFactory.getLog(WebsocketLocalEventAdapterServiceComponent.class); + + /** + * initialize the websocket adapter service here service here. + * + * @param context + */ + protected void activate(ComponentContext context) { + + try { + WebsocketEventAdapterFactory websocketEventAdapterFactory = new WebsocketEventAdapterFactory(); + context.getBundleContext().registerService(OutputEventAdapterFactory.class.getName() + , websocketEventAdapterFactory, null); + WebsocketOutputCallbackControllerServiceImpl UIOutputCallbackRegisterServiceImpl = + new WebsocketOutputCallbackControllerServiceImpl(); + context.getBundleContext().registerService(WebsocketOutputCallbackControllerService.class.getName(), + UIOutputCallbackRegisterServiceImpl, null); + + websocketEventAdapterFactory.setBundleContext(context.getBundleContext()); + + WebsocketEventAdaptorServiceDataHolder.registerUIOutputCallbackRegisterServiceInternal( + UIOutputCallbackRegisterServiceImpl); + if (log.isDebugEnabled()) { + log.debug("Successfully deployed the output websocket adapter service"); + } + } catch (RuntimeException e) { + log.error("Can not create the output websocket adapter service ", e); + } catch (Throwable e) { + log.error("Error occurred while activating UI Event Adapter Service Component", e); + } + } + + protected void setEventStreamService(EventStreamService eventStreamService) { + if (log.isDebugEnabled()) { + log.debug("Setting the EventStreamService reference for the UILocalEventAdaptor Service"); + } + WebsocketEventAdaptorServiceDataHolder.registerEventStreamService(eventStreamService); + } + + protected void unsetEventStreamService(EventStreamService eventStreamService) { + if (log.isDebugEnabled()) { + log.debug("Un-Setting the EventStreamService reference for the UILocalEventAdaptor Service"); + } + WebsocketEventAdaptorServiceDataHolder.registerEventStreamService(null); + } +} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/PropertyUtils.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/PropertyUtils.java new file mode 100644 index 0000000000..55b6539d7b --- /dev/null +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/PropertyUtils.java @@ -0,0 +1,45 @@ +/* +* 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.wso2.carbon.device.mgt.output.adapter.websocket.util; + +import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class PropertyUtils { + + //This method is only used if the mb features are within DAS. + public static String replaceProperty(String urlWithPlaceholders) throws OutputEventAdapterException { + String regex = "\\$\\{(.*?)\\}"; + Pattern pattern = Pattern.compile(regex); + Matcher matchPattern = pattern.matcher(urlWithPlaceholders); + while (matchPattern.find()) { + String sysPropertyName = matchPattern.group(1); + String sysPropertyValue = System.getProperty(sysPropertyName); + if (sysPropertyValue != null && !sysPropertyName.isEmpty()) { + urlWithPlaceholders = urlWithPlaceholders.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue); + } else { + throw new OutputEventAdapterException("System property - " + sysPropertyName + + " is not defined, hence cannot resolve : " + urlWithPlaceholders); + } + } + return urlWithPlaceholders; + } +} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/UIEventAdapterConstants.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/WebsocketEventAdapterConstants.java similarity index 90% rename from components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/UIEventAdapterConstants.java rename to components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/WebsocketEventAdapterConstants.java index bef12b7c3e..7fd15519fc 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/UIEventAdapterConstants.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/WebsocketEventAdapterConstants.java @@ -21,9 +21,9 @@ package org.wso2.carbon.device.mgt.output.adapter.websocket.util; /** * This class contains the constants related to websocket Output Event Adaptor. */ -public class UIEventAdapterConstants { +public class WebsocketEventAdapterConstants { - private UIEventAdapterConstants() { + private WebsocketEventAdapterConstants() { } public static final String ADAPTER_TYPE_UI = "secured-websocket"; @@ -46,5 +46,7 @@ public class UIEventAdapterConstants { public static final String ADAPTER_EVENT_QUEUE_SIZE_NAME = "eventQueueSize"; public static final int EVENTS_QUEUE_SIZE = 30; + public static final String AUTHENTICATOR_CLASS = "authenticator"; + public static final String AUTHORIZER_CLASS = "authorizer"; } diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/WebsocketUtils.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/WebsocketUtils.java deleted file mode 100644 index 162bc99559..0000000000 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/util/WebsocketUtils.java +++ /dev/null @@ -1,45 +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.wso2.carbon.device.mgt.output.adapter.websocket.util; - -import org.w3c.dom.Document; -import org.wso2.carbon.device.mgt.output.adapter.websocket.config.WebsocketValidationConfigurationFailedException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.File; - -/** - * This class holds util methods used by OAuth extension bundle. - */ -public class WebsocketUtils { - - public static Document convertToDocument(File file) throws WebsocketValidationConfigurationFailedException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - try { - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - return docBuilder.parse(file); - } catch (Exception e) { - throw new WebsocketValidationConfigurationFailedException("Error occurred while parsing file, while converting " + - "to a org.w3c.dom.Document", e); - } - } - -} diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.xmpp/pom.xml b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.xmpp/pom.xml index 15f1ac8a92..2ea306b49a 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.xmpp/pom.xml +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.xmpp/pom.xml @@ -20,7 +20,7 @@ org.wso2.carbon.devicemgt-plugins cdmf-transport-adapters - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../../pom.xml diff --git a/components/extensions/cdmf-transport-adapters/pom.xml b/components/extensions/cdmf-transport-adapters/pom.xml index d8b44c000b..2686452249 100644 --- a/components/extensions/cdmf-transport-adapters/pom.xml +++ b/components/extensions/cdmf-transport-adapters/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins extensions - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/pom.xml b/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/pom.xml index b7e13a3221..8d77e5a572 100644 --- a/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/pom.xml +++ b/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins mb-extensions - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/extensions/mb-extensions/pom.xml b/components/extensions/mb-extensions/pom.xml index 955aef40b1..d7ff1c8e95 100644 --- a/components/extensions/mb-extensions/pom.xml +++ b/components/extensions/mb-extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins extensions - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/extensions/pom.xml b/components/extensions/pom.xml index cfdeeaffb2..5f1ca115ad 100644 --- a/components/extensions/pom.xml +++ b/components/extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins carbon-device-mgt-plugins-parent - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../../pom.xml diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/pom.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/pom.xml index fa70569575..d1f5e612b2 100644 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/pom.xml +++ b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/pom.xml @@ -20,7 +20,7 @@ org.wso2.carbon.devicemgt-plugins siddhi-extensions - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/extensions/siddhi-extensions/pom.xml b/components/extensions/siddhi-extensions/pom.xml index c2e8e2cb4d..08457f5e6f 100644 --- a/components/extensions/siddhi-extensions/pom.xml +++ b/components/extensions/siddhi-extensions/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt-plugins extensions - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.analytics/pom.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.analytics/pom.xml index 2497c485fb..c19788ccb8 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.analytics/pom.xml +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.analytics/pom.xml @@ -21,7 +21,7 @@ org.wso2.carbon.devicemgt-plugins android-plugin - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/pom.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/pom.xml index 017ff5400c..b87cc8e2e0 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/pom.xml +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/pom.xml @@ -21,7 +21,7 @@ android-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml @@ -143,6 +143,11 @@ org.wso2.carbon.device.mgt.common provided + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + provided + org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.core diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidDeviceInfo.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidDeviceInfo.java index bf775edfed..41fbb58570 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidDeviceInfo.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidDeviceInfo.java @@ -300,7 +300,7 @@ public class AndroidDeviceInfo extends DeviceInfo implements Serializable { } public Date getUpdatedTime() { - if(this.updatedTime.equals((Object)null)) { + if(this.updatedTime == null) { this.updatedTime = new Date(); } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/GsonMessageBodyHandler.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/GsonMessageBodyHandler.java index a1ae89d151..2976300290 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/GsonMessageBodyHandler.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/GsonMessageBodyHandler.java @@ -83,13 +83,7 @@ public class GsonMessageBodyHandler implements MessageBodyWriter, Messag OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8); try { - Type jsonType; - if (type.equals(type)) { - jsonType = type; - } else { - jsonType = type; - } - getGson().toJson(object, jsonType, writer); + getGson().toJson(object, type, writer); } finally { writer.close(); } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementAdminService.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementAdminService.java index e24f6fbfad..db795dcd80 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementAdminService.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementAdminService.java @@ -24,15 +24,16 @@ import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.Extension; import io.swagger.annotations.Tag; import io.swagger.annotations.Api; -import io.swagger.annotations.AuthorizationScope; -import io.swagger.annotations.Authorization; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ResponseHeader; +import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.mdm.services.android.bean.wrapper.*; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; import javax.validation.Valid; import javax.ws.rs.Consumes; @@ -57,13 +58,167 @@ import java.util.List; } ), tags = { - @Tag(name = "devicemgt_android", description = "") + @Tag(name = "android", description = "") } ) @Path("/admin/devices") @Api(value = "Android Device Management Administrative Service", description = "Device management related admin APIs.") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) +@Scopes( + scopes = { + @Scope( + name = "Lock Device", + description = "Hard lock own device", + key = "perm:android:lock-devices", + permissions = {"/device-mgt/devices/owning-device/operations/android/lock"} + ), + @Scope( + name = "Unlock Device", + description = "Unlock permanently locked device", + key = "perm:android:unlock-devices", + permissions = {"/device-mgt/devices/owning-device/operations/android/unlock"} + ), + @Scope( + name = "Get Location", + description = "Request device location coordinates", + key = "perm:android:location", + permissions = {"/device-mgt/devices/owning-device/operations/android/location"} + ), + @Scope( + name = "Clear Password", + description = "Clear the password on Android devices", + key = "perm:android:clear-password", + permissions = {"/device-mgt/devices/owning-device/operations/android/clear-password"} + ), + @Scope( + name = "Control Camera", + description = "Enabling or Disabling the Camera on Android Devices", + key = "perm:android:control-camera", + permissions = {"/device-mgt/devices/owning-device/operations/android/camera"} + ), + @Scope( + name = "Get Info", + description = "Requesting device information from Android Devices", + key = "perm:android:info", + permissions = {"/device-mgt/devices/owning-device/operations/android/info"} + ), + @Scope( + name = "Get Logs", + description = "Requesting Logcat Details from Android Devices", + key = "perm:android:logcat", + permissions = {"/device-mgt/devices/owning-device/operations/android/logcat"} + ), + @Scope( + name = "Enterprise Wipe", + description = "Enterprise Wiping Android Devices", + key = "perm:android:enterprise-wipe", + permissions = {"/device-mgt/devices/owning-device/operations/android/enterprise-wipe"} + ), + @Scope( + name = "Factory Reset", + description = "Factory Resetting Android Devices", + key = "perm:android:wipe", + permissions = {"/device-mgt/devices/owning-device/operations/android/wipe"} + ), + @Scope( + name = "Get Installed Applications", + description = "Get list of installed applications", + key = "perm:android:applications", + permissions = {"/device-mgt/devices/owning-device/operations/android/applications"} + ), + @Scope( + name = "Ring Device", + description = "Ring Android devices", + key = "perm:android:ring", + permissions = {"/device-mgt/devices/owning-device/operations/android/ring"} + ), + @Scope( + name = "Reboot Device", + description = "Reboot Android devices", + key = "perm:android:reboot", + permissions = {"/device-mgt/devices/owning-device/operations/android/reboot"} + ), + @Scope( + name = "Mute Device", + description = "Mute Android devices", + key = "perm:android:mute", + permissions = {"/device-mgt/devices/owning-device/operations/android/mute"} + ), + @Scope( + name = "Install Applications", + description = "Installing an Application on Android Devices", + key = "perm:android:install-application", + permissions = {"/device-mgt/devices/owning-device/operations/android/install-app"} + ), + @Scope( + name = "Update Applications", + description = "Updating an Application on Android Devices", + key = "perm:android:update-application", + permissions = {"/device-mgt/devices/owning-device/operations/android/update-app"} + ), + @Scope( + name = "Uninstall Applications", + description = "Uninstalling an Application on Android Devices", + key = "perm:android:uninstall-application", + permissions = {"/device-mgt/devices/owning-device/operations/android/uninstall-app"} + ), + @Scope( + name = "Blacklist Applications", + description = "Blacklisting applications on Android Devices", + key = "perm:android:blacklist-applications", + permissions = {"/device-mgt/devices/owning-device/operations/android/blacklist-app"} + ), + @Scope( + name = "Upgrade Firmware", + description = "Upgrading Firmware of Android Devices", + key = "perm:android:upgrade-firmware", + permissions = {"/device-mgt/devices/owning-device/operations/android/upgrade"} + ), + @Scope( + name = "Configure VPN", + description = "Configure VPN on Android Device", + key = "perm:android:configure-vpn", + permissions = {"/device-mgt/devices/owning-device/operations/android/vpn"} + ), + @Scope( + name = "Send Notification", + description = "Sending a notification to Android Device", + key = "perm:android:send-notification", + permissions = {"/device-mgt/devices/owning-device/operations/android/send-notification"} + ), + @Scope( + name = "Configure Wi-Fi", + description = "Configure Wi-Fi on Android Device", + key = "perm:android:configure-wifi", + permissions = {"/device-mgt/devices/owning-device/operations/android/wifi"} + ), + @Scope( + name = "Encrypt Storage", + description = "Encrypting storage on Android Device", + key = "perm:android:encrypt-storage", + permissions = {"/device-mgt/devices/owning-device/operations/android/encrypt"} + ), + @Scope( + name = "Change Password", + description = "Changing the lock code of an Android Device", + key = "perm:android:change-lock-code", + permissions = {"/device-mgt/devices/owning-device/operations/android/change-lock-code"} + ), + @Scope( + name = "Password Policy", + description = "Set password policy of an Android Device", + key = "perm:android:set-password-policy", + permissions = {"/device-mgt/devices/owning-device/operations/android/password-policy"} + ), + @Scope( + name = "Add Web clip", + description = "Setting a Web Clip on Android Devices", + key = "perm:android:set-webclip", + permissions = {"/device-mgt/devices/owning-device/operations/android/webclip"} + ) + } +) public interface DeviceManagementAdminService { @POST @@ -76,13 +231,10 @@ public interface DeviceManagementAdminService { "permanently locks the device or screen locking an Android device.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/lock", - description = "Lock Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:lock-devices") + }) } ) @ApiResponses(value = { @@ -142,13 +294,10 @@ public interface DeviceManagementAdminService { notes = "Unlock devices that were locked permanently using the hard lock operation. Devices that are hard locked can only be unlocked by the EMM administrator.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/unlock", - description = "Unlock Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:unlock-devices") + }) } ) @ApiResponses(value = { @@ -208,13 +357,10 @@ public interface DeviceManagementAdminService { "Example: In situations where you have lost your device and need to find out where it is, you can use this REST API to get the location of the device.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/location", - description = "Get Device Location") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:location") + }) } ) @ApiResponses(value = { @@ -270,13 +416,10 @@ public interface DeviceManagementAdminService { notes = "Clear the password on Android devices", response = Activity.class, tags = "Android Device Management Administrative Service.", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/clear-password", - description = "Clear Password of Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:clear-password") + }) } ) @ApiResponses(value = { @@ -331,13 +474,11 @@ public interface DeviceManagementAdminService { notes = "Enable or disable the camera on Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/devices/owning-device/operations/android/camera", description = "Manage Camera") } - ) - } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:control-camera") + }) + } ) @ApiResponses(value = { @ApiResponse( code = 201, @@ -398,13 +539,10 @@ public interface DeviceManagementAdminService { "the list of operations that needs to be executed on the device", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/info", - description = "Get Device Information") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:info") + }) } ) @ApiResponses(value = { @@ -464,13 +602,10 @@ public interface DeviceManagementAdminService { "the list of operations that needs to be executed on the device.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/logcat", - description = "Get Logs") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:logcat") + }) } ) @ApiResponses(value = { @@ -529,13 +664,10 @@ public interface DeviceManagementAdminService { "personal data intact. You are able to enterprise wipe Android devices using this REST API.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/enterprise-wipe", - description = "Enterprise Wipe") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enterprise-wipe") + }) } ) @ApiResponses(value = { @@ -592,13 +724,10 @@ public interface DeviceManagementAdminService { "to restore them back to the original system.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/wipe", - description = "Factory Reset") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:wipe") + }) } ) @ApiResponses(value = { @@ -659,13 +788,10 @@ public interface DeviceManagementAdminService { "on the device.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/applications", - description = "Get Installed Application") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:applications") + }) } ) @ApiResponses(value = { @@ -722,13 +848,10 @@ public interface DeviceManagementAdminService { notes = "Ring Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/ring", - description = "Ring Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:ring") + }) } ) @ApiResponses(value = { @@ -785,13 +908,10 @@ public interface DeviceManagementAdminService { notes = "Reboot or restart your Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/reboot", - description = "Reboot Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:reboot") + }) } ) @ApiResponses(value = { @@ -840,6 +960,7 @@ public interface DeviceManagementAdminService { List deviceIDs); @POST + @Path("/mute") @ApiOperation( consumes = MediaType.APPLICATION_JSON, httpMethod = "POST", @@ -847,13 +968,10 @@ public interface DeviceManagementAdminService { notes = "Mute or enable a silent profile for Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/mute", - description = "Mute Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:mute") + }) } ) @ApiResponses(value = { @@ -894,7 +1012,6 @@ public interface DeviceManagementAdminService { message = "Internal Server Error. \n " + "Server error occurred while adding a new device mute operation.") }) - @Path("/mute") Response muteDevice( @ApiParam( name = "deviceIDs", @@ -913,13 +1030,10 @@ public interface DeviceManagementAdminService { " the application installation will happen in silent mode, else the device user's consent will be required.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/install-app", - description = "Install Applications") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:install-application") + }) } ) @ApiResponses(value = { @@ -981,13 +1095,10 @@ public interface DeviceManagementAdminService { "mode, else the device user's consent is required.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/update-app", - description = "Update installed applications") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:update-application") + }) } ) @ApiResponses(value = { @@ -1046,13 +1157,10 @@ public interface DeviceManagementAdminService { notes = "Uninstall an application from Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/uninstall-app", - description = "Uninstall Applications") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:uninstall-application") + }) } ) @ApiResponses(value = { @@ -1115,13 +1223,10 @@ public interface DeviceManagementAdminService { "COPE devices. Applications can be blacklisted via the application restriction policy too.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/blacklist-app", - description = "Blacklist Applications") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:blacklist-applications") + }) } ) @ApiResponses(value = { @@ -1176,17 +1281,14 @@ public interface DeviceManagementAdminService { consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, httpMethod = "POST", - value = "UUpgrading Firmware of Android Devices", + value = "Upgrading Firmware of Android Devices", notes = "Upgrade the firmware of Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/upgrade", - description = "Upgrade Firmware") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:upgrade-firmware") + }) } ) @ApiResponses(value = { @@ -1247,13 +1349,10 @@ public interface DeviceManagementAdminService { notes = "Configure VPN on Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/vpn", - description = "Add VPN") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:configure-vpn") + }) } ) @ApiResponses(value = { @@ -1310,13 +1409,10 @@ public interface DeviceManagementAdminService { notes = "Send a notification or message to Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/send-notification", - description = "Send Notifications") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:send-notification") + }) } ) @ApiResponses(value = { @@ -1374,13 +1470,10 @@ public interface DeviceManagementAdminService { notes = "Configure Wi-Fi on Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/wifi", - description = "Add Wifi Configuration") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:configure-wifi") + }) } ) @ApiResponses(value = { @@ -1439,13 +1532,10 @@ public interface DeviceManagementAdminService { notes = "Encrypt the data stored on Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/encrypt", - description = "Encrypt Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:encrypt-storage") + }) } ) @ApiResponses(value = { @@ -1504,13 +1594,10 @@ public interface DeviceManagementAdminService { notes = "Change the lock code on Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/change-lock-code", - description = "Change Password of Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:change-lock-code") + }) } ) @ApiResponses(value = { @@ -1569,13 +1656,10 @@ public interface DeviceManagementAdminService { notes = "Set a password policy on Android devices.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/password-policy", - description = "Set Password Policy") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:set-password-policy") + }) } ) @ApiResponses(value = { @@ -1624,7 +1708,7 @@ public interface DeviceManagementAdminService { PasswordPolicyBeanWrapper passwordPolicyBeanWrapper); @POST - @Path("set-webclip") + @Path("/set-webclip") @ApiOperation( consumes = MediaType.APPLICATION_JSON, httpMethod = "POST", @@ -1632,13 +1716,10 @@ public interface DeviceManagementAdminService { notes = "Set a web clip on Android devices. A web clip is used to add a bookmark to a web application.", response = Activity.class, tags = "Android Device Management Administrative Service", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope( - scope = "/device-mgt/devices/owning-device/operations/android/webclip", - description = "Add Webclips") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:set-webclip") + }) } ) @ApiResponses(value = { diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementService.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementService.java index 4bf71b564a..5c7df5f1f0 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementService.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementService.java @@ -18,22 +18,14 @@ */ package org.wso2.carbon.mdm.services.android.services; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.AuthorizationScope; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; +import io.swagger.annotations.*; + +import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidApplication; import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidDevice; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; import javax.validation.Valid; import javax.validation.constraints.NotNull; @@ -64,7 +56,7 @@ import java.util.List; } ), tags = { - @Tag(name = "devicemgt_android", description = "") + @Tag(name = "android", description = "") } ) @Api(value = "Android Device Management", @@ -72,6 +64,22 @@ import java.util.List; @Path("/devices") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) +@Scopes( + scopes = { + @Scope( + name = "Enroll Device", + description = "Register an Android device", + key = "perm:android:enroll", + permissions = {"/device-mgt/devices/enroll/android"} + ), + @Scope( + name = "Un-enroll Device", + description = "Unregister an Android device", + key = "perm:android:disenroll", + permissions = {"/device-mgt/devices/disenroll/android"} + ) + } +) public interface DeviceManagementService { @PUT @@ -83,12 +91,10 @@ public interface DeviceManagementService { value = "Updating the Application Details on Android Devices", notes = "Update the details of the applications that are installed on Android devices.", tags = "Android Device Management", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/devices/enroll/android", - description = "Enroll Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enroll") + }) } ) @ApiResponses(value = { @@ -150,12 +156,10 @@ public interface DeviceManagementService { "The server then updates the status of the operations that were carried out on the device.", response = Operation.class, tags = "Android Device Management", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/devices/enroll/android", - description = "Enroll Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enroll") + }) } ) @ApiResponses(value = { @@ -216,12 +220,10 @@ public interface DeviceManagementService { " you can use this REST API to register an Android device with WSO2 EMM, without having to install" + " an Android Agent. This API can be mainly used to test the device enrollment process.", tags = "Android Device Management", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/devices/enroll/android", - description = "Enroll Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enroll") + }) } ) @ApiResponses(value = { @@ -273,12 +275,10 @@ public interface DeviceManagementService { value = "Getting the Registration Status of an Android Device", notes = "Use this REST API to retrieve the registration status of an Android device.", tags = "Android Device Management", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/devices/enroll/android", - description = "Enroll Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enroll") + }) } ) @ApiResponses(value = { @@ -328,12 +328,10 @@ public interface DeviceManagementService { value = "Updating the Registration Details of an Android Device", notes = "Use this REST API to update the registration details of an Android device.", tags = "Android Device Management", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/devices/enroll/android", - description = "Enroll Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enroll") + }) } ) @ApiResponses( @@ -386,11 +384,10 @@ public interface DeviceManagementService { value = "Unregistering an Android Device", notes = "Use this REST API to unregister an Android device.", tags = "Android Device Management", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/devices/disenroll/android", description = "Disenroll Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:disenroll") + }) } ) @ApiResponses(value = { diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceTypeConfigurationService.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceTypeConfigurationService.java index 3eab30e353..63f9fa4b4b 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceTypeConfigurationService.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceTypeConfigurationService.java @@ -24,16 +24,17 @@ import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.Extension; import io.swagger.annotations.Tag; import io.swagger.annotations.Api; -import io.swagger.annotations.AuthorizationScope; -import io.swagger.annotations.Authorization; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ResponseHeader; +import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.mdm.services.android.bean.AndroidPlatformConfiguration; import org.wso2.carbon.mdm.services.android.exception.AndroidAgentException; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; import javax.validation.Valid; import javax.ws.rs.*; @@ -54,13 +55,35 @@ import javax.ws.rs.core.Response; } ), tags = { - @Tag(name = "devicemgt_android", description = "") + @Tag(name = "android", description = "") } ) @Api(value = "Android Configuration Management", description = "This API carries all the resource used to mange the Android platform configurations.") @Path("/configuration") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) +@Scopes( + scopes = { + @Scope( + name = "Enroll Device", + description = "Register an Android device", + key = "perm:android:enroll", + permissions = {"/device-mgt/devices/enroll/android"} + ), + @Scope( + name = "View Configurations", + description = "Getting Android Platform Configurations", + key = "perm:android:view-configuration", + permissions = {"/device-mgt/devices/enroll/android"} + ), + @Scope( + name = "Manage Configurations", + description = "Updating Android Platform Configurations", + key = "perm:android:manage-configuration", + permissions = {"/device-mgt/platform-configurations/manage"} + ) + } +) public interface DeviceTypeConfigurationService { @GET @@ -71,12 +94,10 @@ public interface DeviceTypeConfigurationService { notes = "Get the Android platform configuration details using this REST API.", response = PlatformConfiguration.class, tags = "Android Configuration Management", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/platform-configurations/view", - description = "View Configurations") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:view-configuration") + }) } ) @ApiResponses(value = { @@ -127,12 +148,10 @@ public interface DeviceTypeConfigurationService { value = "Updating Android Platform Configurations", notes = "Update the Android platform configurations using this REST API.", tags = "Android Configuration Management", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/platform-configurations/manage", - description = "Manage Configurations") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:manage-configuration") + }) } ) @ApiResponses(value = { @@ -184,12 +203,10 @@ public interface DeviceTypeConfigurationService { "registration process.", response = String.class, tags = "Android Configuration Management", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/devices/enroll/android", - description = "Enroll Device") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enroll") + }) } ) @ApiResponses(value = { diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/EventReceiverService.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/EventReceiverService.java index 744655768d..86a6df265c 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/EventReceiverService.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/EventReceiverService.java @@ -24,15 +24,16 @@ import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.Extension; import io.swagger.annotations.Tag; import io.swagger.annotations.Api; -import io.swagger.annotations.AuthorizationScope; -import io.swagger.annotations.Authorization; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ResponseHeader; +import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.mdm.services.android.bean.DeviceState; import org.wso2.carbon.mdm.services.android.bean.wrapper.EventBeanWrapper; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; import javax.validation.Valid; import javax.validation.constraints.Size; @@ -52,7 +53,7 @@ import javax.ws.rs.core.Response; } ), tags = { - @Tag(name = "devicemgt_android", description = "") + @Tag(name = "android", description = "") } ) @Api(value = "Event Receiver", description = "Event publishing/retrieving related APIs. To enable event publishing/retrieving you need to" + @@ -61,6 +62,16 @@ import javax.ws.rs.core.Response; @Path("/events") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) +@Scopes( + scopes = { + @Scope( + name = "Enroll Device", + description = "Register an Android device", + key = "perm:android:enroll", + permissions = {"/device-mgt/devices/enroll/android"} + ) + } +) public interface EventReceiverService { @POST @@ -72,12 +83,10 @@ public interface EventReceiverService { value = "Publishing Events", notes = "Publish events received by the WSO2 EMM Android client to the WSO2 Data Analytics Server (DAS) using this API.", tags = "Event Receiver", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/devices/enroll/android", - description = "Publish Events to DAS") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enroll") + }) } ) @ApiResponses( @@ -137,12 +146,10 @@ public interface EventReceiverService { response = DeviceState.class, responseContainer = "List", tags = "Event Receiver", - authorizations = { - @Authorization( - value="permission", - scopes = { @AuthorizationScope(scope = "/device-mgt/devices/enroll/android", - description = "Publish Events to DAS") } - ) + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enroll") + }) } ) @ApiResponses( diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementServiceImpl.java index 409dcd758a..e59fac68a7 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementServiceImpl.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementServiceImpl.java @@ -39,7 +39,7 @@ import org.wso2.carbon.mdm.services.android.util.AndroidConstants; import org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils; import org.wso2.carbon.mdm.services.android.util.Message; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; -import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import javax.validation.Valid; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidAPIUtils.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidAPIUtils.java index 9399eb9965..65b7c60b97 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidAPIUtils.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidAPIUtils.java @@ -47,6 +47,7 @@ import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagement import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; 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.common.policy.mgt.monitor.ComplianceFeature; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; @@ -55,7 +56,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.mdm.services.android.bean.DeviceState; import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; import org.wso2.carbon.mdm.services.android.exception.BadRequestException; -import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import javax.ws.rs.core.MediaType; @@ -275,7 +276,8 @@ public class AndroidAPIUtils { if (log.isDebugEnabled()) { log.info("Received compliance status from MONITOR operation ID: " + operation.getId()); } - getPolicyManagerService().checkPolicyCompliance(deviceIdentifier, operation.getPayLoad()); + getPolicyManagerService().checkPolicyCompliance(deviceIdentifier, + getComplianceFeatures(operation.getPayLoad())); } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants. OperationCodes.APPLICATION_LIST.equals(operation.getCode())) { if (log.isDebugEnabled()) { @@ -493,4 +495,29 @@ public class AndroidAPIUtils { } return ""; } + + private static List getComplianceFeatures(Object compliancePayload) throws PolicyComplianceException { + String compliancePayloadString = new Gson().toJson(compliancePayload); + if (compliancePayload == null) { + return null; + } + // Parsing json string to get compliance features. + JsonElement jsonElement; + if (compliancePayloadString instanceof String) { + jsonElement = new JsonParser().parse(compliancePayloadString); + } else { + throw new PolicyComplianceException("Invalid policy compliance payload"); + } + + JsonArray jsonArray = jsonElement.getAsJsonArray(); + Gson gson = new Gson(); + ComplianceFeature complianceFeature; + List complianceFeatures = new ArrayList(jsonArray.size()); + + for (JsonElement element : jsonArray) { + complianceFeature = gson.fromJson(element, ComplianceFeature.class); + complianceFeatures.add(complianceFeature); + } + return complianceFeatures; + } } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidConstants.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidConstants.java index 62ed8afe05..c1e09b4c06 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidConstants.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidConstants.java @@ -26,6 +26,7 @@ public final class AndroidConstants { public static final String DEVICE_TYPE_ANDROID = "android"; public static final String HEADER_CONTENT_TYPE = "Content-Type"; public static final String APPLICATION_JSON = "application/json"; + public static final String SCOPE = "scope"; public final class DeviceProperties { private DeviceProperties() { diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/web.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/web.xml index b39cda6735..63510fe9b1 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/web.xml +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/web.xml @@ -51,10 +51,6 @@ managed-api-enabled true - - managed-api-owner - admin - doAuthentication true diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/pom.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/pom.xml index d2245d5e44..22b0ecc009 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/pom.xml +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/pom.xml @@ -23,13 +23,13 @@ android-plugin org.wso2.carbon.devicemgt-plugins - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.device.mgt.mobile.android.ui - 3.0.5-SNAPSHOT + 3.0.6-SNAPSHOT WSO2 Carbon - Mobile Android UI pom diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/api/user-api.jag b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/api/user-api.jag index b038e66ad5..2a36433ded 100755 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/api/user-api.jag +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/api/user-api.jag @@ -121,9 +121,9 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { } else { userRoles = String(addUserFormData.userRoles).split(","); } - if (username.length < devicemgtProps.usernameLength) { - log.error("Username Must be between 1 and " + devicemgtProps.usernameLength + " characters long"); - result = "Username Must be between 1 and " + devicemgtProps.usernameLength + " characters long"; + if (username.length < devicemgtProps.userValidationConfig.usernameLength) { + log.error("Username Must be between 1 and " + devicemgtProps.userValidationConfig.usernameLength + " characters long"); + result = "Username Must be between 1 and " + devicemgtProps.userValidationConfig.usernameLength + " characters long"; } else { try { result = userModule.addUser(username, firstname, lastname, emailAddress, userRoles); diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/conf/config.json b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/conf/config.json index 75943b23b9..3c82027057 100755 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/conf/config.json +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/conf/config.json @@ -1,6 +1,5 @@ { "appContext" : "/android-web-agent/", - "apiContext" : "api", "httpsURL" : "%https.ip%", "httpURL" : "%http.ip%", "enrollmentDir": "/android-web-agent/enrollment", @@ -24,7 +23,9 @@ "tokenServiceURL": "%https.ip%/oauth2/token" }, "adminUser":"admin", - "usernameLength":30, + "userValidationConfig" : { + "usernameLength":30 + }, "device" : { "ios" : { "location" : "%http.ip%/android-web-agent/public/mdm.page.enrollments.ios.download-agent/asset/ios-agent.ipa", @@ -35,16 +36,6 @@ }, "androidAgentApp" : "android-agent.apk", "windowsConfigRoot" : "%http.ip%/api/device-mgt/windows/v1.0/services/federated/bst/authentication", - "ssoConfiguration" : { - "enabled" : false, - "issuer" : "mdm", - "appName" : "admin_android-web-agent", - "identityProviderURL" : "%https.ip%/sso/samlsso.jag", - "responseSigningEnabled" : "true", - "keyStorePassword" : "wso2carbon", - "identityAlias" : "wso2carbon", - "keyStoreName" : "/repository/resources/security/wso2carbon.jks" - }, "generalConfig" : { "host" : "%http.ip%", "companyName" : "WSO2 Enterprise Mobility Manager", diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/pages/mdm.page.enrollments.android.download-agent/download-agent.hbs b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/pages/mdm.page.enrollments.android.download-agent/download-agent.hbs index 26f32fefb6..8173c413a7 100755 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/pages/mdm.page.enrollments.android.download-agent/download-agent.hbs +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/pages/mdm.page.enrollments.android.download-agent/download-agent.hbs @@ -38,9 +38,9 @@ under the License. --}}
    If you have not already enrolled this device with {{companyName}}, - Download and install following EMM Agent to continue. + Download and install following IoT Server Agent to continue.
    diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.hbs b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.hbs index 1b42bdfc63..66cc6dca4b 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.hbs +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.hbs @@ -337,6 +337,14 @@ data-lat="{{device.location.latitude}}" data-long="{{device.location.longitude}}"> +
    + + + + + View device on the map + {{else}}

    @@ -429,7 +437,6 @@ type="text/x-handlebars-template"> {{js "js/device-detail.js"}} - {{js "js/load-map.js"}} {{/if}} {{/zone}} \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.js b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.js index b7ce950c06..ee77264770 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.js +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.js @@ -21,6 +21,7 @@ function onRequest(context) { var deviceType = context["uriParams"]["deviceType"]; var deviceId = request.getParameter("id"); var deviceViewData = {}; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; if (deviceType && deviceId) { var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; @@ -210,5 +211,9 @@ function onRequest(context) { ]; deviceViewData["autoCompleteParams"] = autoCompleteParams; + + deviceViewData["portalUrl"] = devicemgtProps['portalURL']; + var anchor = { "device" : { "id" : deviceId, "type" : deviceType}}; + deviceViewData["anchor"] = JSON.stringify(anchor); return deviceViewData; -} \ No newline at end of file +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/device_icons/TemperatureController.png b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/device_icons/TemperatureController.png deleted file mode 100755 index e16b48d8ee..0000000000 Binary files a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/device_icons/TemperatureController.png and /dev/null differ diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/device_icons/android.png b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/device_icons/android.png deleted file mode 100755 index 7fee78a646..0000000000 Binary files a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/device_icons/android.png and /dev/null differ diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/device_icons/ios.png b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/device_icons/ios.png deleted file mode 100755 index 4b09796f83..0000000000 Binary files a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/device_icons/ios.png and /dev/null differ diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/graph.png b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/graph.png deleted file mode 100755 index dd819ef4fc..0000000000 Binary files a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/img/graph.png and /dev/null differ diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/load-map.js b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/load-map.js old mode 100755 new mode 100644 index 895f75b949..c09ab8ddb7 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/load-map.js +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/load-map.js @@ -45,7 +45,7 @@ $(document).ready(function () { var url = $(this).prop("href"); var hash = url.substring(url.indexOf("#") + 1); - if (hash == "device_location") { + if (hash == "device_location_tab") { if (!map) { loadLeafletMap(); } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/configuration.hbs b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/configuration.hbs index 7e3708ed9d..5ace32cb31 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/configuration.hbs +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/configuration.hbs @@ -28,7 +28,7 @@
    @@ -42,7 +42,7 @@