From 1432923991f143ce4ff153d2271544a4cb5992b6 Mon Sep 17 00:00:00 2001 From: "tcdlpds@gmail.com" Date: Sun, 29 Mar 2020 23:08:59 +0530 Subject: [PATCH 1/5] Remove reporting components --- .../react-app/src/index.js | 48 --- .../react-app/src/scenes/Home/index.js | 8 +- .../components/DateRangePicker/index.js | 61 --- .../Reports/components/DevicesTable/index.js | 260 ------------- .../src/scenes/Home/scenes/Reports/index.js | 258 ------------- .../components/AppListDropDown/index.js | 100 ----- .../components/AppVersionDropDown/index.js | 118 ------ .../scenes/AppNotInstalledDevices/index.js | 136 ------- .../Reports/scenes/DeviceStatus/index.js | 264 ------------- .../EncryptedDevicesTable.js | 258 ------------- .../Reports/scenes/EncryptionStatus/index.js | 59 --- .../Reports/scenes/EnrollmentType/index.js | 252 ------------- .../scenes/EnrolmentVsUnenrollments/index.js | 255 ------------- .../Reports/scenes/OutdatedOSVersion/index.js | 183 --------- .../components/FeatureListModal/index.js | 128 ------- .../components/PolicyDevicesTable/index.js | 352 ------------------ .../components/SelectPolicyDropDown/index.js | 111 ------ .../Reports/scenes/PolicyCompliance/index.js | 198 ---------- 18 files changed, 1 insertion(+), 3048 deletions(-) delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/components/DateRangePicker/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/components/DevicesTable/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/components/AppListDropDown/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/components/AppVersionDropDown/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/DeviceStatus/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EncryptionStatus/components/EncryptedDeviceTable/EncryptedDevicesTable.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EncryptionStatus/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EnrollmentType/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EnrolmentVsUnenrollments/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/OutdatedOSVersion/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/PolicyDevicesTable/components/FeatureListModal/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/PolicyDevicesTable/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/SelectPolicyDropDown/index.js delete mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/index.js diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/index.js index 90fb75fcd3..b2f485e77b 100644 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/index.js +++ b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/index.js @@ -23,15 +23,7 @@ import App from './App'; import Login from './scenes/Login'; import Home from './scenes/Home'; import './index.css'; -import Reports from './scenes/Home/scenes/Reports'; -import EnrollmentsVsUnenrollmentsReport from './scenes/Home/scenes/Reports/scenes/EnrolmentVsUnenrollments'; -import EnrollmentTypeReport from './scenes/Home/scenes/Reports/scenes/EnrollmentType'; -import PolicyReport from './scenes/Home/scenes/Reports/scenes/PolicyCompliance'; -import DeviceStatusReport from './scenes/Home/scenes/Reports/scenes/DeviceStatus'; -import AppNotInstalledDevicesReport from './scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices'; import Geo from './scenes/Home/scenes/Geo'; -import EncryptionStatus from './scenes/Home/scenes/Reports/scenes/EncryptionStatus'; -import OutdatedOSversionReport from './scenes/Home/scenes/Reports/scenes/OutdatedOSVersion'; import Notifications from './scenes/Home/scenes/Notifications'; import DeviceEnroll from './scenes/Home/scenes/Devices/scenes/Enroll'; import Groups from './scenes/Home/scenes/Groups'; @@ -71,11 +63,6 @@ const routes = [ component: Geo, exact: true, }, - { - path: '/entgra/reports', - component: Reports, - exact: true, - }, { path: '/entgra/groups', component: Groups, @@ -126,41 +113,6 @@ const routes = [ component: Notifications, exact: true, }, - { - path: '/entgra/reports/enrollments', - component: EnrollmentsVsUnenrollmentsReport, - exact: true, - }, - { - path: '/entgra/reports/expired-devices', - component: OutdatedOSversionReport, - exact: true, - }, - { - path: '/entgra/reports/enrollment-type', - component: EnrollmentTypeReport, - exact: true, - }, - { - path: '/entgra/reports/policy/compliance', - component: PolicyReport, - exact: true, - }, - { - path: '/entgra/reports/device-status', - component: DeviceStatusReport, - exact: true, - }, - { - path: '/entgra/reports/app-not-installed', - component: AppNotInstalledDevicesReport, - exact: true, - }, - { - path: '/entgra/reports/encryption-status', - component: EncryptionStatus, - exact: true, - }, ], }, ]; diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/index.js index ab941cfb23..9dfb1b4e7a 100644 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/index.js +++ b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/index.js @@ -58,7 +58,7 @@ class Home extends React.Component {
- + logo
@@ -91,12 +91,6 @@ class Home extends React.Component { - - - - Reports - - diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/components/DateRangePicker/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/components/DateRangePicker/index.js deleted file mode 100644 index 15df294e72..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/components/DateRangePicker/index.js +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { DatePicker } from 'antd'; -import moment from 'moment'; - -class DateRangePicker extends React.Component { - constructor(props) { - super(props); - } - - // Send updated date range to index.js when duration change - onChange = (dates, dateStrings) => { - this.props.updateDurationValue(dateStrings[0], dateStrings[1]); - }; - - render() { - const { RangePicker } = DatePicker; - return ( -
- -
- ); - } -} - -export default DateRangePicker; diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/components/DevicesTable/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/components/DevicesTable/index.js deleted file mode 100644 index bc283b737d..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/components/DevicesTable/index.js +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import axios from 'axios'; -import { Icon, message, notification, Table, Tag, Tooltip } from 'antd'; -import TimeAgo from 'javascript-time-ago'; -// Load locale-specific relative date/time formatting rules. -import en from 'javascript-time-ago/locale/en'; -import { withConfigContext } from '../../../../../../components/ConfigContext'; - -let config = null; - -const columns = [ - { - title: 'Device', - dataIndex: 'name', - width: 100, - }, - { - title: 'Type', - dataIndex: 'type', - key: 'type', - // eslint-disable-next-line react/display-name - render: type => { - const defaultPlatformIcons = config.defaultPlatformIcons; - let icon = defaultPlatformIcons.default.icon; - let color = defaultPlatformIcons.default.color; - let theme = defaultPlatformIcons.default.theme; - - if (defaultPlatformIcons.hasOwnProperty(type)) { - icon = defaultPlatformIcons[type].icon; - color = defaultPlatformIcons[type].color; - theme = defaultPlatformIcons[type].theme; - } - - return ( - - - - ); - }, - // todo add filtering options - }, - { - title: 'Owner', - dataIndex: 'enrolmentInfo', - key: 'owner', - render: enrolmentInfo => enrolmentInfo.owner, - // todo add filtering options - }, - { - title: 'Ownership', - dataIndex: 'enrolmentInfo', - key: 'ownership', - render: enrolmentInfo => enrolmentInfo.ownership, - // todo add filtering options - }, - { - title: 'Status', - dataIndex: 'enrolmentInfo', - key: 'status', - // eslint-disable-next-line react/display-name - render: enrolmentInfo => { - const status = enrolmentInfo.status.toLowerCase(); - let color = '#f9ca24'; - switch (status) { - case 'active': - color = '#badc58'; - break; - case 'created': - color = '#6ab04c'; - break; - case 'removed': - color = '#ff7979'; - break; - case 'inactive': - color = '#f9ca24'; - break; - case 'blocked': - color = '#636e72'; - break; - } - return {status}; - }, - // todo add filtering options - }, - { - title: 'Last Updated', - dataIndex: 'enrolmentInfo', - key: 'dateOfLastUpdate', - // eslint-disable-next-line react/display-name - render: data => { - const { dateOfLastUpdate } = data; - const timeAgoString = getTimeAgo(dateOfLastUpdate); - return ( - - {timeAgoString} - - ); - }, - // todo add filtering options - }, -]; - -const getTimeAgo = time => { - const timeAgo = new TimeAgo('en-US'); - return timeAgo.format(time); -}; - -class deviceTable extends React.Component { - constructor(props) { - super(props); - config = this.props.context; - TimeAgo.addLocale(en); - this.state = { - data: [], - pagination: {}, - loading: false, - selectedRows: [], - paramsObj: {}, - }; - } - - rowSelection = { - onChange: (selectedRowKeys, selectedRows) => { - this.setState({ - selectedRows: selectedRows, - }); - }, - }; - - componentDidMount() { - if (this.props.apiUrl) { - this.fetch(); - } - } - - // Rerender component when parameters change - componentDidUpdate(prevProps, prevState, snapshot) { - if (prevProps.apiUrl !== this.props.apiUrl) { - this.fetch(); - } - } - - // fetch data from api - fetch = (params = {}) => { - this.setState({ loading: true }); - // get current page - const currentPage = params.hasOwnProperty('page') ? params.page : 1; - - const extraParams = { - offset: 10 * (currentPage - 1), // calculate the offset - limit: 10, - }; - - const encodedExtraParams = Object.keys(extraParams) - .map(key => key + '=' + extraParams[key]) - .join('&'); - - // send request to the invokerss - axios - .get(this.props.apiUrl + encodedExtraParams) - .then(res => { - if (res.status === 200) { - const pagination = { ...this.state.pagination }; - if ( - res.data.data.devices.length && - res.data.data.devices[0].hasOwnProperty('deviceInfo') - ) { - columns.push({ - title: 'OS Version', - dataIndex: 'deviceInfo', - key: 'osVersion', - render: deviceInfo => deviceInfo.osVersion, - }); - } - this.setState({ - loading: false, - data: res.data.data, - pagination, - }); - } - }) - .catch(error => { - if (error.hasOwnProperty('response') && error.response.status === 401) { - // todo display a popop with error - message.error('You are not logged in'); - window.location.href = window.location.origin + '/entgra/login'; - } else { - notification.error({ - message: 'There was a problem', - duration: 0, - description: 'Error occurred while trying to load devices.', - }); - } - - this.setState({ loading: false }); - }); - }; - - handleTableChange = (pagination, filters, sorter) => { - const pager = { ...this.state.pagination }; - pager.current = pagination.current; - this.setState({ - pagination: pager, - }); - this.fetch({ - results: pagination.pageSize, - page: pagination.current, - sortField: sorter.field, - sortOrder: sorter.order, - ...filters, - }); - }; - - render() { - const { data, pagination, loading } = this.state; - return ( -
- - record.deviceIdentifier + - record.enrolmentInfo.owner + - record.enrolmentInfo.ownership - } - dataSource={data.devices} - pagination={{ - ...pagination, - size: 'small', - total: data.count, - showTotal: (total, range) => - `showing ${range[0]}-${range[1]} of ${total} devices`, - }} - loading={loading} - onChange={this.handleTableChange} - rowSelection={this.rowSelection} - /> - - ); - } -} - -export default withConfigContext(deviceTable); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/index.js deleted file mode 100644 index 5a15b83241..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/index.js +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { PageHeader, Breadcrumb, Icon, Row, Col, Card } from 'antd'; -import { Link } from 'react-router-dom'; - -class Reports extends React.Component { - routes; - - constructor(props) { - super(props); - this.routes = props.routes; - this.state = { - paramsObject: {}, - }; - } - // Get modified value from datepicker and set it to paramsObject - updateDurationValue = (modifiedFromDate, modifiedToDate) => { - let tempParamObj = this.state.paramsObject; - tempParamObj.from = modifiedFromDate; - tempParamObj.to = modifiedToDate; - this.setState({ paramsObject: tempParamObj }); - }; - - // Get modified value from filters and set it to paramsObject - updateFiltersValue = (modifiedValue, filterType) => { - let tempParamObj = this.state.paramsObject; - if (filterType == 'Device Status') { - tempParamObj.status = modifiedValue; - if (modifiedValue == 'ALL' && tempParamObj.status) { - delete tempParamObj.status; - } - } else { - tempParamObj.ownership = modifiedValue; - if (modifiedValue == 'ALL' && tempParamObj.ownership) { - delete tempParamObj.ownership; - } - } - this.setState({ paramsObject: tempParamObj }); - }; - - render() { - return ( -
- - - - - Home - - - Reports - -
-

Reports

-
- -
- - -
- -

- Policy Compliance Report -

-

Policy compliance details of all enrolled devices

-
-
- - - - - -
- -

- Enrollments vs Unenrollments -

-

Details on device enrollments vs unenrollments

-
-
- - - - - - -
- -

- Device Status Report -

-

Report based on device status

-
-
- - - - - - -
- -

- Outdated OS Version Report -

-

Report based on device OS version

-
-
- - - - - - -
- -

- Device Type Report -

-

Report for all device types

-
-
- - - - - - -
- -

- App NOT Installed Devices Report -

-

Report for all device types

-
-
- - - - - - -
- - ); - } -} - -export default Reports; diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/components/AppListDropDown/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/components/AppListDropDown/index.js deleted file mode 100644 index e24c2afdd5..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/components/AppListDropDown/index.js +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { message, notification, Select } from 'antd'; -import axios from 'axios'; -import { withConfigContext } from '../../../../../../../../components/ConfigContext'; - -const { Option } = Select; - -class AppListDropDown extends React.Component { - constructor(props) { - super(props); - this.state = { - selectItem: [], - }; - } - - componentDidMount() { - this.fetchFullAppList(); - } - - fetchFullAppList = () => { - const config = this.props.context; - axios - .get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/devices/android/applications?offset=0&limit=-1', - ) - .then(res => { - if (res.status === 200) { - let selectItem; - selectItem = res.data.data.applicationList.map(data => ( - - )); - this.setState({ selectItem }); - } - }) - .catch(error => { - if (error.hasOwnProperty('response') && error.response.status === 401) { - // todo display a popop with error - message.error('You are not logged in'); - window.location.href = window.location.origin + '/entgra/login'; - } else { - notification.error({ - message: 'There was a problem', - duration: 0, - description: - 'Error occurred while trying to load application list.', - }); - } - }); - }; - - onChange = (value, data) => { - this.props.getAppList(data.key); - }; - - render() { - const { selectItem } = this.state; - return ( -
- -
- ); - } -} - -export default withConfigContext(AppListDropDown); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/components/AppVersionDropDown/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/components/AppVersionDropDown/index.js deleted file mode 100644 index 979c3a0585..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/components/AppVersionDropDown/index.js +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { message, notification, Select } from 'antd'; -import axios from 'axios'; -import { withConfigContext } from '../../../../../../../../components/ConfigContext'; - -const { Option } = Select; - -class AppVersionDropDown extends React.Component { - constructor(props) { - super(props); - this.state = { - selectItem: [], - loading: false, - }; - } - - componentDidMount() { - if (this.props.packageName) { - this.fetchVersionList(); - } - } - - // Rerender component when parameters change - componentDidUpdate(prevProps, prevState, snapshot) { - if (prevProps.packageName !== this.props.packageName) { - this.fetchVersionList(); - } - } - - fetchVersionList = () => { - const config = this.props.context; - this.setState({ loading: true }); - axios - .get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/devices/application/' + - this.props.packageName + - '/versions', - ) - .then(res => { - if (res.status === 200) { - let selectItem; - selectItem = JSON.parse(res.data.data).map(data => ( - - )); - this.setState({ selectItem, loading: false }); - } - }) - .catch(error => { - if (error.hasOwnProperty('response') && error.response.status === 401) { - // todo display a popop with error - message.error('You are not logged in'); - window.location.href = window.location.origin + '/entgra/login'; - } else { - notification.error({ - message: 'There was a problem', - duration: 0, - description: - 'Error occurred while trying to load application list.', - }); - } - }); - }; - - onChange = value => { - this.props.getVersion(value); - }; - - render() { - const { selectItem, loading } = this.state; - return ( -
- -
- ); - } -} - -export default withConfigContext(AppVersionDropDown); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/index.js deleted file mode 100644 index a23f4df8f0..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/AppNotInstalledDevices/index.js +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { PageHeader, Breadcrumb, Icon, Button } from 'antd'; - -import { Link } from 'react-router-dom'; -import { withConfigContext } from '../../../../../../components/ConfigContext'; - -import AppListDropDown from './components/AppListDropDown'; -import DevicesTable from './../../components/DevicesTable'; -import AppVersionDropDown from './components/AppVersionDropDown'; - -// eslint-disable-next-line no-unused-vars -let config = null; -let url; -let packageName; -let version; - -class AppNotInstalledDevicesReport extends React.Component { - routes; - - constructor(props) { - super(props); - this.routes = props.routes; - config = this.props.context; - this.state = { - apiUrl: null, - visible: false, - packageName: null, - version: 'all', - }; - } - - getAppList = appPackageName => { - packageName = appPackageName; - this.setState({ packageName }); - }; - - getVersion = appVersion => { - version = appVersion; - this.setState({ version }); - }; - - onClickGenerateButton = () => { - const { packageName, version } = this.state; - if (version === 'all') { - url = - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/reports/devices/android/' + - packageName + - '/not-installed?'; - } else { - url = - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/reports/devices/android/' + - packageName + - '/not-installed?app-version=' + - version + - '&'; - } - this.setState({ apiUrl: url }); - }; - - render() { - const { apiUrl, packageName } = this.state; - return ( -
- - - - - Home - - - - Reports - - App NOT Installed Devices Report - -
-

