From 2fb42518b63db4e9e127e7019cee7bcc8bf5dd8e Mon Sep 17 00:00:00 2001 From: geethkokila Date: Wed, 27 Apr 2016 10:26:47 +0530 Subject: [PATCH 1/2] Adding the changes for the device group with policy. --- .../mgt/common/group/mgt/DeviceGroup.java | 11 + .../mgt/dao/impl/DeviceDetailsDAOImpl.java | 4 +- .../core/group/mgt/DeviceGroupBuilder.java | 1 + .../mgt/core/group/mgt/dao/GroupDAO.java | 8 + .../mgt/core/group/mgt/dao/GroupDAOImpl.java | 26 ++ .../search/mgt/impl/QueryBuilderImpl.java | 26 +- .../mgt/core/search/mgt/impl/Utils.java | 84 +++-- .../GroupManagementProviderService.java | 18 ++ .../GroupManagementProviderServiceImpl.java | 40 ++- .../src/test/resources/sql/h2.sql | 58 +++- .../policy/mgt/common/DeviceGroupWrapper.java | 61 ++++ .../carbon/policy/mgt/common/PIPDevice.java | 11 + .../wso2/carbon/policy/mgt/common/Policy.java | 14 + .../policy/mgt/common/PolicyFilter.java | 5 + .../carbon/policy/mgt/core/dao/PolicyDAO.java | 7 +- .../mgt/core/dao/impl/PolicyDAOImpl.java | 71 ++++- .../mgt/core/impl/PolicyFilterImpl.java | 31 +- .../core/impl/PolicyInformationPointImpl.java | 25 +- .../mgt/core/mgt/impl/PolicyManagerImpl.java | 39 ++- .../mgt/core/util/PolicyManagerUtil.java | 10 + .../mgt/core/BasePolicyManagementDAOTest.java | 2 + .../src/test/resources/sql/CreateH2TestDB.sql | 298 ++++++++++++++---- .../main/resources/dbscripts/cdm/mysql.sql | 52 +++ 23 files changed, 768 insertions(+), 134 deletions(-) create mode 100644 components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/DeviceGroupWrapper.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java index a7263c3a69..cb404d1b92 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java @@ -28,6 +28,7 @@ import java.util.List; @XmlRootElement public class DeviceGroup implements Serializable { + private int id; private String description; private String name; private Long dateOfCreation; @@ -36,6 +37,15 @@ public class DeviceGroup implements Serializable { private List users; private List roles; + @XmlElement + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + @XmlElement public String getDescription() { return description; @@ -101,6 +111,7 @@ public class DeviceGroup implements Serializable { protected DeviceGroup getGroup() { DeviceGroup deviceGroup = new DeviceGroup(); + deviceGroup.setId(getId()); deviceGroup.setDescription(getDescription()); deviceGroup.setName(getName()); deviceGroup.setDateOfCreation(getDateOfCreation()); 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 23c73b936b..cd901b2238 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 @@ -83,7 +83,9 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO { public void addDeviceProperties(Map propertyMap, int deviceId) throws DeviceDetailsMgtDAOException { if (propertyMap.isEmpty()) { - log.warn("Property map of device id :" + deviceId + " is empty."); + if(log.isDebugEnabled()) { + log.debug("Property map of device id :" + deviceId + " is empty."); + } return; } Connection conn; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java index ce4183e9b3..c1e37bbd6d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java @@ -36,6 +36,7 @@ public class DeviceGroupBuilder extends DeviceGroup { * @param deviceGroup to decorate */ public DeviceGroupBuilder(DeviceGroup deviceGroup) { + this.setId(deviceGroup.getId()); this.setDescription(deviceGroup.getDescription()); this.setName(deviceGroup.getName()); this.setDateOfCreation(deviceGroup.getDateOfCreation()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java index 10ca96f72a..7e8132fedf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java @@ -82,6 +82,14 @@ public interface GroupDAO { */ DeviceGroupBuilder getGroup(String groupName, String owner, int tenantId) throws GroupManagementDAOException; + /** + * Get the groups of device with device id provided + * @param deviceId + * @return + * @throws GroupManagementDAOException + */ + List getGroups(int deviceId, int tenantId) throws GroupManagementDAOException; + /** * Get the list of Device Groups in tenant. * 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 819d676dc7..b509f136aa 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 @@ -178,6 +178,32 @@ public class GroupDAOImpl implements GroupDAO { } } + @Override + public List getGroups(int deviceId, int tenantId) throws GroupManagementDAOException { + + PreparedStatement stmt = null; + ResultSet resultSet = null; + List deviceGroupBuilders = new ArrayList<>(); + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT G.ID, G.GROUP_NAME, G.DESCRIPTION, G.DATE_OF_CREATE, G.DATE_OF_LAST_UPDATE, \n" + + "G.OWNER FROM DM_GROUP AS G INNER JOIN DM_DEVICE_GROUP_MAP AS GM ON G.ID = GM.GROUP_ID " + + "WHERE GM.DEVICE_ID = ? AND GM.TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + stmt.setInt(2, tenantId); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + deviceGroupBuilders.add(GroupManagementDAOUtil.loadGroup(resultSet)); + } + } catch (SQLException e) { + throw new GroupManagementDAOException("Error occurred while obtaining information of Device Groups ", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroupBuilders; + } + @Override public List getGroups(int startIndex, int rowCount, int tenantId) throws GroupManagementDAOException { 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 cf4d2a03d6..eaca48451f 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 @@ -44,14 +44,14 @@ public class QueryBuilderImpl implements QueryBuilder { List orColumns = new ArrayList<>(); List otherANDColumns = new ArrayList<>(); List otherORColumns = new ArrayList<>(); - Condition locConditon = new Condition(); + Condition locCondition = new Condition(); if (conditions.size() == 1) { if (conditions.get(0).getKey().equalsIgnoreCase(Constants.LOCATION)) { - locConditon = conditions.get(0); - } else if (Utils.getDeviceDetailsColumnNames().containsKey(conditions.get(0).getKey()) || - Utils.getDeviceLocationColumnNames().containsKey(conditions.get(0).getKey())) { + locCondition = conditions.get(0); + } else if (Utils.checkDeviceDetailsColumns(conditions.get(0).getKey()) || + Utils.checkDeviceLocationColumns(conditions.get(0).getKey())) { andColumns.add(conditions.get(0)); } else { otherANDColumns.add(conditions.get(0)); @@ -59,9 +59,9 @@ public class QueryBuilderImpl implements QueryBuilder { } else { for (Condition con : conditions) { if (con.getKey().equalsIgnoreCase(Constants.LOCATION)) { - locConditon = con; - } else if (Utils.getDeviceDetailsColumnNames().containsKey(con.getKey()) || - Utils.getDeviceLocationColumnNames().containsKey(con.getKey())) { + locCondition = con; + } else if (Utils.checkDeviceDetailsColumns(con.getKey()) || + Utils.checkDeviceLocationColumns(con.getKey())) { if (con.getState().equals(Condition.State.AND)) { andColumns.add(con); } else if (con.getState().equals(Condition.State.OR)) { @@ -92,8 +92,8 @@ public class QueryBuilderImpl implements QueryBuilder { if (!otherORColumns.isEmpty()) { queries.put(Constants.PROP_OR, this.processORProperties(otherORColumns)); } - if (locConditon != null && locConditon.getValue() != null) { - queries.put(Constants.LOCATION, this.processLocation(locConditon)); + if (locCondition != null && locCondition.getValue() != null) { + queries.put(Constants.LOCATION, this.processLocation(locCondition)); } if (log.isDebugEnabled()) { @@ -112,10 +112,10 @@ public class QueryBuilderImpl implements QueryBuilder { String querySuffix = ""; for (Condition con : conditions) { - if (Utils.getDeviceDetailsColumnNames().containsKey(con.getKey())) { + if (Utils.checkDeviceDetailsColumns(con.getKey())) { querySuffix = querySuffix + " AND DD." + Utils.getDeviceDetailsColumnNames().get(con.getKey()) + con.getOperator() + con.getValue(); - } else if (Utils.getDeviceLocationColumnNames().containsKey(con.getKey())) { + } else if (Utils.checkDeviceLocationColumns(con.getKey())) { querySuffix = querySuffix + " AND DL." + Utils.getDeviceLocationColumnNames().get(con.getKey()) + con.getOperator() + con.getValue(); } @@ -130,10 +130,10 @@ public class QueryBuilderImpl implements QueryBuilder { String querySuffix = ""; for (Condition con : conditions) { - if (Utils.getDeviceDetailsColumnNames().containsKey(con.getKey())) { + if (Utils.checkDeviceDetailsColumns(con.getKey())) { querySuffix = querySuffix + " OR DD." + Utils.getDeviceDetailsColumnNames().get(con.getKey()) + con.getOperator() + con.getValue(); - } else if (Utils.getDeviceLocationColumnNames().containsKey(con.getKey())) { + } else if (Utils.checkDeviceLocationColumns(con.getKey())) { querySuffix = querySuffix + " OR DL." + Utils.getDeviceLocationColumnNames().get(con.getKey()) + con.getOperator() + con.getValue(); } 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 cef647d727..bc69e76033 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 @@ -28,43 +28,65 @@ import java.util.Map; public class Utils { - public static Map getDeviceDetailsColumnNames() { + private static Map genericColumnsMap = new HashMap<>(); + private static Map locationColumnsMap = new HashMap<>(); + + static { + + genericColumnsMap.put("deviceModel", "DEVICE_MODEL"); + genericColumnsMap.put("vendor", "VENDOR"); + genericColumnsMap.put("osVersion", "OS_VERSION"); + genericColumnsMap.put("batteryLevel", "BATTERY_LEVEL"); + genericColumnsMap.put("internalTotalMemory", "INTERNAL_TOTAL_MEMORY"); + genericColumnsMap.put("internalAvailableMemory", "INTERNAL_AVAILABLE_MEMORY"); + genericColumnsMap.put("externalTotalMemory", "EXTERNAL_TOTAL_MEMORY"); + genericColumnsMap.put("externalAvailableMemory", "EXTERNAL_AVAILABLE_MEMORY"); + genericColumnsMap.put("connectionType", "CONNECTION_TYPE"); + genericColumnsMap.put("ssid", "SSID"); + genericColumnsMap.put("cpuUsage", "CPU_USAGE"); + genericColumnsMap.put("totalRAMMemory", "TOTAL_RAM_MEMORY"); + genericColumnsMap.put("availableRAMMemory", "AVAILABLE_RAM_MEMORY"); + genericColumnsMap.put("pluggedIn", "PLUGGED_IN"); + + + locationColumnsMap.put("latitude", "LATITUDE"); + locationColumnsMap.put("longitude", "LONGITUDE"); + locationColumnsMap.put("street1", "STREET1"); + locationColumnsMap.put("street2", "STREET2"); + locationColumnsMap.put("city", "CITY"); + locationColumnsMap.put("state", "ZIP"); + locationColumnsMap.put("zip", "STATE"); + locationColumnsMap.put("country", "COUNTRY"); + + } - Map colonmsMap = new HashMap<>(); - - colonmsMap.put("deviceModel", "DEVICE_MODEL"); - colonmsMap.put("vendor", "VENDOR"); - colonmsMap.put("osVersion", "OS_VERSION"); - colonmsMap.put("batteryLevel", "BATTERY_LEVEL"); - colonmsMap.put("internalTotalMemory", "INTERNAL_TOTAL_MEMORY"); - colonmsMap.put("internalAvailableMemory", "INTERNAL_AVAILABLE_MEMORY"); - colonmsMap.put("externalTotalMemory", "EXTERNAL_TOTAL_MEMORY"); - colonmsMap.put("externalAvailableMemory", "EXTERNAL_AVAILABLE_MEMORY"); - colonmsMap.put("connectionType", "CONNECTION_TYPE"); - colonmsMap.put("ssid", "SSID"); - colonmsMap.put("cpuUsage", "CPU_USAGE"); - colonmsMap.put("totalRAMMemory", "TOTAL_RAM_MEMORY"); - colonmsMap.put("availableRAMMemory", "AVAILABLE_RAM_MEMORY"); - colonmsMap.put("pluggedIn", "PLUGGED_IN"); - - return colonmsMap; + public static Map getDeviceDetailsColumnNames() { + return genericColumnsMap; } public static Map getDeviceLocationColumnNames() { - Map colonmsMap = new HashMap<>(); - - colonmsMap.put("latitude", "LATITUDE"); - colonmsMap.put("longitude", "LONGITUDE"); - colonmsMap.put("street1", "STREET1"); - colonmsMap.put("street2", "STREET2"); - colonmsMap.put("city", "CITY"); - colonmsMap.put("state", "ZIP"); - colonmsMap.put("zip", "STATE"); - colonmsMap.put("country", "COUNTRY"); - - return colonmsMap; + return locationColumnsMap; } + public static boolean checkDeviceDetailsColumns(String str) { + if (genericColumnsMap.containsKey(str)) { + return true; + } + if (genericColumnsMap.containsValue(str)) { + return true; + } + return false; + } + + public static boolean checkDeviceLocationColumns(String str) { + if (locationColumnsMap.containsKey(str)) { + return true; + } + if (locationColumnsMap.containsValue(str)) { + return true; + } + return false; + } public static List convertStringToList(String str) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java index 6c64b7cf03..b9ffa03340 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java @@ -25,6 +25,7 @@ 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.group.mgt.DeviceGroupBuilder; import java.util.List; @@ -73,6 +74,15 @@ public interface GroupManagementProviderService { */ DeviceGroup getGroup(String groupName, String owner) throws GroupManagementException; + + /** + * Get the device group provided the device group id. + * @param groupId + * @return + * @throws GroupManagementException + */ + DeviceGroup getGroup(int groupId) throws GroupManagementException; + /** * Get list of device groups matched with %groupName% * @@ -288,4 +298,12 @@ public interface GroupManagementProviderService { */ List getGroups(String username, String permission) throws GroupManagementException; + /** + * Get the group of device. + * @param deviceIdentifier + * @return + * @throws GroupManagementException + */ + List getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException; + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index fabbaceb96..e20e033735 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -22,6 +22,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; @@ -190,7 +191,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid return deviceGroupBuilder; } - @SuppressWarnings("Duplicates") + private DeviceGroupBuilder getGroupBuilder(int groupId) throws GroupManagementException { DeviceGroupBuilder groupBroker; try { @@ -210,6 +211,19 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid return groupBroker; } + /** + * {@inheritDoc} + */ + @Override + public DeviceGroup getGroup(int groupId) throws GroupManagementException { + DeviceGroupBuilder groupBroker = this.getGroupBuilder(groupId); + if (groupBroker != null) { + groupBroker.setUsers(this.getUsers(groupBroker.getGroupId())); + groupBroker.setRoles(this.getRoles(groupBroker.getGroupId())); + } + return groupBroker.getGroup(); + } + /** * {@inheritDoc} */ @@ -763,6 +777,30 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } } + @Override + public List getGroups(DeviceIdentifier deviceIdentifier) throws GroupManagementException { + DeviceManagementProviderService managementProviderService = new DeviceManagementProviderServiceImpl(); + List deviceGroups = new ArrayList<>(); + try { + Device device = managementProviderService.getDevice(deviceIdentifier); + GroupManagementDAOFactory.openConnection(); + List builders = groupDAO.getGroups(device.getId(), + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + for (DeviceGroupBuilder d : builders){ + deviceGroups.add(d.getGroup()); + } + } catch (DeviceManagementException e) { + throw new GroupManagementException("Error occurred while retrieving the device details.", e); + } catch (GroupManagementDAOException e) { + throw new GroupManagementException("Error occurred while retrieving device groups.", e); + } catch (SQLException e) { + throw new GroupManagementException("Error occurred while opening database connection.", e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + return deviceGroups; + } + private DeviceGroupBuilder extractNewGroupFromRole(Map groups, String role) throws GroupManagementException { try { 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 793fe551d9..23a88af804 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 @@ -21,6 +21,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( ID INTEGER auto_increment NOT NULL, SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, CERTIFICATE BLOB DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID) ); @@ -218,7 +219,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( ID INT(11) NOT NULL AUTO_INCREMENT, PROFILE_ID INT(11) NOT NULL, - FEATURE_CODE VARCHAR(30) NOT NULL, + FEATURE_CODE VARCHAR(100) NOT NULL, DEVICE_TYPE_ID INT NOT NULL, TENANT_ID INT(11) NOT NULL , CONTENT BLOB NULL DEFAULT NULL, @@ -350,7 +351,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( ID INT NOT NULL AUTO_INCREMENT, COMPLIANCE_STATUS_ID INT NOT NULL, TENANT_ID INT NOT NULL, - FEATURE_CODE VARCHAR(15) NOT NULL, + FEATURE_CODE VARCHAR(100) NOT NULL, STATUS INT NULL, PRIMARY KEY (ID), CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS @@ -385,7 +386,7 @@ CREATE TABLE IF NOT EXISTS DM_APPLICATION ( LOCATION_URL VARCHAR(100) DEFAULT NULL, IMAGE_URL VARCHAR(100) DEFAULT NULL, APP_PROPERTIES BLOB NULL, - MEMORY_USAGE DECIMAL(5) NULL, + MEMORY_USAGE INTEGER(10) NULL, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); @@ -483,3 +484,54 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( ON DELETE NO ACTION ON UPDATE NO ACTION ); + + +-- POLICY AND DEVICE GROUP MAPPING -- + +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_GROUP_ID INT NOT NULL, + POLICY_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_DEVICE_GROUP_POLICY + FOREIGN KEY (DEVICE_GROUP_ID) + REFERENCES DM_GROUP (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY + FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID) + REFERENCES DM_POLICY (ID , ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + +-- END OF POLICY AND DEVICE GROUP MAPPING -- + +CREATE VIEW DEVICES_VIEW_1 AS +SELECT +DEVICE_INFO.DEVICE_ID, +DEVICE_INFO.PLATFORM, +DEVICE_INFO.OWNERSHIP, +DEVICE_INFO.CONNECTIVITY_STATUS, +IFNULL(DEVICE_WITH_POLICY_INFO.POLICY_ID, -1) AS POLICY_ID, +IFNULL(DEVICE_WITH_POLICY_INFO.IS_COMPLIANT, -1) AS IS_COMPLIANT, +DEVICE_INFO.TENANT_ID +FROM +(SELECT +DM_DEVICE.ID AS DEVICE_ID, +DM_DEVICE_TYPE.NAME AS PLATFORM, +DM_ENROLMENT.OWNERSHIP AS OWNERSHIP, +DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS, +DM_DEVICE.TENANT_ID AS TENANT_ID +FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT +WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO +LEFT JOIN +(SELECT +DEVICE_ID, +POLICY_ID, +STATUS AS IS_COMPLIANT +FROM +DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO +ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID +ORDER BY DEVICE_INFO.DEVICE_ID; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/DeviceGroupWrapper.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/DeviceGroupWrapper.java new file mode 100644 index 0000000000..cd6c63b40a --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/DeviceGroupWrapper.java @@ -0,0 +1,61 @@ +/* + * 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.policy.mgt.common; + +public class DeviceGroupWrapper { + + private int id; + private String name; + private String owner; + private int tenantId; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } +} + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PIPDevice.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PIPDevice.java index a77eb02ec2..c3ad90dbf8 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PIPDevice.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PIPDevice.java @@ -21,9 +21,11 @@ package org.wso2.carbon.policy.mgt.common; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import java.sql.Timestamp; +import java.util.List; import java.util.Map; //TODO : @@ -38,6 +40,7 @@ public class PIPDevice { private String latitude; private String longitude; private Timestamp timestamp; + private List deviceGroups; /*This will be used to record attributes to which would come from other PDPs*/ Map attributes; @@ -121,4 +124,12 @@ public class PIPDevice { public void setDeviceIdentifier(DeviceIdentifier deviceIdentifier) { this.deviceIdentifier = deviceIdentifier; } + + public List getDeviceGroups() { + return deviceGroups; + } + + public void setDeviceGroups(List deviceGroups) { + this.deviceGroups = deviceGroups; + } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java index c5b8ed303d..25c5f48cc4 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java @@ -63,6 +63,11 @@ public class Policy implements Comparable, Serializable { private Map attributes; + /*This will keep the list of groups to which the policy will be applied. */ + + private List deviceGroups; + + @XmlElement public int getId() { return id; @@ -217,6 +222,15 @@ public class Policy implements Comparable, Serializable { } + @XmlElement + public List getDeviceGroups() { + return deviceGroups; + } + + public void setDeviceGroups(List deviceGroups) { + this.deviceGroups = deviceGroups; + } + @Override public int compareTo(Policy o) { if (this.priorityId == o.priorityId) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyFilter.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyFilter.java index 44303782ff..f82e252bf6 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyFilter.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyFilter.java @@ -19,12 +19,17 @@ package org.wso2.carbon.policy.mgt.common; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; + import java.util.List; +import java.util.Map; public interface PolicyFilter { List filterActivePolicies(List policies); + List filterDeviceGroupsPolicies(Map groupMap, List policies); + List filterRolesBasedPolicies(String roles[], List policies); List filterOwnershipTypeBasedPolicies(String ownershipType, List policies); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java index facb7528c9..ce519e135f 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java @@ -20,6 +20,7 @@ package org.wso2.carbon.policy.mgt.core.dao; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.policy.mgt.common.Criterion; +import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyCriterion; @@ -41,7 +42,7 @@ public interface PolicyDAO { */ Policy addPolicyToRole(List roleNames, Policy policy) throws PolicyManagerDAOException; - Policy updateRolesOfPolicy(List rolesToAdd, Policy policy) throws PolicyManagerDAOException; + Policy updateRolesOfPolicy(List rolesToAdd, Policy policy) throws PolicyManagerDAOException; /** * This method is used to add/update the users associated with the policy. @@ -56,6 +57,10 @@ public interface PolicyDAO { Policy addPolicyToDevice(List devices, Policy policy) throws PolicyManagerDAOException; + void addDeviceGroupsToPolicy(Policy policy) throws PolicyManagerDAOException; + + List getDeviceGroupsOfPolicy(int policyId) throws PolicyManagerDAOException; + boolean updatePolicyPriorities(List policies) throws PolicyManagerDAOException; void activatePolicy(int policyId) throws PolicyManagerDAOException; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java index 7fd9d04d75..9641dbc516 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java @@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.policy.mgt.common.Criterion; +import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyCriterion; import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO; @@ -272,6 +273,64 @@ public class PolicyDAOImpl implements PolicyDAO { return policy; } + @Override + public void addDeviceGroupsToPolicy(Policy policy) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + List deviceGroupWrappers = policy.getDeviceGroups(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + conn = this.getConnection(); + String query = "INSERT INTO DM_DEVICE_GROUP_POLICY (DEVICE_GROUP_ID, POLICY_ID, TENANT_ID) VALUES (?, ?, ?)"; + stmt = conn.prepareStatement(query); + for (DeviceGroupWrapper wrapper : deviceGroupWrappers) { + stmt.setInt(1, wrapper.getId()); + stmt.setInt(2, policy.getId()); + stmt.setInt(3, tenantId); + stmt.addBatch(); + } + stmt.executeBatch(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while adding the device group details to the policy.", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public List getDeviceGroupsOfPolicy(int policyId) throws PolicyManagerDAOException { + + List deviceGroupWrappers = new ArrayList<>(); + Connection conn; + PreparedStatement stmt = null; + ResultSet resultSet = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = "SELECT * FROM DM_DEVICE_GROUP_POLICY WHERE TENANT_ID = ? AND POLICY_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, tenantId); + stmt.setInt(2, policyId); + resultSet = stmt.executeQuery(); + + while (resultSet.next()) { + DeviceGroupWrapper dgw = new DeviceGroupWrapper(); + dgw.setId(resultSet.getInt("DEVICE_GROUP_ID")); + dgw.setTenantId(tenantId); + deviceGroupWrappers.add(dgw); + } + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while reading the device groups form database.", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return deviceGroupWrappers; + } + @Override public boolean updatePolicyPriorities(List policies) throws PolicyManagerDAOException { Connection conn; @@ -442,7 +501,7 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); String query = "INSERT INTO DM_CRITERIA (TENANT_ID, NAME) VALUES (?, ?)"; - stmt = conn.prepareStatement(query, new String[] {"id"}); + stmt = conn.prepareStatement(query, new String[]{"id"}); stmt.setInt(1, tenantId); stmt.setString(2, criteria.getName()); stmt.executeUpdate(); @@ -622,7 +681,7 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); String query = "INSERT INTO DM_POLICY_CRITERIA (CRITERIA_ID, POLICY_ID) VALUES (?, ?)"; - stmt = conn.prepareStatement(query, new String[] {"id"}); + stmt = conn.prepareStatement(query, new String[]{"id"}); List criteria = policy.getPolicyCriterias(); for (PolicyCriterion criterion : criteria) { @@ -1322,6 +1381,12 @@ public class PolicyDAOImpl implements PolicyDAO { stmt.setInt(1, policyId); stmt.executeUpdate(); + + String deleteDeviceGroups = "DELETE FROM DM_DEVICE_GROUP_POLICY WHERE POLICY_ID = ?"; + stmt = conn.prepareStatement(deleteDeviceGroups); + stmt.setInt(1, policyId); + stmt.executeUpdate(); + if (log.isDebugEnabled()) { log.debug("Policy (" + policyId + ") related configs deleted from database."); } @@ -1348,7 +1413,7 @@ public class PolicyDAOImpl implements PolicyDAO { conn = this.getConnection(); String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," + "UPDATED, ACTIVE, DESCRIPTION) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; - stmt = conn.prepareStatement(query, new String[] {"id"}); + stmt = conn.prepareStatement(query, new String[]{"id"}); stmt.setString(1, policy.getPolicyName()); stmt.setInt(2, policy.getProfile().getProfileId()); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java index 0bd4efe3f5..0d4770a14c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyFilterImpl.java @@ -21,12 +21,16 @@ package org.wso2.carbon.policy.mgt.core.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyFilter; import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; public class PolicyFilterImpl implements PolicyFilter { @@ -59,6 +63,29 @@ public class PolicyFilterImpl implements PolicyFilter { return temp; } + @Override + public List filterDeviceGroupsPolicies(Map groupMap, List policies) { + + List temp = new ArrayList(); + Map policyMap = new HashMap<>(); + for (Policy policy : policies) { + List wrappers = policy.getDeviceGroups(); + if (PolicyManagementConstants.ANY.equalsIgnoreCase(wrappers.get(0).getName())) { + temp.add(policy); + policyMap.put(policy.getId(), policy); + continue; + } else { + for (DeviceGroupWrapper deviceGroupWrapper : wrappers) { + if (groupMap.containsKey(deviceGroupWrapper.getId()) && policyMap.containsKey(policy.getId())) { + temp.add(policy); + policyMap.put(policy.getId(), policy); + } + } + } + } + return temp; + } + @Override public List filterRolesBasedPolicies(String roles[], List policies) { @@ -68,7 +95,7 @@ public class PolicyFilterImpl implements PolicyFilter { log.debug("Names of policy went in to filterRolesBasedPolicies : " + policy.getPolicyName()); } log.debug("Roles passed to match."); - for(String role : roles){ + for (String role : roles) { log.debug("Role name passed : " + role); } } @@ -79,7 +106,7 @@ public class PolicyFilterImpl implements PolicyFilter { List tempRoles = policy.getRoles(); if (tempRoles.isEmpty()) { - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("Roles list is empty."); } temp.add(policy); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java index d3591b28e5..4da09fbb09 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyInformationPointImpl.java @@ -24,10 +24,14 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl; import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager; @@ -62,41 +66,35 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { public PIPDevice getDeviceData(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { PIPDevice pipDevice = new PIPDevice(); Device device; - DeviceType deviceType = new DeviceType(); deviceType.setName(deviceIdentifier.getType()); DeviceManagementProviderService deviceManagementService = new DeviceManagementProviderServiceImpl(); + GroupManagementProviderService groupManagementProviderService = new GroupManagementProviderServiceImpl(); try { device = deviceManagementService.getDevice(deviceIdentifier); - Thread.currentThread(); if (device != null) { - /*deviceManagementService.getDeviceType(deviceIdentifier.getType());*/ pipDevice.setDevice(device); pipDevice.setRoles(getRoleOfDevice(device)); pipDevice.setDeviceType(deviceType); pipDevice.setDeviceIdentifier(deviceIdentifier); pipDevice.setUserId(device.getEnrolmentInfo().getOwner()); pipDevice.setOwnershipType(device.getEnrolmentInfo().getOwnership().toString()); + pipDevice.setDeviceGroups(groupManagementProviderService.getGroups(pipDevice.getDeviceIdentifier())); - // TODO : Find a way to retrieve the timestamp and location (lat, long) of the device - // pipDevice.setLongitude(); - // pipDevice.setAltitude(); - // pipDevice.setTimestamp(); } else { - // Remove this - for (StackTraceElement ste : Thread.currentThread().getStackTrace()) { - log.debug("StackTraceElement : " + ste); - } throw new PolicyManagementException("Device details cannot be null."); } } catch (DeviceManagementException e) { String msg = "Error occurred when retrieving the data related to device from the database."; log.error(msg, e); throw new PolicyManagementException(msg, e); + } catch (GroupManagementException e) { + String msg = "Error occurred when retrieving the data related to device groups from the database."; + log.error(msg, e); + throw new PolicyManagementException(msg, e); } - return pipDevice; } @@ -128,6 +126,9 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { if (pipDevice.getUserId() != null && !pipDevice.getUserId().isEmpty()) { policies = policyFilter.filterUserBasedPolicies(pipDevice.getUserId(), policies); } + if (pipDevice.getDeviceGroups() != null && !pipDevice.getDeviceGroups().isEmpty()) { + + } if (log.isDebugEnabled()) { log.debug("No of policies selected for the device type : " + pipDevice.getDeviceType().getName() + " : " + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index 5c280c0baf..d2907ceef6 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -24,11 +24,15 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl; import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl; import org.wso2.carbon.policy.mgt.core.dao.*; @@ -86,6 +90,10 @@ public class PolicyManagerImpl implements PolicyManager { policyDAO.addPolicyToDevice(policy.getDevices(), policy); } + if (policy.getDeviceGroups() != null && !policy.getDeviceGroups().isEmpty()) { + policyDAO.addDeviceGroupsToPolicy(policy); + } + if (policy.getPolicyCriterias() != null) { List criteria = policy.getPolicyCriterias(); for (PolicyCriterion criterion : criteria) { @@ -164,8 +172,8 @@ public class PolicyManagerImpl implements PolicyManager { } // Check for the features to delete - for(ProfileFeature feature : existingProfileFeaturesList) { - if(!updateDFes.contains(feature.getFeatureCode())){ + for (ProfileFeature feature : existingProfileFeaturesList) { + if (!updateDFes.contains(feature.getFeatureCode())) { feturesToDelete.add(feature); } } @@ -191,9 +199,9 @@ public class PolicyManagerImpl implements PolicyManager { featureDAO.addProfileFeatures(newFeaturesList, profileId); } - if(!feturesToDelete.isEmpty()){ + if (!feturesToDelete.isEmpty()) { for (ProfileFeature pf : feturesToDelete) - featureDAO.deleteProfileFeatures(pf.getId()); + featureDAO.deleteProfileFeatures(pf.getId()); } policyDAO.deleteCriteriaAndDeviceRelatedConfigs(policy.getId()); @@ -211,6 +219,10 @@ public class PolicyManagerImpl implements PolicyManager { policyDAO.addPolicyToDevice(policy.getDevices(), previousPolicy); } + if (policy.getDeviceGroups() != null && !policy.getDeviceGroups().isEmpty()) { + policyDAO.addDeviceGroupsToPolicy(policy); + } + if (policy.getPolicyCriterias() != null) { List criteria = policy.getPolicyCriterias(); for (PolicyCriterion criterion : criteria) { @@ -593,12 +605,21 @@ public class PolicyManagerImpl implements PolicyManager { policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId())); policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId())); policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId())); + + List deviceGroupWrappers = policyDAO.getDeviceGroupsOfPolicy(policy.getId()); + if(!deviceGroupWrappers.isEmpty()){ + deviceGroupWrappers = this.getDeviceGroupNames(deviceGroupWrappers); + } + policy.setDeviceGroups(deviceGroupWrappers); + } Collections.sort(policyList); } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting all the policies.", e); } catch (SQLException e) { throw new PolicyManagementException("Error occurred while opening a connection to the data source", e); + } catch (GroupManagementException e) { + throw new PolicyManagementException("Error occurred while getting device groups.", e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -990,4 +1011,14 @@ public class PolicyManagerImpl implements PolicyManager { } } + private List getDeviceGroupNames(List groupWrappers) throws GroupManagementException { + GroupManagementProviderService groupManagementProviderService = new GroupManagementProviderServiceImpl(); + for (DeviceGroupWrapper wrapper : groupWrappers) { + DeviceGroup deviceGroup = groupManagementProviderService.getGroup(wrapper.getId()); + wrapper.setName(deviceGroup.getName()); + wrapper.setOwner(deviceGroup.getOwner()); + } + return groupWrappers; + } + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java index 26fd3db790..affc876388 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java @@ -26,6 +26,7 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; @@ -224,4 +225,13 @@ public class PolicyManagerUtil { return monitoringFrequency; } + + + public static Map convertDeviceGroupMap(List deviceGroups) { + Map groupMap = new HashMap<>(); + for (DeviceGroup dg: deviceGroups){ + groupMap.put(dg.getId(), dg); + } + return groupMap; + } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java index a01ff15567..cbf329f8c0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/BasePolicyManagementDAOTest.java @@ -30,6 +30,7 @@ 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.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; @@ -76,6 +77,7 @@ public abstract class BasePolicyManagementDAOTest { DeviceManagementDAOFactory.init(dataSource); PolicyManagementDAOFactory.init(dataSource); OperationManagementDAOFactory.init(dataSource); + GroupManagementDAOFactory.init(dataSource); } public void initiatePrivilegedCaronContext() throws Exception { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index 83c3142af4..23a88af804 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -6,38 +6,49 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( PRIMARY KEY (ID) ); +CREATE TABLE IF NOT EXISTS DM_GROUP ( + ID INTEGER AUTO_INCREMENT NOT NULL, + GROUP_NAME VARCHAR(100) DEFAULT NULL, + DESCRIPTION TEXT DEFAULT NULL, + DATE_OF_CREATE BIGINT DEFAULT NULL, + DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL, + OWNER VARCHAR(45) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); + +CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( + ID INTEGER auto_increment NOT NULL, + SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, + CERTIFICATE BLOB DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +); + CREATE TABLE IF NOT EXISTS DM_DEVICE ( ID INTEGER auto_increment NOT NULL, - DESCRIPTION TEXT NULL DEFAULT NULL, - NAME VARCHAR(100) NULL DEFAULT NULL, - DATE_OF_ENROLLMENT BIGINT NULL DEFAULT NULL, - DATE_OF_LAST_UPDATE BIGINT NULL DEFAULT NULL, - OWNERSHIP VARCHAR(45) NULL DEFAULT NULL, - STATUS VARCHAR(15) NULL DEFAULT NULL, - DEVICE_TYPE_ID INT(11) NULL DEFAULT NULL, - DEVICE_IDENTIFICATION VARCHAR(300) NULL DEFAULT NULL, - OWNER VARCHAR(45) NULL DEFAULT NULL, + DESCRIPTION TEXT DEFAULT NULL, + NAME VARCHAR(100) DEFAULT NULL, + DEVICE_TYPE_ID INT(11) DEFAULT NULL, + DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID), CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER NOT NULL, - OWNER VARCHAR(50) NOT NULL, - OWNERSHIP VARCHAR(45) NULL DEFAULT NULL, - STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL, - DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL, - TENANT_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER DEFAULT NULL, + GROUP_ID INTEGER DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID), + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) + REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); - CREATE TABLE IF NOT EXISTS DM_OPERATION ( ID INTEGER AUTO_INCREMENT NOT NULL, TYPE VARCHAR(50) NOT NULL, @@ -81,6 +92,20 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_OPERATION ( DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); +CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OWNER VARCHAR(50) NOT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, + STATUS VARCHAR(50) NULL, + DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( ID INTEGER AUTO_INCREMENT NOT NULL, ENROLMENT_ID INTEGER NOT NULL, @@ -95,29 +120,17 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER NOT NULL, + ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, OPERATION_RESPONSE BLOB DEFAULT NULL, PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_operation_response_device FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES + DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATIONS ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER NOT NULL, - APPLICATIONS BLOB DEFAULT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_applications_device FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - ---- POLICY RELATED TABLES ---- - - - +-- POLICY RELATED TABLES -- CREATE TABLE IF NOT EXISTS DM_PROFILE ( ID INT NOT NULL AUTO_INCREMENT , @@ -140,7 +153,7 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( CREATE TABLE IF NOT EXISTS DM_POLICY ( ID INT(11) NOT NULL AUTO_INCREMENT , - NAME VARCHAR(45) NULL DEFAULT NULL , + NAME VARCHAR(45) DEFAULT NULL , DESCRIPTION VARCHAR(1000) NULL, TENANT_ID INT(11) NOT NULL , PROFILE_ID INT(11) NOT NULL , @@ -206,7 +219,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( ID INT(11) NOT NULL AUTO_INCREMENT, PROFILE_ID INT(11) NOT NULL, - FEATURE_CODE VARCHAR(30) NOT NULL, + FEATURE_CODE VARCHAR(100) NOT NULL, DEVICE_TYPE_ID INT NOT NULL, TENANT_ID INT(11) NOT NULL , CONTENT BLOB NULL DEFAULT NULL, @@ -250,8 +263,8 @@ CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( - ID INT NOT NULL AUTO_INCREMENT, - DEVICE_ID INT NOT NULL, + ID INT NOT NULL AUTO_INCREMENT , + DEVICE_ID INT NOT NULL , ENROLMENT_ID INT(11) NOT NULL, POLICY_ID INT NOT NULL , POLICY_CONTENT BLOB NULL , @@ -296,8 +309,6 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( ON UPDATE NO ACTION ); - - CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( ID INT NOT NULL AUTO_INCREMENT, POLICY_CRITERION_ID INT NOT NULL, @@ -312,8 +323,6 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( ON UPDATE NO ACTION ); - - CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ID INT NOT NULL AUTO_INCREMENT, DEVICE_ID INT NOT NULL, @@ -325,13 +334,16 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( LAST_REQUESTED_TIME TIMESTAMP NULL, LAST_FAILED_TIME TIMESTAMP NULL, ATTEMPTS INT NULL, - PRIMARY KEY (ID), - UNIQUE INDEX DEVICE_ID_UNIQUE (DEVICE_ID ASC), - CONSTRAINT FK_POLICY_COMPLIANCE_STATUS_POLICY - FOREIGN KEY (POLICY_ID) - REFERENCES DM_POLICY (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION + PRIMARY KEY (ID) +); + + +CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( + ID INT NOT NULL AUTO_INCREMENT, + POLICY_ID INT NOT NULL, + DEVICE_TYPE_ID INT NOT NULL, + TENANT_ID INT(11) NOT NULL, + PRIMARY KEY (ID) ); @@ -339,7 +351,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( ID INT NOT NULL AUTO_INCREMENT, COMPLIANCE_STATUS_ID INT NOT NULL, TENANT_ID INT NOT NULL, - FEATURE_CODE VARCHAR(15) NOT NULL, + FEATURE_CODE VARCHAR(100) NOT NULL, STATUS INT NULL, PRIMARY KEY (ID), CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS @@ -349,17 +361,177 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( ON UPDATE NO ACTION ); -CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( - ID INT NOT NULL AUTO_INCREMENT, - POLICY_ID INT NOT NULL, - DEVICE_TYPE_ID INT NOT NULL, - TENANT_ID INT(11) NOT NULL, - PRIMARY KEY (ID) +CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OWNER VARCHAR(50) NOT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, + STATUS VARCHAR(50) NULL, + DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +CREATE TABLE IF NOT EXISTS DM_APPLICATION ( + ID INTEGER AUTO_INCREMENT NOT NULL, + NAME VARCHAR(150) NOT NULL, + APP_IDENTIFIER VARCHAR(150) NOT NULL, + PLATFORM VARCHAR(50) DEFAULT NULL, + CATEGORY VARCHAR(50) NULL, + VERSION VARCHAR(50) NULL, + TYPE VARCHAR(50) NULL, + LOCATION_URL VARCHAR(100) DEFAULT NULL, + IMAGE_URL VARCHAR(100) DEFAULT NULL, + APP_PROPERTIES BLOB NULL, + MEMORY_USAGE INTEGER(10) NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ID) +); + +CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + APPLICATION_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_application FOREIGN KEY (APPLICATION_ID) REFERENCES + DM_APPLICATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); -- POLICY RELATED TABLES FINISHED -- +-- NOTIFICATION TABLE -- +CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( + NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OPERATION_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + STATUS VARCHAR(10) NULL, + DESCRIPTION VARCHAR(100) NULL, + PRIMARY KEY (NOTIFICATION_ID), + CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES + DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); +-- NOTIFICATION TABLE END -- + +DROP TABLE IF EXISTS DM_DEVICE_INFO; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + KEY_FIELD VARCHAR(45) NULL, + VALUE_FIELD VARCHAR(100) NULL, + PRIMARY KEY (ID), + CONSTRAINT DM_DEVICE_INFO_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + + +DROP TABLE IF EXISTS DM_DEVICE_LOCATION; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + LATITUDE DOUBLE NULL, + LONGITUDE DOUBLE NULL, + STREET1 VARCHAR(45) NULL, + STREET2 VARCHAR(45) NULL, + CITY VARCHAR(45) NULL, + ZIP VARCHAR(10) NULL, + STATE VARCHAR(45) NULL, + COUNTRY VARCHAR(45) NULL, + PRIMARY KEY (ID), + CONSTRAINT DM_DEVICE_LOCATION_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + +CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + DEVICE_MODEL VARCHAR(45) NULL, + VENDOR VARCHAR(45) NULL, + OS_VERSION VARCHAR(45) NULL, + BATTERY_LEVEL DECIMAL(4) NULL, + INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, + EXTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, + CONNECTION_TYPE VARCHAR(10) NULL, + SSID VARCHAR(45) NULL, + CPU_USAGE DECIMAL(5) NULL, + TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, + AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, + PLUGGED_IN INT(1) NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE + FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + +-- POLICY AND DEVICE GROUP MAPPING -- + +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_GROUP_ID INT NOT NULL, + POLICY_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_DEVICE_GROUP_POLICY + FOREIGN KEY (DEVICE_GROUP_ID) + REFERENCES DM_GROUP (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY + FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID) + REFERENCES DM_POLICY (ID , ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); --- TO:DO - Remove this INSERT sql statement. ---Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (1, 'android'); ---Insert into DM_DEVICE_TYPE (ID,NAME) VALUES (2, 'ios'); +-- END OF POLICY AND DEVICE GROUP MAPPING -- + +CREATE VIEW DEVICES_VIEW_1 AS +SELECT +DEVICE_INFO.DEVICE_ID, +DEVICE_INFO.PLATFORM, +DEVICE_INFO.OWNERSHIP, +DEVICE_INFO.CONNECTIVITY_STATUS, +IFNULL(DEVICE_WITH_POLICY_INFO.POLICY_ID, -1) AS POLICY_ID, +IFNULL(DEVICE_WITH_POLICY_INFO.IS_COMPLIANT, -1) AS IS_COMPLIANT, +DEVICE_INFO.TENANT_ID +FROM +(SELECT +DM_DEVICE.ID AS DEVICE_ID, +DM_DEVICE_TYPE.NAME AS PLATFORM, +DM_ENROLMENT.OWNERSHIP AS OWNERSHIP, +DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS, +DM_DEVICE.TENANT_ID AS TENANT_ID +FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT +WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO +LEFT JOIN +(SELECT +DEVICE_ID, +POLICY_ID, +STATUS AS IS_COMPLIANT +FROM +DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO +ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID +ORDER BY DEVICE_INFO.DEVICE_ID; diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index 576450d9d7..066e59c8c2 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -379,6 +379,58 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING ( -- END OF POLICY RELATED TABLES -- + +-- DEVICE GROUP TABLES -- + +CREATE TABLE IF NOT EXISTS DM_GROUP ( + ID INTEGER AUTO_INCREMENT NOT NULL, + GROUP_NAME VARCHAR(100) DEFAULT NULL, + DESCRIPTION TEXT DEFAULT NULL, + DATE_OF_CREATE BIGINT DEFAULT NULL, + DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL, + OWNER VARCHAR(45) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +)ENGINE = InnoDB; + + + +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER DEFAULT NULL, + GROUP_ID INTEGER DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID), + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) + REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +)ENGINE = InnoDB; + +-- END OF DEVICE GROUP TABLES -- + +-- POLICY AND DEVICE GROUP MAPPING -- + +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_GROUP_ID INT NOT NULL, + POLICY_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_DEVICE_GROUP_POLICY + FOREIGN KEY (DEVICE_GROUP_ID) + REFERENCES DM_GROUP (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY + FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID) + REFERENCES DM_POLICY (ID , ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +)ENGINE = InnoDB; + +-- END OF POLICY AND DEVICE GROUP MAPPING -- + -- NOTIFICATION TABLES -- CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( From a06327b731da38bc15f60b39c303d6d486eea3c7 Mon Sep 17 00:00:00 2001 From: Ace Date: Wed, 27 Apr 2016 20:43:13 +0530 Subject: [PATCH 2/2] refactoring and bug fixes --- .../webapp/publisher/APIPublisherUtil.java | 13 +- .../lifecycle/util/AnnotationUtil.java | 151 ++++++++++++------ .../feature/mgt/util/AnnotationUtil.java | 26 ++- 3 files changed, 131 insertions(+), 59 deletions(-) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java index f927bb5c84..877f6bb788 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java @@ -72,10 +72,12 @@ public class APIPublisherUtil { } public static API getAPI(APIConfig config) throws APIManagementException { + APIProvider provider = config.getProvider(); String apiVersion = config.getVersion(); APIIdentifier id = new APIIdentifier(replaceEmailDomain(config.getOwner()), config.getName(), apiVersion); API api = new API(id); + api.setApiOwner(config.getOwner()); String context = config.getContext(); context = context.startsWith("/") ? context : ("/" + context); @@ -84,12 +86,14 @@ public class APIPublisherUtil { //Create tenant aware context for API context = "/t/" + providerDomain + context; } + // This is to support the new Pluggable version strategy // if the context does not contain any {version} segment, we use the default version strategy. context = checkAndSetVersionParam(context); api.setContextTemplate(context); context = updateContextWithVersion(config.getVersion(), context); api.setContext(context); + api.setUrl(config.getEndpoint()); api.addAvailableTiers(provider.getTiers()); api.setEndpointSecured(true); @@ -97,12 +101,15 @@ public class APIPublisherUtil { api.setTransports(config.getTransports()); api.setContextTemplate(config.getContextTemplate()); api.setUriTemplates(config.getUriTemplates()); - Set environements = new HashSet<>(); - environements.add(API_PUBLISH_ENVIRONEMENT); - api.setEnvironments(environements); + + Set environments = new HashSet<>(); + environments.add(API_PUBLISH_ENVIRONEMENT); + api.setEnvironments(environments); + Set tiers = new HashSet(); tiers.add(new Tier(APIConstants.UNLIMITED_TIER)); api.addAvailableTiers(tiers); + if (config.isSharedWithAllTenants()) { api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_ALL_TENANTS); api.setVisibility(APIConstants.API_GLOBAL_VISIBILITY); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java index a26c2042f1..8120a9d60e 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationUtil.java @@ -24,8 +24,10 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.scannotation.AnnotationDB; import org.scannotation.WarUrlFinder; +import org.wso2.carbon.apimgt.annotations.api.API; import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource; import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration; + import javax.servlet.ServletContext; import javax.ws.rs.*; import java.io.IOException; @@ -45,17 +47,18 @@ public class AnnotationUtil { private static final String PACKAGE_ORG_APACHE = "org.apache"; private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus"; private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework"; + private static final String AUTH_TYPE = "Any"; private static final String PROTOCOL_HTTP = "http"; private static final String SERVER_HOST = "carbon.local.ip"; private static final String HTTP_PORT = "httpPort"; - public static final String DIR_WEB_INF_LIB = "/WEB-INF/lib"; - public static final String STRING_ARR = "string_arr"; - public static final String STRING = "string"; + private static final String STRING_ARR = "string_arr"; + private static final String STRING = "string"; private StandardContext context; private Method[] pathClazzMethods; private Class pathClazz; + Class apiClazz; private ClassLoader classLoader; private ServletContext servletContext; @@ -68,6 +71,7 @@ public class AnnotationUtil { /** * Scan the context for classes with annotations + * * @return * @throws IOException */ @@ -89,6 +93,7 @@ public class AnnotationUtil { /** * Method identifies the URL templates and context by reading the annotations of a class + * * @param entityClasses * @return */ @@ -107,38 +112,23 @@ public class AnnotationUtil { APIResourceConfiguration apiResourceConfig = null; try { clazz = classLoader.loadClass(className); - Class apiClazz = (Class) - classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); + + apiClazz = (Class) + classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API + .class.getName()); + Annotation apiAnno = clazz.getAnnotation(apiClazz); List resourceList; - apiResourceConfig = new APIResourceConfiguration(); if (apiAnno != null) { - Method[] apiClazzMethods = apiClazz.getMethods(); - if (log.isDebugEnabled()) { log.debug("Application Context root = " + servletContext.getContextPath()); } try { - for(int k=0;k) classLoader.loadClass(Path.class.getName()); @@ -177,7 +167,45 @@ public class AnnotationUtil { return apiResourceConfigs; } - private List getApiResources(String resourceRootContext, String apiRootContext, Method[] annotatedMethods) throws Throwable { + /** + * Iterate API annotation and build API Configuration + * @param apiAnno + * @return + * @throws Throwable + */ + private APIResourceConfiguration processAPIAnnotation(Annotation apiAnno) throws Throwable { + Method[] apiClazzMethods = apiClazz.getMethods(); + APIResourceConfiguration apiResourceConfig = new APIResourceConfiguration(); + for (int k = 0; k < apiClazzMethods.length; k++) { + switch (apiClazzMethods[k].getName()) { + case "name": + apiResourceConfig.setName(invokeMethod(apiClazzMethods[k], apiAnno, STRING)); + break; + case "version": + apiResourceConfig.setVersion(invokeMethod(apiClazzMethods[k], apiAnno, STRING)); + break; + case "context": + apiResourceConfig.setContext(invokeMethod(apiClazzMethods[k], apiAnno, STRING)); + break; + case "tags": + apiResourceConfig.setTags(invokeMethod(apiClazzMethods[k], apiAnno)); + break; + } + } + return apiResourceConfig; + } + + + /** + * Get Resources for each API + * @param resourceRootContext + * @param apiRootContext + * @param annotatedMethods + * @return + * @throws Throwable + */ + private List getApiResources(String resourceRootContext, String apiRootContext, + Method[] annotatedMethods) throws Throwable { List resourceList; resourceList = new ArrayList(); for (Method method : annotatedMethods) { @@ -195,31 +223,19 @@ public class AnnotationUtil { resource.setAuthType(AUTH_TYPE); Annotation[] annotations = method.getDeclaredAnnotations(); - for(int i=0; i consumesClass = (Class) classLoader.loadClass(Consumes.class.getName()); + processHTTPMethodAnnotation(resource, annotations[i]); + if (annotations[i].annotationType().getName().equals(Consumes.class.getName())) { + Class consumesClass = (Class) classLoader.loadClass( + Consumes.class.getName()); Method[] consumesClassMethods = consumesClass.getMethods(); Annotation consumesAnno = method.getAnnotation(consumesClass); resource.setConsumes(invokeMethod(consumesClassMethods[0], consumesAnno, STRING_ARR)); } - if(annotations[i].annotationType().getName().equals(Produces.class.getName())){ - Class producesClass = (Class) classLoader.loadClass(Produces.class.getName()); + if (annotations[i].annotationType().getName().equals(Produces.class.getName())) { + Class producesClass = (Class) classLoader.loadClass( + Produces.class.getName()); Method[] producesClassMethods = producesClass.getMethods(); Annotation producesAnno = method.getAnnotation(producesClass); resource.setProduces(invokeMethod(producesClassMethods[0], producesAnno, STRING_ARR)); @@ -231,12 +247,40 @@ public class AnnotationUtil { return resourceList; } - private String makeContextURLReady(String context){ - if(context != null && !context.equalsIgnoreCase("")){ - if(context.startsWith("/")){ + /** + * Read Method annotations indicating HTTP Methods + * @param resource + * @param annotation + */ + private void processHTTPMethodAnnotation(APIResource resource, Annotation annotation) { + if (annotation.annotationType().getName().equals(GET.class.getName())) { + resource.setHttpVerb(HttpMethod.GET); + } + if (annotation.annotationType().getName().equals(POST.class.getName())) { + resource.setHttpVerb(HttpMethod.POST); + } + if (annotation.annotationType().getName().equals(OPTIONS.class.getName())) { + resource.setHttpVerb(HttpMethod.OPTIONS); + } + if (annotation.annotationType().getName().equals(DELETE.class.getName())) { + resource.setHttpVerb(HttpMethod.DELETE); + } + if (annotation.annotationType().getName().equals(PUT.class.getName())) { + resource.setHttpVerb(HttpMethod.PUT); + } + } + + /** + * Append '/' to the context and make it URL ready + * @param context + * @return + */ + private String makeContextURLReady(String context) { + if (context != null && !context.equalsIgnoreCase("")) { + if (context.startsWith("/")) { return context; - }else{ - return "/"+context; + } else { + return "/" + context; } } return ""; @@ -244,6 +288,7 @@ public class AnnotationUtil { /** * When an annotation and method is passed, this method invokes that executes said method against the annotation + * * @param method * @param annotation * @param returnType @@ -252,11 +297,11 @@ public class AnnotationUtil { */ private String invokeMethod(Method method, Annotation annotation, String returnType) throws Throwable { InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation); - switch (returnType){ + switch (returnType) { case STRING: return (String) methodHandler.invoke(annotation, method, null); case STRING_ARR: - return ((String[])methodHandler.invoke(annotation, method, null))[0]; + return ((String[]) methodHandler.invoke(annotation, method, null))[0]; default: return null; } @@ -267,6 +312,6 @@ public class AnnotationUtil { */ private String[] invokeMethod(Method method, Annotation annotation) throws Throwable { InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation); - return ((String[])methodHandler.invoke(annotation, method, null)); + return ((String[]) methodHandler.invoke(annotation, method, null)); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java index 8941ad0312..dbca91f10e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java @@ -62,8 +62,8 @@ public class AnnotationUtil { private static final String PACKAGE_ORG_APACHE = "org.apache"; private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus"; private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework"; - public static final String STRING_ARR = "string_arr"; - public static final String STRING = "string"; + private static final String STRING_ARR = "string_arr"; + private static final String STRING = "string"; private Class featureAnnotationClazz; private ClassLoader classLoader; @@ -164,7 +164,8 @@ public class AnnotationUtil { return featureList; } - private Map processParamAnnotations(Map apiParams, Method currentMethod) throws Throwable{ + private Map processParamAnnotations(Map apiParams, Method currentMethod) + throws Throwable{ try { apiParams.put("pathParams", processParamAnnotations(currentMethod, PathParam.class)); apiParams.put("queryParams", processParamAnnotations(currentMethod, QueryParam.class)); @@ -196,6 +197,12 @@ public class AnnotationUtil { return params; } + /** + * Read Method annotations indicating HTTP Methods + * @param feature + * @param currentAnnotation + * @return + */ private Feature processHttpMethodAnnotation(Feature feature, Annotation currentAnnotation) { //Extracting method with which feature is exposed if (currentAnnotation.annotationType().getName().equals(GET.class.getName())) { @@ -212,6 +219,13 @@ public class AnnotationUtil { return feature; } + /** + * Read Feature annotation and Identify Features + * @param feature + * @param currentMethod + * @return + * @throws Throwable + */ private Feature processFeatureAnnotation(Feature feature, Method currentMethod) throws Throwable{ Method[] featureAnnoMethods = featureAnnotationClazz.getMethods(); Annotation featureAnno = currentMethod.getAnnotation(featureAnnotationClazz); @@ -234,6 +248,12 @@ public class AnnotationUtil { return feature; } + /** + * Get value depicted by Path Annotation + * @param currentMethod + * @return + * @throws Throwable + */ public String getPathAnnotationValue(Method currentMethod) throws Throwable{ String uri = ""; try {