diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml index 3272165588..cbc22f06c9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml @@ -58,6 +58,8 @@ Device Management Dashboard Analytics Bundle org.wso2.carbon.device.mgt.analytics.dashboard.dao, + org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl, + org.wso2.carbon.device.mgt.analytics.dashboard.impl, org.wso2.carbon.device.mgt.analytics.dashboard.internal diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataService.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataService.java index d34bd4c2e5..7c5b2038e6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataService.java @@ -30,58 +30,61 @@ import java.util.Map; public interface GadgetDataService { @SuppressWarnings("unused") - int getTotalDeviceCount(); + int getTotalDeviceCount() throws GadgetDataServiceException; @SuppressWarnings("unused") - int getActiveDeviceCount(); + int getActiveDeviceCount() throws GadgetDataServiceException; @SuppressWarnings("unused") - int getInactiveDeviceCount(); + int getInactiveDeviceCount() throws GadgetDataServiceException; @SuppressWarnings("unused") - int getRemovedDeviceCount(); + int getRemovedDeviceCount() throws GadgetDataServiceException; @SuppressWarnings("unused") - int getNonCompliantDeviceCount(); + int getNonCompliantDeviceCount() throws GadgetDataServiceException; @SuppressWarnings("unused") - int getUnmonitoredDeviceCount(); + int getUnmonitoredDeviceCount() throws GadgetDataServiceException; @SuppressWarnings("unused") - PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest); + PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) + throws GadgetDataServiceException; @SuppressWarnings("unused") - int getDeviceCount(Map filters); + int getDeviceCount(Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") - int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map filters); + int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") - Map getDeviceCountsByPlatforms(Map filters); + Map getDeviceCountsByPlatforms(Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") Map getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode, - Map filters); + Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") - Map getDeviceCountsByOwnershipTypes(Map filters); + Map getDeviceCountsByOwnershipTypes(Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") Map getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode, - Map filters); + Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") - PaginationResult getDevicesWithDetails(Map filters, PaginationRequest paginationRequest); + PaginationResult getDevicesWithDetails(Map filters, + PaginationRequest paginationRequest) throws GadgetDataServiceException; @SuppressWarnings("unused") PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, - Map filters, PaginationRequest paginationRequest); + Map filters, PaginationRequest paginationRequest) throws GadgetDataServiceException; @SuppressWarnings("unused") - List> getDevicesWithDetails(Map filters); + List> getDevicesWithDetails(Map filters) throws GadgetDataServiceException; @SuppressWarnings("unused") List> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, - Map filters); + Map filters) throws GadgetDataServiceException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataServiceException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataServiceException.java new file mode 100644 index 0000000000..32ebef29f0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/GadgetDataServiceException.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.analytics.dashboard; + +/** + * Custom exception class for GadgetDataService layer. + */ +public class GadgetDataServiceException extends Exception { + + private String errorMessage; + private static final long serialVersionUID = 2021891706072918864L; + + /** + * Constructs a new exception with the specific error message and nested exception. + * + * @param errorMessage specific error message. + * @param nestedException Nested exception. + */ + public GadgetDataServiceException(String errorMessage, Exception nestedException) { + super(errorMessage, nestedException); + setErrorMessage(errorMessage); + } + + /** + * Constructs a new exception with the specific error message and cause. + * + * @param errorMessage Specific error message. + * @param cause Cause of this exception. + */ + @SuppressWarnings("unused") + public GadgetDataServiceException(String errorMessage, Throwable cause) { + super(errorMessage, cause); + setErrorMessage(errorMessage); + } + + /** + * Constructs a new exception with the specific error message. + * + * @param errorMessage Specific error message. + */ + @SuppressWarnings("unused") + public GadgetDataServiceException(String errorMessage) { + super(errorMessage); + setErrorMessage(errorMessage); + } + + /** + * Constructs a new exception with the specific error message and cause. + * + * @param cause Cause of this exception. + */ + @SuppressWarnings("unused") + public GadgetDataServiceException(Throwable cause) { + super(cause); + } + + @SuppressWarnings("unused") + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOException.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOException.java index 3ebf841f13..adb1917c1e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOException.java @@ -18,11 +18,11 @@ package org.wso2.carbon.device.mgt.analytics.dashboard.dao; -@SuppressWarnings("unused") /** - * Custom exception class for data access related exceptions. + * Custom exception class for GadgetDataServiceDAO layer. */ public class GadgetDataServiceDAOException extends Exception { + private String errorMessage; private static final long serialVersionUID = 2021891706072918864L; @@ -43,6 +43,7 @@ public class GadgetDataServiceDAOException extends Exception { * @param errorMessage Specific error message. * @param cause Cause of this exception. */ + @SuppressWarnings("unused") public GadgetDataServiceDAOException(String errorMessage, Throwable cause) { super(errorMessage, cause); setErrorMessage(errorMessage); @@ -53,6 +54,7 @@ public class GadgetDataServiceDAOException extends Exception { * * @param errorMessage Specific error message. */ + @SuppressWarnings("unused") public GadgetDataServiceDAOException(String errorMessage) { super(errorMessage); setErrorMessage(errorMessage); @@ -63,10 +65,12 @@ public class GadgetDataServiceDAOException extends Exception { * * @param cause Cause of this exception. */ + @SuppressWarnings("unused") public GadgetDataServiceDAOException(Throwable cause) { super(cause); } + @SuppressWarnings("unused") public String getErrorMessage() { return errorMessage; } @@ -74,4 +78,5 @@ public class GadgetDataServiceDAOException extends Exception { public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOFactory.java index bb2d44ac63..c5a6097f3f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOFactory.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.analytics.dashboard.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl.GadgetDataServiceDAOImpl; import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; @@ -33,6 +34,7 @@ import java.util.List; @SuppressWarnings("unused") public class GadgetDataServiceDAOFactory { + private static final Log log = LogFactory.getLog(GadgetDataServiceDAOFactory.class); private static DataSource dataSource; private static String databaseEngine; @@ -47,7 +49,7 @@ public class GadgetDataServiceDAOFactory { try { databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); } catch (SQLException e) { - log.error("Error occurred while retrieving config.datasource connection", e); + log.error("Error occurred while retrieving config.datasource connection.", e); } } @@ -56,7 +58,7 @@ public class GadgetDataServiceDAOFactory { try { databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); } catch (SQLException e) { - log.error("Error occurred while retrieving config.datasource connection", e); + log.error("Error occurred while retrieving config.datasource connection.", e); } } @@ -64,8 +66,8 @@ public class GadgetDataServiceDAOFactory { Connection conn = currentConnection.get(); if (conn != null) { throw new IllegalTransactionStateException("A transaction is already active within the context of " + - "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + - "transaction is already active is a sign of improper transaction handling"); + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + + "transaction is already active is a sign of improper transaction handling."); } conn = dataSource.getConnection(); currentConnection.set(conn); @@ -75,8 +77,8 @@ public class GadgetDataServiceDAOFactory { Connection conn = currentConnection.get(); if (conn == null) { throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + - "This might have ideally been caused by not properly initiating the transaction via " + - "'beginTransaction'/'openConnection' methods"); + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods."); } return conn; } @@ -85,36 +87,35 @@ public class GadgetDataServiceDAOFactory { Connection conn = currentConnection.get(); if (conn == null) { throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + - "This might have ideally been caused by not properly initiating the transaction via " + - "'beginTransaction'/'openConnection' methods"); + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods."); } try { conn.close(); } catch (SQLException e) { - log.warn("Error occurred while close the connection"); + log.warn("Error occurred while close the connection."); } currentConnection.remove(); } /** - * Resolve data source from the data source definition + * Resolve data source from the data source definition. * - * @param config data source configuration - * @return data source resolved from the data source definition + * @param config data source configuration. + * @return data source resolved from the data source definition. */ private static DataSource resolveDataSource(DataSourceConfig config) { DataSource dataSource = null; if (config == null) { throw new RuntimeException( - "Device Management Repository data source configuration " + "is null and " + - "thus, is not initialized"); + "Device Management Repository data source configuration " + "is null and " + + "thus, is not initialized."); } JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition(); if (jndiConfig != null) { if (log.isDebugEnabled()) { - log.debug("Initializing Device Management Repository data source using the JNDI " + - "Lookup Definition"); + log.debug("Initializing Device Management Repository data source using the JNDI Lookup Definition."); } List jndiPropertyList = jndiConfig.getJndiProperties(); if (jndiPropertyList != null) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/GadgetDataServiceDAOImpl.java similarity index 90% rename from components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/GadgetDataServiceDAOImpl.java index fabd43ec8e..9f2250d3cf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/GadgetDataServiceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/GadgetDataServiceDAOImpl.java @@ -16,11 +16,12 @@ * under the License. */ -package org.wso2.carbon.device.mgt.analytics.dashboard.dao; +package org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAO; +import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOException; +import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; @@ -34,9 +35,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { - @SuppressWarnings("unused") - private static final Log log = LogFactory.getLog(GadgetDataServiceDAOImpl.class); +public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { @Override public int getTotalDeviceCount() throws GadgetDataServiceDAOException { @@ -72,7 +71,15 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { } @Override - public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) throws GadgetDataServiceDAOException { + public int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException { + Map filters = new HashMap<>(); + filters.put("POLICY_ID", -1); + return this.getDeviceCount(filters); + } + + @Override + public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) + throws GadgetDataServiceDAOException { Connection con; PreparedStatement stmt = null; ResultSet rs = null; @@ -82,7 +89,7 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { try { con = this.getConnection(); String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " + - "WHERE TENANT_ID = ? GROUP BY FEATURE_CODE ORDER BY DEVICE_COUNT DESC LIMIT ?, ?"; + "WHERE TENANT_ID = ? GROUP BY FEATURE_CODE ORDER BY DEVICE_COUNT DESC LIMIT ?, ?"; stmt = con.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setInt(2, paginationRequest.getStartIndex()); @@ -112,7 +119,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT"); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting non compliant device counts by features.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -122,13 +130,6 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { return paginationResult; } - @Override - public int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException { - Map filters = new HashMap<>(); - filters.put("POLICY_ID", -1); - return this.getDeviceCount(filters); - } - public int getDeviceCount(Map filters) throws GadgetDataServiceDAOException { Connection con; PreparedStatement stmt = null; @@ -166,7 +167,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { filteredDeviceCount = rs.getInt("DEVICE_COUNT"); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered device count.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -211,7 +213,9 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { filteredDeviceCount = rs.getInt("DEVICE_COUNT"); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered device count, " + + "non compliant by a particular feature.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -257,7 +261,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { filteredDeviceCountsByPlatforms.put(rs.getString("PLATFORM"), rs.getInt("DEVICE_COUNT")); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of device counts by platforms.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -304,7 +309,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { filteredDeviceCountsByPlatforms.put(rs.getString("PLATFORM"), rs.getInt("DEVICE_COUNT")); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a set of feature non-compliant device counts by platforms.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -350,7 +356,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { filteredDeviceCountsByOwnershipTypes.put(rs.getString("OWNERSHIP"), rs.getInt("DEVICE_COUNT")); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of device counts by ownership types.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -398,7 +405,9 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { filteredDeviceCountsByOwnershipTypes.put(rs.getString("OWNERSHIP"), rs.getInt("DEVICE_COUNT")); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of feature " + + "non-compliant device counts by ownership types.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -469,7 +478,9 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { totalRecordsCount = rs.getInt("DEVICE_COUNT"); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of devices " + + "with details when pagination is enabled.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -485,7 +496,6 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { PreparedStatement stmt = null; ResultSet rs = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - Map filteredDeviceWithDetails = new HashMap<>(); List> filteredDevicesWithDetails = new ArrayList<>(); int totalRecordsCount = 0; try { @@ -499,7 +509,7 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { } } sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " + - "WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?"; + "WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?"; stmt = con.prepareStatement(sql); // [2] appending filter column values, if exist stmt.setInt(1, tenantId); @@ -523,7 +533,9 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { // executing query rs = stmt.executeQuery(); // fetching query results + Map filteredDeviceWithDetails; while (rs.next()) { + filteredDeviceWithDetails = new HashMap<>(); filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID")); filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM")); filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP")); @@ -545,7 +557,9 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { totalRecordsCount = rs.getInt("DEVICE_COUNT"); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of feature non-compliant devices " + + "with details when pagination is enabled.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -599,7 +613,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { filteredDevicesWithDetails.add(filteredDeviceWithDetails); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting a filtered set of devices with details.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } @@ -612,13 +627,12 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { PreparedStatement stmt = null; ResultSet rs = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - Map filteredDeviceWithDetails = new HashMap<>(); List> filteredDevicesWithDetails = new ArrayList<>(); try { con = this.getConnection(); String sql; sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " + - "WHERE TENANT_ID = ? AND FEATURE_CODE = ?"; + "WHERE TENANT_ID = ? AND FEATURE_CODE = ?"; // appending filters to support advanced filtering options // [1] appending filter columns, if exist if (filters != null && filters.size() > 0) { @@ -644,7 +658,9 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { // executing query rs = stmt.executeQuery(); // fetching query results + Map filteredDeviceWithDetails; while (rs.next()) { + filteredDeviceWithDetails = new HashMap<>(); filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID")); filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM")); filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP")); @@ -652,7 +668,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO { filteredDevicesWithDetails.add(filteredDeviceWithDetails); } } catch (SQLException e) { - throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e); + throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " + + "execute relevant SQL queries for getting filtered set of feature non-compliant devices with details.", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/impl/GadgetDataServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/impl/GadgetDataServiceImpl.java new file mode 100644 index 0000000000..eb01fa3ae2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/impl/GadgetDataServiceImpl.java @@ -0,0 +1,363 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.analytics.dashboard.impl; + +import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService; +import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataServiceException; +import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOException; +import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory; +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.PaginationResult; + +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +/** + * To be updated... + */ +public class GadgetDataServiceImpl implements GadgetDataService { + + @Override + public int getTotalDeviceCount() throws GadgetDataServiceException { + int totalDeviceCount; + try { + GadgetDataServiceDAOFactory.openConnection(); + totalDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getTotalDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for total device count.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return totalDeviceCount; + } + + @Override + public int getActiveDeviceCount() throws GadgetDataServiceException { + int activeDeviceCount; + try { + GadgetDataServiceDAOFactory.openConnection(); + activeDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getActiveDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for active device count.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return activeDeviceCount; + } + + @Override + public int getInactiveDeviceCount() throws GadgetDataServiceException { + int inactiveDeviceCount; + try { + GadgetDataServiceDAOFactory.openConnection(); + inactiveDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getInactiveDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for inactive device count.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return inactiveDeviceCount; + } + + @Override + public int getRemovedDeviceCount() throws GadgetDataServiceException { + int removedDeviceCount; + try { + GadgetDataServiceDAOFactory.openConnection(); + removedDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getRemovedDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for removed device count.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return removedDeviceCount; + } + + @Override + public int getNonCompliantDeviceCount() throws GadgetDataServiceException { + int nonCompliantDeviceCount; + try { + GadgetDataServiceDAOFactory.openConnection(); + nonCompliantDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getNonCompliantDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for non-compliant device count.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return nonCompliantDeviceCount; + } + + @Override + public int getUnmonitoredDeviceCount() throws GadgetDataServiceException { + int unmonitoredDeviceCount; + try { + GadgetDataServiceDAOFactory.openConnection(); + unmonitoredDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getUnmonitoredDeviceCount(); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for unmonitored device count.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return unmonitoredDeviceCount; + } + + @Override + public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) + throws GadgetDataServiceException { + PaginationResult paginationResult; + try { + GadgetDataServiceDAOFactory.openConnection(); + paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getNonCompliantDeviceCountsByFeatures(paginationRequest); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for non-compliant device counts by features.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return paginationResult; + } + + @Override + public int getDeviceCount(Map filters) throws GadgetDataServiceException { + int deviceCount; + try { + GadgetDataServiceDAOFactory.openConnection(); + deviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDeviceCount(filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in calling DAO function for getting a filtered device count.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return deviceCount; + } + + @Override + public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map filters) + throws GadgetDataServiceException { + int featureNonCompliantDeviceCount; + try { + GadgetDataServiceDAOFactory.openConnection(); + featureNonCompliantDeviceCount = GadgetDataServiceDAOFactory. + getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCount(nonCompliantFeatureCode, filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting a filtered device count, non compliant by a particular feature.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return featureNonCompliantDeviceCount; + } + + @Override + public Map getDeviceCountsByPlatforms(Map filters) + throws GadgetDataServiceException { + Map deviceCountsByPlatforms; + try { + GadgetDataServiceDAOFactory.openConnection(); + deviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getDeviceCountsByPlatforms(filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered device counts by platforms.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return deviceCountsByPlatforms; + } + + @Override + public Map getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceException { + Map featureNonCompliantDeviceCountsByPlatforms; + try { + GadgetDataServiceDAOFactory.openConnection(); + featureNonCompliantDeviceCountsByPlatforms = GadgetDataServiceDAOFactory. + getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered device counts by platforms, non compliant by a particular feature.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return featureNonCompliantDeviceCountsByPlatforms; + } + + @Override + public Map getDeviceCountsByOwnershipTypes(Map filters) + throws GadgetDataServiceException { + Map deviceCountsByOwnershipTypes; + try { + GadgetDataServiceDAOFactory.openConnection(); + deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getDeviceCountsByOwnershipTypes(filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered device counts by ownership types.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return deviceCountsByOwnershipTypes; + } + + @Override + public Map getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceException { + Map featureNonCompliantDeviceCountsByOwnershipTypes; + try { + GadgetDataServiceDAOFactory.openConnection(); + featureNonCompliantDeviceCountsByOwnershipTypes = + GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection.", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered device counts by ownership types, non compliant by a particular feature.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return featureNonCompliantDeviceCountsByOwnershipTypes; + } + + @Override + public PaginationResult getDevicesWithDetails(Map filters, + PaginationRequest paginationRequest) throws GadgetDataServiceException { + PaginationResult paginationResult; + try { + GadgetDataServiceDAOFactory.openConnection(); + paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getDevicesWithDetails(filters, paginationRequest); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered devices with details when pagination is enabled.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return paginationResult; + } + + @Override + public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, + Map filters, PaginationRequest paginationRequest) throws GadgetDataServiceException { + PaginationResult paginationResult; + try { + GadgetDataServiceDAOFactory.openConnection(); + paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters, paginationRequest); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered devices with details, non compliant by feature when pagination is enabled.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return paginationResult; + } + + @Override + public List> getDevicesWithDetails(Map filters) + throws GadgetDataServiceException { + List> devicesWithDetails; + try { + GadgetDataServiceDAOFactory.openConnection(); + devicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDevicesWithDetails(filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered devices with details.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return devicesWithDetails; + } + + @Override + public List> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, + Map filters) throws GadgetDataServiceException { + List> featureNonCompliantDevicesWithDetails; + try { + GadgetDataServiceDAOFactory.openConnection(); + featureNonCompliantDevicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). + getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters); + } catch (SQLException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " + + "in opening database connection", e); + } catch (GadgetDataServiceDAOException e) { + throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " + + "for getting filtered devices with details, non compliant by feature.", e); + } finally { + GadgetDataServiceDAOFactory.closeConnection(); + } + return featureNonCompliantDevicesWithDetails; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceComponent.java index 193afc92da..7d1bc08c19 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceComponent.java @@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService; import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory; +import org.wso2.carbon.device.mgt.analytics.dashboard.impl.GadgetDataServiceImpl; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; @@ -39,6 +40,7 @@ import org.wso2.carbon.ndatasource.core.DataSourceService; * unbind="unsetDataSourceService" */ public class GadgetDataServiceComponent { + private static final Log log = LogFactory.getLog(GadgetDataServiceComponent.class); protected void activate(ComponentContext componentContext) { @@ -56,10 +58,10 @@ public class GadgetDataServiceComponent { componentContext.getBundleContext(). registerService(GadgetDataService.class.getName(), new GadgetDataServiceImpl(), null); if (log.isDebugEnabled()) { - log.debug("Device Management Dashboard Analytics Bundle has been started successfully"); + log.debug("Device Management Dashboard Analytics Bundle has been started successfully."); } } catch (Throwable e) { - log.error("Error occurred while initializing the bundle", e); + log.error("Error occurred while initializing the bundle.", e); } } @@ -70,11 +72,18 @@ public class GadgetDataServiceComponent { //do nothing } - public void setDataSourceService(DataSourceService dataSourceService){ - + public void setDataSourceService(DataSourceService dataSourceService) { + if (log.isDebugEnabled()) { + log.debug("Binding org.wso2.carbon.ndatasource.core.DataSourceService..."); + } + //do nothing } - public void unsetDataSourceService(DataSourceService dataSourceService){ - + public void unsetDataSourceService(DataSourceService dataSourceService) { + if (log.isDebugEnabled()) { + log.debug("Unbinding org.wso2.carbon.ndatasource.core.DataSourceService..."); + } + //do nothing } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceImpl.java deleted file mode 100644 index 2f31b84f40..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/internal/GadgetDataServiceImpl.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * you may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.analytics.dashboard.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOException; -import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory; -import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; - -import java.sql.SQLException; -import java.util.List; -import java.util.Map; - -/** - * To be updated... - */ -class GadgetDataServiceImpl implements GadgetDataService { - - @SuppressWarnings("unused") - private static final Log log = LogFactory.getLog(GadgetDataServiceImpl.class); - - @Override - public int getTotalDeviceCount() { - int totalDeviceCount; - try { - GadgetDataServiceDAOFactory.openConnection(); - totalDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getTotalDeviceCount(); - } catch (GadgetDataServiceDAOException | SQLException e) { - totalDeviceCount = -1; - return totalDeviceCount; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return totalDeviceCount; - } - - @Override - public int getActiveDeviceCount() { - int activeDeviceCount; - try { - GadgetDataServiceDAOFactory.openConnection(); - activeDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getActiveDeviceCount(); - } catch (GadgetDataServiceDAOException | SQLException e) { - activeDeviceCount = -1; - return activeDeviceCount; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return activeDeviceCount; - } - - @Override - public int getInactiveDeviceCount() { - int inactiveDeviceCount; - try { - GadgetDataServiceDAOFactory.openConnection(); - inactiveDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getInactiveDeviceCount(); - } catch (GadgetDataServiceDAOException | SQLException e) { - inactiveDeviceCount = -1; - return inactiveDeviceCount; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return inactiveDeviceCount; - } - - @Override - public int getRemovedDeviceCount() { - int removedDeviceCount; - try { - GadgetDataServiceDAOFactory.openConnection(); - removedDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getRemovedDeviceCount(); - } catch (GadgetDataServiceDAOException | SQLException e) { - removedDeviceCount = -1; - return removedDeviceCount; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return removedDeviceCount; - } - - @Override - public int getNonCompliantDeviceCount() { - int nonCompliantDeviceCount; - try { - GadgetDataServiceDAOFactory.openConnection(); - nonCompliantDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getNonCompliantDeviceCount(); - } catch (GadgetDataServiceDAOException | SQLException e) { - nonCompliantDeviceCount = -1; - return nonCompliantDeviceCount; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return nonCompliantDeviceCount; - } - - @Override - public int getUnmonitoredDeviceCount() { - int unmonitoredDeviceCount; - try { - GadgetDataServiceDAOFactory.openConnection(); - unmonitoredDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getUnmonitoredDeviceCount(); - } catch (GadgetDataServiceDAOException | SQLException e) { - unmonitoredDeviceCount = -1; - return unmonitoredDeviceCount; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return unmonitoredDeviceCount; - } - - @Override - public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) { - PaginationResult paginationResult = null; - try { - GadgetDataServiceDAOFactory.openConnection(); - paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getNonCompliantDeviceCountsByFeatures(paginationRequest); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return paginationResult; - } - - @Override - public int getDeviceCount(Map filters) { - int deviceCount; - try { - GadgetDataServiceDAOFactory.openConnection(); - deviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDeviceCount(filters); - } catch (GadgetDataServiceDAOException | SQLException e) { - deviceCount = -1; - return deviceCount; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return deviceCount; - } - - @Override - public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map filters) { - int featureNonCompliantDeviceCount; - try { - GadgetDataServiceDAOFactory.openConnection(); - featureNonCompliantDeviceCount = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCount(nonCompliantFeatureCode, filters); - } catch (GadgetDataServiceDAOException | SQLException e) { - featureNonCompliantDeviceCount = -1; - return featureNonCompliantDeviceCount; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return featureNonCompliantDeviceCount; - } - - @Override - public Map getDeviceCountsByPlatforms(Map filters) { - Map deviceCountsByPlatforms = null; - try { - GadgetDataServiceDAOFactory.openConnection(); - deviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getDeviceCountsByPlatforms(filters); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return deviceCountsByPlatforms; - } - - @Override - public Map getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode, - Map filters) { - Map featureNonCompliantDeviceCountsByPlatforms = null; - try { - GadgetDataServiceDAOFactory.openConnection(); - featureNonCompliantDeviceCountsByPlatforms = GadgetDataServiceDAOFactory. - getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filters); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return featureNonCompliantDeviceCountsByPlatforms; - } - - @Override - public Map getDeviceCountsByOwnershipTypes(Map filters) { - Map deviceCountsByOwnershipTypes = null; - try { - GadgetDataServiceDAOFactory.openConnection(); - deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getDeviceCountsByOwnershipTypes(filters); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return deviceCountsByOwnershipTypes; - } - - @Override - public Map getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode, - Map filters) { - Map featureNonCompliantDeviceCountsByOwnershipTypes = null; - try { - GadgetDataServiceDAOFactory.openConnection(); - featureNonCompliantDeviceCountsByOwnershipTypes = - GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filters); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return featureNonCompliantDeviceCountsByOwnershipTypes; - } - - @Override - public PaginationResult getDevicesWithDetails(Map filters, PaginationRequest paginationRequest) { - PaginationResult paginationResult = null; - try { - GadgetDataServiceDAOFactory.openConnection(); - paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getDevicesWithDetails(filters, paginationRequest); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return paginationResult; - } - - @Override - public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, - Map filters, PaginationRequest paginationRequest) { - PaginationResult paginationResult = null; - try { - GadgetDataServiceDAOFactory.openConnection(); - paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters, paginationRequest); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return paginationResult; - } - - @Override - public List> getDevicesWithDetails(Map filters) { - List> devicesWithDetails = null; - try { - GadgetDataServiceDAOFactory.openConnection(); - devicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDevicesWithDetails(filters); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return devicesWithDetails; - } - - @Override - public List> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, - Map filters) { - List> featureNonCompliantDevicesWithDetails = null; - try { - GadgetDataServiceDAOFactory.openConnection(); - featureNonCompliantDevicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO(). - getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters); - } catch (GadgetDataServiceDAOException | SQLException e) { - return null; - } finally { - GadgetDataServiceDAOFactory.closeConnection(); - } - return featureNonCompliantDevicesWithDetails; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Group.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Group.java index 4e1b9b68b7..acd9e98714 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Group.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/api/Group.java @@ -21,15 +21,15 @@ package org.wso2.carbon.device.mgt.jaxrs.api; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; -import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; +import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -141,6 +141,26 @@ public class Group { } } + @Path("/all") + @GET + @Produces("application/json") + public Response getAllGroups() { + try { + GroupManagementProviderService groupManagementProviderService = DeviceMgtAPIUtils + .getGroupManagementProviderService(); + PaginationResult paginationResult = groupManagementProviderService + .getGroups(0, groupManagementProviderService.getGroupCount()); + if (paginationResult.getRecordsTotal() > 0) { + return Response.status(Response.Status.OK).entity(paginationResult.getData()).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + } + @Path("/user/{user}") @GET @Produces("application/json") @@ -364,16 +384,18 @@ public class Group { } @GET - @Path("/owner/{owner}/name/{groupName}/devices/all") + @Path("/owner/{owner}/name/{groupName}/devices") @Produces("application/json") - public Response getDevices(@PathParam("groupName") String groupName, - @PathParam("owner") String owner) { + public Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner, + @QueryParam("start") int startIdx, @QueryParam("length") int length) { try { - List devices = DeviceMgtAPIUtils.getGroupManagementProviderService().getDevices( - groupName, owner); - Device[] deviceArray = new Device[devices.size()]; - devices.toArray(deviceArray); - return Response.status(Response.Status.OK).entity(deviceArray).build(); + PaginationResult paginationResult = DeviceMgtAPIUtils + .getGroupManagementProviderService().getDevices(groupName, owner, startIdx, length); + if (paginationResult.getRecordsTotal() > 0) { + return Response.status(Response.Status.OK).entity(paginationResult).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } } catch (GroupManagementException e) { log.error(e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); @@ -394,15 +416,12 @@ public class Group { } } - @PUT - @Path("/owner/{owner}/name/{groupName}/devices/{deviceType}/{deviceId}") + @POST + @Path("/owner/{owner}/name/{groupName}/devices") @Produces("application/json") public Response addDevice(@PathParam("groupName") String groupName, - @PathParam("owner") String owner, @PathParam("deviceId") String deviceId, - @PathParam("deviceType") String deviceType, - @FormParam("userName") String userName) { + @PathParam("owner") String owner, DeviceIdentifier deviceIdentifier) { try { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice( deviceIdentifier, groupName, owner); if (isAdded) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml index 1768fa9160..e00d1a93ac 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -959,12 +959,19 @@ - List All Groups + List All Groups with Pagination /device-mgt/admin/groups/list /groups GET + + List All Groups + /device-mgt/admin/groups/list + /groups/all + GET + + List Groups /device-mgt/user/groups/list @@ -1080,7 +1087,7 @@ List Group Devices /device-mgt/user/groups/devices/list - /groups/owner/*/name/*/devices/all + /groups/owner/*/name/*/devices GET @@ -1094,8 +1101,8 @@ Add Device to Group /device-mgt/user/groups/devices/add - /groups/owner/*/name/*/devices/*/* - PUT + /groups/owner/*/name/*/devices + POST diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java index dc6bcd886a..92af0d4544 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceInfo.java @@ -22,6 +22,7 @@ package org.wso2.carbon.device.mgt.common.device.details; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import java.io.Serializable; +import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -51,6 +52,7 @@ public class DeviceInfo implements Serializable { private Double totalRAMMemory; private Double availableRAMMemory; private boolean pluggedIn; + private Date updatedTime; private Map deviceDetailsMap = new HashMap<>(); @@ -290,6 +292,17 @@ public class DeviceInfo implements Serializable { this.pluggedIn = pluggedIn; } + public Date getUpdatedTime() { + if(updatedTime.equals(null)){ + updatedTime = new Date(); + } + return updatedTime; + } + + public void setUpdatedTime(Date updatedTime) { + this.updatedTime = updatedTime; + } + public void setDeviceDetailsMap(Map deviceDetailsMap) { this.deviceDetailsMap = deviceDetailsMap; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java index 0b05406522..1368b92806 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/device/details/DeviceLocation.java @@ -22,6 +22,7 @@ package org.wso2.carbon.device.mgt.common.device.details; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import java.io.Serializable; +import java.util.Date; public class DeviceLocation implements Serializable { @@ -39,6 +40,7 @@ public class DeviceLocation implements Serializable { private String state; private String zip; private String country; + private Date updatedTime; public int getDeviceId() { return deviceId; @@ -119,5 +121,16 @@ public class DeviceLocation implements Serializable { public void setCountry(String country) { this.country = country; } + + public Date getUpdatedTime() { + if(updatedTime.equals(null)){ + updatedTime = new Date(); + } + return updatedTime; + } + + public void setUpdatedTime(Date updatedTime) { + this.updatedTime = updatedTime; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java index 5f141c44d5..3496bacb8c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/Operation.java @@ -31,7 +31,11 @@ public class Operation implements Serializable { } public enum Status { - IN_PROGRESS, PENDING, COMPLETED, ERROR + IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED + } + + public enum Control { + REPEAT, NO_REPEAT, PAUSE_SEQUENCE, STOP_SEQUENCE } private String code; @@ -39,11 +43,13 @@ public class Operation implements Serializable { private Type type; private int id; private Status status; + private Control control; private String receivedTimeStamp; private String createdTimeStamp; private boolean isEnabled; private Object payLoad; private String operationResponse; + private String activityId; @Override public boolean equals(Object o) { @@ -87,6 +93,11 @@ public class Operation implements Serializable { if (status != operation.status) { return false; } + + if(control != operation.control){ + return false; + } + if (type != operation.type) { return false; } @@ -151,6 +162,14 @@ public class Operation implements Serializable { this.status = status; } + public Control getControl() { + return control; + } + + public void setControl(Control control) { + this.control = control; + } + public String getReceivedTimeStamp() { return receivedTimeStamp; } @@ -191,6 +210,14 @@ public class Operation implements Serializable { this.operationResponse = operationResponse; } + public String getActivityId() { + return activityId; + } + + public void setActivityId(String activityId) { + this.activityId = activityId; + } + @Override public String toString() { return "Operation{" + @@ -198,6 +225,7 @@ public class Operation implements Serializable { ", type=" + type + ", id=" + id + ", status=" + status + + ", control=" + control + ", receivedTimeStamp='" + receivedTimeStamp + '\'' + ", createdTimeStamp='" + createdTimeStamp + '\'' + ", isEnabled=" + isEnabled + 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 1d86b618f8..26ed93bddb 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 @@ -85,4 +85,6 @@ public interface OperationManager { Operation getOperation(int operationId) throws OperationManagementException; + Operation getOperationByActivityId(String activity) throws OperationManagementException; + } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java index ad4a8e64ee..379ca8c3d6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java @@ -75,4 +75,9 @@ public final class DeviceManagementConstants { public static final String DOWNLOAD_URL = "download-url"; } + public static final class OperationAttributes { + private OperationAttributes() {throw new AssertionError(); } + public static final String ACTIVITY = "ACTIVITY_"; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java index cd901b2238..3b392cc820 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/dao/impl/DeviceDetailsDAOImpl.java @@ -50,8 +50,8 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_DETAIL (DEVICE_ID, DEVICE_MODEL, " + "VENDOR, OS_VERSION, BATTERY_LEVEL, INTERNAL_TOTAL_MEMORY, INTERNAL_AVAILABLE_MEMORY, " + "EXTERNAL_TOTAL_MEMORY, EXTERNAL_AVAILABLE_MEMORY, CONNECTION_TYPE, " + - "SSID, CPU_USAGE, TOTAL_RAM_MEMORY, AVAILABLE_RAM_MEMORY, PLUGGED_IN) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + "SSID, CPU_USAGE, TOTAL_RAM_MEMORY, AVAILABLE_RAM_MEMORY, PLUGGED_IN, UPDATE_TIMESTAMP) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setInt(1, deviceInfo.getDeviceId()); stmt.setString(2, deviceInfo.getDeviceModel()); @@ -68,6 +68,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { stmt.setDouble(13, deviceInfo.getTotalRAMMemory()); stmt.setDouble(14, deviceInfo.getAvailableRAMMemory()); stmt.setBoolean(15, deviceInfo.isPluggedIn()); + stmt.setLong(16, System.currentTimeMillis()); stmt.execute(); @@ -144,6 +145,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); + deviceInfo.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP"))); } deviceInfo.setDeviceId(deviceId); @@ -226,7 +228,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { try { conn = this.getConnection(); stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_LOCATION (DEVICE_ID, LATITUDE, LONGITUDE, STREET1, " + - "STREET2, CITY, ZIP, STATE, COUNTRY) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); + "STREET2, CITY, ZIP, STATE, COUNTRY, UPDATE_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setInt(1, deviceLocation.getDeviceId()); stmt.setDouble(2, deviceLocation.getLatitude()); stmt.setDouble(3, deviceLocation.getLongitude()); @@ -236,6 +238,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { stmt.setString(7, deviceLocation.getZip()); stmt.setString(8, deviceLocation.getState()); stmt.setString(9, deviceLocation.getCountry()); + stmt.setLong(10, System.currentTimeMillis()); stmt.execute(); } catch (SQLException e) { throw new DeviceDetailsMgtDAOException("Error occurred while adding the device location to database.", e); @@ -268,6 +271,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { location.setZip(rs.getString("ZIP")); location.setState(rs.getString("STATE")); location.setCountry(rs.getString("COUNTRY")); + location.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP"))); } location.setDeviceId(deviceId); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/CommandOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/CommandOperation.java index 28c43cd6bd..bc132a9b20 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/CommandOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/CommandOperation.java @@ -34,4 +34,8 @@ public class CommandOperation extends Operation { return Type.COMMAND; } + public Control getControl(){ + return Control.NO_REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ConfigOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ConfigOperation.java index bd4fc50ae6..c2be65a372 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ConfigOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ConfigOperation.java @@ -77,4 +77,9 @@ public class ConfigOperation extends Operation { return Type.CONFIG; } + + public Control getControl(){ + return Control.REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java index 37e0736eb5..360deb868a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/Operation.java @@ -18,8 +18,6 @@ */ package org.wso2.carbon.device.mgt.core.dto.operation.mgt; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import java.util.Properties; @@ -30,7 +28,11 @@ public class Operation implements Serializable { } public enum Status { - IN_PROGRESS, PENDING, COMPLETED, ERROR + IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED + } + + public enum Control { + REPEAT, NO_REPEAT, PAUSE_SEQUENCE, STOP_SEQUENCE } private String code; @@ -38,6 +40,7 @@ public class Operation implements Serializable { private Type type; private int id; private Status status; + private Control control; private String receivedTimeStamp; private String createdTimeStamp; private boolean isEnabled; @@ -84,6 +87,14 @@ public class Operation implements Serializable { this.status = status; } + public Control getControl() { + return control; + } + + public void setControl(Control control) { + this.control = control; + } + public String getReceivedTimeStamp() { return receivedTimeStamp; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/PolicyOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/PolicyOperation.java index f1d97a0dd0..dc6ae4dd78 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/PolicyOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/PolicyOperation.java @@ -31,4 +31,8 @@ public class PolicyOperation extends Operation{ private List profileOperations; + public Control getControl(){ + return Control.REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ProfileOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ProfileOperation.java index 61bb18d698..107cf091d7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ProfileOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dto/operation/mgt/ProfileOperation.java @@ -26,4 +26,9 @@ public class ProfileOperation extends ConfigOperation implements Serializable { return Type.PROFILE; } + + public Control getControl(){ + return Control.REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java index b509f136aa..1dc62b8046 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java @@ -382,9 +382,9 @@ public class GroupDAOImpl implements GroupDAO { ResultSet resultSet = null; try { Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "SELECT COUNT(gm.ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP gm, (SELECT ID as GROUP_ID " + + String sql = "SELECT COUNT(gm.ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP gm, (SELECT ID " + "FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) dg " + - "WHERE dm.GROUP_ID = dg.GROUP_ID AND dm.TENANT_ID = ?"; + "WHERE gm.GROUP_ID = dg.ID AND gm.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, groupName); stmt.setString(2, owner); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/CommandOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/CommandOperation.java index 852142c1b8..3a9ecefca3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/CommandOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/CommandOperation.java @@ -35,5 +35,8 @@ public class CommandOperation extends Operation { public Type getType() { return Type.COMMAND; } + public Control getControl(){ + return Control.NO_REPEAT; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ConfigOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ConfigOperation.java index 83cfd0e612..69d8aafc4a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ConfigOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ConfigOperation.java @@ -78,4 +78,8 @@ public class ConfigOperation extends Operation { return Type.CONFIG; } + public Control getControl(){ + return Control.REPEAT; + } + } 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 265dd02f8c..9e156618b6 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 @@ -109,6 +109,12 @@ public class OperationManagerImpl implements OperationManager { OperationDAOUtil.convertOperation(operation); int operationId = this.lookupOperationDAO(operation).addOperation(operationDto); for (EnrolmentInfo enrolmentInfo : enrolments) { + if(operationDto.getControl() == + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT){ + operationDAO.updateEnrollmentOperationsStatus(enrolmentInfo.getId(), operationDto.getCode(), + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING, + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.REPEATED); + } operationMappingDAO.addOperationMapping(operationId, enrolmentInfo.getId()); } OperationManagementDAOFactory.commitTransaction(); @@ -613,7 +619,7 @@ public class OperationManagerImpl implements OperationManager { public Operation getOperation(int operationId) throws OperationManagementException { Operation operation; try { - OperationManagementDAOFactory.getConnection(); + OperationManagementDAOFactory.openConnection(); org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. getOperation(operationId); if (dtoOperation == null) { @@ -648,6 +654,17 @@ public class OperationManagerImpl implements OperationManager { return operation; } + @Override + public Operation getOperationByActivityId(String activity) throws OperationManagementException { + // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer. + int operationId = Integer.parseInt( + activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "")); + if(operationId == 0){ + throw new IllegalArgumentException("Operation ID cannot be null or zero (0)."); + } + return this.getOperation(operationId); + } + private OperationDAO lookupOperationDAO(Operation operation) { if (operation instanceof CommandOperation) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/PolicyOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/PolicyOperation.java index 0740728be0..6b36492a83 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/PolicyOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/PolicyOperation.java @@ -33,4 +33,8 @@ public class PolicyOperation extends Operation { this.profileOperations = profileOperations; } + public Control getControl(){ + return Control.REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ProfileOperation.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ProfileOperation.java index 6c9abbed4c..f984fdfb0c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ProfileOperation.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/ProfileOperation.java @@ -26,4 +26,8 @@ public class ProfileOperation extends ConfigOperation implements Serializable { return Type.PROFILE; } + public Control getControl(){ + return Control.REPEAT; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java index c24887d1bf..9234953829 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java @@ -52,6 +52,9 @@ public interface OperationDAO { void updateOperationStatus(int enrolmentId, int operationId,Operation.Status status) throws OperationManagementDAOException; + void updateEnrollmentOperationsStatus(int enrolmentId, String operationCode, Operation.Status existingStatus, + Operation.Status newStatus) throws OperationManagementDAOException; + void addOperationResponse(int enrolmentId, int operationId, Object operationResponse) throws OperationManagementDAOException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index b866285ff0..592be91c71 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -105,6 +105,41 @@ public class GenericOperationDAOImpl implements OperationDAO { } } + @Override + public void updateEnrollmentOperationsStatus(int enrolmentId, String operationCode, Operation.Status existingStatus, + Operation.Status newStatus) throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + try { + Connection connection = OperationManagementDAOFactory.getConnection(); + String query = "SELECT EOM.ID FROM DM_ENROLMENT_OP_MAPPING AS EOM INNER JOIN DM_OPERATION DM " + + "ON DM.ID = EOM.OPERATION_ID WHERE EOM.ENROLMENT_ID = ? AND DM.OPERATION_CODE = ? " + + "AND EOM.STATUS = ?;"; + stmt = connection.prepareStatement(query); + stmt.setInt(1, enrolmentId); + stmt.setString(2, operationCode); + stmt.setString(3, existingStatus.toString()); + // This will return only one result always. + rs = stmt.executeQuery(); + int id = 0; + while (rs.next()){ + id = rs.getInt("ID"); + } + if (id != 0){ + stmt = connection.prepareStatement("UPDATE DM_ENROLMENT_OP_MAPPING SET STATUS = ? WHERE ID = ?"); + stmt.setString(1, newStatus.toString()); + stmt.setInt(2, id); + stmt.executeUpdate(); + } + + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while update device mapping operation status " + + "metadata", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt); + } + } + @Override public void addOperationResponse(int enrolmentId, int operationId, Object operationResponse) throws OperationManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java index 44a93761a7..6625ceab89 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/util/OperationDAOUtil.java @@ -18,6 +18,7 @@ */ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.util; +import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.*; public class OperationDAOUtil { @@ -94,6 +95,8 @@ public class OperationDAOUtil { operation.setReceivedTimeStamp(dtoOperation.getReceivedTimeStamp()); operation.setEnabled(dtoOperation.isEnabled()); operation.setProperties(dtoOperation.getProperties()); + operation.setActivityId(DeviceManagementConstants.OperationAttributes.ACTIVITY + dtoOperation.getId()); + return operation; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Processor.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Processor.java index 88affab477..4c7058be02 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Processor.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/Processor.java @@ -28,4 +28,6 @@ import java.util.List; public interface Processor { List execute(SearchContext searchContext) throws SearchMgtException; + + List getUpdatedDevices(long epochTime) throws SearchMgtException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java index db028edc19..c3e912fcb8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/QueryBuilder.java @@ -38,4 +38,6 @@ public interface QueryBuilder { List processORProperties(List conditions) throws InvalidOperatorException; + String processUpdatedDevices(long epochTime) throws InvalidOperatorException; + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchManagerService.java index ad78ca171f..554ecfc0f9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchManagerService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/SearchManagerService.java @@ -27,5 +27,7 @@ import java.util.List; public interface SearchManagerService { List search(SearchContext searchContext) throws SearchMgtException; + + List getUpdated(long epochTime) throws SearchMgtException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java index e80da38167..ac8f670b7a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/dao/impl/SearchDAOImpl.java @@ -34,7 +34,9 @@ import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils; import java.sql.*; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; public class SearchDAOImpl implements SearchDAO { @@ -52,61 +54,62 @@ public class SearchDAOImpl implements SearchDAO { PreparedStatement stmt = null; ResultSet rs; List devices = new ArrayList<>(); + Map devs = new HashMap<>(); try { conn = this.getConnection(); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); while (rs.next()) { - - Device device = new Device(); - device.setId(rs.getInt("ID")); - device.setDescription(rs.getString("DESCRIPTION")); - device.setName("NAME"); - device.setType(rs.getString("DEVICE_TYPE_NAME")); - device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); - - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setType(rs.getString("DEVICE_TYPE_NAME")); - identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); - - DeviceInfo deviceInfo = new DeviceInfo(); - deviceInfo.setDeviceId(rs.getInt("ID")); - deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); - deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); - deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); - deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); - deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); - deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); - deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); -// deviceInfo.setIMEI(rs.getString("IMEI")); -// deviceInfo.setIMSI(rs.getString("IMSI")); - deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); - deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); -// deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); -// deviceInfo.setOperator(rs.getString("OPERATOR")); - deviceInfo.setOsVersion(rs.getString("OS_VERSION")); - deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); - deviceInfo.setSsid(rs.getString("SSID")); - deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); - deviceInfo.setVendor(rs.getString("VENDOR")); - - DeviceLocation deviceLocation = new DeviceLocation(); - deviceLocation.setLatitude(rs.getDouble("LATITUDE")); - deviceLocation.setLongitude(rs.getDouble("LONGITUDE")); - deviceLocation.setStreet1(rs.getString("STREET1")); - deviceLocation.setStreet2(rs.getString("STREET2")); - deviceLocation.setCity(rs.getString("CITY")); - deviceLocation.setState(rs.getString("STATE")); - deviceLocation.setZip(rs.getString("ZIP")); - deviceLocation.setCountry(rs.getString("COUNTRY")); - deviceLocation.setDeviceId(rs.getInt("ID")); - - DeviceWrapper wrapper = new DeviceWrapper(); - wrapper.setDevice(device); - wrapper.setDeviceInfo(deviceInfo); - wrapper.setDeviceLocation(deviceLocation); - wrapper.setDeviceIdentifier(identifier); - devices.add(wrapper); + if(!devs.containsKey(rs.getInt("ID"))) { + Device device = new Device(); + device.setId(rs.getInt("ID")); + device.setDescription(rs.getString("DESCRIPTION")); + device.setName("NAME"); + device.setType(rs.getString("DEVICE_TYPE_NAME")); + device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setType(rs.getString("DEVICE_TYPE_NAME")); + identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceInfo deviceInfo = new DeviceInfo(); + deviceInfo.setDeviceId(rs.getInt("ID")); + deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); + deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); + deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); + deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); + deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); + deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setOsVersion(rs.getString("OS_VERSION")); + deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); + deviceInfo.setSsid(rs.getString("SSID")); + deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); + deviceInfo.setVendor(rs.getString("VENDOR")); + deviceInfo.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP"))); + + DeviceLocation deviceLocation = new DeviceLocation(); + deviceLocation.setLatitude(rs.getDouble("LATITUDE")); + deviceLocation.setLongitude(rs.getDouble("LONGITUDE")); + deviceLocation.setStreet1(rs.getString("STREET1")); + deviceLocation.setStreet2(rs.getString("STREET2")); + deviceLocation.setCity(rs.getString("CITY")); + deviceLocation.setState(rs.getString("STATE")); + deviceLocation.setZip(rs.getString("ZIP")); + deviceLocation.setCountry(rs.getString("COUNTRY")); + deviceLocation.setDeviceId(rs.getInt("ID")); + deviceLocation.setUpdatedTime(new java.util.Date(rs.getLong("DL_UPDATED_TIMESTAMP"))); + + DeviceWrapper wrapper = new DeviceWrapper(); + wrapper.setDevice(device); + wrapper.setDeviceInfo(deviceInfo); + wrapper.setDeviceLocation(deviceLocation); + wrapper.setDeviceIdentifier(identifier); + devices.add(wrapper); + devs.put(device.getId(), device.getId()); + } } } catch (SQLException e) { @@ -134,61 +137,63 @@ public class SearchDAOImpl implements SearchDAO { PreparedStatement stmt = null; ResultSet rs; List devices = new ArrayList<>(); + Map devs = new HashMap<>(); try { conn = this.getConnection(); stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); while (rs.next()) { - - Device device = new Device(); - device.setId(rs.getInt("ID")); - device.setDescription(rs.getString("DESCRIPTION")); - device.setName(rs.getString("NAME")); - device.setType(rs.getString("DEVICE_TYPE_NAME")); - device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); - - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setType(rs.getString("DEVICE_TYPE_NAME")); - identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); - - DeviceInfo deviceInfo = new DeviceInfo(); - deviceInfo.setDeviceId(rs.getInt("ID")); - deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); - deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); - deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); - deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); - deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); - deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); - deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); -// deviceInfo.setIMEI(rs.getString("IMEI")); -// deviceInfo.setIMSI(rs.getString("IMSI")); - deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); - deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); -// deviceInfo.setMobileSignalStrength(rs.getDouble("MOBILE_SIGNAL_STRENGTH")); -// deviceInfo.setOperator(rs.getString("OPERATOR")); - deviceInfo.setOsVersion(rs.getString("OS_VERSION")); - deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); - deviceInfo.setSsid(rs.getString("SSID")); - deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); - deviceInfo.setVendor(rs.getString("VENDOR")); - - DeviceLocation deviceLocation = new DeviceLocation(); - deviceLocation.setLatitude(rs.getDouble("LATITUDE")); - deviceLocation.setLongitude(rs.getDouble("LONGITUDE")); - deviceLocation.setStreet1(rs.getString("STREET1")); - deviceLocation.setStreet2(rs.getString("STREET2")); - deviceLocation.setCity(rs.getString("CITY")); - deviceLocation.setState(rs.getString("STATE")); - deviceLocation.setZip(rs.getString("ZIP")); - deviceLocation.setCountry(rs.getString("COUNTRY")); - deviceLocation.setDeviceId(rs.getInt("ID")); - - DeviceWrapper wrapper = new DeviceWrapper(); - wrapper.setDevice(device); - wrapper.setDeviceInfo(deviceInfo); - wrapper.setDeviceLocation(deviceLocation); - wrapper.setDeviceIdentifier(identifier); - devices.add(wrapper); + if(!devs.containsKey(rs.getInt("ID"))) { + Device device = new Device(); + device.setId(rs.getInt("ID")); + device.setDescription(rs.getString("DESCRIPTION")); + device.setName(rs.getString("NAME")); + device.setType(rs.getString("DEVICE_TYPE_NAME")); + device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setType(rs.getString("DEVICE_TYPE_NAME")); + identifier.setId(rs.getString("DEVICE_IDENTIFICATION")); + + DeviceInfo deviceInfo = new DeviceInfo(); + deviceInfo.setDeviceId(rs.getInt("ID")); + deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY")); + deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL")); + deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE")); + deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE")); + deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL")); + deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY")); + deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY")); + deviceInfo.setOsVersion(rs.getString("OS_VERSION")); + deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN")); + deviceInfo.setSsid(rs.getString("SSID")); + deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY")); + deviceInfo.setVendor(rs.getString("VENDOR")); + deviceInfo.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP"))); + + DeviceLocation deviceLocation = new DeviceLocation(); + deviceLocation.setLatitude(rs.getDouble("LATITUDE")); + deviceLocation.setLongitude(rs.getDouble("LONGITUDE")); + deviceLocation.setStreet1(rs.getString("STREET1")); + deviceLocation.setStreet2(rs.getString("STREET2")); + deviceLocation.setCity(rs.getString("CITY")); + deviceLocation.setState(rs.getString("STATE")); + deviceLocation.setZip(rs.getString("ZIP")); + deviceLocation.setCountry(rs.getString("COUNTRY")); + deviceLocation.setDeviceId(rs.getInt("ID")); + deviceLocation.setUpdatedTime(new java.util.Date(rs.getLong("DL_UPDATED_TIMESTAMP"))); + + DeviceWrapper wrapper = new DeviceWrapper(); + wrapper.setDevice(device); + wrapper.setDeviceInfo(deviceInfo); + wrapper.setDeviceLocation(deviceLocation); + wrapper.setDeviceIdentifier(identifier); + + devices.add(wrapper); + devs.put(device.getId(), device.getId()); + } } } catch (SQLException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java index 4a97f1fdbe..55b377d4f5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/ProcessorImpl.java @@ -94,6 +94,28 @@ public class ProcessorImpl implements Processor { return aggregator.aggregate(deviceWrappers); } + @Override + public List getUpdatedDevices(long epochTime) throws SearchMgtException { + + if((1 + (int)Math.floor(Math.log10(epochTime))) <=10 ) { + epochTime = epochTime * 1000; + } + QueryBuilder queryBuilder = new QueryBuilderImpl(); + try { + String query = queryBuilder.processUpdatedDevices(epochTime); + DeviceManagementDAOFactory.openConnection(); + return searchDAO.searchDeviceDetailsTable(query); + } catch (InvalidOperatorException e) { + throw new SearchMgtException("Invalid operator was provided, so cannot execute the search.", e); + } catch (SQLException e) { + throw new SearchMgtException("Error occurred while managing database transactions.", e); + } catch (SearchDAOException e) { + throw new SearchMgtException("Error occurred while running the search operations for given time.", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + } + private List processANDSearch(List> deLists) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java index eaca48451f..5864966f0c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java @@ -114,7 +114,7 @@ public class QueryBuilderImpl implements QueryBuilder { for (Condition con : conditions) { if (Utils.checkDeviceDetailsColumns(con.getKey())) { querySuffix = querySuffix + " AND DD." + Utils.getDeviceDetailsColumnNames().get(con.getKey()) + - con.getOperator() + con.getValue(); + con.getOperator() + Utils.getConvertedValue(con.getKey(), con.getValue()); } else if (Utils.checkDeviceLocationColumns(con.getKey())) { querySuffix = querySuffix + " AND DL." + Utils.getDeviceLocationColumnNames().get(con.getKey()) + con.getOperator() + con.getValue(); @@ -132,7 +132,7 @@ public class QueryBuilderImpl implements QueryBuilder { for (Condition con : conditions) { if (Utils.checkDeviceDetailsColumns(con.getKey())) { querySuffix = querySuffix + " OR DD." + Utils.getDeviceDetailsColumnNames().get(con.getKey()) + - con.getOperator() + con.getValue(); + con.getOperator() + Utils.getConvertedValue(con.getKey(), con.getValue()); } else if (Utils.checkDeviceLocationColumns(con.getKey())) { querySuffix = querySuffix + " OR DL." + Utils.getDeviceLocationColumnNames().get(con.getKey()) + con.getOperator() + con.getValue(); @@ -158,6 +158,12 @@ public class QueryBuilderImpl implements QueryBuilder { return this.getQueryList(conditions); } + @Override + public String processUpdatedDevices(long epochTime) throws InvalidOperatorException { + return this.getGenericQueryPart() + " AND ( DD.UPDATE_TIMESTAMP > " + epochTime + + " OR DL.UPDATE_TIMESTAMP > " + epochTime + " )"; + } + private List getQueryList(List conditions) { List queryList = new ArrayList<>(); for (Condition con : conditions) { @@ -189,8 +195,9 @@ public class QueryBuilderImpl implements QueryBuilder { "DD.OS_VERSION, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.CONNECTION_TYPE, \n" + "DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + - "DD.PLUGGED_IN, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + - "DL.STATE, DL.COUNTRY FROM DM_DEVICE_DETAIL AS DD, DM_DEVICE AS D, DM_DEVICE_LOCATION AS DL, " + + "DD.PLUGGED_IN, DD.UPDATE_TIMESTAMP, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + + "DL.STATE, DL.COUNTRY, DL.UPDATE_TIMESTAMP AS DL_UPDATED_TIMESTAMP " + + "FROM DM_DEVICE_DETAIL AS DD, DM_DEVICE AS D, DM_DEVICE_LOCATION AS DL, " + "DM_DEVICE_TYPE AS DT WHERE DEVICE_TYPE_ID=D.DEVICE_TYPE_ID AND D.TENANT_ID = " + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); @@ -205,8 +212,9 @@ public class QueryBuilderImpl implements QueryBuilder { "DD.OS_VERSION, DD.BATTERY_LEVEL, DD.INTERNAL_TOTAL_MEMORY, DD.INTERNAL_AVAILABLE_MEMORY,\n" + "DD.EXTERNAL_TOTAL_MEMORY, DD.EXTERNAL_AVAILABLE_MEMORY, DD.CONNECTION_TYPE, \n" + "DD.SSID, DD.CPU_USAGE, DD.TOTAL_RAM_MEMORY, DD.AVAILABLE_RAM_MEMORY, \n" + - "DD.PLUGGED_IN, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + - "DL.STATE, DL.COUNTRY, DI.KEY_FIELD, DI.VALUE_FIELD FROM DM_DEVICE_DETAIL AS DD, " + + "DD.PLUGGED_IN, DD.UPDATE_TIMESTAMP, DL.LATITUDE, DL.LONGITUDE, DL.STREET1, DL.STREET2, DL.CITY, DL.ZIP, \n" + + "DL.STATE, DL.COUNTRY, DL.UPDATE_TIMESTAMP AS DL_UPDATED_TIMESTAMP, " + + "DI.KEY_FIELD, DI.VALUE_FIELD FROM DM_DEVICE_DETAIL AS DD, " + "DM_DEVICE AS D, DM_DEVICE_LOCATION AS DL, \n" + "DM_DEVICE_INFO AS DI, DM_DEVICE_TYPE AS DT WHERE DEVICE_TYPE_ID=D.DEVICE_TYPE_ID AND D.TENANT_ID = " + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/SearchManagerServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/SearchManagerServiceImpl.java index 888f3edc36..cc9a51d919 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/SearchManagerServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/SearchManagerServiceImpl.java @@ -40,5 +40,10 @@ public class SearchManagerServiceImpl implements SearchManagerService { public List search(SearchContext searchContext) throws SearchMgtException { return processor.execute(searchContext); } + + @Override + public List getUpdated(long epochTime) throws SearchMgtException { + return processor.getUpdatedDevices(epochTime); + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java index bc69e76033..3522228511 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/Utils.java @@ -60,6 +60,41 @@ public class Utils { } + public static boolean checkColumnType(String column) { + + boolean bool = false; + + switch (column) { + case "deviceModel": + bool = true; + break; + case "vendor": + bool = true; + break; + case "osVersion": + bool = true; + break; + case "connectionType": + bool = true; + break; + case "ssid": + bool = true; + break; + default: bool =false; + break; + } + + return bool; + } + + public static String getConvertedValue(String column, String value) { + + if(checkColumnType(column)){ + return "\'" + value + "\'"; + } else return value; + + } + public static Map getDeviceDetailsColumnNames() { return genericColumnsMap; } 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 88bd74cdaa..9d5e6b46d5 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 @@ -867,6 +867,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return DeviceManagementDataHolder.getInstance().getOperationManager().getOperation(operationId); } + @Override + public Operation getOperationByActivityId(String activity) throws OperationManagementException { + return DeviceManagementDataHolder.getInstance().getOperationManager().getOperationByActivityId(activity); + } + @Override public List getDevicesOfUser(String username) throws DeviceManagementException { List devices = new ArrayList<>(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java index 88acffe514..93c15914ad 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/Search/SearchDevice.java @@ -93,62 +93,91 @@ public class SearchDevice extends BaseDeviceManagementTest { } -// @Test -// public void doValidLocationSearch() throws Exception{ -// -// SearchContext context = new SearchContext(); -// List conditions = new ArrayList<>(); -// -// Condition cond = new Condition(); -// cond.setKey("LOCATION"); -// cond.setOperator("="); -// cond.setValue("Karan"); -// cond.setState(Condition.State.AND); -// conditions.add(cond); -// -// context.setConditions(conditions); -// -// SearchManagerService service = new SearchManagerServiceImpl(); -// List deviceWrappers = service.search(context); -// -// Gson gson = new Gson(); -// String bbbb = gson.toJson(deviceWrappers); -// log.info("Valid Search " + bbbb); -// -// -// for (DeviceWrapper dw : deviceWrappers) { -// log.debug(dw.getDevice().getDescription()); -// log.debug(dw.getDevice().getDeviceIdentifier()); -// } -// } -// -// @Test -// public void doInvalidLocationSearch() throws Exception{ -// -// SearchContext context = new SearchContext(); -// List conditions = new ArrayList<>(); -// -// Condition cond = new Condition(); -// cond.setKey("LOCATION"); -// cond.setOperator("="); -// cond.setValue("Colombo"); -// cond.setState(Condition.State.AND); -// conditions.add(cond); -// -// context.setConditions(conditions); -// -// SearchManagerService service = new SearchManagerServiceImpl(); -// List deviceWrappers = service.search(context); -// -// Gson gson = new Gson(); -// String bbbb = gson.toJson(deviceWrappers); -// log.info("Invalid Search " + bbbb); -// -// -// for (DeviceWrapper dw : deviceWrappers) { -// log.debug(dw.getDevice().getDescription()); -// log.debug(dw.getDevice().getDeviceIdentifier()); -// } -// } + @Test + public void doValidLocationSearch() throws Exception{ + + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("LOCATION"); + cond.setOperator("="); + cond.setValue("Karan"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List deviceWrappers = service.search(context); + + Gson gson = new Gson(); + String bbbb = gson.toJson(deviceWrappers); + log.info("Valid Search " + bbbb); + + + for (DeviceWrapper dw : deviceWrappers) { + log.debug(dw.getDevice().getDescription()); + log.debug(dw.getDevice().getDeviceIdentifier()); + } + } + + @Test + public void doInvalidLocationSearch() throws Exception{ + + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("LOCATION"); + cond.setOperator("="); + cond.setValue("Colombo"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List deviceWrappers = service.search(context); + + Gson gson = new Gson(); + String bbbb = gson.toJson(deviceWrappers); + log.info("Invalid Search " + bbbb); + + + for (DeviceWrapper dw : deviceWrappers) { + log.debug(dw.getDevice().getDescription()); + log.debug(dw.getDevice().getDeviceIdentifier()); + } + } + + @Test + public void doStringSearch() throws Exception{ + + SearchContext context = new SearchContext(); + List conditions = new ArrayList<>(); + + Condition cond = new Condition(); + cond.setKey("deviceModel"); + cond.setOperator("="); + cond.setValue("SM-T520"); + cond.setState(Condition.State.AND); + conditions.add(cond); + + context.setConditions(conditions); + + SearchManagerService service = new SearchManagerServiceImpl(); + List deviceWrappers = service.search(context); + + Gson gson = new Gson(); + String bbbb = gson.toJson(deviceWrappers); + log.info("Invalid Search " + bbbb); + + + for (DeviceWrapper dw : deviceWrappers) { + log.debug(dw.getDevice().getDescription()); + log.debug(dw.getDevice().getDeviceIdentifier()); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index 23a88af804..7d6159a87f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -451,6 +451,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( ZIP VARCHAR(10) NULL, STATE VARCHAR(45) NULL, COUNTRY VARCHAR(45) NULL, + UPDATE_TIMESTAMP BIGINT(15) NOT NULL, PRIMARY KEY (ID), CONSTRAINT DM_DEVICE_LOCATION_DEVICE FOREIGN KEY (DEVICE_ID) @@ -477,6 +478,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, PLUGGED_IN INT(1) NULL, + UPDATE_TIMESTAMP BIGINT(15) NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE FOREIGN KEY (DEVICE_ID) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag new file mode 100644 index 0000000000..4d5bd9973f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag @@ -0,0 +1,87 @@ +<% +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +var uri = request.getRequestURI(); +var uriMatcher = new URIMatcher(String(uri)); + +var log = new Log("api/device-api.jag"); +var constants = require("/app/modules/constants.js"); +var utility = require("/app/modules/utility.js").utility; +var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); +var serviceInvokers = require("/app/modules/backend-service-invoker.js").backendServiceInvoker; + +var user = session.get(constants.USER_SESSION_KEY); +var result; + +response.contentType = 'application/json'; + +if (!user) { + response.sendRedirect("/devicemgt/login?#login-required"); + exit(); +} else { + if (uriMatcher.match("/{context}/api/groups")) { + var url = request.getParameter("url"); + var draw = request.getParameter("draw"); + var length = request.getParameter("length"); + var start = request.getParameter("start"); + var search = request.getParameter("search[value]"); + var groupName = request.getParameter("columns[1][search][value]"); + var owner = request.getParameter("columns[2][search][value]"); + var targetURL; + + function appendQueryParam(url, queryParam, value) { + if (url.indexOf("?") > 0) { + return url + "&" + queryParam + "=" + value; + } + return url + "?" + queryParam + "=" + value; + } + + targetURL = devicemgtProps.httpsURL + request.getParameter("url"); + targetURL = appendQueryParam(targetURL, "start", start); + targetURL = appendQueryParam(targetURL, "length", length); + + if (search && search !== "") { + targetURL = appendQueryParam(targetURL, "search", search); + } + + if (groupName && groupName !== "") { + targetURL = appendQueryParam(targetURL, "group-name", groupName); + } + + if (owner && owner !== "") { + targetURL = appendQueryParam(targetURL, "user", owner); + } + + serviceInvokers.XMLHttp.get( + targetURL, function (responsePayload) { + response.status = 200; + result = responsePayload; + }, + function (responsePayload) { + response.status = responsePayload.status; + result = responsePayload.responseText; + }); + } +} + +if (result) { + print(result); +} + +%> \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/stats-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/stats-api.jag deleted file mode 100644 index 5c8fd94355..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/stats-api.jag +++ /dev/null @@ -1,124 +0,0 @@ -<% -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -var uri = request.getRequestURI(); -var uriMatcher = new URIMatcher(String(uri)); - -var log = new Log("api/stats-api.jag"); - -var from = request.getParameter("from"); -var to = request.getParameter("to"); - -var constants = require("/app/modules/constants.js"); -var utility = require("/app/modules/utility.js").utility; -var devicemgtProps = require('/app/conf/devicemgt-props.js').config(); - -var deviceCloudGroupService = devicemgtProps["httpsURL"] + "/common/group_manager"; -var deviceCloudDeviceService = devicemgtProps["httpsURL"] + "/common/device_manager"; -var deviceCloudStatsService = devicemgtProps["httpsURL"] + "/common/stats_manager"; - -var stats = {}; -var deviceId; -var deviceType; - -var responseProcessor = require('utils').response; -response.contentType = 'application/json'; - -var user = session.get(constants.USER_SESSION_KEY); - -if (!user) { - response = responseProcessor.buildErrorResponse(response, 401, "Unauthorized"); -} else { - if (uriMatcher.match("/{context}/api/stats")) { - deviceId = request.getParameter("deviceId"); - deviceType = request.getParameter("deviceType"); - - getDeviceData(deviceType, deviceId); - - } else if (uriMatcher.match("/{context}/api/stats/group")) { - var groupId = request.getParameter("groupId"); - - //URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/device/all - var endPoint = deviceCloudGroupService + "/group/id/" + groupId + "/device/all"; - var data = {"username": user}; - var devices = get(endPoint, data, "json").data; - - for (var device in devices) { - deviceId = devices[device].deviceIdentifier; - deviceType = devices[device].type; - getDeviceData(deviceType, deviceId); - } - } - log.info(stats); - // returning the result. - if (stats) { - print(stats); - } -} - -function getDeviceData(deviceType, deviceId) { - //URL: GET https://localhost:9443/devicecloud/device_manager/device/type/{type}/identifier/{identifier} - var endPoint = deviceCloudDeviceService + "/device/type/" + deviceType + "/identifier/" + deviceId; - var data = {"username": user}; - var device = get(endPoint, data, "json").data; - log.info(device); - if (!device) { - return; - } - var uname = device.enrolmentInfo.owner; - - var analyticStreams = utility.getDeviceTypeConfig(deviceType)["analyticStreams"]; - - if (analyticStreams) { - var streamTableName; - for (var stream in analyticStreams) { - streamTableName = analyticStreams[stream]["table"]; - if (stats[streamTableName] == null) { - stats[streamTableName] = []; - } - stats[streamTableName].push({ - "device": device.name, - "stats": getSensorData(streamTableName, analyticStreams[stream]["ui_unit"]["data"][1]["column"]["name"], uname, device.type, device.deviceIdentifier, from, to), - "stream": analyticStreams[stream] - }); - } - } -} - -function getSensorData(table, column, user, type, deviceIdentifier, from, to) { - - var fetchedData = []; - - try { - ///stats/device/type/{type}/identifier/{identifier} - var endPoint = deviceCloudStatsService + "/stats/device/type/" + type + "/identifier/" + deviceIdentifier; - var query = "?table=" + encodeURIComponent(table) - + "&column=" + encodeURIComponent(column) - + "&username=" + encodeURIComponent(user) - + "&from=" + from - + "&to=" + to; - endPoint = endPoint + query; - fetchedData = get(endPoint, {}, "json").data; - return fetchedData; - } catch (error) { - log.error(error); - } -} - -%> diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js index 3d050b38a1..31fac7176d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js @@ -54,7 +54,7 @@ var groupModule = {}; }; groupModule.getGroupDeviceCount = function (groupName, owner) { - endPoint = groupServiceEndpoint + "/" + owner + "/" + groupName + "/devices/count"; + endPoint = groupServiceEndpoint + "/owner/" + owner + "/name/" + groupName + "/devices/count"; return serviceInvokers.XMLHttp.get( endPoint, function (responsePayload) { return responsePayload; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs index 2966fa09a2..b800c8777e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs @@ -55,6 +55,11 @@ {{/zone}} {{#zone "content"}} +
+
+ {{title}} +
+
@@ -275,7 +280,7 @@