Policy Report

- -
-
- -
- -
- -
- - -
-
- -
-
-
-
-
- ); - } -} - -export default withConfigContext(AppNotInstalledDevicesReport); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/DeviceStatus/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/DeviceStatus/index.js deleted file mode 100644 index 862c5200cd..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/DeviceStatus/index.js +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { PageHeader, Breadcrumb, Icon, Radio, Popover, Button } from 'antd'; - -import { Link } from 'react-router-dom'; -import { withConfigContext } from '../../../../../../components/ConfigContext'; -import axios from 'axios'; -import DateRangePicker from '../../components/DateRangePicker'; -import moment from 'moment'; -import { Chart, Geom, Axis, Tooltip, Legend } from 'bizcharts'; -import DataSet from '@antv/data-set'; -import { handleApiError } from '../../../../../../services/utils/errorHandler'; - -class DeviceStatusReport extends React.Component { - routes; - - constructor(props) { - super(props); - this.routes = props.routes; - this.state = { - paramsObject: { - from: moment() - .subtract(6, 'days') - .format('YYYY-MM-DD'), - to: moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - }, - data: [], - fields: [], - durationMode: 'weekly', - visible: false, - }; - } - - handleDurationModeChange = e => { - const durationMode = e.target.value; - switch (durationMode) { - case 'daily': - this.updateDurationValue( - moment().format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - case 'weekly': - this.updateDurationValue( - moment() - .subtract(6, 'days') - .format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - case 'monthly': - this.updateDurationValue( - moment() - .subtract(29, 'days') - .format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - } - this.setState({ durationMode }); - }; - - handlePopoverVisibleChange = visible => { - this.setState({ visible }); - }; - - componentDidMount() { - this.fetchData(); - } - - // Get modified value from datepicker and set it to paramsObject - updateDurationValue = (modifiedFromDate, modifiedToDate) => { - let tempParamObj = this.state.paramsObject; - tempParamObj.from = modifiedFromDate; - tempParamObj.to = modifiedToDate; - this.setState({ paramsObject: tempParamObj }); - this.fetchData(); - }; - - // Call count APIs and get count for given parameters, then create data object to build pie chart - fetchData = () => { - this.setState({ loading: true }); - - const { paramsObject } = this.state; - const config = this.props.context; - - const encodedExtraParams = Object.keys(paramsObject) - .map(key => key + '=' + paramsObject[key]) - .join('&'); - - axios - .all([ - axios.get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/reports/count?status=ACTIVE&' + - encodedExtraParams, - 'Active', - ), - axios.get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/reports/count?status=INACTIVE&' + - encodedExtraParams, - 'Inactive', - ), - axios.get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/reports/count?status=REMOVED&' + - encodedExtraParams, - 'Removed', - ), - ]) - .then(res => { - let keys = Object.keys(res[0].data.data); - let active = res[0].data.data; - let inactive = res[1].data.data; - let removed = res[2].data.data; - - if (Object.keys(active).length != 0) { - active.name = 'Active'; - inactive.name = 'Inactive'; - removed.name = 'Removed'; - } - - const finalData = [active, inactive, removed]; - - this.setState({ - data: finalData, - fields: keys, - }); - }) - .catch(error => { - handleApiError( - error, - 'Error occurred while trying to get device count.', - ); - }); - }; - - render() { - const { durationMode } = this.state; - - const ds = new DataSet(); - const dv = ds.createView().source(this.state.data); - dv.transform({ - type: 'fold', - fields: this.state.fields, - key: 'Time', - value: 'Number of Devices', - }); - - return ( -
- - - - - Home - - - - Reports - - Device Status Report - -
-

Device Status Report

- - - Today - Last Week - Last Month - - - - -
- } - visible={this.state.visible} - onVisibleChange={this.handlePopoverVisibleChange} - > - - - -
- - - - - - - -
-
- -
- - ); - } -} - -export default withConfigContext(DeviceStatusReport); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EncryptionStatus/components/EncryptedDeviceTable/EncryptedDevicesTable.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EncryptionStatus/components/EncryptedDeviceTable/EncryptedDevicesTable.js deleted file mode 100644 index a18985d64b..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EncryptionStatus/components/EncryptedDeviceTable/EncryptedDevicesTable.js +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import axios from 'axios'; -import { Icon, message, notification, Radio, Table, Tag, Tooltip } from 'antd'; -import TimeAgo from 'javascript-time-ago'; -// Load locale-specific relative date/time formatting rules. -import en from 'javascript-time-ago/locale/en'; -import { withConfigContext } from '../../../../../../../../components/ConfigContext'; - -let config = null; - -const columns = [ - { - title: 'Device', - dataIndex: 'name', - }, - { - title: 'Type', - dataIndex: 'type', - key: 'type', - // eslint-disable-next-line react/display-name - render: type => { - const defaultPlatformIcons = config.defaultPlatformIcons; - let icon = defaultPlatformIcons.default.icon; - let color = defaultPlatformIcons.default.color; - let theme = defaultPlatformIcons.default.theme; - - if (defaultPlatformIcons.hasOwnProperty(type)) { - icon = defaultPlatformIcons[type].icon; - color = defaultPlatformIcons[type].color; - theme = defaultPlatformIcons[type].theme; - } - - return ( - - - - ); - }, - // todo add filtering options - }, - { - title: 'Owner', - dataIndex: 'enrolmentInfo', - key: 'owner', - render: enrolmentInfo => enrolmentInfo.owner, - // todo add filtering options - }, - { - title: 'Ownership', - dataIndex: 'enrolmentInfo', - key: 'ownership', - render: enrolmentInfo => enrolmentInfo.ownership, - // todo add filtering options - }, - { - title: 'Status', - dataIndex: 'enrolmentInfo', - key: 'status', - // eslint-disable-next-line react/display-name - render: enrolmentInfo => { - const status = enrolmentInfo.status.toLowerCase(); - let color = '#f9ca24'; - switch (status) { - case 'active': - color = '#badc58'; - break; - case 'created': - color = '#6ab04c'; - break; - case 'removed': - color = '#ff7979'; - break; - case 'inactive': - color = '#f9ca24'; - break; - case 'blocked': - color = '#636e72'; - break; - } - return {status}; - }, - // todo add filtering options - }, - { - title: 'Last Updated', - dataIndex: 'enrolmentInfo', - key: 'dateOfLastUpdate', - // eslint-disable-next-line react/display-name - render: data => { - const { dateOfLastUpdate } = data; - const timeAgoString = getTimeAgo(dateOfLastUpdate); - return ( - - {timeAgoString} - - ); - }, - // todo add filtering options - }, -]; - -const getTimeAgo = time => { - const timeAgo = new TimeAgo('en-US'); - return timeAgo.format(time); -}; - -class EncryptedDeviceTable extends React.Component { - constructor(props) { - super(props); - config = this.props.context; - TimeAgo.addLocale(en); - this.state = { - data: [], - pagination: {}, - loading: false, - isEncrypted: true, - }; - } - - componentDidMount() { - this.fetch(); - } - - // fetch data from api - fetch = (params = {}) => { - const config = this.props.context; - this.setState({ loading: true }); - // get current page - const currentPage = params.hasOwnProperty('page') ? params.page : 1; - - const extraParams = { - offset: 10 * (currentPage - 1), // calculate the offset - limit: 10, - requireDeviceInfo: true, - isEncrypted: this.state.isEncrypted, - }; - - const encodedExtraParams = Object.keys(extraParams) - .map(key => key + '=' + extraParams[key]) - .join('&'); - - // send request to the invoker - axios - .get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/reports/encryption-status?' + - encodedExtraParams, - ) - .then(res => { - if (res.status === 200) { - const pagination = { ...this.state.pagination }; - this.setState({ - loading: false, - data: res.data.data.devices, - pagination, - }); - } - }) - .catch(error => { - if (error.hasOwnProperty('response') && error.response.status === 401) { - // todo display a popop with error - message.error('You are not logged in'); - window.location.href = window.location.origin + '/entgra/login'; - } else { - notification.error({ - message: 'There was a problem', - duration: 0, - description: 'Error occurred while trying to load devices.', - }); - } - this.setState({ loading: false }); - }); - }; - - handleTableChange = (pagination, filters, sorter) => { - const pager = { ...this.state.pagination }; - pager.current = pagination.current; - this.setState({ - pagination: pager, - }); - this.fetch({ - results: pagination.pageSize, - page: pagination.current, - sortField: sorter.field, - sortOrder: sorter.order, - ...filters, - }); - }; - - handleModeChange = value => { - this.setState( - { - isEncrypted: value.target.value, - }, - this.fetch, - ); - }; - - render() { - const { data, pagination, loading } = this.state; - - return ( -
- - Enabled Devices - Disabled Devices - -
-
- record.deviceIdentifier + - record.enrolmentInfo.owner + - record.enrolmentInfo.ownership - } - dataSource={data} - pagination={{ - ...pagination, - size: 'small', - // position: "top", - showTotal: (total, range) => - `showing ${range[0]}-${range[1]} of ${total} devices`, - // showQuickJumper: true - }} - loading={loading} - onChange={this.handleTableChange} - /> - - - ); - } -} - -export default withConfigContext(EncryptedDeviceTable); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EncryptionStatus/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EncryptionStatus/index.js deleted file mode 100644 index cd9f568ec7..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EncryptionStatus/index.js +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { PageHeader, Breadcrumb, Icon } from 'antd'; -import { Link } from 'react-router-dom'; -import EncryptedDeviceTable from './components/EncryptedDeviceTable/EncryptedDevicesTable'; - -class EncryptionStatus extends React.Component { - routes; - - constructor(props) { - super(props); - this.routes = props.routes; - } - render() { - return ( -
- - - - - Home - - - - Reports - - Encryption Status - -
-

Encryption Status Report

-
- -
-
-
- ); - } -} - -export default EncryptionStatus; diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EnrollmentType/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EnrollmentType/index.js deleted file mode 100644 index 795c5daea7..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EnrollmentType/index.js +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { PageHeader, Breadcrumb, Icon, Radio, Popover, Button } from 'antd'; - -import { Link } from 'react-router-dom'; -import { withConfigContext } from '../../../../../../components/ConfigContext'; -import axios from 'axios'; -import DateRangePicker from '../../components/DateRangePicker'; -import moment from 'moment'; -import { Chart, Geom, Axis, Tooltip, Legend } from 'bizcharts'; -import DataSet from '@antv/data-set'; -import { handleApiError } from '../../../../../../services/utils/errorHandler'; - -class EnrollmentTypeReport extends React.Component { - routes; - - constructor(props) { - super(props); - this.routes = props.routes; - this.state = { - paramsObject: { - from: moment() - .subtract(6, 'days') - .format('YYYY-MM-DD'), - to: moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - }, - data: [], - fields: [], - durationMode: 'weekly', - visible: false, - }; - } - - componentDidMount() { - this.fetchData(); - } - - handleDurationModeChange = e => { - const durationMode = e.target.value; - switch (durationMode) { - case 'daily': - this.updateDurationValue( - moment().format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - case 'weekly': - this.updateDurationValue( - moment() - .subtract(6, 'days') - .format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - case 'monthly': - this.updateDurationValue( - moment() - .subtract(29, 'days') - .format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - } - this.setState({ durationMode }); - }; - - handlePopoverVisibleChange = visible => { - this.setState({ visible }); - }; - - // Get modified value from datepicker and set it to paramsObject - updateDurationValue = (modifiedFromDate, modifiedToDate) => { - let tempParamObj = this.state.paramsObject; - tempParamObj.from = modifiedFromDate; - tempParamObj.to = modifiedToDate; - this.setState({ paramsObject: tempParamObj }); - this.fetchData(); - }; - - // Call count APIs and get count for given parameters, then create data object to build pie chart - fetchData = () => { - this.setState({ loading: true }); - - const { paramsObject } = this.state; - const config = this.props.context; - - const encodedExtraParams = Object.keys(paramsObject) - .map(key => key + '=' + paramsObject[key]) - .join('&'); - - axios - .all([ - axios.get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/reports/count?ownership=BYOD&' + - encodedExtraParams, - 'BYOD', - ), - axios.get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/reports/count?ownership=COPE&' + - encodedExtraParams, - 'COPE', - ), - ]) - .then(res => { - let keys = Object.keys(res[0].data.data); - let byod = res[0].data.data; - let cope = res[1].data.data; - if (Object.keys(byod).length != 0) { - byod.name = 'BYOD'; - cope.name = 'COPE'; - } - - const finalData = [byod, cope]; - - this.setState({ - data: finalData, - fields: keys, - }); - }) - .catch(error => { - handleApiError( - error, - 'Error occurred while trying to get device count.', - ); - }); - }; - - render() { - const { durationMode } = this.state; - - const ds = new DataSet(); - const dv = ds.createView().source(this.state.data); - dv.transform({ - type: 'fold', - fields: this.state.fields, - key: 'Time', - value: 'Number of Devices', - }); - - return ( -
- - - - - Home - - - - Reports - - Device Enrollment Type Report - -
-

Device Enrollment Type Report

- - Today - Last Week - Last Month - - - - -
- } - visible={this.state.visible} - onVisibleChange={this.handlePopoverVisibleChange} - > - - - -
- - - - - - - -
-
- -
- - ); - } -} - -export default withConfigContext(EnrollmentTypeReport); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EnrolmentVsUnenrollments/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EnrolmentVsUnenrollments/index.js deleted file mode 100644 index bf262d4476..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/EnrolmentVsUnenrollments/index.js +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { PageHeader, Breadcrumb, Icon, Radio, Popover, Button } from 'antd'; - -import { Link } from 'react-router-dom'; -import { withConfigContext } from '../../../../../../components/ConfigContext'; -import axios from 'axios'; -import DateRangePicker from '../../components/DateRangePicker'; -import moment from 'moment'; -import { Chart, Geom, Axis, Tooltip, Legend } from 'bizcharts'; -import DataSet from '@antv/data-set'; -import { handleApiError } from '../../../../../../services/utils/errorHandler'; - -class EnrollmentsVsUnenrollmentsReport extends React.Component { - routes; - - constructor(props) { - super(props); - this.routes = props.routes; - this.state = { - paramsObject: { - from: moment() - .subtract(6, 'days') - .format('YYYY-MM-DD'), - to: moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - }, - data: [], - fields: [], - durationMode: 'weekly', - visible: false, - }; - } - - componentDidMount() { - this.fetchData(); - } - - handleDurationModeChange = e => { - const durationMode = e.target.value; - switch (durationMode) { - case 'daily': - this.updateDurationValue( - moment().format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - case 'weekly': - this.updateDurationValue( - moment() - .subtract(6, 'days') - .format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - case 'monthly': - this.updateDurationValue( - moment() - .subtract(29, 'days') - .format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - } - this.setState({ durationMode }); - }; - - handlePopoverVisibleChange = visible => { - this.setState({ visible }); - }; - - // Get modified value from datepicker and set it to paramsObject - updateDurationValue = (modifiedFromDate, modifiedToDate) => { - let tempParamObj = this.state.paramsObject; - tempParamObj.from = modifiedFromDate; - tempParamObj.to = modifiedToDate; - this.setState({ paramsObject: tempParamObj }); - this.fetchData(); - }; - - // Call count APIs and get count for given parameters, then create data object to build pie chart - fetchData = () => { - this.setState({ loading: true }); - - const { paramsObject } = this.state; - const config = this.props.context; - - const encodedExtraParams = Object.keys(paramsObject) - .map(key => key + '=' + paramsObject[key]) - .join('&'); - - axios - .all([ - axios.get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/reports/count?status=ACTIVE&status=INACTIVE&' + - encodedExtraParams, - 'Enrollments', - ), - axios.get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/reports/count?status=REMOVED&' + - encodedExtraParams, - 'Unenrollments', - ), - ]) - .then(res => { - let keys = Object.keys(res[0].data.data); - let enrollments = res[0].data.data; - let unenrollments = res[1].data.data; - if (Object.keys(enrollments).length != 0) { - enrollments.name = 'Enrollments'; - unenrollments.name = 'Unenrollments'; - } - - const finalData = [enrollments, unenrollments]; - - this.setState({ - data: finalData, - fields: keys, - }); - }) - .catch(error => { - handleApiError( - error, - 'Error occurred while trying to get device count.', - ); - }); - }; - - render() { - const { durationMode } = this.state; - - const ds = new DataSet(); - const dv = ds.createView().source(this.state.data); - dv.transform({ - type: 'fold', - fields: this.state.fields, - key: 'Time', - value: 'Number of Devices', - }); - - return ( -
- - - - - Home - - - - Reports - - - Enrollments vs Unenrollments Report - - -
-

Enrollments vs Unenrollments Report

- - - Today - Last Week - Last Month - - - - -
- } - visible={this.state.visible} - onVisibleChange={this.handlePopoverVisibleChange} - > - - - -
- - - - - - - -
-
- -
- - ); - } -} - -export default withConfigContext(EnrollmentsVsUnenrollmentsReport); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/OutdatedOSVersion/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/OutdatedOSVersion/index.js deleted file mode 100644 index fca5ca7534..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/OutdatedOSVersion/index.js +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import axios from 'axios'; -import { - PageHeader, - Breadcrumb, - Icon, - Button, - Select, - message, - notification, -} from 'antd'; - -import { Link } from 'react-router-dom'; -import { withConfigContext } from '../../../../../../components/ConfigContext'; -import DeviceTable from '../../components/DevicesTable'; - -let config = null; -const { Option } = Select; -let { typeSelected, versionSelected } = false; - -class OutdatedOSversionReport extends React.Component { - routes; - - constructor(props) { - super(props); - this.routes = props.routes; - config = this.props.context; - - this.state = { - deviceType: null, - osVersion: null, - apiURL: null, - visible: false, - supportedOsVersions: [], - }; - } - - onDeviceTypeChange = value => { - typeSelected = true; - this.setState({ deviceType: value }); - this.getSupportedOsVersions(value); - }; - - onOSVersionChange = value => { - versionSelected = true; - this.setState({ osVersion: value }); - }; - - onClickGenerateButton = () => { - const { osVersion, deviceType } = this.state; - if (osVersion && deviceType != null) { - let apiURL = - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - `/reports/expired-devices/${deviceType}?osVersion=${osVersion}&`; - this.setState({ apiURL }); - } - }; - - getSupportedOsVersions = deviceType => { - const config = this.props.context; - axios - .get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - `/admin/device-types/${deviceType}/versions`, - ) - .then(res => { - if (res.status === 200) { - let supportedOsVersions = JSON.parse(res.data.data); - this.setState({ - supportedOsVersions, - }); - } - }) - .catch(error => { - if (error.hasOwnProperty('response') && error.response.status === 401) { - message.error('You are not logged in'); - window.location.href = window.location.origin + '/entgra/login'; - } else { - notification.error({ - message: 'There was a problem', - duration: 0, - description: 'Error occurred while trying to load OS Versions.', - }); - } - }); - }; - - render() { - const { apiURL, supportedOsVersions } = this.state; - return ( -
- - - - - Home - - - - Reports - - Outdated OS Version - -
-

Outdated OS Version Report

-

- This report displays devices with an OS Version below the - specified version. -

-
- - - {typeSelected && versionSelected ? ( - - ) : null} -
-
- -
-
-
-
-
- ); - } -} - -export default withConfigContext(OutdatedOSversionReport); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/PolicyDevicesTable/components/FeatureListModal/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/PolicyDevicesTable/components/FeatureListModal/index.js deleted file mode 100644 index 2b23bcb141..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/PolicyDevicesTable/components/FeatureListModal/index.js +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { Button, message, Modal, notification, List, Typography } from 'antd'; -import axios from 'axios'; -import { withConfigContext } from '../../../../../../../../../../components/ConfigContext'; - -class FeatureListModal extends React.Component { - constructor(props) { - super(props); - this.state = { - modalVisible: false, - name: '', - description: '', - features: [], - }; - } - - fetchViolatedFeatures = id => { - const config = this.props.context; - - axios - .get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/devices/' + - id + - '/features', - ) - .then(res => { - if (res.status === 200) { - this.setState({ - features: JSON.parse(res.data.data), - }); - } - }) - .catch(error => { - if (error.hasOwnProperty('response') && error.response.status === 401) { - // todo display a popop with error - message.error('You are not logged in'); - window.location.href = window.location.origin + '/entgra/login'; - } else { - notification.error({ - message: 'There was a problem', - duration: 0, - description: - 'Error occurred while trying to load non compliance feature list.', - }); - } - }); - }; - - openModal = () => { - this.fetchViolatedFeatures(this.props.id); - this.setState({ - modalVisible: true, - }); - }; - - handleOk = e => { - this.setState({ - modalVisible: false, - }); - }; - - render() { - const { features, modalVisible } = this.state; - - let featureList = features.map(data => ( - - - {data.featureCode} - - - )); - - return ( -
-
- -
-
- - OK - , - ]} - > - - {featureList} - - -
-
- ); - } -} - -export default withConfigContext(FeatureListModal); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/PolicyDevicesTable/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/PolicyDevicesTable/index.js deleted file mode 100644 index 0c820d0f7b..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/PolicyDevicesTable/index.js +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import axios from 'axios'; -import { Button, Icon, Table, Tooltip } from 'antd'; -import TimeAgo from 'javascript-time-ago'; -import moment from 'moment'; -// Load locale-specific relative date/time formatting rules. -import en from 'javascript-time-ago/locale/en'; -import { withConfigContext } from '../../../../../../../../components/ConfigContext'; -import FeatureListModal from './components/FeatureListModal'; -import { handleApiError } from '../../../../../../../../services/utils/errorHandler'; - -let config = null; - -// Table columns for non compliant devices -const columnsNonCompliant = [ - { - title: 'Device', - dataIndex: 'deviceName', - width: 100, - sorter: (a, b) => a.deviceName.localeCompare(b.deviceName), - }, - { - title: 'Type', - dataIndex: 'deviceType', - key: 'type', - // eslint-disable-next-line react/display-name - render: type => { - const defaultPlatformIcons = config.defaultPlatformIcons; - let icon = defaultPlatformIcons.default.icon; - let color = defaultPlatformIcons.default.color; - let theme = defaultPlatformIcons.default.theme; - - if (defaultPlatformIcons.hasOwnProperty(type)) { - icon = defaultPlatformIcons[type].icon; - color = defaultPlatformIcons[type].color; - theme = defaultPlatformIcons[type].theme; - } - - return ( - - - - ); - }, - }, - { - title: 'Owner', - dataIndex: 'owner', - key: 'owner', - }, - { - title: 'Policy', - dataIndex: 'policyName', - key: 'policy', - sorter: (a, b) => a.policyName.localeCompare(b.policyName), - }, - { - title: 'Last Failed Time', - dataIndex: 'lastFailedTime', - key: 'lastFailedTime', - render: data => { - if (data) { - return ( - - {moment(data).fromNow()} - - ); - } - return 'Not available'; - }, - }, - { - title: 'Last Success Time', - dataIndex: 'lastSucceededTime', - key: 'lastSucceededTime', - render: data => { - if (data) { - return ( - - {moment(data).fromNow()} - - ); - } - return 'Not available'; - }, - }, - { - title: 'Attempts', - dataIndex: 'attempts', - key: 'attempts', - }, - { - title: 'Violated Features', - dataIndex: 'id', - key: 'violated_features', - // eslint-disable-next-line react/display-name - render: id => , - }, - { - title: 'Device Details', - dataIndex: 'id', - key: 'device_details', - // eslint-disable-next-line react/display-name - render: id => ( - - ), - }, -]; - -// Table columns for compliant devices -const columnsCompliant = [ - { - title: 'Device', - dataIndex: 'deviceName', - width: 100, - sorter: (a, b) => a.deviceName.localeCompare(b.deviceName), - }, - { - title: 'Type', - dataIndex: 'deviceType', - key: 'type', - // eslint-disable-next-line react/display-name - render: type => { - const defaultPlatformIcons = config.defaultPlatformIcons; - let icon = defaultPlatformIcons.default.icon; - let color = defaultPlatformIcons.default.color; - let theme = defaultPlatformIcons.default.theme; - - if (defaultPlatformIcons.hasOwnProperty(type)) { - icon = defaultPlatformIcons[type].icon; - color = defaultPlatformIcons[type].color; - theme = defaultPlatformIcons[type].theme; - } - - return ( - - - - ); - }, - }, - { - title: 'Owner', - dataIndex: 'owner', - key: 'owner', - }, - { - title: 'Policy', - dataIndex: 'policyName', - key: 'policy', - sorter: (a, b) => a.policyName.localeCompare(b.policyName), - }, - { - title: 'Last Success Time', - dataIndex: 'lastSucceededTime', - key: 'lastSucceededTime', - render: data => { - if (data) { - return ( - - {moment(data).fromNow()} - - ); - } - return 'Not available'; - }, - }, - { - title: 'Attempts', - dataIndex: 'attempts', - key: 'attempts', - }, - { - title: 'Device Details', - dataIndex: 'id', - key: 'device_details', - // eslint-disable-next-line react/display-name - render: id => ( - - ), - }, -]; - -class PolicyDevicesTable extends React.Component { - constructor(props) { - super(props); - config = this.props.context; - TimeAgo.addLocale(en); - this.state = { - data: [], - pagination: {}, - loading: false, - selectedRows: [], - paramsObj: {}, - }; - } - - rowSelection = { - onChange: (selectedRowKeys, selectedRows) => { - this.setState({ - selectedRows: selectedRows, - }); - }, - }; - - componentDidMount() { - this.fetchData(); - } - - // Rerender component when parameters change - componentDidUpdate(prevProps, prevState, snapshot) { - if ( - prevProps.isCompliant !== this.props.isCompliant || - prevProps.policyReportData !== this.props.policyReportData - ) { - this.fetchData(); - } - } - - // fetch data from api - fetchData = (params = {}) => { - // const policyReportData = this.props; - this.setState({ loading: true }); - // get current page - const currentPage = params.hasOwnProperty('page') ? params.page : 1; - - let extraParams; - - if (this.props.policyReportData.policy) { - extraParams = { - policy: this.props.policyReportData.policy, - from: this.props.policyReportData.from, - to: this.props.policyReportData.to, - offset: 10 * (currentPage - 1), // calculate the offset - limit: 10, - }; - } else { - extraParams = { - from: this.props.policyReportData.from, - to: this.props.policyReportData.to, - offset: 10 * (currentPage - 1), // calculate the offset - limit: 10, - }; - } - - const encodedExtraParams = Object.keys(extraParams) - .map(key => key + '=' + extraParams[key]) - .join('&'); - - let apiUrl; - - if (this.props.isCompliant) { - apiUrl = - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/devices/compliance/true?' + - encodedExtraParams; - } else { - apiUrl = - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/devices/compliance/false?' + - encodedExtraParams; - } - - // send request to the invoker - axios - .get(apiUrl) - .then(res => { - if (res.status === 200) { - const pagination = { ...this.state.pagination }; - this.setState({ - loading: false, - data: res.data.data, - pagination, - }); - } - }) - .catch(error => { - handleApiError(error, 'Error occurred while trying to load devices.'); - this.setState({ loading: false }); - }); - }; - - handleTableChange = (pagination, filters, sorter) => { - const pager = { ...this.state.pagination }; - pager.current = pagination.current; - this.setState({ - pagination: pager, - }); - this.fetchData({ - results: pagination.pageSize, - page: pagination.current, - sortField: sorter.field, - sortOrder: sorter.order, - ...filters, - }); - }; - - render() { - let { data, pagination, loading } = this.state; - const { isCompliant } = this.props; - - return ( -
-
record.id} - dataSource={data.complianceData} - pagination={{ - ...pagination, - size: 'small', - // position: "top", - total: data.count, - showTotal: (total, range) => - `showing ${range[0]}-${range[1]} of ${total} devices`, - // showQuickJumper: true - }} - loading={loading} - onChange={this.handleTableChange} - rowSelection={this.rowSelection} - /> - - ); - } -} - -export default withConfigContext(PolicyDevicesTable); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/SelectPolicyDropDown/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/SelectPolicyDropDown/index.js deleted file mode 100644 index 1ec9aa2bfe..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/components/SelectPolicyDropDown/index.js +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { Select, message, notification } from 'antd'; - -import { withConfigContext } from '../../../../../../../../components/ConfigContext'; -import axios from 'axios'; - -const { Option } = Select; - -class SelectPolicyDropDown extends React.Component { - routes; - - constructor(props) { - super(props); - this.routes = props.routes; - this.state = { - isOpen: false, - currentPage: 1, - data: [], - pagination: {}, - loading: false, - }; - } - - componentDidMount() { - this.fetchPolicies(); - } - - // fetch data from api - fetchPolicies = (params = {}) => { - const config = this.props.context; - this.setState({ loading: true }); - - // send request to the invokerss - axios - .get( - window.location.origin + - config.serverConfig.invoker.uri + - config.serverConfig.invoker.deviceMgt + - '/policies', - ) - .then(res => { - if (res.status === 200) { - this.setState({ - loading: false, - data: res.data.data.policies, - }); - } - }) - .catch(error => { - if (error.hasOwnProperty('response') && error.response.status === 401) { - // todo display a popop with error - message.error('You are not logged in'); - window.location.href = window.location.origin + '/entgra/login'; - } else { - notification.error({ - message: 'There was a problem', - duration: 0, - description: 'Error occurred while trying to load policies.', - }); - } - - this.setState({ loading: false }); - }); - }; - - handleChange = value => { - this.props.getPolicyId(value); - }; - - render() { - let item; - if (this.state.data) { - item = this.state.data.map(data => ( - - {data.profile.profileName} - - )); - } - - return ( - - ); - } -} - -export default withConfigContext(SelectPolicyDropDown); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/index.js deleted file mode 100644 index 29f789311d..0000000000 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Reports/scenes/PolicyCompliance/index.js +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import React from 'react'; -import { PageHeader, Breadcrumb, Icon, Radio, Popover, Button } from 'antd'; - -import { Link } from 'react-router-dom'; -import { withConfigContext } from '../../../../../../components/ConfigContext'; -import PolicyDevicesTable from './components/PolicyDevicesTable'; -import moment from 'moment'; -import DateRangePicker from '../../components/DateRangePicker'; -import SelectPolicyDropDown from './components/SelectPolicyDropDown'; - -// eslint-disable-next-line no-unused-vars -let config = null; - -class PolicyReport extends React.Component { - routes; - - constructor(props) { - super(props); - this.routes = props.routes; - config = this.props.context; - this.state = { - durationMode: 'weekly', - isCompliant: true, - // This object contains parameters which pass into API endpoint - policyReportData: { - from: moment() - .subtract(6, 'days') - .format('YYYY-MM-DD'), - to: moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - }, - visible: false, - }; - } - - handleModeChange = e => { - const isCompliant = e.target.value; - this.setState({ isCompliant }); - }; - - handleDurationModeChange = e => { - const durationMode = e.target.value; - switch (durationMode) { - case 'daily': - this.updateDurationValue( - moment().format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - case 'weekly': - this.updateDurationValue( - moment() - .subtract(6, 'days') - .format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - case 'monthly': - this.updateDurationValue( - moment() - .subtract(29, 'days') - .format('YYYY-MM-DD'), - moment() - .add(1, 'days') - .format('YYYY-MM-DD'), - ); - break; - } - this.setState({ durationMode }); - }; - - hidePopover = () => { - this.setState({ - visible: false, - }); - }; - - handlePopoverVisibleChange = visible => { - this.setState({ visible }); - }; - - getPolicyId = policyId => { - let tempParamObj = this.state.policyReportData; - if (policyId === 'all') { - delete tempParamObj.policy; - } else { - tempParamObj.policy = policyId; - } - this.setState({ policyReportData: tempParamObj }); - }; - - // Get modified value from datepicker and set it to paramsObject - updateDurationValue = (modifiedFromDate, modifiedToDate) => { - let tempParamObj = this.state.policyReportData; - tempParamObj.from = modifiedFromDate; - tempParamObj.to = modifiedToDate; - this.setState({ policyReportData: tempParamObj }); - }; - - render() { - const { isCompliant, durationMode } = this.state; - const policyData = { ...this.state.policyReportData }; - return ( -
- - - - - Home - - - - Reports - - Policy Compliance Report - -
-

Policy Report

- - - Policy Compliant Devices - - Policy Non-Compliant Devices - - - - - Today - Last Week - Last Month - - - -
- } - visible={this.state.visible} - onVisibleChange={this.handlePopoverVisibleChange} - > - - - - - -
- -
-
- -
- - ); - } -} - -export default withConfigContext(PolicyReport); From 9843b2e5b9b48cf6c821df7d1878da6de0f534ea Mon Sep 17 00:00:00 2001 From: Shamalka Navod Date: Sun, 29 Mar 2020 19:35:38 +0000 Subject: [PATCH 2/5] Fix DevicesTable import issue in GroupDevicesModal component --- .../Home/components/DevicesTable/index.js | 260 ++++++++++++++++++ .../components/GroupDevicesModal/index.js | 2 +- 2 files changed, 261 insertions(+), 1 deletion(-) create mode 100644 components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/components/DevicesTable/index.js diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/components/DevicesTable/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/components/DevicesTable/index.js new file mode 100644 index 0000000000..79ad40585f --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/components/DevicesTable/index.js @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import React from 'react'; +import axios from 'axios'; +import { Icon, message, notification, Table, Tag, Tooltip } from 'antd'; +import TimeAgo from 'javascript-time-ago'; +// Load locale-specific relative date/time formatting rules. +import en from 'javascript-time-ago/locale/en'; +import { withConfigContext } from '../../../../components/ConfigContext'; + +let config = null; + +const columns = [ + { + title: 'Device', + dataIndex: 'name', + width: 100, + }, + { + title: 'Type', + dataIndex: 'type', + key: 'type', + // eslint-disable-next-line react/display-name + render: type => { + const defaultPlatformIcons = config.defaultPlatformIcons; + let icon = defaultPlatformIcons.default.icon; + let color = defaultPlatformIcons.default.color; + let theme = defaultPlatformIcons.default.theme; + + if (defaultPlatformIcons.hasOwnProperty(type)) { + icon = defaultPlatformIcons[type].icon; + color = defaultPlatformIcons[type].color; + theme = defaultPlatformIcons[type].theme; + } + + return ( + + + + ); + }, + // todo add filtering options + }, + { + title: 'Owner', + dataIndex: 'enrolmentInfo', + key: 'owner', + render: enrolmentInfo => enrolmentInfo.owner, + // todo add filtering options + }, + { + title: 'Ownership', + dataIndex: 'enrolmentInfo', + key: 'ownership', + render: enrolmentInfo => enrolmentInfo.ownership, + // todo add filtering options + }, + { + title: 'Status', + dataIndex: 'enrolmentInfo', + key: 'status', + // eslint-disable-next-line react/display-name + render: enrolmentInfo => { + const status = enrolmentInfo.status.toLowerCase(); + let color = '#f9ca24'; + switch (status) { + case 'active': + color = '#badc58'; + break; + case 'created': + color = '#6ab04c'; + break; + case 'removed': + color = '#ff7979'; + break; + case 'inactive': + color = '#f9ca24'; + break; + case 'blocked': + color = '#636e72'; + break; + } + return {status}; + }, + // todo add filtering options + }, + { + title: 'Last Updated', + dataIndex: 'enrolmentInfo', + key: 'dateOfLastUpdate', + // eslint-disable-next-line react/display-name + render: data => { + const { dateOfLastUpdate } = data; + const timeAgoString = getTimeAgo(dateOfLastUpdate); + return ( + + {timeAgoString} + + ); + }, + // todo add filtering options + }, +]; + +const getTimeAgo = time => { + const timeAgo = new TimeAgo('en-US'); + return timeAgo.format(time); +}; + +class deviceTable extends React.Component { + constructor(props) { + super(props); + config = this.props.context; + TimeAgo.addLocale(en); + this.state = { + data: [], + pagination: {}, + loading: false, + selectedRows: [], + paramsObj: {}, + }; + } + + rowSelection = { + onChange: (selectedRowKeys, selectedRows) => { + this.setState({ + selectedRows: selectedRows, + }); + }, + }; + + componentDidMount() { + if (this.props.apiUrl) { + this.fetch(); + } + } + + // Rerender component when parameters change + componentDidUpdate(prevProps, prevState, snapshot) { + if (prevProps.apiUrl !== this.props.apiUrl) { + this.fetch(); + } + } + + // fetch data from api + fetch = (params = {}) => { + this.setState({ loading: true }); + // get current page + const currentPage = params.hasOwnProperty('page') ? params.page : 1; + + const extraParams = { + offset: 10 * (currentPage - 1), // calculate the offset + limit: 10, + }; + + const encodedExtraParams = Object.keys(extraParams) + .map(key => key + '=' + extraParams[key]) + .join('&'); + + // send request to the invokerss + axios + .get(this.props.apiUrl + encodedExtraParams) + .then(res => { + if (res.status === 200) { + const pagination = { ...this.state.pagination }; + if ( + res.data.data.devices.length && + res.data.data.devices[0].hasOwnProperty('deviceInfo') + ) { + columns.push({ + title: 'OS Version', + dataIndex: 'deviceInfo', + key: 'osVersion', + render: deviceInfo => deviceInfo.osVersion, + }); + } + this.setState({ + loading: false, + data: res.data.data, + pagination, + }); + } + }) + .catch(error => { + if (error.hasOwnProperty('response') && error.response.status === 401) { + // todo display a popop with error + message.error('You are not logged in'); + window.location.href = window.location.origin + '/entgra/login'; + } else { + notification.error({ + message: 'There was a problem', + duration: 0, + description: 'Error occurred while trying to load devices.', + }); + } + + this.setState({ loading: false }); + }); + }; + + handleTableChange = (pagination, filters, sorter) => { + const pager = { ...this.state.pagination }; + pager.current = pagination.current; + this.setState({ + pagination: pager, + }); + this.fetch({ + results: pagination.pageSize, + page: pagination.current, + sortField: sorter.field, + sortOrder: sorter.order, + ...filters, + }); + }; + + render() { + const { data, pagination, loading } = this.state; + return ( +
+
+ record.deviceIdentifier + + record.enrolmentInfo.owner + + record.enrolmentInfo.ownership + } + dataSource={data.devices} + pagination={{ + ...pagination, + size: 'small', + total: data.count, + showTotal: (total, range) => + `showing ${range[0]}-${range[1]} of ${total} devices`, + }} + loading={loading} + onChange={this.handleTableChange} + rowSelection={this.rowSelection} + /> + + ); + } +} + +export default withConfigContext(deviceTable); diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Groups/components/GroupsTable/components/GroupDevicesModal/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Groups/components/GroupsTable/components/GroupDevicesModal/index.js index c456b2e452..f844b79db2 100644 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Groups/components/GroupsTable/components/GroupDevicesModal/index.js +++ b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Groups/components/GroupsTable/components/GroupDevicesModal/index.js @@ -23,7 +23,7 @@ import TimeAgo from 'javascript-time-ago'; // Load locale-specific relative date/time formatting rules. import en from 'javascript-time-ago/locale/en'; import { withConfigContext } from '../../../../../../../../components/ConfigContext'; -import DevicesTable from '../../../../../Reports/components/DevicesTable'; +import DevicesTable from '../../../../../../components/DevicesTable'; let apiUrl; From 460ce4f64adfe74044648987382507f1daae1987 Mon Sep 17 00:00:00 2001 From: Saad Sahibjan Date: Mon, 30 Mar 2020 13:17:47 +0530 Subject: [PATCH 3/5] Fix device type DAO handler being persisted in a wrong way --- .../DeviceTypePluginExtensionServiceImpl.java | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypePluginExtensionServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypePluginExtensionServiceImpl.java index e32c9e2d57..d3a1330218 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypePluginExtensionServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypePluginExtensionServiceImpl.java @@ -19,7 +19,6 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager; import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypePluginExtensionException; import org.wso2.carbon.device.mgt.extensions.spi.DeviceTypePluginExtensionService; @@ -36,34 +35,29 @@ public class DeviceTypePluginExtensionServiceImpl implements DeviceTypePluginExt @Override public void addPluginDAOManager(String deviceType, DeviceTypePluginDAOManager pluginDAOManager) throws DeviceTypePluginExtensionException { - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); if (pluginDAOManager == null) { - String msg = "Cannot save DeviceTypePluginDAOManager against tenant id " + tenantId - + " and device type: " + deviceType + " since DeviceTypePluginDAOManager is null"; + String msg = "Cannot save DeviceTypePluginDAOManager of device type: " + deviceType + + " since DeviceTypePluginDAOManager is null"; log.error(msg); throw new DeviceTypePluginExtensionException(msg); } - if (!pluginDAOManagers.containsKey(tenantId + deviceType)) { + if (!pluginDAOManagers.containsKey(deviceType)) { if (log.isDebugEnabled()) { - log.debug("Saving DeviceTypePluginDAOManager against tenant id " + tenantId + - " and device type: " + deviceType); + log.debug("Saving DeviceTypePluginDAOManager of device type: " + deviceType); } - pluginDAOManagers.put(tenantId + deviceType, pluginDAOManager); + pluginDAOManagers.put(deviceType, pluginDAOManager); } } @Override public DeviceTypePluginDAOManager getPluginDAOManager(String deviceType) throws DeviceTypePluginExtensionException { - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - if (pluginDAOManagers.containsKey(tenantId + deviceType)) { + if (pluginDAOManagers.containsKey(deviceType)) { if (log.isDebugEnabled()) { - log.debug("Retrieving DeviceTypePluginDAOManager against tenant id " + tenantId + - " and device type: " + deviceType); + log.debug("Retrieving DeviceTypePluginDAOManager of device type: " + deviceType); } - return pluginDAOManagers.get(tenantId + deviceType); + return pluginDAOManagers.get(deviceType); } else { - String msg = "DeviceTypePluginDAOManager could not be found against tenant id " + tenantId + - " and device type: " + deviceType; + String msg = "DeviceTypePluginDAOManager of device type: " + deviceType + " cannot be found"; log.error(msg); throw new DeviceTypePluginExtensionException(msg); } From 5dc235d8d641b0af04eb21fb8a98d8794a3dc5b4 Mon Sep 17 00:00:00 2001 From: Charitha Goonetilleke Date: Mon, 30 Mar 2020 09:56:10 +0000 Subject: [PATCH 4/5] Performance improvements --- .../client/IntegrationClientServiceImpl.java | 3 +- .../publisher/config/APIResourceManager.java | 69 --------------- .../mgt/core/config/ConfigurationManager.java | 2 +- .../application/mgt/core/util/APIUtil.java | 10 +-- .../application/mgt/core/util/DAOUtil.java | 6 +- .../application/mgt/core/util/HelperUtil.java | 40 +++------ ...CertificateManagementAdminServiceImpl.java | 77 ++--------------- .../impl/CertificateCacheManagerImpl.java | 18 ++-- .../CertificateConfigurationManager.java | 2 +- .../mgt/core/scep/SCEPManagerImpl.java | 2 +- .../PullNotificationSubscriberImpl.java | 15 ++-- .../service/api/DeviceManagementService.java | 24 +++--- .../service/impl/DeviceAgentServiceImpl.java | 21 ++--- .../impl/DeviceManagementServiceImpl.java | 60 +++++++++---- .../impl/PolicyManagementServiceImpl.java | 12 ++- .../mgt/jaxrs/util/DeviceMgtAPIUtils.java | 7 +- .../service/impl/DeviceAgentServiceTest.java | 49 ++++++----- .../impl/DeviceManagementServiceImplTest.java | 12 ++- .../mgt/NotificationManagementService.java | 5 ++ .../operation/mgt/OperationManager.java | 1 - .../PullNotificationSubscriber.java | 5 +- .../core/dao/DeviceManagementDAOFactory.java | 2 +- .../details/mgt/DeviceInformationManager.java | 1 + .../impl/DeviceInformationManagerImpl.java | 1 + .../NotificationManagementServiceImpl.java | 36 ++++---- .../operation/mgt/OperationManagerImpl.java | 5 -- .../DeviceManagementProviderService.java | 7 +- .../DeviceManagementProviderServiceImpl.java | 15 ++-- ...otificationManagementServiceImplTests.java | 5 +- .../policy/mgt/core/PolicyManagerService.java | 17 +++- .../mgt/core/PolicyManagerServiceImpl.java | 37 ++++++-- .../PolicyEnforcementDelegatorImpl.java | 8 +- .../mgt/core/mgt/MonitoringManager.java | 11 ++- .../policy/mgt/core/mgt/PolicyManager.java | 3 + .../core/mgt/impl/MonitoringManagerImpl.java | 86 +++++++++++-------- .../mgt/core/mgt/impl/PolicyManagerImpl.java | 22 +++-- 36 files changed, 330 insertions(+), 366 deletions(-) delete mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManager.java diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java index 66c519733e..2dcefcce20 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java @@ -18,14 +18,13 @@ package org.wso2.carbon.apimgt.integration.client; -import feign.RequestInterceptor; import org.wso2.carbon.apimgt.integration.client.publisher.PublisherClient; import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService; import org.wso2.carbon.apimgt.integration.client.store.StoreClient; public class IntegrationClientServiceImpl implements IntegrationClientService { - private static IntegrationClientServiceImpl instance; + private static volatile IntegrationClientServiceImpl instance; private StoreClient storeClient; private PublisherClient publisherClient; private OAuthRequestInterceptor oAuthRequestInterceptor; diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManager.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManager.java deleted file mode 100644 index c1f88d83ab..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/APIResourceManager.java +++ /dev/null @@ -1,69 +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.apimgt.webapp.publisher.config; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import java.io.InputStream; -import java.util.List; -import java.util.Set; - -/** - * This class will add, update custom permissions defined in resources.xml in webapps. - */ -public class APIResourceManager { - - private static APIResourceManager resourceManager; - private List resourceList; - - private APIResourceManager(){}; - - public static APIResourceManager getInstance() { - if (resourceManager == null) { - synchronized (APIResourceManager.class) { - if (resourceManager == null) { - resourceManager = new APIResourceManager(); - } - } - } - return resourceManager; - } - - public void initializeResources(InputStream resourceStream) throws APIResourceManagementException { - try { - if(resourceStream != null){ - /* Un-marshaling Device Management configuration */ - JAXBContext cdmContext = JAXBContext.newInstance(APIResourceConfiguration.class); - Unmarshaller unmarshaller = cdmContext.createUnmarshaller(); - APIResourceConfiguration resourcesConfiguration = (APIResourceConfiguration) - unmarshaller.unmarshal(resourceStream); - if((resourcesConfiguration != null) && (resourcesConfiguration.getResources() != null)){ - this.resourceList = resourcesConfiguration.getResources(); - } - } - } catch (JAXBException e) { - throw new APIResourceManagementException("Error occurred while initializing Data Source config", e); - } - } - - public List getAPIResources(){ - return resourceList; - } -} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/ConfigurationManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/ConfigurationManager.java index 17ff4410f2..da8146cf2e 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/ConfigurationManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/config/ConfigurationManager.java @@ -38,7 +38,7 @@ public class ConfigurationManager { private static String configPath; - private static ConfigurationManager configurationManager; + private static volatile ConfigurationManager configurationManager; private ConfigurationManager() { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/APIUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/APIUtil.java index 5765ecebf5..0a7869fd72 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/APIUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/APIUtil.java @@ -58,11 +58,11 @@ public class APIUtil { private static Log log = LogFactory.getLog(APIUtil.class); - private static ApplicationManager applicationManager; - private static ApplicationStorageManager applicationStorageManager; - private static SubscriptionManager subscriptionManager; - private static ReviewManager reviewManager; - private static AppmDataHandler appmDataHandler; + private static volatile ApplicationManager applicationManager; + private static volatile ApplicationStorageManager applicationStorageManager; + private static volatile SubscriptionManager subscriptionManager; + private static volatile ReviewManager reviewManager; + private static volatile AppmDataHandler appmDataHandler; public static ApplicationManager getApplicationManager() { if (applicationManager == null) { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/DAOUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/DAOUtil.java index 5ca4370f97..929c8975c7 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/DAOUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/DAOUtil.java @@ -311,9 +311,9 @@ public class DAOUtil { } } - private static ApplicationManager applicationManager; - private static ApplicationStorageManager applicationStorageManager; - private static SubscriptionManager subscriptionManager; + private static volatile ApplicationManager applicationManager; + private static volatile ApplicationStorageManager applicationStorageManager; + private static volatile SubscriptionManager subscriptionManager; public static ApplicationManager getApplicationManager() { if (applicationManager == null) { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/HelperUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/HelperUtil.java index d748dc25ea..bcfd052326 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/HelperUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/HelperUtil.java @@ -37,23 +37,15 @@ public class HelperUtil { private static DeviceManagementProviderService deviceManagementProviderService; private static GroupManagementProviderService groupManagementProviderService; - public static String generateApplicationUuid() { - return UUID.randomUUID().toString(); - } - public static DeviceManagementProviderService getDeviceManagementProviderService() { if (deviceManagementProviderService == null) { - synchronized (HelperUtil.class) { - if (deviceManagementProviderService == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - deviceManagementProviderService = (DeviceManagementProviderService) ctx - .getOSGiService(DeviceManagementProviderService.class, null); - if (deviceManagementProviderService == null) { - String msg = "Device management provider service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + deviceManagementProviderService = (DeviceManagementProviderService) ctx + .getOSGiService(DeviceManagementProviderService.class, null); + if (deviceManagementProviderService == null) { + String msg = "Device management provider service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } } return deviceManagementProviderService; @@ -61,17 +53,13 @@ public class HelperUtil { public static GroupManagementProviderService getGroupManagementProviderService() { if (groupManagementProviderService == null) { - synchronized (HelperUtil.class) { - if (groupManagementProviderService == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - groupManagementProviderService = (GroupManagementProviderService) ctx - .getOSGiService(GroupManagementProviderService.class, null); - if (groupManagementProviderService == null) { - String msg = "Group management provider service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + groupManagementProviderService = (GroupManagementProviderService) ctx + .getOSGiService(GroupManagementProviderService.class, null); + if (groupManagementProviderService == null) { + String msg = "Group management provider service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); } } return groupManagementProviderService; diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java index 506fcac51e..d898e632ae 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java @@ -18,6 +18,14 @@ package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +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.MediaType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -31,7 +39,6 @@ import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.RequestValidationUtil import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; -import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; import org.wso2.carbon.certificate.mgt.core.scep.SCEPException; import org.wso2.carbon.certificate.mgt.core.scep.SCEPManager; import org.wso2.carbon.certificate.mgt.core.scep.TenantedDeviceWrapper; @@ -43,7 +50,6 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; -import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.security.cert.X509Certificate; import java.util.ArrayList; @@ -170,71 +176,6 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem } } -// @POST -// @Path("/verify/ios") -// public Response verifyIOSCertificate(@ApiParam(name = "certificate", value = "Mdm-Signature of the " + -// "certificate that needs to be verified", required = true) EnrollmentCertificate certificate) { -// try { -// CertificateManagementService certMgtService = CertificateMgtAPIUtils.getCertificateManagementService(); -// X509Certificate cert = certMgtService.extractCertificateFromSignature(certificate.getPem()); -// String challengeToken = certMgtService.extractChallengeToken(cert); -// -// if (challengeToken != null) { -// challengeToken = challengeToken.substring(challengeToken.indexOf("(") + 1).trim(); -// -// SCEPManager scepManager = CertificateMgtAPIUtils.getSCEPManagerService(); -// DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); -// deviceIdentifier.setId(challengeToken); -// deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS); -// TenantedDeviceWrapper tenantedDeviceWrapper = scepManager.getValidatedDevice(deviceIdentifier); -// -// if (tenantedDeviceWrapper != null) { -// return Response.status(Response.Status.OK).entity("valid").build(); -// } -// } -// } catch (SCEPException e) { -// String msg = "Error occurred while extracting information from certificate."; -// log.error(msg, e); -// return Response.serverError().entity( -// new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build(); -// } catch (KeystoreException e) { -// String msg = "Error occurred while converting PEM file to X509Certificate."; -// log.error(msg, e); -// return Response.serverError().entity( -// new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build(); -// } -// return Response.status(Response.Status.OK).entity("invalid").build(); -// } -// -// @POST -// @Path("/verify/android") -// public Response verifyAndroidCertificate(@ApiParam(name = "certificate", value = "Base64 encoded .pem file of the " + -// "certificate that needs to be verified", required = true) EnrollmentCertificate certificate) { -// CertificateResponse certificateResponse = null; -// try { -// CertificateManagementService certMgtService = CertificateMgtAPIUtils.getCertificateManagementService(); -// if (certificate.getSerial().toLowerCase().contains(PROXY_AUTH_MUTUAL_HEADER)) { -// certificateResponse = certMgtService.verifySubjectDN(certificate.getPem()); -// } else { -// X509Certificate clientCertificate = certMgtService.pemToX509Certificate(certificate.getPem()); -// if (clientCertificate != null) { -// certificateResponse = certMgtService.verifyPEMSignature(clientCertificate); -// } -// } -// -// if (certificateResponse != null && certificateResponse.getCommonName() != null && !certificateResponse -// .getCommonName().isEmpty()) { -// return Response.status(Response.Status.OK).entity("valid").build(); -// } -// } catch (KeystoreException e) { -// String msg = "Error occurred while converting PEM file to X509Certificate."; -// log.error(msg, e); -// return Response.serverError().entity( -// new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build(); -// } -// return Response.status(Response.Status.OK).entity("invalid").build(); -// } - @POST @Path("/verify/{type}") public Response verifyCertificate(@PathParam("type") String type, EnrollmentCertificate certificate) { @@ -323,7 +264,7 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build(); } catch (JWTClientException e) { - String msg = "Error occurred while converting PEM file to X509Certificate."; + String msg = "Error occurred while getting jwt token."; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build(); diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/cache/impl/CertificateCacheManagerImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/cache/impl/CertificateCacheManagerImpl.java index b76af59b3e..017b5820c4 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/cache/impl/CertificateCacheManagerImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/cache/impl/CertificateCacheManagerImpl.java @@ -38,7 +38,7 @@ public class CertificateCacheManagerImpl implements CertificateCacheManager { private static String SERIAL_PRE = "S_"; private static String COMMON_NAME_PRE = "C_"; - private static CertificateCacheManager certificateCacheManager; + private static volatile CertificateCacheManager certificateCacheManager; private CertificateCacheManagerImpl() { @@ -89,10 +89,10 @@ public class CertificateCacheManagerImpl implements CertificateCacheManager { initializeCertificateCache(); } if (manager != null) { - certificateCache = manager.getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); + certificateCache = manager.getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); } else { - certificateCache = Caching.getCacheManager(CertificateCacheManagerImpl.CERTIFICATE_CACHE_MANAGER). - getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); + certificateCache = Caching.getCacheManager(CertificateCacheManagerImpl.CERTIFICATE_CACHE_MANAGER) + .getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); } } return certificateCache; @@ -107,22 +107,22 @@ public class CertificateCacheManagerImpl implements CertificateCacheManager { isCertificateCacheInitialized = true; if (manager != null) { if (certificateCacheExpiry > 0) { - manager.createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE). + manager.createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration. Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setStoreByValue(true).build(); } else { - manager.getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); + manager.getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); } } else { if (certificateCacheExpiry > 0) { - Caching.getCacheManager(). - createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE). + Caching.getCacheManager() + .createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration. Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setStoreByValue(true).build(); } else { - Caching.getCacheManager().getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); + Caching.getCacheManager().getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); } } } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateConfigurationManager.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateConfigurationManager.java index f7ce3b3aae..cae78fe48a 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateConfigurationManager.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateConfigurationManager.java @@ -35,7 +35,7 @@ import java.io.File; public class CertificateConfigurationManager { private CertificateManagementConfig certificateManagementConfig; - private static CertificateConfigurationManager certificateConfigurationManager; + private static volatile CertificateConfigurationManager certificateConfigurationManager; private final String certMgtConfigXMLPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + CertificateManagementConstants.CERTIFICATE_CONFIG_XML_FILE; diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/scep/SCEPManagerImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/scep/SCEPManagerImpl.java index 13b1048891..2917176d54 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/scep/SCEPManagerImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/scep/SCEPManagerImpl.java @@ -46,7 +46,7 @@ public class SCEPManagerImpl implements SCEPManager { HashMap deviceHashMap = dms.getTenantedDevice(deviceIdentifier); Object[] keySet = deviceHashMap.keySet().toArray(); - if (keySet == null || keySet.length == 0) { + if (keySet.length == 0) { throw new SCEPException("Lookup device not found for the device identifier"); } diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/PullNotificationSubscriberImpl.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/PullNotificationSubscriberImpl.java index 532c89dea0..620757ace1 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/PullNotificationSubscriberImpl.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/src/main/java/org/wso2/carbon/device/mgt/extensions/pull/notification/PullNotificationSubscriberImpl.java @@ -59,7 +59,7 @@ public class PullNotificationSubscriberImpl implements PullNotificationSubscribe } @Override - public void execute(DeviceIdentifier deviceIdentifier, Operation operation) throws PullNotificationExecutionFailedException { + public void execute(Device device, Operation operation) throws PullNotificationExecutionFailedException { try { if (!Operation.Status.ERROR.equals(operation.getStatus()) && operation.getCode() != null && OperationCodes.POLICY_MONITOR.equals(operation.getCode())) { @@ -68,17 +68,17 @@ public class PullNotificationSubscriberImpl implements PullNotificationSubscribe } List features = getComplianceFeatures(operation.getPayLoad()); PullNotificationDataHolder.getInstance().getPolicyManagerService() - .checkCompliance(deviceIdentifier, features); + .checkCompliance(device, features); } else { PullNotificationDataHolder.getInstance().getDeviceManagementProviderService().updateOperation( - deviceIdentifier, operation); + device, operation); if (OperationCodes.INSTALL_APPLICATION.equals(operation.getCode()) && Operation.Status.COMPLETED == operation.getStatus()) { - updateAppSubStatus(deviceIdentifier, operation.getId(), operation.getCode()); + updateAppSubStatus(device, operation.getId(), operation.getCode()); } } - } catch (OperationManagementException | DeviceManagementException | ApplicationManagementException e) { + } catch (OperationManagementException | ApplicationManagementException e) { throw new PullNotificationExecutionFailedException(e); } catch (PolicyComplianceException e) { throw new PullNotificationExecutionFailedException("Invalid payload format compliant feature", e); @@ -109,10 +109,9 @@ public class PullNotificationSubscriberImpl implements PullNotificationSubscribe return complianceFeatures; } - private void updateAppSubStatus(DeviceIdentifier deviceIdentifier, int operationId, String status) - throws DeviceManagementException, ApplicationManagementException { + private void updateAppSubStatus(Device device, int operationId, String status) + throws ApplicationManagementException { ApplicationManager applicationManager = PullNotificationDataHolder.getInstance().getApplicationManager(); - Device device = PullNotificationDataHolder.getInstance().getDeviceManagementProviderService().getDevice(deviceIdentifier); applicationManager.updateSubsStatus(device.getId(), operationId, status); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index a7b96b501a..085e1fe914 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -843,7 +843,7 @@ public interface DeviceManagementService { @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) - @Path("/type/{device-type}/id/{device-id}/rename") + @Path("/type/{deviceType}/id/{deviceId}/rename") @ApiOperation( produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON, @@ -904,14 +904,14 @@ public interface DeviceManagementService { name = "device-type", value = "The device type, such as ios, android, or windows.", required = true) - @PathParam("device-type") + @PathParam("deviceType") @Size(max = 45) String deviceType, @ApiParam( name = "device-id", value = "The device identifier of the device.", required = true) - @PathParam("device-id") + @PathParam("deviceId") @Size(max = 45) String deviceId); @@ -919,7 +919,7 @@ public interface DeviceManagementService { //DELETE devices/type/virtual_firealarm/id/us06ww93auzp @DELETE @Produces(MediaType.APPLICATION_JSON) - @Path("/type/{device-type}/id/{device-id}") + @Path("/type/{deviceType}/id/{deviceId}") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "DELETE", @@ -974,14 +974,14 @@ public interface DeviceManagementService { name = "device-type", value = "The device type, such as ios, android, or windows.", required = true) - @PathParam("device-type") + @PathParam("deviceType") @Size(max = 45) String deviceType, @ApiParam( name = "device-id", value = "The device identifier of the device.", required = true) - @PathParam("device-id") + @PathParam("deviceId") @Size(max = 45) String deviceId); @@ -1923,7 +1923,7 @@ public interface DeviceManagementService { @GET @Produces(MediaType.APPLICATION_JSON) - @Path("/compliance/{compliance-status}") + @Path("/compliance/{complianceStatus}") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", @@ -1958,7 +1958,7 @@ public interface DeviceManagementService { value = "Compliance status for devices. If true, devices which are compliant with policies. " + "If false, devices which are not compliant", required = true) - @PathParam("compliance-status") + @PathParam("complianceStatus") boolean complianceStatus, @ApiParam( name = "policy", @@ -2030,7 +2030,7 @@ public interface DeviceManagementService { int id); @GET - @Path("/{device-type}/applications") + @Path("/{deviceType}/applications") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", @@ -2076,7 +2076,7 @@ public interface DeviceManagementService { name = "device-type", value = "Device type (platform) of the application", required = true) - @PathParam("device-type") + @PathParam("deviceType") String deviceType, @ApiParam( name = "offset", @@ -2092,7 +2092,7 @@ public interface DeviceManagementService { int limit); @GET - @Path("/application/{package-name}/versions") + @Path("/application/{packageName}/versions") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", @@ -2133,6 +2133,6 @@ public interface DeviceManagementService { name = "package-name", value = "The package name of the app.", required = true) - @PathParam("package-name") + @PathParam("packageName") String packageName); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java index bb5bbc6755..ca034edec3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceImpl.java @@ -29,11 +29,11 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException; 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; @@ -84,7 +84,8 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { String errorMessage = "The payload of the device enrollment is incorrect."; return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); } - Device existingDevice = dms.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + Device existingDevice = dms.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()), + false); if (existingDevice != null && existingDevice.getEnrolmentInfo() != null && existingDevice .getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) { String errorMessage = "An active enrolment exists"; @@ -136,7 +137,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { deviceIdentifier.setId(id); deviceIdentifier.setType(type); try { - device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier); + device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false); } catch (DeviceManagementException e) { String msg = "Error occurred while getting enrollment details of the device that carries the id '" + id + "'"; @@ -489,16 +490,16 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { log.error(msg); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } + Device device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false); if (!Operation.Status.ERROR.equals(operation.getStatus()) && operation.getCode() != null && POLICY_MONITOR.equals(operation.getCode())) { if (log.isDebugEnabled()) { log.info("Received compliance status from POLICY_MONITOR operation ID: " + operation.getId()); } List features = getComplianceFeatures(operation.getPayLoad()); - DeviceMgtAPIUtils.getPolicyManagementService().checkCompliance(deviceIdentifier, features); - + DeviceMgtAPIUtils.getPolicyManagementService().checkCompliance(device, features); } else { - DeviceMgtAPIUtils.getDeviceManagementService().updateOperation(deviceIdentifier, operation); + DeviceMgtAPIUtils.getDeviceManagementService().updateOperation(device, operation); } return Response.status(Response.Status.OK).build(); } catch (OperationManagementException e) { @@ -506,11 +507,11 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { log.error(errorMessage, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); } catch (DeviceManagementException e) { - String errorMessage = "Issue in retrieving deivce management service instance"; + String errorMessage = "Issue in retrieving device management service instance"; log.error(errorMessage, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); } catch (PolicyComplianceException e) { - String errorMessage = "Issue in retrieving deivce management service instance"; + String errorMessage = "Issue in retrieving policy management service instance"; log.error(errorMessage, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); } @@ -596,7 +597,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService { JsonArray jsonArray = jsonElement.getAsJsonArray(); Gson gson = new Gson(); ComplianceFeature complianceFeature; - List complianceFeatures = new ArrayList(jsonArray.size()); + List complianceFeatures = new ArrayList<>(jsonArray.size()); for (JsonElement element : jsonArray) { complianceFeature = gson.fromJson(element, ComplianceFeature.class); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 4de4d5a2ff..936192b8da 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -80,6 +80,7 @@ import org.wso2.carbon.device.mgt.common.search.SearchContext; 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; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; @@ -374,9 +375,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @DELETE @Override - @Path("/type/{device-type}/id/{device-id}") - public Response deleteDevice(@PathParam("device-type") String deviceType, - @PathParam("device-id") String deviceId) { + @Path("/type/{deviceType}/id/{deviceId}") + public Response deleteDevice(@PathParam("deviceType") String deviceType, + @PathParam("deviceId") String deviceId) { DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); try { @@ -399,9 +400,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @POST @Override - @Path("/type/{device-type}/id/{device-id}/rename") - public Response renameDevice(Device device, @PathParam("device-type") String deviceType, - @PathParam("device-id") String deviceId) { + @Path("/type/{deviceType}/id/{deviceId}/rename") + public Response renameDevice(Device device, @PathParam("deviceType") String deviceType, + @PathParam("deviceId") String deviceId) { DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); try { Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier @@ -810,9 +811,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { ApplicationManagementProviderService amc; try { RequestValidationUtil.validateDeviceIdentifier(type, id); - + Device device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id, false); amc = DeviceMgtAPIUtils.getAppManagementService(); - applications = amc.getApplicationListForDevice(new DeviceIdentifier(id, type)); + applications = amc.getApplicationListForDevice(device); return Response.status(Response.Status.OK).entity(applications).build(); } catch (ApplicationManagementException e) { String msg = "Error occurred while fetching the apps of the '" + type + "' device, which carries " + @@ -820,6 +821,12 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while getting '" + type + "' device, which carries " + + "the id '" + id + "'"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -868,9 +875,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @HeaderParam("If-Modified-Since") String ifModifiedSince) { try { RequestValidationUtil.validateDeviceIdentifier(type, id); - + Device device = DeviceMgtAPIUtils.getDeviceManagementService() + .getDevice(new DeviceIdentifier(id, type), false); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - Policy policy = policyManagementService.getAppliedPolicyToDevice(new DeviceIdentifier(id, type)); + Policy policy = policyManagementService.getAppliedPolicyToDevice(device); return Response.status(Response.Status.OK).entity(policy).build(); } catch (PolicyManagementException e) { @@ -879,6 +887,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (DeviceManagementException e) { + String msg = "Error occurred while retrieving '" + type + "' device, which carries the id '" + id + "'"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @@ -888,13 +901,23 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @PathParam("id") @Size(max = 45) String id) { RequestValidationUtil.validateDeviceIdentifier(type, id); + Device device; + try { + device = DeviceMgtAPIUtils.getDeviceManagementService() + .getDevice(new DeviceIdentifier(id, type), false); + } catch (DeviceManagementException e) { + String msg = "Error occurred while retrieving '" + type + "' device, which carries the id '" + id + "'"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); Policy policy; NonComplianceData complianceData; DeviceCompliance deviceCompliance = new DeviceCompliance(); try { - policy = policyManagementService.getAppliedPolicyToDevice(new DeviceIdentifier(id, type)); + policy = policyManagementService.getAppliedPolicyToDevice(device); } catch (PolicyManagementException e) { String msg = "Error occurred while retrieving the current policy associated with the '" + type + "' device, which carries the id '" + id + "'"; @@ -910,8 +933,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } else { try { policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); - complianceData = policyManagementService.getDeviceCompliance( - new DeviceIdentifier(id, type)); + complianceData = policyManagementService.getDeviceCompliance(device); deviceCompliance.setDeviceID(id); deviceCompliance.setComplianceData(complianceData); return Response.status(Response.Status.OK).entity(deviceCompliance).build(); @@ -1090,9 +1112,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @GET @Override - @Path("/compliance/{compliance-status}") + @Path("/compliance/{complianceStatus}") public Response getPolicyCompliance( - @PathParam("compliance-status") boolean complianceStatus, + @PathParam("complianceStatus") boolean complianceStatus, @QueryParam("policy") String policyId, @DefaultValue("false") @QueryParam("pending") boolean isPending, @@ -1152,9 +1174,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @GET @Override - @Path("/{device-type}/applications") + @Path("/{deviceType}/applications") public Response getApplications( - @PathParam("device-type") String deviceType, + @PathParam("deviceType") String deviceType, @DefaultValue("0") @QueryParam("offset") int offset, @DefaultValue("10") @@ -1189,10 +1211,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } @GET - @Path("/application/{package-name}/versions") + @Path("/application/{packageName}/versions") @Override public Response getAppVersions( - @PathParam("package-name") String packageName) { + @PathParam("packageName") String packageName) { try { List versions = DeviceMgtAPIUtils.getDeviceManagementService() .getAppVersions(packageName); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java index e196c5ddd4..415bda4f55 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -406,7 +406,17 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(deviceId); deviceIdentifier.setType(deviceType); - policy = policyManagementService.getAppliedPolicyToDevice(deviceIdentifier); + Device device; + try { + device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false); + } catch (DeviceManagementException e) { + String msg = "Error occurred while retrieving '" + deviceType + "' device, which carries the id '" + + deviceId + "'"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + policy = policyManagementService.getAppliedPolicyToDevice(device); if (policy == null) { return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage( diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java index 2b932f455b..f6796a6217 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java @@ -215,14 +215,11 @@ public class DeviceMgtAPIUtils { } public static boolean isValidDeviceIdentifier(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { - Device device = getDeviceManagementService().getDevice(deviceIdentifier); + Device device = getDeviceManagementService().getDevice(deviceIdentifier, false); if (device == null || device.getDeviceIdentifier() == null || device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null) { return false; - } else if (EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())) { - return false; - } - return true; + } else return !EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus()); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java index f183f2e10b..c1aa2d41bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceAgentServiceTest.java @@ -39,10 +39,10 @@ import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublish import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherServiceImpl; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; 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.PolicyComplianceException; @@ -62,7 +62,6 @@ import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.CarbonUtils; -import javax.cache.CacheManager; import javax.ws.rs.core.Response; import java.rmi.RemoteException; import java.util.ArrayList; @@ -88,8 +87,6 @@ public class DeviceAgentServiceTest { private DeviceAgentService deviceAgentService; private EventStreamAdminServiceStub eventStreamAdminServiceStub; private PrivilegedCarbonContext privilegedCarbonContext; - private CarbonContext carbonContext; - private CacheManager cacheManager; private DeviceAccessAuthorizationService deviceAccessAuthorizationService; private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE"; private static final String TEST_DEVICE_IDENTIFIER = "11222334455"; @@ -112,10 +109,8 @@ public class DeviceAgentServiceTest { this.deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class, Mockito.RETURNS_MOCKS); this.privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class, Mockito.RETURNS_MOCKS); - this.carbonContext = Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS); this.eventStreamAdminServiceStub = Mockito.mock(EventStreamAdminServiceStub.class, Mockito.RETURNS_MOCKS); demoDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - this.cacheManager = Mockito.mock(CacheManager.class, Mockito.RETURNS_MOCKS); } @Test(description = "Test device Enrollment when the device is null") @@ -154,9 +149,11 @@ public class DeviceAgentServiceTest { public void testEnrollExistingDevice() throws DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(demoDevice); + Mockito.when(this.deviceManagementProviderService + .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(demoDevice); Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(device); + Mockito.when(this.deviceManagementProviderService + .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(device); Response response = this.deviceAgentService.enrollDevice(device); Assert.assertNotNull(response, "Response should not be null"); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), @@ -173,7 +170,8 @@ public class DeviceAgentServiceTest { EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo(); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); demoDevice.setEnrolmentInfo(enrolmentInfo); - Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(demoDevice); + Mockito.when(this.deviceManagementProviderService + .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(demoDevice); Response response = this.deviceAgentService.enrollDevice(demoDevice); Assert.assertNotNull(response, "Response should not be null"); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), @@ -191,7 +189,8 @@ public class DeviceAgentServiceTest { EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); device.setEnrolmentInfo(enrolmentInfo); - Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(device); + Mockito.when(this.deviceManagementProviderService + .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(device); Mockito.when(this.deviceManagementProviderService.enrollDevice(Mockito.any())) .thenThrow(new DeviceManagementException()); Response response = this.deviceAgentService.enrollDevice(device); @@ -214,7 +213,7 @@ public class DeviceAgentServiceTest { } @Test(description = "Test dis-enrolling non existing device.") - public void testDisEnrollWithNonExistingDevice() throws DeviceManagementException { + public void testDisEnrollWithNonExistingDevice() { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); Response response = deviceAgentService.disEnrollDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); @@ -240,7 +239,8 @@ public class DeviceAgentServiceTest { public void testUpdateDeviceWithDeviceManagementException() throws DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenThrow(new + Mockito.when(this.deviceManagementProviderService + .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenThrow(new DeviceManagementException()); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); @@ -264,7 +264,8 @@ public class DeviceAgentServiceTest { public void testUpdateDeviceWithNonExistingDevice() throws DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(null); + Mockito.when(this.deviceManagementProviderService + .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(null); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Assert.assertNotNull(response, "Response should not be null"); @@ -281,7 +282,8 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService + .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenThrow(new DeviceAccessAuthorizationException()); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); @@ -300,7 +302,8 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService + .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(false); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); @@ -321,7 +324,8 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService + .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false); @@ -343,7 +347,8 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService + .getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())) @@ -365,7 +370,7 @@ public class DeviceAgentServiceTest { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); - Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); + Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice); Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) .thenReturn(true); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true)); @@ -944,7 +949,7 @@ public class DeviceAgentServiceTest { .RETURNS_MOCKS); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) .toReturn(policyManagementService); - Mockito.when(policyManagementService.checkCompliance(Mockito.any(), Mockito.any())).thenReturn(true); + Mockito.when(policyManagementService.checkCompliance(Mockito.any(Device.class), Mockito.any())).thenReturn(true); Operation operation = new Operation(); operation.setCode(MONITOR_OPERATION); @@ -973,7 +978,7 @@ public class DeviceAgentServiceTest { deviceTypes.add(TEST_DEVICE_TYPE); Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes); Mockito.doThrow(new OperationManagementException()).when(this.deviceManagementProviderService) - .updateOperation(Mockito.any(DeviceIdentifier.class), Mockito.any()); + .updateOperation(Mockito.any(Device.class), Mockito.any()); Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, operation); Assert.assertNotNull(response, "The response should not be null"); @@ -1013,7 +1018,7 @@ public class DeviceAgentServiceTest { .RETURNS_MOCKS); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) .toReturn(policyManagementService); - Mockito.when(policyManagementService.checkCompliance(Mockito.any(), Mockito.any())) + Mockito.when(policyManagementService.checkCompliance(Mockito.any(Device.class), Mockito.any())) .thenThrow(new PolicyComplianceException()); Operation operation = new Operation(); @@ -1088,8 +1093,6 @@ public class DeviceAgentServiceTest { public void testGetOperationsWithDeviceManagementException() throws DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); - List deviceTypes = new ArrayList<>(); - deviceTypes.add(TEST_DEVICE_TYPE); Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) .thenThrow(new DeviceManagementException()); Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE, diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java index 53a2b39d7b..d6adc35fc2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java @@ -621,6 +621,8 @@ public class DeviceManagementServiceImplTest { .mock(ApplicationManagementProviderService.class, Mockito.RETURNS_MOCKS); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAppManagementService")) .toReturn(applicationManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); Response response = this.deviceManagementService .getInstalledApplications(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), @@ -633,8 +635,10 @@ public class DeviceManagementServiceImplTest { .mock(ApplicationManagementProviderService.class, Mockito.RETURNS_MOCKS); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAppManagementService")) .toReturn(applicationManagementProviderService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); Mockito.when( - applicationManagementProviderService.getApplicationListForDevice(Mockito.any(DeviceIdentifier.class))) + applicationManagementProviderService.getApplicationListForDevice(Mockito.any(Device.class))) .thenThrow(new ApplicationManagementException()); Response response = this.deviceManagementService .getInstalledApplications(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5); @@ -671,6 +675,8 @@ public class DeviceManagementServiceImplTest { PolicyManagerService policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) .toReturn(policyManagerService); + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); Response response = this.deviceManagementService .getEffectivePolicyOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), @@ -682,7 +688,9 @@ public class DeviceManagementServiceImplTest { PolicyManagerService policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) .toReturn(policyManagerService); - Mockito.when(policyManagerService.getAppliedPolicyToDevice(Mockito.any(DeviceIdentifier.class))) + PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) + .toReturn(this.deviceManagementProviderService); + Mockito.when(policyManagerService.getAppliedPolicyToDevice(Mockito.any(Device.class))) .thenThrow(new PolicyManagementException()); Response response = this.deviceManagementService .getEffectivePolicyOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java index 2f4837a4a4..ab048c1db5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/NotificationManagementService.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.common.notification.mgt; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; @@ -38,9 +39,13 @@ public interface NotificationManagementService { * @throws NotificationManagementException * if something goes wrong while adding the Notification. */ + @Deprecated boolean addNotification(DeviceIdentifier deviceId, Notification notification) throws NotificationManagementException; + boolean addNotification(Device device, + Notification notification) throws NotificationManagementException; + /** * Method to update a notification in the database. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java index c46c56adf3..3b9a24385f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java @@ -75,7 +75,6 @@ public interface OperationManager { * @throws OperationManagementException If some unusual behaviour is observed while fetching the * operation list. */ - @Deprecated List getPendingOperations(DeviceIdentifier deviceId) throws OperationManagementException; List getPendingOperations(Device device) throws OperationManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/pull/notification/PullNotificationSubscriber.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/pull/notification/PullNotificationSubscriber.java index 8d59500ee0..d4086080b6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/pull/notification/PullNotificationSubscriber.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/pull/notification/PullNotificationSubscriber.java @@ -18,8 +18,7 @@ */ package org.wso2.carbon.device.mgt.common.pull.notification; - -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import java.util.Map; @@ -31,7 +30,7 @@ public interface PullNotificationSubscriber { void init(Map properties); - void execute(DeviceIdentifier deviceIdentifier, Operation operation) throws PullNotificationExecutionFailedException; + void execute(Device device, Operation operation) throws PullNotificationExecutionFailedException; void clean(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java index 78632c3e65..0e1e0695a9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java @@ -96,7 +96,7 @@ public class DeviceManagementDAOFactory { private static DataSource dataSource; private static String databaseEngine; private static final Log log = LogFactory.getLog(DeviceManagementDAOFactory.class); - private static ThreadLocal currentConnection = new ThreadLocal(); + private static ThreadLocal currentConnection = new ThreadLocal<>(); public static DeviceDAO getDeviceDAO() { if (databaseEngine != null) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java index 44e5278cfa..83c79a24dd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/DeviceInformationManager.java @@ -73,6 +73,7 @@ public interface DeviceInformationManager { * @param deviceLocation - Device location object. * @throws DeviceDetailsMgtException */ + @Deprecated void addDeviceLocation(DeviceLocation deviceLocation) throws DeviceDetailsMgtException; void addDeviceLocation(Device device, DeviceLocation deviceLocation) throws DeviceDetailsMgtException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 56d91b2d9f..50261f46a9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -291,6 +291,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } @Override + @Deprecated public void addDeviceLocation(DeviceLocation deviceLocation) throws DeviceDetailsMgtException { try { Device device = DeviceManagementDataHolder.getInstance(). diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java index 7623ef1dcc..41686a4646 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java @@ -54,19 +54,32 @@ public class NotificationManagementServiceImpl implements NotificationManagement } @Override + @Deprecated public boolean addNotification(DeviceIdentifier deviceId, Notification notification) throws NotificationManagementException { - if (log.isDebugEnabled()) { - log.debug("Adding a Notification : [" + notification.toString() + "]"); + Device device; + try { + device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider() + .getDevice(deviceId, false); + } catch (DeviceManagementException e) { + throw new NotificationManagementException("Error occurred while retrieving device data for " + + " adding notification", e); } - int notificationId; - int tenantId = NotificationDAOUtil.getTenantId(); - - Device device = this.getDevice(deviceId); if (device == null) { throw new EntityDoesNotExistException("No device is found with type '" + deviceId.getType() + "' and id '" + deviceId.getId() + "'"); } + return addNotification(device, notification); + } + + @Override + public boolean addNotification(Device device, + Notification notification) throws NotificationManagementException { + if (log.isDebugEnabled()) { + log.debug("Adding a Notification : [" + notification.toString() + "]"); + } + int notificationId; + int tenantId = NotificationDAOUtil.getTenantId(); try { NotificationManagementDAOFactory.beginTransaction(); @@ -84,17 +97,6 @@ public class NotificationManagementServiceImpl implements NotificationManagement return true; } - private Device getDevice(DeviceIdentifier deviceId) throws NotificationManagementException { - Device device; - try { - device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId, false); - } catch (DeviceManagementException e) { - throw new NotificationManagementException("Error occurred while retrieving device data for " + - " adding notification", e); - } - return device; - } - @Override public boolean updateNotification(Notification notification) throws NotificationManagementException { if (log.isDebugEnabled()) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index 5fff1c77da..cb7c7a84f3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -1147,7 +1147,6 @@ public class OperationManagerImpl implements OperationManager { try { DeviceManagementDAOFactory.beginTransaction(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - String user = this.getUser(); updateStatus = enrollmentDAO.setStatus(enrolmentId, status, tenantId); DeviceManagementDAOFactory.commitTransaction(); } catch (DeviceManagementDAOException e) { @@ -1174,10 +1173,6 @@ public class OperationManagerImpl implements OperationManager { return false; } - private boolean isSameUser(String user, String owner) { - return user.equalsIgnoreCase(owner); - } - private List getOperations(DeviceIdentifier deviceId, Operation.Status status, int enrolmentId) throws OperationManagementException { List operations = new ArrayList<>(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index cbeedfa98e..209ae86bba 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -197,6 +197,7 @@ public interface DeviceManagementProviderService { * @return Device returns null when device is not available. * @throws DeviceManagementException */ + @Deprecated Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException; /** @@ -656,7 +657,6 @@ public interface DeviceManagementProviderService { PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException; - @Deprecated List getPendingOperations( DeviceIdentifier deviceId) throws OperationManagementException; @@ -770,15 +770,14 @@ public interface DeviceManagementProviderService { /** * This retrieves the device pull notification payload and passes to device type pull notification subscriber. - * @throws PullNotificationExecutionFailedException */ - void notifyPullNotificationSubscriber(DeviceIdentifier deviceIdentifier, Operation operation) + void notifyPullNotificationSubscriber(Device device, Operation operation) throws PullNotificationExecutionFailedException; List getDeviceEnrolledTenants() throws DeviceManagementException; List findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, - int geohashLength) throws DeviceManagementException; + int geohashLength) throws DeviceManagementException; int getDeviceCountOfTypeByStatus(String deviceType, String deviceStatus) throws DeviceManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index eeb78e14f0..ba5e26af51 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -1193,7 +1193,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv log.debug("No device is found upon the type '" + deviceIdentifier.getType() + "' and id '" + deviceIdentifier.getId() + "'"); } - return null; + return new HashMap<>(); } } catch (DeviceManagementDAOException e) { String msg = "Error occurred while obtaining the device for id '" + deviceIdentifier.getId() + "'"; @@ -1214,6 +1214,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override + @Deprecated public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { return this.getDevice(deviceId, true); } @@ -3043,15 +3044,15 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } @Override - public void notifyPullNotificationSubscriber(DeviceIdentifier deviceIdentifier, Operation operation) + public void notifyPullNotificationSubscriber(Device device, Operation operation) throws PullNotificationExecutionFailedException { if (log.isDebugEnabled()) { log.debug("Notify pull notification subscriber"); } DeviceManagementService dms = - pluginRepository.getDeviceManagementService(deviceIdentifier.getType(), this.getTenantId()); + pluginRepository.getDeviceManagementService(device.getType(), this.getTenantId()); if (dms == null) { - String message = "Device type '" + deviceIdentifier.getType() + "' does not have an associated " + + String message = "Device type '" + device.getType() + "' does not have an associated " + "device management plugin registered within the framework"; log.error(message); throw new PullNotificationExecutionFailedException(message); @@ -3059,11 +3060,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv PullNotificationSubscriber pullNotificationSubscriber = dms.getPullNotificationSubscriber(); if (pullNotificationSubscriber == null) { String message = "Pull Notification Subscriber is not configured " + - "for device type" + deviceIdentifier.getType(); + "for device type" + device.getType(); log.error(message); throw new PullNotificationExecutionFailedException(message); } - pullNotificationSubscriber.execute(deviceIdentifier, operation); + pullNotificationSubscriber.execute(device, operation); } /** @@ -3427,7 +3428,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv deviceLocation.setDistance(Double.parseDouble(distance)); deviceLocation.setSpeed(Float.parseFloat(speed)); deviceLocation.setBearing(Float.parseFloat(bearing)); - deviceInformationManager.addDeviceLocation(deviceLocation); + deviceInformationManager.addDeviceLocation(device, deviceLocation); } catch (Exception e) { //We are not failing the execution since this is not critical for the functionality. But logging as // a warning for reference. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImplTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImplTests.java index f440f3a738..bff759be00 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImplTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImplTests.java @@ -125,8 +125,7 @@ public class NotificationManagementServiceImplTests { Notification notification = TestDataHolder.getNotification(1, Notification.Status.NEW.toString(), testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + 123, NOTIFICATION_OPERATION_ID, DEVICE_TYPE); - notificationManagementService.addNotification(new DeviceIdentifier(DEVICE_ID_PREFIX + 123, - DEVICE_TYPE), notification); + notificationManagementService.addNotification(testDeviceIdentifier, notification); } @Test(expectedExceptions = NotificationManagementException.class, description = "This tests the method getDevice which" + @@ -136,7 +135,7 @@ public class NotificationManagementServiceImplTests { Notification notification = TestDataHolder.getNotification(1, Notification.Status.NEW.toString(), testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + 123, NOTIFICATION_OPERATION_ID, DEVICE_TYPE); - notificationManagementService.addNotification(null, notification); + notificationManagementService.addNotification((DeviceIdentifier) null, notification); } @Test(dependsOnMethods = "addNotification", description = "This tests the updateNotification Method" + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerService.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerService.java index 3e562c1e80..98acf75781 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerService.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerService.java @@ -19,6 +19,7 @@ package org.wso2.carbon.policy.mgt.core; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.PaginationRequest; @@ -72,16 +73,28 @@ public interface PolicyManagerService { int getPolicyCount() throws PolicyManagementException; - Policy getAppliedPolicyToDevice( - DeviceIdentifier deviceIdentifier) throws PolicyManagementException; + @Deprecated + Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; + Policy getAppliedPolicyToDevice(Device device) throws PolicyManagementException; + + @Deprecated List checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object deviceResponse) throws PolicyComplianceException; + List checkPolicyCompliance(Device device, Object + deviceResponse) throws PolicyComplianceException; + + @Deprecated boolean checkCompliance(DeviceIdentifier deviceIdentifier, Object response) throws PolicyComplianceException; + boolean checkCompliance(Device device, Object response) throws PolicyComplianceException; + + @Deprecated NonComplianceData getDeviceCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; + NonComplianceData getDeviceCompliance(Device device) throws PolicyComplianceException; + boolean isCompliant(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; PaginationResult getPolicyCompliance( diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java index 7e25bb213d..f7ca96c02e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java @@ -37,6 +37,7 @@ package org.wso2.carbon.policy.mgt.core; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.PaginationRequest; @@ -216,36 +217,56 @@ public class PolicyManagerServiceImpl implements PolicyManagerService { } @Override - public Policy getAppliedPolicyToDevice( - DeviceIdentifier deviceIdentifier) throws PolicyManagementException { + @Deprecated + public Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { return policyManager.getAppliedPolicyToDevice(deviceIdentifier); } @Override + public Policy getAppliedPolicyToDevice(Device device) throws PolicyManagementException { + return policyManager.getAppliedPolicyToDevice(device); + } + + @Override + @Deprecated public List checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object deviceResponse) throws PolicyComplianceException { return monitoringManager.checkPolicyCompliance(deviceIdentifier, deviceResponse); } @Override + public List checkPolicyCompliance(Device device, Object + deviceResponse) throws PolicyComplianceException { + return monitoringManager.checkPolicyCompliance(device, deviceResponse); + } + + @Override + @Deprecated public boolean checkCompliance(DeviceIdentifier deviceIdentifier, Object response) throws PolicyComplianceException { - List complianceFeatures = monitoringManager.checkPolicyCompliance(deviceIdentifier, response); - if(complianceFeatures == null || complianceFeatures.isEmpty()) { - return true; - } else { - return false; - } + return complianceFeatures == null || complianceFeatures.isEmpty(); + } + @Override + public boolean checkCompliance(Device device, Object response) throws PolicyComplianceException { + List complianceFeatures = + monitoringManager.checkPolicyCompliance(device, response); + return complianceFeatures == null || complianceFeatures.isEmpty(); } @Override + @Deprecated public NonComplianceData getDeviceCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { return monitoringManager.getDevicePolicyCompliance(deviceIdentifier); } + @Override + public NonComplianceData getDeviceCompliance(Device device) throws PolicyComplianceException { + return monitoringManager.getDevicePolicyCompliance(device); + } + @Override public boolean isCompliant(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { return monitoringManager.isCompliant(deviceIdentifier); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java index 3981c4c4d5..9bf9c6023a 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java @@ -85,7 +85,7 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato identifier.setId(device.getDeviceIdentifier()); identifier.setType(device.getType()); - Policy devicePolicy = this.getAppliedPolicyToDevice(identifier); + Policy devicePolicy = this.getAppliedPolicyToDevice(device); Policy policy = this.getEffectivePolicy(identifier); List deviceIdentifiers = new ArrayList<>(); deviceIdentifiers.add(identifier); @@ -193,14 +193,14 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato /** * Provides the applied policy for give device * - * @param identifier Device Identifier + * @param device Device * @return Applied Policy * @throws PolicyDelegationException exception throws when retrieving applied policy for given device */ - public Policy getAppliedPolicyToDevice(DeviceIdentifier identifier) throws PolicyDelegationException { + public Policy getAppliedPolicyToDevice(Device device) throws PolicyDelegationException { try { PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); - return policyManagerService.getAppliedPolicyToDevice(identifier); + return policyManagerService.getAppliedPolicyToDevice(device); } catch (PolicyManagementException e) { String msg = "Error occurred while retrieving the applied policy for devices."; log.error(msg, e); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/MonitoringManager.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/MonitoringManager.java index b46e2612ca..b058ff5fcb 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/MonitoringManager.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/MonitoringManager.java @@ -16,7 +16,6 @@ * under the License. */ - package org.wso2.carbon.policy.mgt.core.mgt; import org.wso2.carbon.device.mgt.common.Device; @@ -31,21 +30,27 @@ import java.util.List; public interface MonitoringManager { + @Deprecated List checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object deviceResponse) throws PolicyComplianceException; + List checkPolicyCompliance(Device device, Object deviceResponse) + throws PolicyComplianceException; boolean isCompliant(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; + @Deprecated NonComplianceData getDevicePolicyCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; + NonComplianceData getDevicePolicyCompliance(Device device) throws PolicyComplianceException; + void addMonitoringOperation(List devices) throws PolicyComplianceException; List getDeviceTypes() throws PolicyComplianceException; PaginationResult getPolicyCompliance( - PaginationRequest paginationRequest, String policyId, boolean complianceStatus, boolean isPending, String fromDate, String toDate) - throws PolicyComplianceException; + PaginationRequest paginationRequest, String policyId, boolean complianceStatus, boolean isPending, + String fromDate, String toDate) throws PolicyComplianceException; List getNoneComplianceFeatures(int complianceStatusId) throws PolicyComplianceException; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java index 187bbaaae2..886e0a5715 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java @@ -80,8 +80,11 @@ public interface PolicyManager { int getPolicyCount() throws PolicyManagementException; + @Deprecated Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; + Policy getAppliedPolicyToDevice(Device device) throws PolicyManagementException; + HashMap getAppliedPolicyIdsDeviceIds() throws PolicyManagementException; List getPolicies(String type) throws PolicyManagementException; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index 756fd68e07..a2d4039826 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -28,20 +28,23 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; 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.Policy; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; +import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceData; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; -import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; -import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; -import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; -import org.wso2.carbon.policy.mgt.common.monitor.*; -import org.wso2.carbon.policy.mgt.core.dao.*; +import org.wso2.carbon.policy.mgt.common.monitor.ComplianceDecisionPoint; +import org.wso2.carbon.policy.mgt.common.monitor.PolicyDeviceWrapper; +import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAO; +import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAOException; +import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO; +import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; +import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException; import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; @@ -58,7 +61,6 @@ public class MonitoringManagerImpl implements MonitoringManager { private PolicyDAO policyDAO; private MonitoringDAO monitoringDAO; private ComplianceDecisionPoint complianceDecisionPoint; - private PolicyConfiguration policyConfiguration; private static final Log log = LogFactory.getLog(MonitoringManagerImpl.class); private static final String OPERATION_MONITOR = "MONITOR"; @@ -68,34 +70,44 @@ public class MonitoringManagerImpl implements MonitoringManager { this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO(); this.monitoringDAO = PolicyManagementDAOFactory.getMonitoringDAO(); this.complianceDecisionPoint = new ComplianceDecisionPointImpl(); - this.policyConfiguration = - DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getPolicyConfiguration(); } @Override - public List checkPolicyCompliance( - DeviceIdentifier deviceIdentifier, - Object deviceResponse) throws PolicyComplianceException { + @Deprecated + public List checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object deviceResponse) + throws PolicyComplianceException { + DeviceManagementProviderService service = + PolicyManagementDataHolder.getInstance().getDeviceManagementService(); + Device device; + try { + device = service.getDevice(deviceIdentifier, false); + } catch (DeviceManagementException e) { + throw new PolicyComplianceException("Unable tor retrieve device data from DB for " + + deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); + } + return checkPolicyCompliance(device, deviceResponse); + } + @Override + public List checkPolicyCompliance(Device device, Object deviceResponse) + throws PolicyComplianceException { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()); List complianceFeatures = new ArrayList<>(); try { - DeviceManagementProviderService service = - PolicyManagementDataHolder.getInstance().getDeviceManagementService(); PolicyManager manager = PolicyManagementDataHolder.getInstance().getPolicyManager(); - Device device = service.getDevice(deviceIdentifier, false); - Policy policy = manager.getAppliedPolicyToDevice(deviceIdentifier); + Policy policy = manager.getAppliedPolicyToDevice(device); if (policy != null) { PolicyMonitoringManager monitoringService = PolicyManagementDataHolder.getInstance(). - getDeviceManagementService().getPolicyMonitoringManager(deviceIdentifier.getType()); + getDeviceManagementService().getPolicyMonitoringManager(device.getType()); NonComplianceData complianceData; // This was retrieved from database because compliance id must be present for other dao operations to // run. try { PolicyManagementDAOFactory.openConnection(); - NonComplianceData cmd = monitoringDAO.getCompliance(device.getId(), device.getEnrolmentInfo().getId()); - complianceData = monitoringService.checkPolicyCompliance(deviceIdentifier, - policy, deviceResponse); + NonComplianceData cmd = monitoringDAO.getCompliance(device.getId(), + device.getEnrolmentInfo().getId()); + complianceData = monitoringService.checkPolicyCompliance(deviceIdentifier, policy, deviceResponse); if (cmd != null) { complianceData.setId(cmd.getId()); complianceData.setPolicy(policy); @@ -109,7 +121,7 @@ public class MonitoringManagerImpl implements MonitoringManager { } catch (MonitoringDAOException e) { throw new PolicyComplianceException( "Unable to add the none compliance features to database for device " + - deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); + device.getDeviceIdentifier() + " - " + device.getType(), e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -133,7 +145,7 @@ public class MonitoringManagerImpl implements MonitoringManager { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyComplianceException( "Unable to add the none compliance features to database for device " + - deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); + device.getDeviceIdentifier() + " - " + device.getType(), e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -167,9 +179,6 @@ public class MonitoringManagerImpl implements MonitoringManager { log.debug("There is no policy applied to this device, hence compliance monitoring was not called."); } } - } catch (DeviceManagementException e) { - throw new PolicyComplianceException("Unable tor retrieve device data from DB for " + - deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); } catch (PolicyManagerDAOException | PolicyManagementException e) { throw new PolicyComplianceException("Unable tor retrieve policy data from DB for device " + deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); @@ -208,26 +217,33 @@ public class MonitoringManagerImpl implements MonitoringManager { } @Override + @Deprecated public NonComplianceData getDevicePolicyCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { + DeviceManagementProviderService service = + PolicyManagementDataHolder.getInstance().getDeviceManagementService(); + Device device; + try { + device = service.getDevice(deviceIdentifier, false); + } catch (DeviceManagementException e) { + throw new PolicyComplianceException("Unable to retrieve device data for " + deviceIdentifier.getId() + + " - " + deviceIdentifier.getType(), e); + } + return getDevicePolicyCompliance(device); + } + + @Override + public NonComplianceData getDevicePolicyCompliance(Device device) throws PolicyComplianceException { NonComplianceData complianceData; try { PolicyManagementDAOFactory.openConnection(); - DeviceManagementProviderService service = - PolicyManagementDataHolder.getInstance().getDeviceManagementService(); - Device device = service.getDevice(deviceIdentifier, false); complianceData = monitoringDAO.getCompliance(device.getId(), device.getEnrolmentInfo().getId()); List complianceFeatures = monitoringDAO.getNoneComplianceFeatures(complianceData.getId()); complianceData.setComplianceFeatures(complianceFeatures); - - } catch (DeviceManagementException e) { - throw new PolicyComplianceException("Unable to retrieve device data for " + deviceIdentifier.getId() + - " - " + deviceIdentifier.getType(), e); - } catch (MonitoringDAOException e) { - throw new PolicyComplianceException("Unable to retrieve compliance data for " + deviceIdentifier.getId() + - " - " + deviceIdentifier.getType(), e); + throw new PolicyComplianceException("Unable to retrieve compliance data for " + device.getType() + + " device " + device.getDeviceIdentifier(), e); } catch (SQLException e) { throw new PolicyComplianceException("Error occurred while opening a connection to the data source", e); } finally { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index cb25814f57..afa35e106d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -31,7 +31,7 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. -*/ + */ package org.wso2.carbon.policy.mgt.core.mgt.impl; @@ -145,7 +145,7 @@ public class PolicyManagerImpl implements PolicyManager { if (policy.getCorrectiveActions() != null && !policy.getCorrectiveActions().isEmpty()) { if (log.isDebugEnabled()) { log.debug("Adding corrective actions for policy " + policy.getPolicyName() + - " having policy id " + policy.getId()); + " having policy id " + policy.getId()); } policyDAO.addCorrectiveActionsOfPolicy(policy.getCorrectiveActions(), policy.getId()); } @@ -308,7 +308,7 @@ public class PolicyManagerImpl implements PolicyManager { if (log.isDebugEnabled()) { log.debug("Updating corrective actions for policy " + policy.getPolicyName() + - " having policy id " + policy.getId()); + " having policy id " + policy.getId()); } if (!correctiveActionsToUpdate.isEmpty()) { @@ -348,7 +348,7 @@ public class PolicyManagerImpl implements PolicyManager { boolean bool; try { // List existingPolicies = this.getPolicies(); - List existingPolicies; + List existingPolicies; if (policyConfiguration.getCacheEnable()) { existingPolicies = PolicyCacheManagerImpl.getInstance().getAllPolicies(); } else { @@ -655,7 +655,7 @@ public class PolicyManagerImpl implements PolicyManager { if (log.isDebugEnabled()) { log.debug("Retrieving corrective actions of policy " + policy.getPolicyName() + - " having policy id " + policy.getId()); + " having policy id " + policy.getId()); } policy.setCorrectiveActions(policyDAO.getCorrectiveActionsOfPolicy(policyId)); @@ -986,7 +986,7 @@ public class PolicyManagerImpl implements PolicyManager { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyManagementException("Error occurred while applying the changes to policy operations.", e); } finally { - if(transactionDone) { + if (transactionDone) { PolicyManagementDAOFactory.closeConnection(); } } @@ -1113,8 +1113,8 @@ public class PolicyManagerImpl implements PolicyManager { } @Override + @Deprecated public Policy getAppliedPolicyToDevice(DeviceIdentifier deviceId) throws PolicyManagementException { - Policy policy; DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device; try { @@ -1129,6 +1129,12 @@ public class PolicyManagerImpl implements PolicyManager { } catch (DeviceManagementException e) { throw new PolicyManagementException("Error occurred while getting device id.", e); } + return getAppliedPolicyToDevice(device); + } + + @Override + public Policy getAppliedPolicyToDevice(Device device) throws PolicyManagementException { + Policy policy; try { //int policyId = policyDAO.getAppliedPolicyId(device.getId()); PolicyManagementDAOFactory.openConnection(); @@ -1262,7 +1268,7 @@ public class PolicyManagerImpl implements PolicyManager { policy.setDeviceGroups(deviceGroupWrappers); if (log.isDebugEnabled()) { log.debug("Retrieving corrective actions for policy " + policy.getPolicyName() + - " having policy id " + policy.getId()); + " having policy id " + policy.getId()); } policy.setCorrectiveActions(policyDAO.getCorrectiveActionsOfPolicy(policy.getId())); } From 514d38d0b58b913feb4a28c729e7f698c366995e Mon Sep 17 00:00:00 2001 From: Kaveesha Mihirangi Date: Mon, 30 Mar 2020 18:33:51 +0000 Subject: [PATCH 5/5] Add UIs for Restriction and Passcode Policies --- .../components/ConfigureProfile/index.js | 90 +++++++++++++++---- .../components/ConfigureProfile/index.js | 51 +++++++++-- .../component/PolicyBulkActionBar/index.js | 18 ++-- .../component/PolicyInfo/index.js | 88 ++++++++++++++---- .../template/config/SubPanelValuesList.java | 18 ++++ 5 files changed, 220 insertions(+), 45 deletions(-) diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/AddPolicy/components/ConfigureProfile/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/AddPolicy/components/ConfigureProfile/index.js index 9e6fedb7e9..b8af15f553 100644 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/AddPolicy/components/ConfigureProfile/index.js +++ b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/AddPolicy/components/ConfigureProfile/index.js @@ -46,6 +46,7 @@ const { Option } = Select; const { TextArea } = Input; const subPanelpayloadAttributes = {}; +let formContainers = {}; class ConfigureProfile extends React.Component { constructor(props) { @@ -303,7 +304,7 @@ class ConfigureProfile extends React.Component { onHandleContinue = (e, formname) => { const allFields = this.props.form.getFieldsValue(); let activeFields = []; - // get currently active field list + let subContentsList = {}; for (let i = 0; i < this.state.activePanelKeys.length; i++) { Object.keys(allFields).map(key => { if (key.includes(`${this.state.activePanelKeys[i]}-`)) { @@ -312,14 +313,16 @@ class ConfigureProfile extends React.Component { `${this.state.activePanelKeys[i]}`, ) ) { - Object.keys( + Object.entries( subPanelpayloadAttributes[this.state.activePanelKeys[i]], - ).map(subPanel => { - if (`${this.state.activePanelKeys[i]}-${subPanel}` === true) { - if (key.includes(`-${subPanel}-`)) { - activeFields.push(key); - } - } else if (!key.includes(`-${subPanel}-`)) { + ).map(([subPanel, subContent]) => { + subContentsList[subContent] = {}; + if ( + allFields[`${this.state.activePanelKeys[i]}-${subPanel}`] === + true + ) { + activeFields.push(key); + } else if (!key.includes(`-${subPanel}`)) { activeFields.push(key); } }); @@ -337,17 +340,67 @@ class ConfigureProfile extends React.Component { let content = {}; Object.entries(values).map(([key, value]) => { if (key.includes(`${this.state.activePanelKeys[i]}-`)) { - content[ - key.replace(`${this.state.activePanelKeys[i]}-`, '') - ] = value; + if ( + subPanelpayloadAttributes.hasOwnProperty( + `${this.state.activePanelKeys[i]}`, + ) + ) { + Object.entries( + subPanelpayloadAttributes[this.state.activePanelKeys[i]], + ).map(([subPanel, contentKey]) => { + if (key.includes(`-${subPanel}-`)) { + subContentsList[contentKey][ + key.replace( + `${this.state.activePanelKeys[i]}-${subPanel}-`, + '', + ) + ] = value; + content = { ...content, ...subContentsList }; + } else { + content[ + key.replace(`${this.state.activePanelKeys[i]}-`, '') + ] = value; + } + }); + } else if (this.state.activePanelKeys[i] in formContainers) { + formContainers[this.state.activePanelKeys[i]].forEach( + subFeature => { + if ( + key.includes( + `${this.state.activePanelKeys[i]}-${subFeature}-`, + ) + ) { + let subFormContent = {}; + subFormContent[ + key.replace( + `${this.state.activePanelKeys[i]}-${subFeature}-`, + '', + ) + ] = value; + let feature = { + featureCode: subFeature, + deviceType: 'android', + content: subFormContent, + }; + profileFeaturesList.push(feature); + } + }, + ); + } else { + content[ + key.replace(`${this.state.activePanelKeys[i]}-`, '') + ] = value; + } } }); - let feature = { - featureCode: this.state.activePanelKeys[i], - deviceType: 'android', - content: content, - }; - profileFeaturesList.push(feature); + if (!(this.state.activePanelKeys[i] in formContainers)) { + let feature = { + featureCode: this.state.activePanelKeys[i], + deviceType: 'android', + content: content, + }; + profileFeaturesList.push(feature); + } } this.props.getPolicyPayloadData(formname, profileFeaturesList); this.props.getNextStep(); @@ -751,6 +804,7 @@ class ConfigureProfile extends React.Component { {element.name}} key={i}> {Object.values(element.panels).map((panel, j) => { panel = panel.panel; + let subForms = []; return (
{Object.values(panel.subFormLists).map( (form, i) => { + subForms.push(form.id); + formContainers[`${panel.panelId}`] = subForms; return (
diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/EditPolicy/components/ConfigureProfile/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/EditPolicy/components/ConfigureProfile/index.js index 7766b8ac23..bd2624e83d 100644 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/EditPolicy/components/ConfigureProfile/index.js +++ b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/EditPolicy/components/ConfigureProfile/index.js @@ -46,6 +46,7 @@ const { Option } = Select; const { TextArea } = Input; const subPanelpayloadAttributes = {}; +let subFormContainer = {}; class ConfigureProfile extends React.Component { constructor(props) { @@ -65,22 +66,57 @@ class ConfigureProfile extends React.Component { setProfileInfo = e => { let activePolicies = []; let activePolicyFields = {}; + let activeSubPanels = []; const allFields = this.props.form.getFieldsValue(); this.props.policyFeatureList.map(element => { activePolicies.push(element.featureCode); let featureData = JSON.parse(element.content); Object.keys(featureData).map(key => { - let regex = new RegExp(`${element.featureCode}.+${key}`, 'g'); - Object.keys(allFields).map(fieldName => { - if (fieldName.match(regex) != null) { - activePolicyFields[fieldName] = featureData[key]; - } - }); + if (element.featureCode in subPanelpayloadAttributes) { + Object.entries(subPanelpayloadAttributes[element.featureCode]).map( + ([panelKey, payloadAttr]) => { + if (key === payloadAttr) { + activeSubPanels.push(`${element.featureCode}-${panelKey}`); + } + }, + ); + + let regex = new RegExp(`${element.featureCode}.+${key}`, 'g'); + Object.keys(allFields).map(fieldName => { + if (fieldName.match(regex) != null) { + activePolicyFields[fieldName] = featureData[key]; + } + }); + } else if (element.featureCode in subFormContainer) { + let regex = new RegExp(`.+${element.featureCode}-${key}`, 'g'); + Object.keys(allFields).map(fieldName => { + if (fieldName.match(regex) != null) { + activePolicyFields[fieldName] = featureData[key]; + if ( + !activePolicies.includes( + fieldName.replace(`-${element.featureCode}-${key}`, ''), + ) + ) { + activePolicies.push( + fieldName.replace(`-${element.featureCode}-${key}`, ''), + ); + } + } + }); + } else { + let regex = new RegExp(`${element.featureCode}.+${key}`, 'g'); + Object.keys(allFields).map(fieldName => { + if (fieldName.match(regex) != null) { + activePolicyFields[fieldName] = featureData[key]; + } + }); + } }); }); this.props.form.setFieldsValue(activePolicyFields); this.setState({ activePanelKeys: activePolicies, + activeSubPanelKeys: activeSubPanels, }); }; @@ -795,6 +831,7 @@ class ConfigureProfile extends React.Component {
@@ -829,6 +866,8 @@ class ConfigureProfile extends React.Component {
{Object.values(panel.subFormLists).map( (form, i) => { + subFormContainer[`${form.id}`] = + panel.panelId; return ( diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/PoliciesTable/component/PolicyBulkActionBar/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/PoliciesTable/component/PolicyBulkActionBar/index.js index 2964380805..c2751c20a0 100644 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/PoliciesTable/component/PolicyBulkActionBar/index.js +++ b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/PoliciesTable/component/PolicyBulkActionBar/index.js @@ -65,7 +65,7 @@ class BulkActionBar extends React.Component { return (
-
+
+ > + APPLY CHANGES TO DEVICES +
@@ -110,7 +112,9 @@ class BulkActionBar extends React.Component { size={'default'} onClick={this.onCheckPolicyStatus} style={{ margin: '2px' }} - /> + > + Remove + @@ -135,7 +139,9 @@ class BulkActionBar extends React.Component { style={{ margin: '2px', }} - /> + > + Publish + @@ -158,7 +164,9 @@ class BulkActionBar extends React.Component { onClick={this.onCheckPolicyStatus} size={'default'} style={{ margin: '2px' }} - /> + > + Unpublish +
diff --git a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/PolicyProfile/component/PolicyInfo/index.js b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/PolicyProfile/component/PolicyInfo/index.js index 825897c830..a24e6f5de8 100644 --- a/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/PolicyProfile/component/PolicyInfo/index.js +++ b/components/device-mgt/io.entgra.device.mgt.ui/react-app/src/scenes/Home/scenes/Policies/components/PolicyProfile/component/PolicyInfo/index.js @@ -46,6 +46,7 @@ const { TextArea } = Input; const subPanelpayloadAttributes = {}; const fieldKeys = []; +let subFormContainer = {}; class PolicyInfo extends React.Component { constructor(props) { @@ -55,6 +56,7 @@ class PolicyInfo extends React.Component { data: {}, policyFeatureList: [], activePanelKeys: [], + activeSubPanelKeys: [], profilePreviewKey: '', customInputDataArray: [], inputTableDataSources: {}, @@ -65,22 +67,57 @@ class PolicyInfo extends React.Component { setProfileInfo = e => { let activePolicies = []; let activePolicyFields = {}; + let activeSubPanels = []; const allFields = this.props.form.getFieldsValue(); this.props.policyFeatureList.map(element => { activePolicies.push(element.featureCode); let featureData = JSON.parse(element.content); Object.keys(featureData).map(key => { - let regex = new RegExp(`${element.featureCode}.+${key}`, 'g'); - Object.keys(allFields).map(fieldName => { - if (fieldName.match(regex) != null) { - activePolicyFields[fieldName] = featureData[key]; - } - }); + if (element.featureCode in subPanelpayloadAttributes) { + Object.entries(subPanelpayloadAttributes[element.featureCode]).map( + ([panelKey, payloadAttr]) => { + if (key === payloadAttr) { + activeSubPanels.push(`${element.featureCode}-${panelKey}`); + } + }, + ); + + let regex = new RegExp(`${element.featureCode}.+${key}`, 'g'); + Object.keys(allFields).map(fieldName => { + if (fieldName.match(regex) != null) { + activePolicyFields[fieldName] = featureData[key]; + } + }); + } else if (element.featureCode in subFormContainer) { + let regex = new RegExp(`.+${element.featureCode}-${key}`, 'g'); + Object.keys(allFields).map(fieldName => { + if (fieldName.match(regex) != null) { + activePolicyFields[fieldName] = featureData[key]; + if ( + !activePolicies.includes( + fieldName.replace(`-${element.featureCode}-${key}`, ''), + ) + ) { + activePolicies.push( + fieldName.replace(`-${element.featureCode}-${key}`, ''), + ); + } + } + }); + } else { + let regex = new RegExp(`${element.featureCode}.+${key}`, 'g'); + Object.keys(allFields).map(fieldName => { + if (fieldName.match(regex) != null) { + activePolicyFields[fieldName] = featureData[key]; + } + }); + } }); }); this.props.form.setFieldsValue(activePolicyFields); this.setState({ activePanelKeys: activePolicies, + activeSubPanelKeys: activeSubPanels, }); }; @@ -235,7 +272,7 @@ class PolicyInfo extends React.Component { {getFieldDecorator(`${columnData.key}${i}`, { initialValue: columnData.others.initialDataIndex, })( - {columnData.others.option.map((option, i) => { return (
- +