From 12a2e1f11feb85735b708a08a8a3addb2ad550b8 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Fri, 28 Aug 2015 12:31:03 +0530 Subject: [PATCH 1/4] Partially commiting to fix update problem --- .../src/main/resources/dbscripts/cdm/h2.sql | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 44a178ef51..45e0ac4dd9 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -133,7 +133,9 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( PROFILE_ID INT(11) NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, - PRIORITY INT NOT NULL , + PRIORITY INT NOT NULL, + ACTIVE INT(2) NOT NULL, + UPDATED INT(1) NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_PROFILE_DM_POLICY FOREIGN KEY (PROFILE_ID ) @@ -317,6 +319,20 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( ); +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), + CONSTRAINT FK_POLICY_CHANGE_MGT_POLICY + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + + CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( ID INT NOT NULL AUTO_INCREMENT, COMPLIANCE_STATUS_ID INT NOT NULL, From 44b496d3503ff1ad5f938cfd6c24f263c681a41f Mon Sep 17 00:00:00 2001 From: geethkokila Date: Fri, 28 Aug 2015 12:33:10 +0530 Subject: [PATCH 2/4] Partially commiting due to update --- .../wso2/carbon/device/mgt/common/Device.java | 5 +- .../device/mgt/common/EnrolmentInfo.java | 6 +- .../wso2/carbon/policy/mgt/common/Policy.java | 99 ++----- .../mgt/common/PolicyAdministratorPoint.java | 6 + .../policy/mgt/common/PolicyFilter.java | 2 + .../carbon/policy/mgt/core/dao/PolicyDAO.java | 18 ++ .../mgt/core/dao/impl/PolicyDAOImpl.java | 262 +++++++++++++++++- .../mgt/core/dao/impl/ProfileDAOImpl.java | 38 +-- .../PolicyEnforcementDelegator.java | 7 +- .../PolicyEnforcementDelegatorImpl.java | 89 +++++- .../impl/PolicyAdministratorPointImpl.java | 65 ++++- .../mgt/core/impl/PolicyFilterImpl.java | 100 +++++++ .../core/impl/PolicyInformationPointImpl.java | 38 ++- .../policy/mgt/core/mgt/PolicyManager.java | 10 + .../core/mgt/impl/MonitoringManagerImpl.java | 24 +- .../mgt/core/mgt/impl/PolicyManagerImpl.java | 217 +++++++++++---- .../mgt/core/mgt/impl/ProfileManagerImpl.java | 5 +- .../mgt/core/util/PolicyManagerUtil.java | 26 +- .../mgt/core/BasePolicyManagementDAOTest.java | 2 +- .../policy/mgt/core/MonitoringTestCase.java | 20 +- .../policy/mgt/core/PolicyDAOTestCase.java | 74 +++-- .../mgt/core/PolicyEvaluationTestCase.java | 122 ++++++++ .../services/SimplePolicyEvaluationTest.java | 84 ++++++ .../policy/mgt/core/util/DeviceCreator.java | 134 ++++++++- .../policy/mgt/core/util/FeatureCreator.java | 73 ++++- .../policy/mgt/core/util/PolicyCreator.java | 6 +- .../policy/mgt/core/util/ProfileCreator.java | 62 +++++ .../config/datasource/data-source-config.xml | 16 +- .../src/test/resources/sql/CreateH2TestDB.sql | 19 +- .../src/test/resources/testng.xml | 1 + 30 files changed, 1354 insertions(+), 276 deletions(-) create mode 100644 components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java create mode 100644 components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/services/SimplePolicyEvaluationTest.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java index 331c81b749..07842fbc6b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java @@ -19,9 +19,12 @@ package org.wso2.carbon.device.mgt.common; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; import java.util.List; -public class Device { +public class Device implements Serializable{ + + private static final long serialVersionUID = 1998101711L; private int id; private String name; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java index 2c599474fc..0a3f32ba62 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java @@ -18,7 +18,11 @@ */ package org.wso2.carbon.device.mgt.common; -public class EnrolmentInfo { +import java.io.Serializable; + +public class EnrolmentInfo implements Serializable{ + + private static final long serialVersionUID = 1998101712L; public enum Status { CREATED, ACTIVE, INACTIVE, UNREACHABLE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED, DISENROLLMENT_REQUESTED 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 121454e77a..6087207db1 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 @@ -42,6 +42,8 @@ public class Policy implements Comparable, Serializable { private String ownershipType; // Ownership type (COPE, BYOD, CPE) private List devices; // Individual devices this policy should be applied private List users; + private boolean active; + private boolean updated; /* Compliance data*/ @@ -53,19 +55,6 @@ public class Policy implements Comparable, Serializable { private List policyCriterias; - /*These are related to time based policies*/ - -// private int startTime; // Start time to apply the policy. -// private int endTime; // After this time policy will not be applied -// private Date startDate; // Start date to apply the policy -// private Date endDate; // After this date policy will not be applied. - - - /*These are related to location based policies*/ - - // private String latitude; // Latitude -// private String longitude; // Longitude -// private int tenantId; private int profileId; @@ -163,6 +152,24 @@ public class Policy implements Comparable, Serializable { this.users = users; } + @XmlElement + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + @XmlElement + public boolean isUpdated() { + return updated; + } + + public void setUpdated(boolean updated) { + this.updated = updated; + } + @XmlElement public List getPolicyCriterias() { return policyCriterias; @@ -172,6 +179,7 @@ public class Policy implements Comparable, Serializable { this.policyCriterias = policyCriterias; } + @XmlElement public String getCompliance() { return Compliance; } @@ -180,59 +188,6 @@ public class Policy implements Comparable, Serializable { Compliance = compliance; } - // public int getStartTime() { -// return startTime; -// } -// -// public void setStartTime(int startTime) { -// this.startTime = startTime; -// } -// -// @XmlElement -// public int getEndTime() { -// return endTime; -// } -// -// public void setEndTime(int endTime) { -// this.endTime = endTime; -// } -// -// @XmlElement -// public Date getStartDate() { -// return startDate; -// } -// -// public void setStartDate(Date startDate) { -// this.startDate = startDate; -// } -// -// @XmlElement -// public Date getEndDate() { -// return endDate; -// } -// -// public void setEndDate(Date endDate) { -// this.endDate = endDate; -// } -// -// @XmlElement -// public String getLatitude() { -// return latitude; -// } -// -// public void setLatitude(String latitude) { -// this.latitude = latitude; -// } -// -// @XmlElement -// public String getLongitude() { -// return longitude; -// } -// -// public void setLongitude(String longitude) { -// this.longitude = longitude; -// } - @XmlElement public Map getAttributes() { return attributes; @@ -252,18 +207,6 @@ public class Policy implements Comparable, Serializable { } - /* static final Comparator PRIORITY_ORDER = - new Comparator() { - public int compare(Policy p1, Policy p2) { - int dateCmp = new Integer(p2.getId()).compareTo(new Integer(p1.getId())); - if (dateCmp != 0) - return dateCmp; - - return (p1.getId() < p2.getId() ? -1 : - (p1.getId() == p2.getId() ? 0 : 1)); - } - };*/ - @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/PolicyAdministratorPoint.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java index f59e722d5f..2774c3bf4f 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java @@ -40,9 +40,15 @@ public interface PolicyAdministratorPoint { boolean updatePolicyPriorities(List policies) throws PolicyManagementException; + void activatePolicy(int policyId) throws PolicyManagementException; + + void inactivatePolicy(int policyId) throws PolicyManagementException; + boolean deletePolicy(Policy policy) throws PolicyManagementException; boolean deletePolicy(int policyId) throws PolicyManagementException; + void publishChanges() throws PolicyManagementException; + /** * This method adds a policy per device which should be implemented by the related plugins. */ 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 b636d5d9c3..44303782ff 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 @@ -23,6 +23,8 @@ import java.util.List; public interface PolicyFilter { + List filterActivePolicies(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 071612fdd2..d0c04add50 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 @@ -42,6 +42,16 @@ public interface PolicyDAO { boolean updatePolicyPriorities(List policies) throws PolicyManagerDAOException; + void activatePolicy(int policyId) throws PolicyManagerDAOException; + + void activatePolicies(List policyIds) throws PolicyManagerDAOException; + + void markPoliciesAsUpdated(List policyIds) throws PolicyManagerDAOException; + + void inactivatePolicy(int policyId) throws PolicyManagerDAOException; + + HashMap getUpdatedPolicyIdandDeviceTypeId() throws PolicyManagerDAOException; + Criterion addCriterion(Criterion criteria) throws PolicyManagerDAOException; Criterion updateCriterion(Criterion criteria) throws PolicyManagerDAOException; @@ -64,6 +74,12 @@ public interface PolicyDAO { Policy updatePolicy(Policy policy) throws PolicyManagerDAOException; + void recordUpdatedPolicy(Policy policy) throws PolicyManagerDAOException; + + void recordUpdatedPolicies(List policies) throws PolicyManagerDAOException; + + void removeRecordsAboutUpdatedPolicies() throws PolicyManagerDAOException; + Policy getPolicy(int policyId) throws PolicyManagerDAOException; Policy getPolicyByProfileID(int profileId) throws PolicyManagerDAOException; @@ -107,4 +123,6 @@ public interface PolicyDAO { Policy getAppliedPolicy(int deviceId) throws PolicyManagerDAOException; HashMap getAppliedPolicyIds(List deviceIds) throws PolicyManagerDAOException; + + HashMap getAppliedPolicyIdsDeviceIds() 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 8b08ee968c..8f7d8d5e3b 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 @@ -144,13 +144,14 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); - String query = "UPDATE DM_POLICY SET PRIORITY = ? WHERE ID = ? AND TENANT_ID = ?"; + String query = "UPDATE DM_POLICY SET PRIORITY = ?, UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(query); for (Policy policy : policies) { stmt.setInt(1, policy.getPriorityId()); - stmt.setInt(2, policy.getId()); - stmt.setInt(3, tenantId); + stmt.setInt(2, 1); + stmt.setInt(3, policy.getId()); + stmt.setInt(4, tenantId); stmt.addBatch(); } stmt.executeBatch(); @@ -162,6 +163,137 @@ public class PolicyDAOImpl implements PolicyDAO { return true; } + @Override + public void activatePolicy(int policyId) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + conn = this.getConnection(); + String query = "UPDATE DM_POLICY SET UPDATED = ?, ACTIVE = ? WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, 1); + stmt.setInt(2, 1); + stmt.setInt(3, policyId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating policy id (" + policyId + + ") in database", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + + } + + @Override + public void activatePolicies(List policyIds) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + conn = this.getConnection(); + String query = "UPDATE DM_POLICY SET UPDATED = ?, ACTIVE = ? WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + for (int policyId : policyIds) { + stmt.setInt(1, 1); + stmt.setInt(2, 1); + stmt.setInt(3, policyId); + stmt.setInt(4, tenantId); + stmt.addBatch(); + } + stmt.executeBatch(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating all the updated in database", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void markPoliciesAsUpdated(List policyIds) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + conn = this.getConnection(); + String query = "UPDATE DM_POLICY SET UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + for (int policyId : policyIds) { + stmt.setInt(1, 0); + stmt.setInt(2, policyId); + stmt.setInt(3, tenantId); + stmt.addBatch(); + } + stmt.executeBatch(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating all the updated in database", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void inactivatePolicy(int policyId) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + conn = this.getConnection(); + String query = "UPDATE DM_POLICY SET ACTIVE = ?, UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, 0); + stmt.setInt(2, 1); + stmt.setInt(3, policyId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating policy id (" + policyId + + ") in database", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public HashMap getUpdatedPolicyIdandDeviceTypeId() throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + ResultSet resultSet = null; + HashMap map = new HashMap<>(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = "SELECT * FROM DM_POLICY_CHANGE_MGT WHERE TENANT_ID = ?"; + stmt.setInt(1, tenantId); + stmt = conn.prepareStatement(query); + resultSet = stmt.executeQuery(); + + while (resultSet.next()) { + map.put(resultSet.getInt("POLICY_ID"), resultSet.getInt("DEVICE_TYPE_ID")); + } + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while reading the changed policies form database.", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return map; + } + @Override public Criterion addCriterion(Criterion criteria) throws PolicyManagerDAOException { @@ -477,15 +609,16 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); - String query = "UPDATE DM_POLICY SET NAME= ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?" + - " WHERE ID = ? AND TENANT_ID = ?"; + String query = "UPDATE DM_POLICY SET NAME = ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?," + + " UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setString(1, policy.getPolicyName()); stmt.setInt(2, policy.getProfile().getProfileId()); stmt.setInt(3, policy.getPriorityId()); stmt.setString(4, policy.getCompliance()); - stmt.setInt(5, policy.getId()); - stmt.setInt(6, tenantId); + stmt.setInt(5, 1); + stmt.setInt(6, policy.getId()); + stmt.setInt(7, tenantId); stmt.executeUpdate(); } catch (SQLException e) { @@ -497,6 +630,77 @@ public class PolicyDAOImpl implements PolicyDAO { return policy; } + @Override + public void recordUpdatedPolicy(Policy policy) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = "INSERT INTO DM_POLICY_CHANGE_MGT (POLICY_ID, DEVICE_TYPE_ID, TENANT_ID) VALUES (?, ?, ?)"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, policy.getId()); + stmt.setInt(2, policy.getProfile().getDeviceType().getId()); + stmt.setInt(3, tenantId); + stmt.executeUpdate(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating the policy changes in the database for" + + " " + + "policy name (" + policy.getPolicyName() + ")", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void recordUpdatedPolicies(List policies) throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = "INSERT INTO DM_POLICY_CHANGE_MGT (POLICY_ID, DEVICE_TYPE_ID, TENANT_ID) VALUES (?, ?, ?)"; + stmt = conn.prepareStatement(query); + for (Policy policy : policies) { + stmt.setInt(1, policy.getId()); + stmt.setInt(2, policy.getProfile().getDeviceType().getId()); + stmt.setInt(3, tenantId); + stmt.addBatch(); + } + stmt.executeBatch(); + + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while updating the policy changes in the database.", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void removeRecordsAboutUpdatedPolicies() throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = "DELETE FROM DM_POLICY_CHANGE_MGT WHERE TENANT_ID = ? "; + stmt = conn.prepareStatement(query); + stmt.setInt(1, tenantId); + stmt.executeUpdate(); + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while deleting the policy changes in the database for" + + " " + + "tenant id (" + tenantId + ")", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, null); + } + + } + @Override public Policy getPolicy(int policyId) throws PolicyManagerDAOException { Connection conn; @@ -585,6 +789,8 @@ public class PolicyDAOImpl implements PolicyDAO { policy.setPriorityId(resultSet.getInt("PRIORITY")); policy.setCompliance(resultSet.getString("COMPLIANCE")); policy.setOwnershipType(resultSet.getString("OWNERSHIP_TYPE")); + policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED"))); + policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE"))); policies.add(policy); } return policies; @@ -884,12 +1090,16 @@ public class PolicyDAOImpl implements PolicyDAO { stmt = conn.prepareStatement(query); stmt.setInt(1, policyId); stmt.setInt(2, tenantId); - stmt.executeUpdate(); + int deleted = stmt.executeUpdate(); if (log.isDebugEnabled()) { log.debug("Policy (" + policyId + ") delete from database."); } - return true; + if (deleted > 0) { + return true; + } else { + return false; + } } catch (SQLException e) { throw new PolicyManagerDAOException("Unable to delete the policy (" + policyId + ") from database", e); } finally { @@ -948,8 +1158,9 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); - String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE)" + - " VALUES (?, ?, ?, ?, ?, ?)"; + String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," + + " " + + "UPDATED, ACTIVE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); stmt.setString(1, policy.getPolicyName()); @@ -958,6 +1169,8 @@ public class PolicyDAOImpl implements PolicyDAO { stmt.setInt(4, readHighestPriorityOfPolicies()); stmt.setString(5, policy.getCompliance()); stmt.setString(6, policy.getOwnershipType()); + stmt.setInt(7, 0); + stmt.setInt(8, 0); int affectedRows = stmt.executeUpdate(); @@ -1183,4 +1396,31 @@ public class PolicyDAOImpl implements PolicyDAO { return devicePolicyIds; } + @Override + public HashMap getAppliedPolicyIdsDeviceIds() throws PolicyManagerDAOException { + + Connection conn; + PreparedStatement stmt = null; + ResultSet resultSet = null; + HashMap devicePolicyIds = new HashMap<>(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + + try { + conn = this.getConnection(); + String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setInt(1, tenantId); + resultSet = stmt.executeQuery(); + + while (resultSet.next()) { + devicePolicyIds.put(resultSet.getInt("DEVICE_ID"), resultSet.getInt("POLICY_ID")); + } + } catch (SQLException e) { + throw new PolicyManagerDAOException("Error occurred while getting the applied policy", e); + } finally { + PolicyManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return devicePolicyIds; + } + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java index 58ceefba76..6515031029 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/ProfileDAOImpl.java @@ -91,19 +91,19 @@ public class ProfileDAOImpl implements ProfileDAO { Connection conn; PreparedStatement stmt = null; - ResultSet generatedKeys = null; + // ResultSet generatedKeys = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); - String query = "UPDATE DM_PROFILE SET PROFILE_NAME = ? ,TENANT_ID = ?, DEVICE_TYPE_ID = ? , UPDATED_TIME = ? " + - "WHERE ID = ?"; - stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); - stmt.setString(1, profile.getProfileName()); - stmt.setInt(2, tenantId); - stmt.setLong(3, profile.getDeviceType().getId()); - stmt.setTimestamp(4, profile.getUpdatedDate()); - stmt.setInt(5, profile.getProfileId()); + String query = "UPDATE DM_PROFILE SET PROFILE_NAME = ? , DEVICE_TYPE_ID = ? , UPDATED_TIME = ? " + + "WHERE ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(query); + stmt.setString(1, profile.getProfileName()); + stmt.setLong(2, profile.getDeviceType().getId()); + stmt.setTimestamp(3, profile.getUpdatedDate()); + stmt.setInt(4, profile.getProfileId()); + stmt.setInt(5, tenantId); int affectedRows = stmt.executeUpdate(); @@ -111,22 +111,22 @@ public class ProfileDAOImpl implements ProfileDAO { String msg = "No rows are updated on the profile table."; log.debug(msg); } - generatedKeys = stmt.getGeneratedKeys(); - - if (generatedKeys.next()) { - profile.setProfileId(generatedKeys.getInt(1)); - } - // Checking the profile id here, because profile id could have been passed from the calling method. - if (profile.getProfileId() == 0) { - throw new RuntimeException("Profile id is 0, this could be an issue."); - } +// generatedKeys = stmt.getGeneratedKeys(); +// +// if (generatedKeys.next()) { +// profile.setProfileId(generatedKeys.getInt(1)); +// } +// // Checking the profile id here, because profile id could have been passed from the calling method. +// if (profile.getProfileId() == 0) { +// throw new RuntimeException("Profile id is 0, this could be an issue."); +// } } catch (SQLException e) { String msg = "Error occurred while updating the profile (" + profile.getProfileName() + ") in database."; log.error(msg, e); throw new ProfileManagerDAOException(msg, e); } finally { - PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys); + PolicyManagementDAOUtil.cleanupResources(stmt, null); } return profile; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java index f1e7a52e12..9ffb0c9e3d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java @@ -22,10 +22,15 @@ import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.policy.mgt.common.Policy; +import java.util.HashMap; import java.util.List; public interface PolicyEnforcementDelegator { - void delegate(Policy policy, List devices) throws PolicyDelegationException; + void delegate() throws PolicyDelegationException; + + Policy getEffectivePolicy(DeviceIdentifier identifier) throws PolicyDelegationException; + + void addPolicyOperation(List deviceIdentifiers, Policy policy) throws PolicyDelegationException; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java index ab03f36626..fa7d1f478f 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java @@ -18,33 +18,102 @@ */ package org.wso2.carbon.policy.mgt.core.enforcement; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; import org.wso2.carbon.policy.mgt.common.Policy; +import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException; +import org.wso2.carbon.policy.mgt.common.PolicyManagementException; +import org.wso2.carbon.policy.mgt.core.PolicyManagerService; +import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import java.util.ArrayList; import java.util.List; -public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegator { +public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegator, Runnable { - private OperationManager operationManager = new OperationManagerImpl(); + private static final Log log = LogFactory.getLog(PolicyEnforcementDelegatorImpl.class); - @Override - public void delegate(Policy policy, List devices) throws PolicyDelegationException { - try { - List deviceIds = new ArrayList<>(); + private List devices; + + public PolicyEnforcementDelegatorImpl(List devices) { + + log.info("Policy re-enforcing stared due to change of the policies."); + + if (log.isDebugEnabled()) { for (Device device : devices) { - deviceIds.add(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + log.debug("Policy re-enforcing for device :" + device.getDeviceIdentifier() + " - Type : " + + device.getType()); + } + } + this.devices = devices; + + } + + @Override + public void delegate() throws PolicyDelegationException { + + for (Device device : devices) { + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setId(device.getDeviceIdentifier()); + identifier.setType(device.getType()); + + Policy policy = this.getEffectivePolicy(identifier); + + if (policy != null) { + List deviceIdentifiers = new ArrayList<>(); + deviceIdentifiers.add(identifier); + this.addPolicyOperation(deviceIdentifiers, policy); } - operationManager.addOperation(PolicyManagerUtil.transformPolicy(policy), deviceIds); + + } + } + + @Override + public Policy getEffectivePolicy(DeviceIdentifier identifier) throws PolicyDelegationException { + + try { + PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); + return policyManagerService.getPEP().getEffectivePolicy(identifier); + //return PolicyManagementDataHolder.getInstance().getPolicyEvaluationPoint().getEffectivePolicy(identifier); + } catch (PolicyEvaluationException e) { + String msg = "Error occurred while retrieving the effective policy for devices."; + log.error(msg, e); + throw new PolicyDelegationException(msg, e); + } catch (PolicyManagementException e) { + String msg = "Error occurred while retrieving the effective policy for devices."; + log.error(msg, e); + throw new PolicyDelegationException(msg, e); + } + } + + @Override + public void addPolicyOperation(List deviceIdentifiers, Policy policy) throws + PolicyDelegationException { + + try { + OperationManager operationManager = new OperationManagerImpl(); + operationManager.addOperation(PolicyManagerUtil.transformPolicy(policy), deviceIdentifiers); } catch (OperationManagementException e) { - throw new PolicyDelegationException("Error occurred while delegating policy information to " + - "the respective enforcement points", e); + String msg = "Error occurred while adding the operation to device."; + log.error(msg, e); + throw new PolicyDelegationException(msg, e); } + } + @Override + public void run() { + try { + this.delegate(); + } catch (PolicyDelegationException e) { + log.error("Error occurred while running the policy change delegation thread.", e); + } + } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java index e406e9fbaf..bec741f8ff 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java @@ -20,16 +20,20 @@ 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.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.policy.mgt.common.FeatureManagementException; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.Profile; import org.wso2.carbon.policy.mgt.common.ProfileManagementException; -import org.wso2.carbon.policy.mgt.core.enforcement.PolicyDelegationException; import org.wso2.carbon.policy.mgt.core.enforcement.PolicyEnforcementDelegator; import org.wso2.carbon.policy.mgt.core.enforcement.PolicyEnforcementDelegatorImpl; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager; @@ -37,6 +41,8 @@ import org.wso2.carbon.policy.mgt.core.mgt.impl.FeatureManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.ProfileManagerImpl; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { @@ -46,13 +52,13 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { private PolicyManager policyManager; private ProfileManager profileManager; private FeatureManager featureManager; - private PolicyEnforcementDelegator delegator; + // private PolicyEnforcementDelegator delegator; public PolicyAdministratorPointImpl() { this.policyManager = new PolicyManagerImpl(); this.profileManager = new ProfileManagerImpl(); this.featureManager = new FeatureManagerImpl(); - this.delegator = new PolicyEnforcementDelegatorImpl(); + // this.delegator = new PolicyEnforcementDelegatorImpl(); } @Override @@ -82,6 +88,16 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { return policyManager.updatePolicyPriorities(policies); } + @Override + public void activatePolicy(int policyId) throws PolicyManagementException { + policyManager.activatePolicy(policyId); + } + + @Override + public void inactivatePolicy(int policyId) throws PolicyManagementException { + policyManager.inactivatePolicy(policyId); + } + @Override public boolean deletePolicy(Policy policy) throws PolicyManagementException { return policyManager.deletePolicy(policy); @@ -93,7 +109,46 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { } @Override - public Policy addPolicyToDevice(List deviceIdentifierList, Policy policy) throws PolicyManagementException { + public void publishChanges() throws PolicyManagementException { + + List deviceTypes = policyManager.applyChangesMadeToPolicies(); + + if(log.isDebugEnabled()) { + log.debug("Number of device types which policies are changed .......... : " + deviceTypes.size() ); + } + + if (!deviceTypes.isEmpty()) { + + + DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance() + .getDeviceManagementService(); + List devices = new ArrayList<>(); + for (DeviceType deviceType : deviceTypes) { + try { + devices.addAll(service.getAllDevices(deviceType.getName())); + } catch (DeviceManagementException e) { + throw new PolicyManagementException("Error occurred while taking the devices", e); + } + } + HashMap deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds(); + List toBeNotified = new ArrayList<>(); + + for (Device device : devices) { + if (deviceIdPolicy.containsKey(device.getId())) { + toBeNotified.add(device); + } + } + if (!toBeNotified.isEmpty()) { + // PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl(toBeNotified); + Thread thread = new Thread(new PolicyEnforcementDelegatorImpl(toBeNotified)); + thread.start(); + } + } + } + + @Override + public Policy addPolicyToDevice(List deviceIdentifierList, Policy policy) throws + PolicyManagementException { return policyManager.addPolicyToDevice(deviceIdentifierList, policy); } @@ -185,7 +240,7 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { try { return profileManager.getProfile(profileId); } catch (ProfileManagementException e) { - String msg = "Error occurred while retriving profile"; + String msg = "Error occurred while retrieving profile"; log.error(msg, e); throw new PolicyManagementException(msg, e); } 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 f6448508aa..0bd4efe3f5 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 @@ -32,14 +32,56 @@ public class PolicyFilterImpl implements PolicyFilter { private static final Log log = LogFactory.getLog(PolicyFilterImpl.class); + @Override + public List filterActivePolicies(List policies) { + + if (log.isDebugEnabled()) { + log.debug("No of policies went in to filterActivePolicies : " + policies.size()); + for (Policy policy : policies) { + log.debug("Names of policy went in to filterActivePolicies : " + policy.getPolicyName()); + } + } + + List temp = new ArrayList(); + for (Policy policy : policies) { + if (policy.isActive()) { + temp.add(policy); + } + } + + if (log.isDebugEnabled()) { + log.debug("No of policies returned from filterActivePolicies :" + policies.size()); + for (Policy policy : temp) { + log.debug("Names of policy filtered in filterActivePolicies : " + policy.getPolicyName()); + } + } + + return temp; + } + @Override public List filterRolesBasedPolicies(String roles[], List policies) { + if (log.isDebugEnabled()) { + log.debug("No of policies went in to filterRolesBasedPolicies : " + policies.size()); + for (Policy policy : policies) { + log.debug("Names of policy went in to filterRolesBasedPolicies : " + policy.getPolicyName()); + } + log.debug("Roles passed to match."); + for(String role : roles){ + log.debug("Role name passed : " + role); + } + } + List temp = new ArrayList(); for (Policy policy : policies) { List tempRoles = policy.getRoles(); if (tempRoles.isEmpty()) { + + if(log.isDebugEnabled()) { + log.debug("Roles list is empty."); + } temp.add(policy); continue; } @@ -57,12 +99,28 @@ public class PolicyFilterImpl implements PolicyFilter { } } } + + if (log.isDebugEnabled()) { + log.debug("No of policies returned from filterRolesBasedPolicies : " + policies.size()); + for (Policy policy : temp) { + log.debug("Names of policy filtered in filterRolesBasedPolicies : " + policy.getPolicyName()); + } + } + return temp; } @Override public List filterOwnershipTypeBasedPolicies(String ownershipType, List policies) { + if (log.isDebugEnabled()) { + log.debug("No of policies went in to filterOwnershipTypeBasedPolicies : " + policies.size()); + log.debug("Ownership type : " + ownershipType); + for (Policy policy : policies) { + log.debug("Names of policy went in to filterOwnershipTypeBasedPolicies : " + policy.getPolicyName()); + } + } + List temp = new ArrayList(); for (Policy policy : policies) { if (ownershipType.equalsIgnoreCase(policy.getOwnershipType()) || @@ -70,22 +128,56 @@ public class PolicyFilterImpl implements PolicyFilter { temp.add(policy); } } + + if (log.isDebugEnabled()) { + log.debug("No of policies returned from filterOwnershipTypeBasedPolicies : " + policies.size()); + for (Policy policy : temp) { + log.debug("Names of policy filtered in filterOwnershipTypeBasedPolicies : " + policy.getPolicyName()); + } + } return temp; } @Override public List filterDeviceTypeBasedPolicies(String deviceType, List policies) { + + if (log.isDebugEnabled()) { + log.debug("No of policies went in to filterDeviceTypeBasedPolicies : " + policies.size()); + log.debug("Device type : " + deviceType); + for (Policy policy : policies) { + log.debug("Names of policy went in to filterDeviceTypeBasedPolicies : " + policy.getPolicyName()); + } + } + + List temp = new ArrayList(); for (Policy policy : policies) { if (deviceType.equalsIgnoreCase(policy.getProfile().getDeviceType().getName())) { temp.add(policy); } } + + if (log.isDebugEnabled()) { + log.debug("No of policies returned from filterDeviceTypeBasedPolicies : " + policies.size()); + for (Policy policy : temp) { + log.debug("Names of policy filtered in filterDeviceTypeBasedPolicies : " + policy.getPolicyName()); + } + } + return temp; } @Override public List filterUserBasedPolicies(String username, List policies) { + + if (log.isDebugEnabled()) { + log.debug("No of policies went in to filterUserBasedPolicies : " + policies.size()); + log.debug("User name : " + username); + for (Policy policy : policies) { + log.debug("Names of policy went in to filterUserBasedPolicies : " + policy.getPolicyName()); + } + } + List temp = new ArrayList(); for (Policy policy : policies) { @@ -106,6 +198,14 @@ public class PolicyFilterImpl implements PolicyFilter { } } } + + if (log.isDebugEnabled()) { + log.debug("No of policies returned from filterUserBasedPolicies : " + policies.size()); + for (Policy policy : temp) { + log.debug("Names of policy filtered in filterUserBasedPolicies : " + policy.getPolicyName()); + } + } + return temp; } } 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 fde4b6d173..5a335094f6 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 @@ -27,13 +27,16 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; 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.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.FeatureManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.impl.FeatureManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; +import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; import java.util.ArrayList; import java.util.HashMap; @@ -93,6 +96,16 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { List policies = policyManager.getPoliciesOfDeviceType(pipDevice.getDeviceType().getName()); PolicyFilter policyFilter = new PolicyFilterImpl(); + if (log.isDebugEnabled()) { + log.debug("No of policies for the device type : " + pipDevice.getDeviceType().getName() + " : " + + policies.size()); + for (Policy policy : policies) { + log.debug("Names of policy for above device type : " + policy.getPolicyName()); + } + } + + policies = policyFilter.filterActivePolicies(policies); + if (pipDevice.getDeviceType() != null) { policies = policyFilter.filterDeviceTypeBasedPolicies(pipDevice.getDeviceType().getName(), policies); } @@ -102,10 +115,18 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { if (pipDevice.getRoles() != null) { policies = policyFilter.filterRolesBasedPolicies(pipDevice.getRoles(), policies); } - if(pipDevice.getUserId() != null && !pipDevice.getUserId().isEmpty()) { + if (pipDevice.getUserId() != null && !pipDevice.getUserId().isEmpty()) { policies = policyFilter.filterUserBasedPolicies(pipDevice.getUserId(), policies); } + if (log.isDebugEnabled()) { + log.debug("No of policies selected for the device type : " + pipDevice.getDeviceType().getName() + " : " + + policies.size()); + for (Policy policy : policies) { + log.debug("Names of selected policy for above device type : " + policy.getPolicyName()); + } + } + return policies; } @@ -117,12 +138,14 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { private String[] getRoleOfDevice(Device device) throws PolicyManagementException { try { - return CarbonContext.getThreadLocalCarbonContext().getUserRealm(). - getUserStoreManager().getRoleListOfUser(device.getEnrolmentInfo().getOwner()); + UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm(); + if (userRealm != null) { + return userRealm.getUserStoreManager().getRoleListOfUser(device.getEnrolmentInfo().getOwner()); + } else { + return null; + } } catch (UserStoreException e) { - String msg = "Error occurred when retrieving roles related to user name."; - log.error(msg, e); - throw new PolicyManagementException(msg, e); + throw new PolicyManagementException("Error occurred when retrieving roles related to user name.", e); } } @@ -139,12 +162,11 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { } } } - return finalPolicies; } private DeviceManagementProviderService getDeviceManagementService() { - return PolicyManagementDataHolder.getInstance().getDeviceManagementService(); + return new DeviceManagementProviderServiceImpl(); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java index edc02bb973..6ac0e6b50b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java @@ -19,10 +19,12 @@ package org.wso2.carbon.policy.mgt.core.mgt; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.ProfileFeature; +import java.util.HashMap; import java.util.List; public interface PolicyManager { @@ -37,6 +39,10 @@ public interface PolicyManager { boolean deletePolicy(int policyId) throws PolicyManagementException; + void activatePolicy(int policyId) throws PolicyManagementException; + + void inactivatePolicy(int policyId) throws PolicyManagementException; + Policy addPolicyToDevice(List deviceIdentifierList, Policy policy) throws PolicyManagementException; @@ -63,6 +69,8 @@ public interface PolicyManager { void addAppliedPolicyFeaturesToDevice(DeviceIdentifier deviceIdentifier, Policy policy) throws PolicyManagementException; + List applyChangesMadeToPolicies() throws PolicyManagementException; + void addAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier, Policy policy) throws PolicyManagementException; boolean checkPolicyAvailable(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; @@ -72,4 +80,6 @@ public interface PolicyManager { int getPolicyCount() throws PolicyManagementException; Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; + + HashMap getAppliedPolicyIdsDeviceIds() throws PolicyManagementException; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index 34a9ad9aaa..70e45127d3 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -21,39 +21,35 @@ package org.wso2.carbon.policy.mgt.core.mgt.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.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.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; +import org.wso2.carbon.policy.mgt.common.ProfileFeature; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceDecisionPoint; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature; import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; -import org.wso2.carbon.policy.mgt.common.Policy; -import org.wso2.carbon.policy.mgt.common.ProfileFeature; import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService; -import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAO; -import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAOException; -import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO; -import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; -import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException; +import org.wso2.carbon.policy.mgt.core.dao.*; import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; -import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import java.sql.SQLException; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class MonitoringManagerImpl implements MonitoringManager { @@ -81,8 +77,7 @@ public class MonitoringManagerImpl implements MonitoringManager { DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); PolicyManager manager = new PolicyManagerImpl(); Device device = service.getDevice(deviceIdentifier); - Policy policy = manager.getAppliedPolicyToDevice(deviceIdentifier); //policyDAO.getAppliedPolicy(device - // .getId()); + Policy policy = manager.getAppliedPolicyToDevice(deviceIdentifier); if (policy != null) { PolicyMonitoringService monitoringService = PolicyManagementDataHolder.getInstance(). getPolicyMonitoringService(deviceIdentifier.getType()); @@ -115,7 +110,6 @@ public class MonitoringManagerImpl implements MonitoringManager { if (log.isDebugEnabled()) { log.debug("Compliance status primary key " + complianceData.getId()); } -// complianceData.setId(cmf.getId()); monitoringDAO.addNoneComplianceFeatures(complianceData.getId(), device.getId(), complianceFeatures); PolicyManagementDAOFactory.commitTransaction(); complianceDecisionPoint.validateDevicePolicyCompliance(deviceIdentifier, complianceData); @@ -130,7 +124,6 @@ public class MonitoringManagerImpl implements MonitoringManager { } else { PolicyManagementDAOFactory.beginTransaction(); monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId()); - //complianceData.setId(cmf.getId()); monitoringDAO.deleteNoneComplianceData(complianceData.getId()); PolicyManagementDAOFactory.commitTransaction(); } @@ -162,7 +155,6 @@ public class MonitoringManagerImpl implements MonitoringManager { try { DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); - //deviceDAO.getDevice(deviceIdentifier, tenantId); PolicyManagementDAOFactory.openConnection(); ComplianceData complianceData = monitoringDAO.getCompliance(device.getId()); if (complianceData == null || !complianceData.isStatus()) { 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 7456d57a8c..d72eb83099 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 @@ -27,19 +27,18 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; 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.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.core.dao.*; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import java.sql.SQLException; import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.List; +import java.util.*; public class PolicyManagerImpl implements PolicyManager { @@ -47,7 +46,6 @@ public class PolicyManagerImpl implements PolicyManager { private ProfileDAO profileDAO; private FeatureDAO featureDAO; private DeviceDAO deviceDAO; - // private DeviceTypeDAO deviceTypeDAO; private ProfileManager profileManager; private static Log log = LogFactory.getLog(PolicyManagerImpl.class); @@ -56,7 +54,6 @@ public class PolicyManagerImpl implements PolicyManager { this.profileDAO = PolicyManagementDAOFactory.getProfileDAO(); this.featureDAO = PolicyManagementDAOFactory.getFeatureDAO(); this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); -// this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); this.profileManager = new ProfileManagerImpl(); } @@ -72,7 +69,6 @@ public class PolicyManagerImpl implements PolicyManager { profile.setCreatedDate(currentTimestamp); profile.setUpdatedDate(currentTimestamp); - profileDAO.addProfile(profile); featureDAO.addProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId()); } @@ -110,17 +106,6 @@ public class PolicyManagerImpl implements PolicyManager { policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias()); } -// if (policy.getEndDate() != null & policy.getStartDate() != null) { -// policyDAO.addDatesToPolicy(policy.getStartDate(), policy.getEndDate(), policy); -// } -// -// if (policy.getStartTime() != 0 & policy.getEndTime() != 0) { -// policyDAO.addTimesToPolicy(policy.getStartTime(), policy.getEndTime(), policy); -// } -// -// if (policy.getLatitude() != null && policy.getLongitude() != null) { -// policyDAO.addLocationToPolicy(policy.getLatitude(), policy.getLongitude(), policy); -// } PolicyManagementDAOFactory.commitTransaction(); } catch (PolicyManagerDAOException e) { @@ -147,7 +132,13 @@ public class PolicyManagerImpl implements PolicyManager { try { PolicyManagementDAOFactory.beginTransaction(); - policy = policyDAO.updatePolicy(policy); + // This will keep track of the policies updated. + policyDAO.recordUpdatedPolicy(policy); + + policyDAO.updatePolicy(policy); + profileDAO.updateProfile(policy.getProfile()); + featureDAO.updateProfileFeatures(policy.getProfile().getProfileFeaturesList(), policy.getProfile() + .getProfileId()); policyDAO.deleteAllPolicyRelatedConfigs(policy.getId()); if (policy.getUsers() != null) { @@ -177,23 +168,20 @@ public class PolicyManagerImpl implements PolicyManager { policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias()); } -// if (policy.getEndDate() != null & policy.getStartDate() != null) { -// policyDAO.addDatesToPolicy(policy.getStartDate(), policy.getEndDate(), policy); -// } -// -// if (policy.getStartTime() != 0 & policy.getEndTime() != 0) { -// policyDAO.addTimesToPolicy(policy.getStartTime(), policy.getEndTime(), policy); -// } -// -// if (policy.getLatitude() != null && policy.getLongitude() != null) { -// policyDAO.addLocationToPolicy(policy.getLatitude(), policy.getLongitude(), policy); -// } - PolicyManagementDAOFactory.commitTransaction(); } catch (PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyManagementException("Error occurred while updating the policy (" + policy.getId() + " - " + policy.getPolicyName() + ")", e); + } catch (ProfileManagerDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while updating the profile (" + + policy.getProfile().getProfileName() + ")", e); + } catch (FeatureManagerDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while updating the profile features (" + + policy.getProfile().getProfileName() + ")", e); + } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -206,6 +194,7 @@ public class PolicyManagerImpl implements PolicyManager { try { PolicyManagementDAOFactory.beginTransaction(); bool = policyDAO.updatePolicyPriorities(policies); + policyDAO.recordUpdatedPolicies(policies); PolicyManagementDAOFactory.commitTransaction(); } catch (PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); @@ -245,12 +234,13 @@ public class PolicyManagerImpl implements PolicyManager { @Override public boolean deletePolicy(int policyId) throws PolicyManagementException { + boolean bool; try { PolicyManagementDAOFactory.beginTransaction(); Policy policy = policyDAO.getPolicy(policyId); policyDAO.deleteAllPolicyRelatedConfigs(policyId); - policyDAO.deletePolicy(policyId); + bool = policyDAO.deletePolicy(policyId); if (log.isDebugEnabled()) { log.debug("Profile ID: " + policy.getProfileId()); @@ -260,7 +250,7 @@ public class PolicyManagerImpl implements PolicyManager { profileDAO.deleteProfile(policy.getProfileId()); PolicyManagementDAOFactory.commitTransaction(); - return true; + return bool; } catch (PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyManagementException("Error occurred while deleting the policy (" + policyId + ")", e); @@ -277,6 +267,41 @@ public class PolicyManagerImpl implements PolicyManager { } } + @Override + public void activatePolicy(int policyId) throws PolicyManagementException { + try { + Policy policy = this.getPolicy(policyId); + PolicyManagementDAOFactory.beginTransaction(); + policyDAO.activatePolicy(policyId); + policyDAO.recordUpdatedPolicy(policy); + PolicyManagementDAOFactory.commitTransaction(); + } catch (PolicyManagerDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while activating the policy. (Id : " + policyId + ")" + + "", e); + } finally { + PolicyManagementDAOFactory.closeConnection(); + } + } + + @Override + public void inactivatePolicy(int policyId) throws PolicyManagementException { + try { + Policy policy = this.getPolicy(policyId); + PolicyManagementDAOFactory.beginTransaction(); + policyDAO.inactivatePolicy(policyId); + policyDAO.recordUpdatedPolicy(policy); + PolicyManagementDAOFactory.commitTransaction(); + } catch (PolicyManagerDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while inactivating the policy. (Id : " + policyId + + ")" + + "", e); + } finally { + PolicyManagementDAOFactory.closeConnection(); + } + } + @Override public Policy addPolicyToDevice(List deviceIdentifierList, Policy policy) throws PolicyManagementException { @@ -391,17 +416,12 @@ public class PolicyManagerImpl implements PolicyManager { try { PolicyManagementDAOFactory.openConnection(); policy = policyDAO.getPolicyByProfileID(profileId); - deviceList = getPolicyAppliedDevicesIds(policy.getId()); - roleNames = policyDAO.getPolicyAppliedRoles(policy.getId()); -// policyDAO.getDatesOfPolicy(policy); -// policyDAO.getTimesOfPolicy(policy); -// policyDAO.getLocationsOfPolicy(policy); + roleNames = policyDAO.getPolicyAppliedRoles(policy.getId()); profile = profileDAO.getProfiles(profileId); - policy.setProfile(profile); policy.setRoles(roleNames); - policy.setDevices(deviceList); + } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the policy related to profile ID (" + @@ -414,6 +434,10 @@ public class PolicyManagerImpl implements PolicyManager { } finally { PolicyManagementDAOFactory.closeConnection(); } + + // This is due to connection close in following method too. + deviceList = getPolicyAppliedDevicesIds(policy.getId()); + policy.setDevices(deviceList); return policy; } @@ -427,17 +451,13 @@ public class PolicyManagerImpl implements PolicyManager { try { PolicyManagementDAOFactory.openConnection(); policy = policyDAO.getPolicy(policyId); - deviceList = getPolicyAppliedDevicesIds(policyId); - roleNames = policyDAO.getPolicyAppliedRoles(policyId); -// policyDAO.getDatesOfPolicy(policy); -// policyDAO.getTimesOfPolicy(policy); -// policyDAO.getLocationsOfPolicy(policy); + roleNames = policyDAO.getPolicyAppliedRoles(policyId); Profile profile = profileDAO.getProfiles(policy.getProfileId()); policy.setProfile(profile); policy.setRoles(roleNames); - policy.setDevices(deviceList); + } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the policy related to policy ID (" + @@ -450,11 +470,16 @@ public class PolicyManagerImpl implements PolicyManager { } finally { PolicyManagementDAOFactory.closeConnection(); } + + // This is done because connection close in below method too. + deviceList = this.getPolicyAppliedDevicesIds(policyId); + policy.setDevices(deviceList); return policy; } @Override public List getPolicies() throws PolicyManagementException { + List policyList; List profileList; try { @@ -465,7 +490,6 @@ public class PolicyManagerImpl implements PolicyManager { try { PolicyManagementDAOFactory.openConnection(); policyList = policyDAO.getAllPolicies(); -// List profileList = profileDAO.getAllProfiles(); for (Policy policy : policyList) { for (Profile profile : profileList) { @@ -473,13 +497,9 @@ public class PolicyManagerImpl implements PolicyManager { policy.setProfile(profile); } } - policy.setDevices(getPolicyAppliedDevicesIds(policy.getId())); policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId())); policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId())); policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId())); -// policyDAO.getDatesOfPolicy(policy); -// policyDAO.getTimesOfPolicy(policy); -// policyDAO.getLocationsOfPolicy(policy); } Collections.sort(policyList); } catch (PolicyManagerDAOException e) { @@ -489,6 +509,13 @@ public class PolicyManagerImpl implements PolicyManager { } finally { PolicyManagementDAOFactory.closeConnection(); } + + // Following is done because connection close has been implemented in every method. + + for (Policy policy : policyList) { + policy.setDevices(this.getPolicyAppliedDevicesIds(policy.getId())); + } + return policyList; } @@ -612,24 +639,43 @@ public class PolicyManagerImpl implements PolicyManager { @Override public List getPolicyAppliedDevicesIds(int policyId) throws PolicyManagementException { + List deviceList = new ArrayList<>(); List deviceIds; try { PolicyManagementDAOFactory.openConnection(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); deviceIds = policyDAO.getPolicyAppliedDevicesIds(policyId); + DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); + List allDevices = service.getAllDevices(); + + HashMap allDeviceMap = new HashMap<>(); + + if(!allDevices.isEmpty()) { + allDeviceMap = PolicyManagerUtil.covertDeviceListToMap(allDevices); + } + for (int deviceId : deviceIds) { - //TODO FIX ME - deviceList.add(deviceDAO.getDevice(new DeviceIdentifier(Integer.toString(deviceId), ""), tenantId)); + + if(allDeviceMap.containsKey(deviceId)){ + if(log.isDebugEnabled()) { + log.debug("Policy Applied device ids .............: " + deviceId + " - Policy Id " + policyId); + } + deviceList.add(allDeviceMap.get(deviceId)); + } + + //TODO FIX ME -- This is wrong, Device id is not device identifier, so converting is wrong. + + //deviceList.add(deviceDAO.getDevice(new DeviceIdentifier(Integer.toString(deviceId), ""), tenantId)); } } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the device ids related to policy id (" + policyId + ")", e); - } catch (DeviceManagementDAOException e) { - throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" + - policyId + ")", e); } catch (SQLException e) { throw new PolicyManagementException("Error occurred while opening a connection to the data source", e); + } catch (DeviceManagementException e) { + throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" + + policyId + ")", e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -665,6 +711,47 @@ public class PolicyManagerImpl implements PolicyManager { } } + @Override + public List applyChangesMadeToPolicies() throws PolicyManagementException { + + List changedDeviceTypes = new ArrayList<>(); + try { + //HashMap map = policyDAO.getUpdatedPolicyIdandDeviceTypeId(); + List updatedPolicies = new ArrayList<>(); +// List activePolicies = new ArrayList<>(); +// List inactivePolicies = new ArrayList<>(); + List updatedPolicyIds = new ArrayList<>(); + + List allPolicies = this.getPolicies(); + + for (Policy policy : allPolicies) { + if (policy.isUpdated()) { + updatedPolicies.add(policy); + updatedPolicyIds.add(policy.getId()); + if (!changedDeviceTypes.contains(policy.getProfile().getDeviceType())) { + changedDeviceTypes.add(policy.getProfile().getDeviceType()); + } + } +// if (policy.isActive()) { +// activePolicies.add(policy); +// } else { +// inactivePolicies.add(policy); +// } + } + PolicyManagementDAOFactory.beginTransaction(); + policyDAO.markPoliciesAsUpdated(updatedPolicyIds); + policyDAO.removeRecordsAboutUpdatedPolicies(); + PolicyManagementDAOFactory.commitTransaction(); + } catch (PolicyManagerDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyManagementException("Error occurred while applying the changes to policy operations.", e); + } finally { + PolicyManagementDAOFactory.closeConnection(); + } + return changedDeviceTypes; + } + + @Override public void addAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier, Policy policy) throws PolicyManagementException { @@ -674,13 +761,11 @@ public class PolicyManagerImpl implements PolicyManager { DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); deviceId = device.getId(); - // boolean exist = policyDAO.checkPolicyAvailable(deviceId); - PolicyManagementDAOFactory.beginTransaction(); Policy policySaved = policyDAO.getAppliedPolicy(deviceId); if (policySaved != null && policySaved.getId() != 0) { - if (policy.getId() != policySaved.getId()){ + if (policy.getId() != policySaved.getId()) { policyDAO.updateEffectivePolicyToDevice(deviceId, policy); } } else { @@ -782,4 +867,18 @@ public class PolicyManagerImpl implements PolicyManager { return policy; } + @Override + public HashMap getAppliedPolicyIdsDeviceIds() throws PolicyManagementException { + try { + PolicyManagementDAOFactory.openConnection(); + return policyDAO.getAppliedPolicyIdsDeviceIds(); + } catch (PolicyManagerDAOException e) { + throw new PolicyManagementException("Error occurred while reading the policy applied database.", e); + } catch (SQLException e) { + throw new PolicyManagementException("Error occurred while reading the policy applied database.", e); + } finally { + PolicyManagementDAOFactory.closeConnection(); + } + } + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java index 2dc77739cd..931b97a37c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java @@ -91,7 +91,7 @@ public class ProfileManagerImpl implements ProfileManager { try { PolicyManagementDAOFactory.beginTransaction(); - profile = profileDAO.updateProfile(profile); + profileDAO.updateProfile(profile); featureDAO.updateProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId()); PolicyManagementDAOFactory.commitTransaction(); } catch (ProfileManagerDAOException e) { @@ -166,6 +166,7 @@ public class ProfileManagerImpl implements ProfileManager { throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); } finally { PolicyManagementDAOFactory.closeConnection(); + DeviceManagementDAOFactory.closeConnection(); } return profile; } @@ -204,6 +205,7 @@ public class ProfileManagerImpl implements ProfileManager { throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); } finally { PolicyManagementDAOFactory.closeConnection(); + DeviceManagementDAOFactory.closeConnection(); } return profileList; } @@ -238,6 +240,7 @@ public class ProfileManagerImpl implements ProfileManager { throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); } finally { PolicyManagementDAOFactory.closeConnection(); + DeviceManagementDAOFactory.closeConnection(); } return profileList; } 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 1beea7f39f..198913c055 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 @@ -21,6 +21,7 @@ package org.wso2.carbon.policy.mgt.core.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; @@ -41,6 +42,7 @@ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.ObjectOutputStream; import java.util.ArrayList; +import java.util.HashMap; import java.util.Hashtable; import java.util.List; @@ -140,9 +142,29 @@ public class PolicyManagerUtil { return data; } + public static boolean convertIntToBoolean(int x) { - public static Cache getCacheManagerImpl(){ + if (x == 1) { + return true; + } else { + return false; + } + } + + + public static Cache getCacheManagerImpl() { return Caching.getCacheManagerFactory() - .getCacheManager(PolicyManagementConstants.DM_CACHE_MANAGER).getCache(PolicyManagementConstants.DM_CACHE); + .getCacheManager(PolicyManagementConstants.DM_CACHE_MANAGER).getCache(PolicyManagementConstants + .DM_CACHE); + } + + + public static HashMap covertDeviceListToMap(List devices) { + + HashMap deviceHashMap = new HashMap<>(); + for (Device device : devices) { + deviceHashMap.put(device.getId(), device); + } + return deviceHashMap; } } 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 8cad5f5b78..617bf9ad86 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 @@ -49,7 +49,7 @@ public abstract class BasePolicyManagementDAOTest { @BeforeSuite public void setupDataSource() throws Exception { this.initDatSource(); - this.initSQLScript(); + // this.initSQLScript(); } public void initDatSource() throws Exception { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java index 986f642e8f..bde1b14d8b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java @@ -81,9 +81,9 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { identifier.setType(ANDROID); identifier.setId(devices.get(0).getDeviceIdentifier()); - PolicyAdministratorPoint administratorPoint = new PolicyAdministratorPointImpl(); - - administratorPoint.setPolicyUsed(identifier, policies.get(0)); +// PolicyAdministratorPoint administratorPoint = new PolicyAdministratorPointImpl(); +// +// administratorPoint.setPolicyUsed(identifier, policies.get(0)); } @@ -116,9 +116,11 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { DeviceManagementDataHolder.getInstance().setOperationManager(operationManager); - log.debug(policy.getId()); - log.debug(policy.getPolicyName()); - log.debug(policy.getCompliance()); + if (policy != null) { + log.debug(policy.getId()); + log.debug(policy.getPolicyName()); + log.debug(policy.getCompliance()); + } MonitoringManager monitoringManager = new MonitoringManagerImpl(); @@ -137,14 +139,13 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { PolicyComplianceException { - PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest(); PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(), monitoringServiceTest); DeviceManagementProviderService adminService = new DeviceManagementProviderServiceImpl(); - // PolicyManager policyManagerService = new PolicyManagerImpl(); + // PolicyManager policyManagerService = new PolicyManagerImpl(); List devices = adminService.getAllDevices(); @@ -166,7 +167,8 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { @Test(dependsOnMethods = ("checkComplianceFromMonitoringService")) - public void checkCompliance() throws DeviceManagementException, PolicyComplianceException, PolicyManagementException { + public void checkCompliance() throws DeviceManagementException, PolicyComplianceException, + PolicyManagementException { PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest(); PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(), diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java index e14ea1a1b3..6fdb405973 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java @@ -76,25 +76,30 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); DeviceType type = DeviceTypeCreator.getDeviceType(); devices = DeviceCreator.getDeviceList(type); + devices.addAll(DeviceCreator.getDeviceList2(type)); + devices.addAll(DeviceCreator.getDeviceList3(type)); + devices.addAll(DeviceCreator.getDeviceList4(type)); + devices.addAll(DeviceCreator.getDeviceList5(type)); + devices.addAll(DeviceCreator.getDeviceList6(type)); for (Device device : devices) { int id = deviceDAO.addDevice(type.getId(), device, -1234); enrolmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -1234); } - List devices = deviceDAO.getDevices(-1234); - - log.debug("--- Printing device taken by calling the device dao layer by tenant id."); - for (Device device : devices) { - log.debug(device.getDeviceIdentifier()); - } - - - log.debug("--- Printing device taken by calling the device dao layer by tenant id and device type."); - List devices2 = deviceDAO.getDevices("android", -1234); - - for (Device device : devices2) { - log.debug(device.getDeviceIdentifier()); - } +// List devices = deviceDAO.getDevices(-1234); +// +// log.debug("--- Printing device taken by calling the device dao layer by tenant id."); +// for (Device device : devices) { +// log.debug(device.getDeviceIdentifier()); +// } +// +// +// log.debug("--- Printing device taken by calling the device dao layer by tenant id and device type."); +// List devices2 = deviceDAO.getDevices("android", -1234); +// +// for (Device device : devices2) { +// log.debug(device.getDeviceIdentifier()); +// } DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); @@ -103,6 +108,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { log.debug("Printing device taken by calling the service layer with device type."); List devices3 = service.getAllDevices("android"); + log.debug("Device list size ..........................!" + devices3.size()); for (Device device : devices3) { log.debug(device.getDeviceIdentifier()); } @@ -125,15 +131,15 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { public void addProfileFeatures() throws ProfileManagementException { ProfileManager profileManager = new ProfileManagerImpl(); - profile = ProfileCreator.getProfile(featureList); - profileManager.addProfile(profile); - profileFeatureList = profile.getProfileFeaturesList(); + Profile profile = ProfileCreator.getProfile2(FeatureCreator.getFeatureList2()); +// profileManager.addProfile(profile); +// profileFeatureList = profile.getProfileFeaturesList(); } @Test(dependsOnMethods = ("addProfileFeatures")) public void addPolicy() throws PolicyManagementException, ProfileManagementException { ProfileManager profileManager = new ProfileManagerImpl(); - profile = ProfileCreator.getProfile(featureList); + Profile profile = ProfileCreator.getProfile5(FeatureCreator.getFeatureList5()); profileManager.addProfile(profile); PolicyManager policyManager = new PolicyManagerImpl(); policy = PolicyCreator.createPolicy(profile); @@ -171,10 +177,10 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { @Test(dependsOnMethods = ("addPolicyToDevice")) public void addNewPolicy() throws PolicyManagementException, ProfileManagementException { ProfileManager profileManager = new ProfileManagerImpl(); - profile = ProfileCreator.getProfile(featureList); + Profile profile = ProfileCreator.getProfile3(FeatureCreator.getFeatureList3()); profileManager.addProfile(profile); PolicyManager policyManager = new PolicyManagerImpl(); - policy = PolicyCreator.createPolicy2(profile); + Policy policy = PolicyCreator.createPolicy2(profile); policyManager.addPolicy(policy); } @@ -182,10 +188,10 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { @Test(dependsOnMethods = ("addPolicyToDevice")) public void addThirdPolicy() throws PolicyManagementException, ProfileManagementException { ProfileManager profileManager = new ProfileManagerImpl(); - profile = ProfileCreator.getProfile(featureList); + Profile profile = ProfileCreator.getProfile4(FeatureCreator.getFeatureList4()); profileManager.addProfile(profile); PolicyManager policyManager = new PolicyManagerImpl(); - policy = PolicyCreator.createPolicy4(profile); + Policy policy = PolicyCreator.createPolicy4(profile); policyManager.addPolicy(policy); } @@ -279,14 +285,28 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { @Test(dependsOnMethods = ("getRoleRelatedPolicy")) public void addSecondPolicy() throws PolicyManagementException, ProfileManagementException { ProfileManager profileManager = new ProfileManagerImpl(); - profile = ProfileCreator.getProfile(featureList); + Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList()); profileManager.addProfile(profile); PolicyManager policyManager = new PolicyManagerImpl(); - policy = PolicyCreator.createPolicy3(profile); + Policy policy = PolicyCreator.createPolicy3(profile); policyManager.addPolicy(policy); } - @Test(dependsOnMethods = ("getDeviceTypeRelatedPolicy")) + @Test(dependsOnMethods = ("addSecondPolicy")) + public void updatedPolicy() throws PolicyManagementException { + PolicyManager policyManager = new PolicyManagerImpl(); + Profile profile = ProfileCreator.getProfile3(FeatureCreator.getFeatureList3()); + Policy policy = PolicyCreator.createPolicy3(profile); + policy.setPolicyName("Policy_05"); + policy = policyManager.addPolicy(policy); + List users = new ArrayList<>(); + users.add("Udara"); + users.add("Dileesha"); + policy.setUsers(users); + policyManager.updatePolicy(policy); + } + + @Test(dependsOnMethods = ("updatedPolicy")) public void getRoleRelatedPolicySecondTime() throws PolicyManagementException { PolicyAdministratorPoint policyAdministratorPoint = new PolicyAdministratorPointImpl(); @@ -369,6 +389,8 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { log.debug(device.getDeviceIdentifier() + " ----- D"); } - } + + + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java new file mode 100644 index 0000000000..49fe843cbe --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +package org.wso2.carbon.policy.mgt.core; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +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.core.service.DeviceManagementProviderService; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.policy.mgt.common.*; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; +import org.wso2.carbon.policy.mgt.core.services.SimplePolicyEvaluationTest; + +import java.util.Collections; +import java.util.List; + +public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest { + + private static final String ANDROID = "android"; + private static final Log log = LogFactory.getLog(PolicyEvaluationTestCase.class); + + + @BeforeClass + @Override + public void init() throws Exception { + + PolicyEvaluationPoint evaluationPoint = new SimplePolicyEvaluationTest(); + PolicyManagementDataHolder.getInstance().setPolicyEvaluationPoint(evaluationPoint); + } + + @Test + public void activatePolicies() throws PolicyManagementException { + PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); + PolicyAdministratorPoint administratorPoint = policyManagerService.getPAP(); + List policies = policyManagerService.getPolicies(ANDROID); + + for (Policy policy : policies) { + log.debug("Policy status : " + policy.getPolicyName() + " - " + policy.isActive() + " - " + policy + .isUpdated()); + + if (!policy.isActive()) { + administratorPoint.activatePolicy(policy.getId()); + } + } + administratorPoint.publishChanges(); + } + + @Test(dependsOnMethods = ("activatePolicies")) + public void getEffectivePolicy() throws DeviceManagementException, PolicyEvaluationException { + + log.debug("Getting effective policy for device started .........."); + + DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); + List devices = service.getAllDevices(ANDROID); + + PolicyEvaluationPoint evaluationPoint = PolicyManagementDataHolder.getInstance().getPolicyEvaluationPoint(); + + for (Device device : devices) { + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setType(device.getType()); + identifier.setId(device.getDeviceIdentifier()); + Policy policy = evaluationPoint.getEffectivePolicy(identifier); + + if (policy != null) { + log.debug("Name of the policy applied to device is " + policy.getPolicyName()); + } else { + log.debug("No policy is applied to device."); + } + } + } + + + @Test(dependsOnMethods = ("getEffectivePolicy")) + public void updatePriorities() throws PolicyManagementException { + + PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); + PolicyAdministratorPoint administratorPoint = policyManagerService.getPAP(); + + List policies = administratorPoint.getPolicies(); + + log.debug("Re-enforcing policy started...."); + + int sixe = policies.size(); + + sortPolicies(policies); + int x = 0; + for (Policy policy : policies) { + policy.setPriorityId(sixe - x); + x++; + } + + + + administratorPoint.updatePolicyPriorities(policies); + administratorPoint.publishChanges(); + } + + public void sortPolicies(List policyList) { + Collections.sort(policyList); + } +} diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/services/SimplePolicyEvaluationTest.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/services/SimplePolicyEvaluationTest.java new file mode 100644 index 0000000000..4895155371 --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/services/SimplePolicyEvaluationTest.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +package org.wso2.carbon.policy.mgt.core.services; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.policy.mgt.common.*; +import org.wso2.carbon.policy.mgt.core.PolicyManagerService; +import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl; + +import java.util.Collections; +import java.util.List; + +public class SimplePolicyEvaluationTest implements PolicyEvaluationPoint { + + private static final Log log = LogFactory.getLog(SimplePolicyEvaluationTest.class); + + @Override + public Policy getEffectivePolicy(DeviceIdentifier deviceIdentifier) throws PolicyEvaluationException { + Policy policy = new Policy(); + + List policyList; + PolicyAdministratorPoint policyAdministratorPoint; + PolicyInformationPoint policyInformationPoint; + PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); + + try { + if (policyManagerService != null) { + + policyInformationPoint = policyManagerService.getPIP(); + PIPDevice pipDevice = policyInformationPoint.getDeviceData(deviceIdentifier); + policyList = policyInformationPoint.getRelatedPolicies(pipDevice); + + for(Policy pol : policyList) { + log.debug("Policy used in evaluation - Name : " + pol.getPolicyName() ); + } + + sortPolicies(policyList); + if(!policyList.isEmpty()) { + policy = policyList.get(0); + } else { + return null; + } + + policyAdministratorPoint = policyManagerService.getPAP(); + policyAdministratorPoint.setPolicyUsed(deviceIdentifier, policy); + + } + + } catch (PolicyManagementException e) { + String msg = "Error occurred when retrieving the policy related data from policy management service."; + log.error(msg, e); + throw new PolicyEvaluationException(msg, e); + } + return policy; + } + + @Override + public List getEffectiveFeatures(DeviceIdentifier deviceIdentifier) throws PolicyEvaluationException { + return null; + } + + public void sortPolicies(List policyList) throws PolicyEvaluationException { + Collections.sort(policyList); + } +} diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/DeviceCreator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/DeviceCreator.java index 769c83c514..0fc65b9dca 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/DeviceCreator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/DeviceCreator.java @@ -27,10 +27,12 @@ import java.util.List; public class DeviceCreator { - private static List deviceList = new ArrayList(); + //private static ; public static List getDeviceList(DeviceType deviceType) { + List deviceList = new ArrayList(); + Device device = new Device(); device.setId(1); device.setType(deviceType.getName()); @@ -42,25 +44,131 @@ public class DeviceCreator { enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); device.setEnrolmentInfo(enrolmentInfo); - Device device1 = new Device(); - device1.setId(1); - device1.setType(deviceType.getName()); - device1.setName("Nexus 5"); - device1.setDeviceIdentifier("def456"); - EnrolmentInfo enrolmentInfo1 = new EnrolmentInfo(); - enrolmentInfo1.setOwner("Manoj"); - enrolmentInfo1.setOwnership(EnrolmentInfo.OwnerShip.BYOD); - enrolmentInfo1.setStatus(EnrolmentInfo.Status.ACTIVE); - device1.setEnrolmentInfo(enrolmentInfo); +// Device device1 = new Device(); +// device1.setId(2); +// device1.setType(deviceType.getName()); +// device1.setName("Nexus 5"); +// device1.setDeviceIdentifier("def456"); +// EnrolmentInfo enrolmentInfo1 = new EnrolmentInfo(); +// enrolmentInfo1.setOwner("Manoj"); +// enrolmentInfo1.setOwnership(EnrolmentInfo.OwnerShip.BYOD); +// enrolmentInfo1.setStatus(EnrolmentInfo.Status.ACTIVE); +// device1.setEnrolmentInfo(enrolmentInfo); + + deviceList.add(device); + // deviceList.add(device1); + + return deviceList; + } + + + public static List getDeviceList2 (DeviceType deviceType) { + List deviceList = new ArrayList(); + + Device device = new Device(); + device.setId(2); + device.setType(deviceType.getName()); + device.setName("Apple 5S"); + device.setDeviceIdentifier("def123"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Dilshan"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + + deviceList.add(device); + return deviceList; + } + + public static List getDeviceList3 (DeviceType deviceType) { + List deviceList = new ArrayList(); + + Device device = new Device(); + device.setId(3); + device.setType(deviceType.getName()); + device.setName("Apple 6 Large"); + device.setDeviceIdentifier("xxxx123"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Harshan"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + + deviceList.add(device); + return deviceList; + } + + public static List getDeviceList4 (DeviceType deviceType) { + List deviceList = new ArrayList(); + + Device device = new Device(); + device.setId(4); + device.setType(deviceType.getName()); + device.setName("HTC M"); + device.setDeviceIdentifier("ppp456"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Dilan"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + + deviceList.add(device); + return deviceList; + } + + public static List getDeviceList5 (DeviceType deviceType) { + List deviceList = new ArrayList(); + + Device device = new Device(); + device.setId(5); + device.setType(deviceType.getName()); + device.setName("Sony Experia L"); + device.setDeviceIdentifier("ssss123"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Milan"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); deviceList.add(device); - // deviceList.add(device2); + return deviceList; + } + + + public static List getDeviceList6 (DeviceType deviceType) { + List deviceList = new ArrayList(); + + Device device = new Device(); + device.setId(6); + device.setType(deviceType.getName()); + device.setName("Alcatel RTS"); + device.setDeviceIdentifier("ttt123"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Dileesha"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + deviceList.add(device); return deviceList; } + public static Device getSingleDevice() { - return deviceList.get(0); + + Device device = new Device(); + device.setId(1); + device.setType("android"); + device.setName("Galaxy S6"); + device.setDeviceIdentifier("abc123"); + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setOwner("Geeth"); + enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); + enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); + device.setEnrolmentInfo(enrolmentInfo); + + + return device; } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/FeatureCreator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/FeatureCreator.java index c487e7c6ea..6456773a08 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/FeatureCreator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/FeatureCreator.java @@ -21,10 +21,15 @@ package org.wso2.carbon.policy.mgt.core.util; import org.wso2.carbon.device.mgt.common.Feature; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; public class FeatureCreator { + private static List featureList = new ArrayList(); + + private static HashMap featureMap = new HashMap<>(); + public static List getFeatureList() { Feature feature1 = new Feature(); @@ -119,7 +124,7 @@ public class FeatureCreator { feature11.setDeviceType("android"); - List featureList = new ArrayList(); + List featureList2 = new ArrayList(); featureList.add(feature1); featureList.add(feature2); featureList.add(feature3); @@ -132,6 +137,70 @@ public class FeatureCreator { featureList.add(feature10); featureList.add(feature11); - return featureList; + featureList2.add(feature1); + featureList2.add(feature2); + + + int i = 1; + for (Feature feature : featureList) { + featureMap.put(i, feature); + i++; + } + + return featureList2; + } + + public static List getFeatureList2() { + List featureList2 = new ArrayList(); + + featureList2.add(featureMap.get(3)); + featureList2.add(featureMap.get(4)); + + return featureList2; + } + + public static List getFeatureList3() { + List featureList2 = new ArrayList(); + + featureList2.add(featureMap.get(5)); + featureList2.add(featureMap.get(6)); + featureList2.add(featureMap.get(7)); + + return featureList2; + } + + public static List getFeatureList4() { + List featureList2 = new ArrayList(); + + featureList2.add(featureMap.get(7)); + featureList2.add(featureMap.get(8)); + featureList2.add(featureMap.get(9)); + + return featureList2; + } + + public static List getFeatureList5() { + List featureList2 = new ArrayList(); + + featureList2.add(featureMap.get(9)); + featureList2.add(featureMap.get(10)); + featureList2.add(featureMap.get(11)); + featureList2.add(featureMap.get(3)); + + return featureList2; + } + + + public static List getFeatureList6() { + List featureList2 = new ArrayList(); + + featureList2.add(featureMap.get(3)); + featureList2.add(featureMap.get(8)); + featureList2.add(featureMap.get(9)); + featureList2.add(featureMap.get(5)); + + return featureList2; } } + + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java index 7ef7ab4a37..a7dbe5c4a6 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java @@ -50,7 +50,7 @@ public class PolicyCreator { policy.setPolicyName("Test_Policy_02"); policy.setGeneric(true); policy.setProfile(profile); - policy.setDevices(DeviceCreator.getDeviceList(DeviceTypeCreator.getDeviceType())); + policy.setDevices(DeviceCreator.getDeviceList2(DeviceTypeCreator.getDeviceType())); policy.setCompliance("ENFORCE"); @@ -99,7 +99,7 @@ public class PolicyCreator { policy.setPolicyName("Test_Policy_03"); policy.setGeneric(true); policy.setProfile(profile); - policy.setDevices(DeviceCreator.getDeviceList(DeviceTypeCreator.getDeviceType())); + policy.setDevices(DeviceCreator.getDeviceList3(DeviceTypeCreator.getDeviceType())); List roles = new ArrayList(); roles.add("Role_01"); @@ -138,7 +138,7 @@ public class PolicyCreator { policy.setPolicyName("Test_Policy_04"); policy.setGeneric(true); policy.setProfile(profile); - policy.setDevices(DeviceCreator.getDeviceList(DeviceTypeCreator.getDeviceType())); + policy.setDevices(DeviceCreator.getDeviceList4(DeviceTypeCreator.getDeviceType())); policy.setCompliance("MONITOR"); policy.setOwnershipType("BYOD"); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java index 4bd1392590..19574abdf6 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/ProfileCreator.java @@ -41,4 +41,66 @@ public class ProfileCreator { return profile; } + + public static Profile getProfile2(List features) { + Profile profile = new Profile(); + DeviceType deviceType = new DeviceType(); + + deviceType.setId(1); + deviceType.setName("android"); + + profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features)); + profile.setProfileName("Test Profile 2"); + profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + profile.setDeviceType(deviceType); + + return profile; + } + + public static Profile getProfile3(List features) { + Profile profile = new Profile(); + DeviceType deviceType = new DeviceType(); + + deviceType.setId(1); + deviceType.setName("android"); + + profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features)); + profile.setProfileName("Test Profile 3"); + profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + profile.setDeviceType(deviceType); + + return profile; + } + + public static Profile getProfile4(List features) { + Profile profile = new Profile(); + DeviceType deviceType = new DeviceType(); + + deviceType.setId(1); + deviceType.setName("android"); + + profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features)); + profile.setProfileName("Test Profile 4"); + profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + profile.setDeviceType(deviceType); + + return profile; + } + + + public static Profile getProfile5(List features) { + Profile profile = new Profile(); + DeviceType deviceType = new DeviceType(); + + deviceType.setId(1); + deviceType.setName("android"); + + profile.setProfileFeaturesList(ProfileFeatureCreator.getProfileFeature(features)); + profile.setProfileName("Test Profile 5"); + profile.setTenantId(MultitenantConstants.SUPER_TENANT_ID); + profile.setDeviceType(deviceType); + + return profile; + } } + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml index 7450e52f77..2a9ebfc1b0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml @@ -23,18 +23,18 @@ - jdbc:h2:mem:cdm-test-db;DB_CLOSE_DELAY=-1 - org.h2.Driver - wso2carbon - wso2carbon + + + + - - - - + jdbc:mysql://localhost:3306/WSO2CDM + com.mysql.jdbc.Driver + root + 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 3263fa8290..4a32bc8db7 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 @@ -109,7 +109,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATIONS ( 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, + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ); --- POLICY RELATED TABLES ---- @@ -143,7 +143,9 @@ CREATE TABLE IF NOT EXISTS DM_POLICY ( PROFILE_ID INT(11) NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, - PRIORITY INT NOT NULL , + PRIORITY INT NOT NULL, + ACTIVE INT(2) NOT NULL, + UPDATED INT(1) NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_PROFILE_DM_POLICY FOREIGN KEY (PROFILE_ID ) @@ -345,6 +347,19 @@ 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), + CONSTRAINT FK_POLICY_CHANGE_MGT_POLICY + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + -- POLICY RELATED TABLES FINISHED -- diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml index 5fd31bb67c..24a1f0d80e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/testng.xml @@ -27,6 +27,7 @@ + \ No newline at end of file From bcb2c1ddb12b33fd8b417e3b59e9114282e056c8 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Sat, 29 Aug 2015 17:39:07 +0530 Subject: [PATCH 3/4] Commiting the monitoring changes and test case changes --- .../mgt/core/dao/impl/DeviceDAOImpl.java | 2 +- .../DeviceManagementProviderServiceImpl.java | 4 + .../org.wso2.carbon.policy.mgt.core/pom.xml | 9 ++ .../mgt/core/enforcement/DelegationTask.java | 94 +++++++++++++++ .../PolicyEnforcementDelegator.java | 2 - .../PolicyEnforcementDelegatorImpl.java | 11 +- .../impl/ComplianceDecisionPointImpl.java | 6 +- .../impl/PolicyAdministratorPointImpl.java | 111 +++++++++++------- .../core/impl/PolicyInformationPointImpl.java | 36 ++++-- .../PolicyManagementServiceComponent.java | 5 + .../core/mgt/impl/MonitoringManagerImpl.java | 90 ++++++++------ .../mgt/core/mgt/impl/PolicyManagerImpl.java | 32 ++--- .../mgt/core/mgt/impl/ProfileManagerImpl.java | 47 ++++++-- .../policy/mgt/core/task/MonitoringTask.java | 86 ++++++++------ .../core/task/TaskScheduleServiceImpl.java | 19 ++- .../core/util/PolicyManagementConstants.java | 10 +- .../mgt/core/BasePolicyManagementDAOTest.java | 17 ++- .../policy/mgt/core/MonitoringTestCase.java | 20 ++-- .../policy/mgt/core/PolicyDAOTestCase.java | 36 ++---- .../mgt/core/PolicyEvaluationTestCase.java | 28 +++-- .../repository/conf/etc/tasks-config.xml | 51 ++++++++ .../config/datasource/data-source-config.xml | 16 +-- 22 files changed, 506 insertions(+), 226 deletions(-) create mode 100644 components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java create mode 100644 components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/etc/tasks-config.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java index 6d8d4107bf..69c297d7f5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceDAOImpl.java @@ -179,7 +179,7 @@ public class DeviceDAOImpl implements DeviceDAO { String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, d1.DEVICE_IDENTIFICATION, " + "e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID " + - "FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, d.OWNER, t.NAME " + + "FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME " + "AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + "AND d.TENANT_ID = ?) d1 WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); 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 197a9321e3..0d47afaa18 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 @@ -492,10 +492,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { Device device; try { + DeviceManagementDAOFactory.openConnection(); device = deviceDAO.getDevice(deviceId, this.getTenantId()); } catch (DeviceManagementDAOException e) { throw new DeviceManagementException("Error occurred while obtaining the device for id " + "'" + deviceId.getId() + "'", e); + } catch (SQLException e) { + throw new DeviceManagementException("Error occurred while obtaining the device for id " + + "'" + deviceId.getId() + "'", e); } finally { DeviceManagementDAOFactory.closeConnection(); } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml index c818c48bef..953650fd8e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml @@ -144,6 +144,15 @@ org.wso2.carbon.ntask.core + + + org.wso2.carbon + org.wso2.carbon.registry.api + + + org.wso2.carbon + org.wso2.carbon.registry.core + org.wso2.carbon.devicemgt diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java new file mode 100644 index 0000000000..33ce6bd606 --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/DelegationTask.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +package org.wso2.carbon.policy.mgt.core.enforcement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; +import org.wso2.carbon.ntask.core.Task; +import org.wso2.carbon.policy.mgt.common.PolicyManagementException; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; +import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; +import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DelegationTask implements Task { + + private static final Log log = LogFactory.getLog(DelegationTask.class); + + @Override + public void setProperties(Map map) { + + } + + @Override + public void init() { + + } + + @Override + public void execute() { + + try { + PolicyManager policyManager = new PolicyManagerImpl(); + List deviceTypes = policyManager.applyChangesMadeToPolicies(); + + if (log.isDebugEnabled()) { + log.debug("Number of device types which policies are changed .......... : " + deviceTypes.size()); + } + if (!deviceTypes.isEmpty()) { + DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance() + .getDeviceManagementService(); + List devices = new ArrayList<>(); + for (DeviceType deviceType : deviceTypes) { + try { + devices.addAll(service.getAllDevices(deviceType.getName())); + } catch (DeviceManagementException e) { + throw new PolicyManagementException("Error occurred while taking the devices", e); + } + } + HashMap deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds(); + List toBeNotified = new ArrayList<>(); + + for (Device device : devices) { + if (deviceIdPolicy.containsKey(device.getId())) { + toBeNotified.add(device); + } + } + if (!toBeNotified.isEmpty()) { + PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl(toBeNotified); + enforcementDelegator.delegate(); + } + } + + } catch (PolicyManagementException e) { + log.error("Error occurred while getting the policies applied to devices.", e); + } catch (PolicyDelegationException e) { + log.error("Error occurred while running the delegation task.", e); + } + } +} diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java index 9ffb0c9e3d..218fe0398e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegator.java @@ -18,11 +18,9 @@ */ package org.wso2.carbon.policy.mgt.core.enforcement; -import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.policy.mgt.common.Policy; -import java.util.HashMap; import java.util.List; public interface PolicyEnforcementDelegator { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java index fa7d1f478f..3e3b605c85 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java @@ -30,13 +30,12 @@ import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl; -import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import java.util.ArrayList; import java.util.List; -public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegator, Runnable { +public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegator{ private static final Log log = LogFactory.getLog(PolicyEnforcementDelegatorImpl.class); @@ -108,12 +107,4 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato } - @Override - public void run() { - try { - this.delegate(); - } catch (PolicyDelegationException e) { - log.error("Error occurred while running the policy change delegation thread.", e); - } - } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java index 971d2e268a..d78e6b16e2 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java @@ -166,10 +166,8 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { } } catch (OperationManagementException e) { - String msg = "Error occurred while re-enforcing the policy to device " + deviceIdentifier.getId() + " - " + - deviceIdentifier.getType(); - log.error(msg, e); - throw new PolicyComplianceException(msg, e); + throw new PolicyComplianceException("Error occurred while re-enforcing the policy to device " + deviceIdentifier.getId() + " - " + + deviceIdentifier.getType(), e); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java index bec741f8ff..c6680d1a74 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java @@ -20,19 +20,13 @@ 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.Device; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.dto.DeviceType; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.policy.mgt.common.FeatureManagementException; -import org.wso2.carbon.policy.mgt.common.Policy; -import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; -import org.wso2.carbon.policy.mgt.common.PolicyManagementException; -import org.wso2.carbon.policy.mgt.common.Profile; -import org.wso2.carbon.policy.mgt.common.ProfileManagementException; -import org.wso2.carbon.policy.mgt.core.enforcement.PolicyEnforcementDelegator; -import org.wso2.carbon.policy.mgt.core.enforcement.PolicyEnforcementDelegatorImpl; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.TaskInfo; +import org.wso2.carbon.ntask.core.TaskManager; +import org.wso2.carbon.ntask.core.service.TaskService; +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; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; @@ -40,10 +34,11 @@ import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager; import org.wso2.carbon.policy.mgt.core.mgt.impl.FeatureManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.ProfileManagerImpl; +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 PolicyAdministratorPointImpl implements PolicyAdministratorPoint { @@ -111,39 +106,75 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { @Override public void publishChanges() throws PolicyManagementException { - List deviceTypes = policyManager.applyChangesMadeToPolicies(); + try { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); + taskService.registerTaskType(PolicyManagementConstants.DELEGATION_TASK_TYPE); - if(log.isDebugEnabled()) { - log.debug("Number of device types which policies are changed .......... : " + deviceTypes.size() ); - } + if (log.isDebugEnabled()) { + log.debug("Policy delegations task is started for the tenant id " + tenantId); + } - if (!deviceTypes.isEmpty()) { + TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.DELEGATION_TASK_TYPE); + TaskInfo.TriggerInfo triggerInfo = new TaskInfo.TriggerInfo(); - DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance() - .getDeviceManagementService(); - List devices = new ArrayList<>(); - for (DeviceType deviceType : deviceTypes) { - try { - devices.addAll(service.getAllDevices(deviceType.getName())); - } catch (DeviceManagementException e) { - throw new PolicyManagementException("Error occurred while taking the devices", e); - } - } - HashMap deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds(); - List toBeNotified = new ArrayList<>(); + triggerInfo.setIntervalMillis(0); + triggerInfo.setRepeatCount(1); - for (Device device : devices) { - if (deviceIdPolicy.containsKey(device.getId())) { - toBeNotified.add(device); - } - } - if (!toBeNotified.isEmpty()) { - // PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl(toBeNotified); - Thread thread = new Thread(new PolicyEnforcementDelegatorImpl(toBeNotified)); - thread.start(); - } + Map properties = new HashMap<>(); + properties.put(PolicyManagementConstants.TENANT_ID, String.valueOf(tenantId)); + + String taskName = PolicyManagementConstants.DELEGATION_TASK_NAME + "_" + String.valueOf(tenantId); + + TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.DELEGATION_TASK_CLAZZ, properties, triggerInfo); + + taskManager.registerTask(taskInfo); + taskManager.rescheduleTask(taskInfo.getName()); + + + } catch (TaskException e) { + String msg = "Error occurred while creating the policy delegation task for tenant " + PrivilegedCarbonContext. + getThreadLocalCarbonContext().getTenantId(); + log.error(msg, e); + throw new PolicyManagementException(msg, e); } + +// List deviceTypes = policyManager.applyChangesMadeToPolicies(); +// +// if(log.isDebugEnabled()) { +// log.debug("Number of device types which policies are changed .......... : " + deviceTypes.size() ); +// } +// +// if (!deviceTypes.isEmpty()) { +// +// +// DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance() +// .getDeviceManagementService(); +// List devices = new ArrayList<>(); +// for (DeviceType deviceType : deviceTypes) { +// try { +// devices.addAll(service.getAllDevices(deviceType.getName())); +// } catch (DeviceManagementException e) { +// throw new PolicyManagementException("Error occurred while taking the devices", e); +// } +// } +// HashMap deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds(); +// List toBeNotified = new ArrayList<>(); +// +// for (Device device : devices) { +// if (deviceIdPolicy.containsKey(device.getId())) { +// toBeNotified.add(device); +// } +// } +// if (!toBeNotified.isEmpty()) { +// +// // ExecutorService executorService = getExecutor(); +// // PolicyEnforcementDelegator enforcementDelegator = new PolicyEnforcementDelegatorImpl(toBeNotified); +//// Thread thread = new Thread(new PolicyEnforcementDelegatorImpl(toBeNotified)); +//// thread.start(); +// } +// } } @Override 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 5a335094f6..d3591b28e5 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 @@ -61,26 +61,36 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint { @Override public PIPDevice getDeviceData(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { PIPDevice pipDevice = new PIPDevice(); - org.wso2.carbon.device.mgt.common.Device device; + Device device; DeviceType deviceType = new DeviceType(); deviceType.setName(deviceIdentifier.getType()); - deviceManagementService = getDeviceManagementService(); + DeviceManagementProviderService deviceManagementService = new DeviceManagementProviderServiceImpl(); 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()); - - // TODO : Find a way to retrieve the timestamp and location (lat, long) of the device - // pipDevice.setLongitude(); - // pipDevice.setAltitude(); - // pipDevice.setTimestamp(); + pipDevice.setDevice(device); + pipDevice.setRoles(getRoleOfDevice(device)); + pipDevice.setDeviceType(deviceType); + pipDevice.setDeviceIdentifier(deviceIdentifier); + pipDevice.setUserId(device.getEnrolmentInfo().getOwner()); + pipDevice.setOwnershipType(device.getEnrolmentInfo().getOwnership().toString()); + + // 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); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java index f0b98fa6f6..676595230b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java @@ -31,6 +31,8 @@ import org.wso2.carbon.policy.mgt.core.config.PolicyConfigurationManager; import org.wso2.carbon.policy.mgt.core.config.PolicyManagementConfig; import org.wso2.carbon.policy.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; +import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; +import org.wso2.carbon.policy.mgt.core.task.TaskScheduleServiceImpl; import org.wso2.carbon.user.core.service.RealmService; /** @@ -82,6 +84,9 @@ public class PolicyManagementServiceComponent { componentContext.getBundleContext().registerService( PolicyManagerService.class.getName(), new PolicyManagerServiceImpl(), null); + TaskScheduleService taskScheduleService = new TaskScheduleServiceImpl(); + taskScheduleService.startTask(30000); + } catch (Throwable t) { log.error("Error occurred while initializing the Policy management core.", t); } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index 70e45127d3..b0ba65a2a8 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -105,13 +105,19 @@ public class MonitoringManagerImpl implements MonitoringManager { //This was added because update query below that did not return the update table primary key. if (complianceFeatures != null && !complianceFeatures.isEmpty()) { - PolicyManagementDAOFactory.beginTransaction(); - monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId()); - if (log.isDebugEnabled()) { - log.debug("Compliance status primary key " + complianceData.getId()); + try { + PolicyManagementDAOFactory.beginTransaction(); + monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId()); + if (log.isDebugEnabled()) { + log.debug("Compliance status primary key " + complianceData.getId()); + } + monitoringDAO.addNoneComplianceFeatures(complianceData.getId(), device.getId(), + complianceFeatures); + + PolicyManagementDAOFactory.commitTransaction(); + } finally { + PolicyManagementDAOFactory.closeConnection(); } - monitoringDAO.addNoneComplianceFeatures(complianceData.getId(), device.getId(), complianceFeatures); - PolicyManagementDAOFactory.commitTransaction(); complianceDecisionPoint.validateDevicePolicyCompliance(deviceIdentifier, complianceData); List profileFeatures = policy.getProfile().getProfileFeaturesList(); for (ComplianceFeature compFeature : complianceFeatures) { @@ -122,10 +128,14 @@ public class MonitoringManagerImpl implements MonitoringManager { } } } else { - PolicyManagementDAOFactory.beginTransaction(); - monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId()); - monitoringDAO.deleteNoneComplianceData(complianceData.getId()); - PolicyManagementDAOFactory.commitTransaction(); + try { + PolicyManagementDAOFactory.beginTransaction(); + monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId()); + monitoringDAO.deleteNoneComplianceData(complianceData.getId()); + PolicyManagementDAOFactory.commitTransaction(); + } finally { + PolicyManagementDAOFactory.closeConnection(); + } } } else { if (log.isDebugEnabled()) { @@ -144,8 +154,6 @@ public class MonitoringManagerImpl implements MonitoringManager { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyComplianceException("Unable to add the none compliance features to database for device " + deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); - } finally { - PolicyManagementDAOFactory.closeConnection(); } return complianceFeatures; } @@ -206,28 +214,39 @@ public class MonitoringManagerImpl implements MonitoringManager { @Override public void addMonitoringOperation(List devices) throws PolicyComplianceException { - try { - ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl(); - //int tenantId = PolicyManagerUtil.getTenantId(); - Map deviceIds = new HashMap<>(); + ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl(); - for (Device device : devices) { - deviceIds.put(device.getId(), device); - } + //int tenantId = PolicyManagerUtil.getTenantId(); + Map deviceIds = new HashMap<>(); + List complianceDatas; + HashMap devicePolicyIdMap; - List deviceIDs = new ArrayList<>(deviceIds.keySet()); - List complianceDatas = monitoringDAO.getCompliance(deviceIDs); - HashMap devicePolicyIdMap = policyDAO.getAppliedPolicyIds(deviceIDs); + for (Device device : devices) { + deviceIds.put(device.getId(), device); + } - Map deviceIdsToAddOperation = new HashMap<>(); - Map deviceIdsWithExistingOperation = new HashMap<>(); - Map inactiveDeviceIds = new HashMap<>(); - Map firstTimeDeviceIdsWithPolicyIds = new HashMap<>(); + List deviceIDs = new ArrayList<>(deviceIds.keySet()); + try { + PolicyManagementDAOFactory.openConnection(); + complianceDatas = monitoringDAO.getCompliance(deviceIDs); + devicePolicyIdMap = policyDAO.getAppliedPolicyIds(deviceIDs); + } catch (SQLException e) { + throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e); + } catch (MonitoringDAOException e) { + throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e); + } catch (PolicyManagerDAOException e) { + throw new PolicyComplianceException("SQL error occurred while getting policy details.", e); + } - Map tempMap = new HashMap<>(); + Map deviceIdsToAddOperation = new HashMap<>(); + Map deviceIdsWithExistingOperation = new HashMap<>(); + Map inactiveDeviceIds = new HashMap<>(); + Map firstTimeDeviceIdsWithPolicyIds = new HashMap<>(); + Map tempMap = new HashMap<>(); + try { if (complianceDatas != null || !complianceDatas.isEmpty()) { for (ComplianceData complianceData : complianceDatas) { @@ -248,7 +267,7 @@ public class MonitoringManagerImpl implements MonitoringManager { } for (Device device : devices) { - if (!tempMap.containsKey(device.getId())) { + if ((!tempMap.containsKey(device.getId())) && (devicePolicyIdMap.containsKey(device.getId()))) { deviceIdsToAddOperation.put(device.getId(), device); firstTimeDeviceIdsWithPolicyIds.put(device.getId(), devicePolicyIdMap.get(device.getId())); } @@ -264,7 +283,6 @@ public class MonitoringManagerImpl implements MonitoringManager { PolicyManagementDAOFactory.beginTransaction(); if (!deviceIdsToAddOperation.isEmpty()) { - this.addMonitoringOperationsToDatabase(new ArrayList<>(deviceIdsToAddOperation.values())); monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds); } @@ -274,20 +292,26 @@ public class MonitoringManagerImpl implements MonitoringManager { // decisionPoint.setDevicesAsUnreachable(this.getDeviceIdentifiersFromDevices( // new ArrayList<>(deviceIdsWithExistingOperation.values()))); } - PolicyManagementDAOFactory.commitTransaction(); + } catch (MonitoringDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyComplianceException("Error occurred from monitoring dao.", e); - } catch (OperationManagementException e) { - PolicyManagementDAOFactory.rollbackTransaction(); - throw new PolicyComplianceException("Error occurred while adding monitoring operation to devices", e); } catch (PolicyManagerDAOException e) { PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyComplianceException("Error occurred reading the applied policies to devices.", e); } finally { PolicyManagementDAOFactory.closeConnection(); } + + if (!deviceIdsToAddOperation.isEmpty()) { + try { + this.addMonitoringOperationsToDatabase(new ArrayList<>(deviceIdsToAddOperation.values())); + } catch (OperationManagementException e) { + throw new PolicyComplianceException("Error occurred while adding monitoring operation to devices", e); + } + } + } private void addMonitoringOperationsToDatabase(List devices) 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 d72eb83099..9c879e5493 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 @@ -20,12 +20,10 @@ package org.wso2.carbon.policy.mgt.core.mgt.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.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; 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; @@ -45,7 +43,6 @@ public class PolicyManagerImpl implements PolicyManager { private PolicyDAO policyDAO; private ProfileDAO profileDAO; private FeatureDAO featureDAO; - private DeviceDAO deviceDAO; private ProfileManager profileManager; private static Log log = LogFactory.getLog(PolicyManagerImpl.class); @@ -53,7 +50,6 @@ public class PolicyManagerImpl implements PolicyManager { this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO(); this.profileDAO = PolicyManagementDAOFactory.getProfileDAO(); this.featureDAO = PolicyManagementDAOFactory.getFeatureDAO(); - this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); this.profileManager = new ProfileManagerImpl(); } @@ -306,15 +302,18 @@ public class PolicyManagerImpl implements PolicyManager { public Policy addPolicyToDevice(List deviceIdentifierList, Policy policy) throws PolicyManagementException { try { - PolicyManagementDAOFactory.beginTransaction(); - if (policy.getId() == 0) { - policyDAO.addPolicy(policy); - } + List deviceList = new ArrayList<>(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); for (DeviceIdentifier deviceIdentifier : deviceIdentifierList) { deviceList.add(service.getDevice(deviceIdentifier)); } + + PolicyManagementDAOFactory.beginTransaction(); + if (policy.getId() == 0) { + policyDAO.addPolicy(policy); + } + policy = policyDAO.addPolicyToDevice(deviceList, policy); PolicyManagementDAOFactory.commitTransaction(); @@ -525,9 +524,11 @@ public class PolicyManagerImpl implements PolicyManager { List policyIdList; List policies = new ArrayList<>(); try { - PolicyManagementDAOFactory.openConnection(); + DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); + + PolicyManagementDAOFactory.openConnection(); policyIdList = policyDAO.getPolicyIdsOfDevice(device); } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the policies for device identifier (" + @@ -643,12 +644,14 @@ public class PolicyManagerImpl implements PolicyManager { List deviceList = new ArrayList<>(); List deviceIds; try { - PolicyManagementDAOFactory.openConnection(); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - deviceIds = policyDAO.getPolicyAppliedDevicesIds(policyId); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); List allDevices = service.getAllDevices(); + PolicyManagementDAOFactory.openConnection(); + //int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + deviceIds = policyDAO.getPolicyAppliedDevicesIds(policyId); + + HashMap allDeviceMap = new HashMap<>(); if(!allDevices.isEmpty()) { @@ -790,9 +793,9 @@ public class PolicyManagerImpl implements PolicyManager { boolean exist; try { - PolicyManagementDAOFactory.openConnection(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); + PolicyManagementDAOFactory.openConnection(); exist = policyDAO.checkPolicyAvailable(device.getId()); } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while checking whether device has a policy " + @@ -811,9 +814,10 @@ public class PolicyManagerImpl implements PolicyManager { @Override public boolean setPolicyApplied(DeviceIdentifier deviceIdentifier) throws PolicyManagementException { try { - PolicyManagementDAOFactory.openConnection(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); Device device = service.getDevice(deviceIdentifier); + + PolicyManagementDAOFactory.openConnection(); policyDAO.setPolicyApplied(device.getId()); return true; } catch (PolicyManagerDAOException e) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java index 931b97a37c..c5574c2daf 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/ProfileManagerImpl.java @@ -42,13 +42,13 @@ public class ProfileManagerImpl implements ProfileManager { private static Log log = LogFactory.getLog(ProfileManagerImpl.class); private ProfileDAO profileDAO; private FeatureDAO featureDAO; - private DeviceDAO deviceDAO; +// private DeviceDAO deviceDAO; private DeviceTypeDAO deviceTypeDAO; public ProfileManagerImpl() { profileDAO = PolicyManagementDAOFactory.getProfileDAO(); featureDAO = PolicyManagementDAOFactory.getFeatureDAO(); - deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); +// deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); } @@ -149,36 +149,54 @@ public class ProfileManagerImpl implements ProfileManager { PolicyManagementDAOFactory.openConnection(); profile = profileDAO.getProfiles(profileId); featureList = featureDAO.getFeaturesForProfile(profileId); - deviceType = deviceTypeDAO.getDeviceType(profile.getDeviceType().getId()); profile.setProfileFeaturesList(featureList); - profile.setDeviceType(deviceType); } catch (ProfileManagerDAOException e) { throw new ProfileManagementException("Error occurred while getting profile id (" + profileId + ")", e); } catch (FeatureManagerDAOException e) { throw new ProfileManagementException("Error occurred while getting features related profile id (" + profileId + ")", e); - } catch (DeviceManagementDAOException e) { - throw new ProfileManagementException("Error occurred while getting device type related profile id (" + - profileId + ")", e); } catch (SQLException e) { throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); } finally { PolicyManagementDAOFactory.closeConnection(); + + } + + try { + DeviceManagementDAOFactory.openConnection(); + deviceType = deviceTypeDAO.getDeviceType(profile.getDeviceType().getId()); + } catch (DeviceManagementDAOException e) { + throw new ProfileManagementException("Error occurred while getting features related profile id (" + + profileId + ")", e); + } catch (SQLException e) { + throw new ProfileManagementException("SQL exception occurred while getting features related profile id (" + + profileId + ")", e); + } finally { DeviceManagementDAOFactory.closeConnection(); } + + profile.setDeviceType(deviceType); return profile; } @Override public List getAllProfiles() throws ProfileManagementException { List profileList; + List deviceTypes; try { + try { + DeviceManagementDAOFactory.openConnection(); + deviceTypes = deviceTypeDAO.getDeviceTypes(); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + PolicyManagementDAOFactory.openConnection(); profileList = profileDAO.getAllProfiles(); List featureList = featureDAO.getAllProfileFeatures(); - List deviceTypes = deviceTypeDAO.getDeviceTypes(); + for (Profile profile : profileList) { List list = new ArrayList(); @@ -205,7 +223,7 @@ public class ProfileManagerImpl implements ProfileManager { throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); } finally { PolicyManagementDAOFactory.closeConnection(); - DeviceManagementDAOFactory.closeConnection(); + // DeviceManagementDAOFactory.closeConnection(); } return profileList; } @@ -214,9 +232,16 @@ public class ProfileManagerImpl implements ProfileManager { public List getProfilesOfDeviceType(String deviceTypeName) throws ProfileManagementException { List profileList; List featureList; + DeviceType deviceType; try { + try { + DeviceManagementDAOFactory.openConnection(); + deviceType = deviceTypeDAO.getDeviceType(deviceTypeName); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } PolicyManagementDAOFactory.openConnection(); - DeviceType deviceType = deviceTypeDAO.getDeviceType(deviceTypeName); + profileList = profileDAO.getProfilesOfDeviceType(deviceType); featureList = featureDAO.getAllProfileFeatures(); @@ -240,7 +265,7 @@ public class ProfileManagerImpl implements ProfileManager { throw new ProfileManagementException("Error occurred while opening a connection to the data source", e); } finally { PolicyManagementDAOFactory.closeConnection(); - DeviceManagementDAOFactory.closeConnection(); + } return profileList; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java index ac4563bd8a..1c4492e239 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java @@ -23,6 +23,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; import org.wso2.carbon.device.mgt.core.dto.DeviceType; @@ -62,48 +63,61 @@ public class MonitoringTask implements Task { log.debug("Monitoring task started to run."); } + List deviceTypes = new ArrayList<>(); try { - List deviceTypes = deviceTypeDAO.getDeviceTypes(); - DeviceManagementProviderService deviceManagementProviderService = - PolicyManagementDataHolder.getInstance().getDeviceManagementService(); - MonitoringManager monitoringManager = new MonitoringManagerImpl(); - - for (DeviceType deviceType : deviceTypes) { - PolicyMonitoringService monitoringService = - PolicyManagementDataHolder.getInstance().getPolicyMonitoringService(deviceType.getName()); - List devices = deviceManagementProviderService.getAllDevices(deviceType.getName()); - if (monitoringService != null && !devices.isEmpty()) { - monitoringManager.addMonitoringOperation(devices); - - List notifiableDevices = new ArrayList<>(); - - if (log.isDebugEnabled()) { - log.debug("Removing inactive and blocked devices from the list for the device type : " + - deviceType); - } - for (Device device : devices) { - if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.INACTIVE) || - device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.BLOCKED)) { - continue; - } else { - notifiableDevices.add(device); + DeviceManagementDAOFactory.openConnection(); + deviceTypes = deviceTypeDAO.getDeviceTypes(); + } catch (Exception e) { + log.error("Error occurred while getting the device types.", e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + if (!deviceTypes.isEmpty()) { + try { + + DeviceManagementProviderService deviceManagementProviderService = + PolicyManagementDataHolder.getInstance().getDeviceManagementService(); + MonitoringManager monitoringManager = new MonitoringManagerImpl(); + + for (DeviceType deviceType : deviceTypes) { + PolicyMonitoringService monitoringService = + PolicyManagementDataHolder.getInstance().getPolicyMonitoringService(deviceType.getName()); + List devices = deviceManagementProviderService.getAllDevices(deviceType.getName()); + if (monitoringService != null && !devices.isEmpty()) { + monitoringManager.addMonitoringOperation(devices); + + List notifiableDevices = new ArrayList<>(); + + if (log.isDebugEnabled()) { + log.debug("Removing inactive and blocked devices from the list for the device type : " + + deviceType); } - } - if (log.isDebugEnabled()) { - log.debug("Following devices selected to send the notification for " + deviceType); - for (Device device : notifiableDevices) { - log.debug(device.getDeviceIdentifier()); + for (Device device : devices) { + if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.INACTIVE) || + device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.BLOCKED)) { + continue; + } else { + notifiableDevices.add(device); + } + } + if (log.isDebugEnabled()) { + log.debug("Following devices selected to send the notification for " + deviceType); + for (Device device : notifiableDevices) { + log.debug(device.getDeviceIdentifier()); + } } + monitoringService.notifyDevices(notifiableDevices); } - monitoringService.notifyDevices(notifiableDevices); } + if (log.isDebugEnabled()) { + log.debug("Monitoring task running completed."); + } + } catch (Exception e) { + log.error("Error occurred while trying to run a task.", e); } - if (log.isDebugEnabled()) { - log.debug("Monitoring task running completed."); - } - } catch (Exception e) { - String msg = "Error occurred while trying to run a task."; - log.error(msg, e); + } else { + log.info("No device types registered currently. So did not run the monitoring task."); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java index 0f874a1468..a8121f99ac 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/TaskScheduleServiceImpl.java @@ -29,7 +29,6 @@ import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants; -import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import org.wso2.carbon.ntask.core.TaskInfo.TriggerInfo; import java.util.HashMap; @@ -48,13 +47,13 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); - taskService.registerTaskType(PolicyManagementConstants.TASK_TYPE); + taskService.registerTaskType(PolicyManagementConstants.MONITORING_TASK_TYPE); if (log.isDebugEnabled()) { log.debug("Monitoring task is started for the tenant id " + tenantId); } - TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE); + TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE); TriggerInfo triggerInfo = new TriggerInfo(); @@ -64,9 +63,9 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { Map properties = new HashMap<>(); properties.put(PolicyManagementConstants.TENANT_ID, String.valueOf(tenantId)); - String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId); + String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId); - TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.TASK_CLAZZ, properties, triggerInfo); + TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.MONITORING_TASK_CLAZZ, properties, triggerInfo); taskManager.registerTask(taskInfo); taskManager.rescheduleTask(taskInfo.getName()); @@ -86,9 +85,9 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { public void stopTask() throws PolicyMonitoringTaskException { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId); + String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId); TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); - TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE); + TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE); taskManager.deleteTask(taskName); } catch (TaskException e) { String msg = "Error occurred while deleting the task for tenant " + PrivilegedCarbonContext. @@ -102,10 +101,10 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { public void updateTask(int monitoringFrequency) throws PolicyMonitoringTaskException { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - String taskName = PolicyManagementConstants.TASK_NAME + "_" + String.valueOf(tenantId); + String taskName = PolicyManagementConstants.MONITORING_TASK_NAME + "_" + String.valueOf(tenantId); TaskService taskService = PolicyManagementDataHolder.getInstance().getTaskService(); - TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.TASK_TYPE); + TaskManager taskManager = taskService.getTaskManager(PolicyManagementConstants.MONITORING_TASK_TYPE); taskManager.deleteTask(taskName); @@ -117,7 +116,7 @@ public class TaskScheduleServiceImpl implements TaskScheduleService { Map properties = new HashMap<>(); properties.put("tenantId", String.valueOf(tenantId)); - TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.TASK_CLAZZ, properties, triggerInfo); + TaskInfo taskInfo = new TaskInfo(taskName, PolicyManagementConstants.MONITORING_TASK_CLAZZ, properties, triggerInfo); taskManager.registerTask(taskInfo); taskManager.rescheduleTask(taskInfo.getName()); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java index 2c033151ca..e8354b3e99 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java @@ -32,14 +32,18 @@ public final class PolicyManagementConstants { public static final String BLOCK = "BLOCK"; - public static final String TASK_TYPE = "MONITORING_TASK"; - public static final String TASK_NAME = "MONITORING"; - public static final String TASK_CLAZZ = "org.wso2.carbon.policy.mgt.core.task.MonitoringTask"; + public static final String MONITORING_TASK_TYPE = "MONITORING_TASK"; + public static final String MONITORING_TASK_NAME = "MONITORING"; + public static final String MONITORING_TASK_CLAZZ = "org.wso2.carbon.policy.mgt.core.task.MonitoringTask"; public static final String DM_CACHE_MANAGER = "DM_CACHE_MANAGER"; public static final String DM_CACHE = "DM_CACHE"; + public static final String DELEGATION_TASK_TYPE = "DELEGATION__TASK"; + public static final String DELEGATION_TASK_NAME = "DELEGATION"; + public static final String DELEGATION_TASK_CLAZZ = "org.wso2.carbon.policy.mgt.core.enforcement.DelegationTask"; + } 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 617bf9ad86..6b15d82d2e 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 @@ -28,9 +28,18 @@ import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; 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; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.service.TaskService; +import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl; +import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.common.DataSourceConfig; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; +import org.wso2.carbon.policy.mgt.core.services.PolicyMonitoringServiceTest; +import org.wso2.carbon.policy.mgt.core.services.SimplePolicyEvaluationTest; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import javax.sql.DataSource; @@ -49,7 +58,13 @@ public abstract class BasePolicyManagementDAOTest { @BeforeSuite public void setupDataSource() throws Exception { this.initDatSource(); - // this.initSQLScript(); + this.initSQLScript(); + this.initialize(); + this.initiatePrivilegedCaronContext(); + } + + public void initialize() throws TaskException { + } public void initDatSource() throws Exception { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java index bde1b14d8b..34eb288682 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/MonitoringTestCase.java @@ -29,21 +29,21 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementAdminService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.service.TaskService; +import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl; import org.wso2.carbon.policy.mgt.common.Policy; -import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; +import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException; import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; -import org.wso2.carbon.policy.mgt.core.impl.PolicyAdministratorPointImpl; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.impl.MonitoringManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; import org.wso2.carbon.policy.mgt.core.services.PolicyMonitoringServiceTest; -import org.wso2.carbon.policy.mgt.core.task.MonitoringTask; import java.util.List; @@ -70,14 +70,13 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { List devices = service.getAllDevices(ANDROID); for (Policy policy : policies) { - log.debug(policy.getPolicyName() + "-----P"); + log.debug("Policy Name : " + policy.getPolicyName()); } for (Device device : devices) { - log.debug(device.getDeviceIdentifier() + " ----- D"); + log.debug("Device Name : " + device.getDeviceIdentifier()); } - identifier.setType(ANDROID); identifier.setId(devices.get(0).getDeviceIdentifier()); @@ -160,9 +159,11 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { PolicyManager manager = new PolicyManagerImpl(); Policy policy = manager.getAppliedPolicyToDevice(identifier); - Object ob = new Object(); + if(policy != null) { + Object ob = new Object(); - monitoringServiceTest.checkPolicyCompliance(identifier, policy, ob); + monitoringServiceTest.checkPolicyCompliance(identifier, policy, ob); + } } @@ -193,4 +194,5 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest { monitoringManager.checkPolicyCompliance(identifier, ob); } + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java index 6fdb405973..b836aaac4b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java @@ -86,20 +86,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { enrolmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -1234); } -// List devices = deviceDAO.getDevices(-1234); -// -// log.debug("--- Printing device taken by calling the device dao layer by tenant id."); -// for (Device device : devices) { -// log.debug(device.getDeviceIdentifier()); -// } -// -// -// log.debug("--- Printing device taken by calling the device dao layer by tenant id and device type."); -// List devices2 = deviceDAO.getDevices("android", -1234); -// -// for (Device device : devices2) { -// log.debug(device.getDeviceIdentifier()); -// } + DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); @@ -108,7 +95,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { log.debug("Printing device taken by calling the service layer with device type."); List devices3 = service.getAllDevices("android"); - log.debug("Device list size ..........................!" + devices3.size()); + log.debug("Device list size ...! " + devices3.size()); for (Device device : devices3) { log.debug(device.getDeviceIdentifier()); } @@ -118,12 +105,14 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { @Test(dependsOnMethods = ("addDevice")) public void addFeatures() throws FeatureManagementException { - FeatureManager featureManager = new FeatureManagerImpl(); + //This test case was removed because architecture was changed + +// FeatureManager featureManager = new FeatureManagerImpl(); featureList = FeatureCreator.getFeatureList(); - //featureManager.addFeatures(featureList); - for (Feature feature : featureList) { -// featureManager.addFeature(feature); - } +// featureManager.addFeatures(featureList); +// for (Feature feature : featureList) { +// featureManager.addFeature(feature); +// } } @@ -368,7 +357,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { PolicyAdministratorPoint policyAdministratorPoint = new PolicyAdministratorPointImpl(); policyAdministratorPoint.deletePolicy(1); - log.debug("First policy deleted."); + log.debug("First policy deleted..!"); } @@ -382,15 +371,14 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { List devices = service.getAllDevices("android"); for (Policy policy : policies) { - log.debug(policy.getPolicyName() + "-----P"); + log.debug("Policy Name : " + policy.getPolicyName()); } for (Device device : devices) { - log.debug(device.getDeviceIdentifier() + " ----- D"); + log.debug("Device Name : " + device.getDeviceIdentifier()); } } - } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java index 49fe843cbe..e1ebc13e9d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyEvaluationTestCase.java @@ -28,7 +28,11 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; +import org.wso2.carbon.ntask.common.TaskException; +import org.wso2.carbon.ntask.core.service.TaskService; +import org.wso2.carbon.ntask.core.service.impl.TaskServiceImpl; import org.wso2.carbon.policy.mgt.common.*; +import org.wso2.carbon.policy.mgt.core.enforcement.DelegationTask; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.services.SimplePolicyEvaluationTest; @@ -50,20 +54,22 @@ public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest { } @Test - public void activatePolicies() throws PolicyManagementException { + public void activatePolicies() throws PolicyManagementException, TaskException { PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); PolicyAdministratorPoint administratorPoint = policyManagerService.getPAP(); + List policies = policyManagerService.getPolicies(ANDROID); for (Policy policy : policies) { log.debug("Policy status : " + policy.getPolicyName() + " - " + policy.isActive() + " - " + policy - .isUpdated()); + .isUpdated() + " Policy id : " + policy.getId()); if (!policy.isActive()) { administratorPoint.activatePolicy(policy.getId()); } } - administratorPoint.publishChanges(); + // This cannot be called due to task service cannot be started from the + //administratorPoint.publishChanges(); } @Test(dependsOnMethods = ("activatePolicies")) @@ -92,14 +98,14 @@ public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest { @Test(dependsOnMethods = ("getEffectivePolicy")) - public void updatePriorities() throws PolicyManagementException { + public void updatePriorities() throws PolicyManagementException, TaskException { PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); PolicyAdministratorPoint administratorPoint = policyManagerService.getPAP(); List policies = administratorPoint.getPolicies(); - log.debug("Re-enforcing policy started...."); + log.debug("Re-enforcing policy started...!"); int sixe = policies.size(); @@ -110,10 +116,18 @@ public class PolicyEvaluationTestCase extends BasePolicyManagementDAOTest { x++; } + administratorPoint.updatePolicyPriorities(policies); + // administratorPoint.publishChanges(); + } + + @Test(dependsOnMethods = ("updatePriorities")) + public void checkDelegations() { - administratorPoint.updatePolicyPriorities(policies); - administratorPoint.publishChanges(); + log.debug("Delegation methods calls started because tasks cannot be started due to osgi constraints.....!"); + + DelegationTask delegationTask = new DelegationTask(); + delegationTask.execute(); } public void sortPolicies(List policyList) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/etc/tasks-config.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/etc/tasks-config.xml new file mode 100644 index 0000000000..dec2307f1d --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/carbon-home/repository/conf/etc/tasks-config.xml @@ -0,0 +1,51 @@ + + + + AUTO + + + 2 + + + + org.wso2.carbon.ntask.core.impl.RoundRobinTaskLocationResolver + + + + + + + https://localhost:9448 + + + https://localhost:9443 + + + admin + + + admin + + + + + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml index 2a9ebfc1b0..3b7e74c0a1 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/config/datasource/data-source-config.xml @@ -23,18 +23,18 @@ - - - - + jdbc:h2:mem:cdm-test-db;DB_CLOSE_DELAY=-1 + org.h2.Driver + wso2carbon + wso2carbon - jdbc:mysql://localhost:3306/WSO2CDM - com.mysql.jdbc.Driver - root - + + + + From b906d43cc82197eb9a9b772ee099e614ad6d3ec2 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sat, 29 Aug 2015 22:14:07 +0530 Subject: [PATCH 4/4] Committing tenant configuration manager service --- .../mgt/ConfigurationManagementException.java | 55 +++++++++++ .../TenantConfigurationManagementService.java | 45 +++++++++ .../config/ConfigurationManagerConstants.java | 41 ++++++++ ...antConfigurationManagementServiceImpl.java | 97 +++++++++++++++++++ .../config/util/ConfigurationManagerUtil.java | 70 +++++++++++++ .../DeviceManagementServiceComponent.java | 7 ++ 6 files changed, 315 insertions(+) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/ConfigurationManagementException.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfigurationManagementService.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ConfigurationManagerConstants.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/tenant/TenantConfigurationManagementServiceImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/util/ConfigurationManagerUtil.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/ConfigurationManagementException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/ConfigurationManagementException.java new file mode 100644 index 0000000000..370f37fe29 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/ConfigurationManagementException.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2014, 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.common.configuration.mgt; + +public class ConfigurationManagementException extends Exception { + private static final long serialVersionUID = -3151279311929070299L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public ConfigurationManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public ConfigurationManagementException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public ConfigurationManagementException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public ConfigurationManagementException() { + super(); + } + + public ConfigurationManagementException(Throwable cause) { + super(cause); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfigurationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfigurationManagementService.java new file mode 100644 index 0000000000..59b9e1c7ae --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/configuration/mgt/TenantConfigurationManagementService.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2014, 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.common.configuration.mgt; + +/** + * This represents the tenant configuration management functionality which should be implemented by + * the device type plugins. + */ +public interface TenantConfigurationManagementService { + + /** + * Method to add a operation to a device or a set of devices. + * + * @param tenantConfiguration Operation to be added. + * @param resourcePath Registry resource path. + * @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while adding the + * configuration. + */ + public boolean saveConfiguration(TenantConfiguration tenantConfiguration, String resourcePath) throws ConfigurationManagementException; + + /** + * Method to retrieve the list of general tenant configurations. + * + * @param resourcePath Registry resource path. + * @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while fetching the + * operation list. + */ + public TenantConfiguration getConfiguration(String resourcePath) throws ConfigurationManagementException; + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ConfigurationManagerConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ConfigurationManagerConstants.java new file mode 100644 index 0000000000..2006ac336e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ConfigurationManagerConstants.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2014, 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.core.config; + +/** + * This class holds the constants used throughout the configuration manager. + */ +public class ConfigurationManagerConstants { + + public static final class ContentTypes { + private ContentTypes() { + throw new AssertionError(); + } + + public static final String CONTENT_TYPE_ANY = "*/*"; + public static final String MEDIA_TYPE_XML = "application/xml"; + } + + public static final class CharSets { + private CharSets() { + throw new AssertionError(); + } + + public static final String CHARSET_UTF8 = "UTF8"; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/tenant/TenantConfigurationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/tenant/TenantConfigurationManagementServiceImpl.java new file mode 100644 index 0000000000..803a53f7ff --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/tenant/TenantConfigurationManagementServiceImpl.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2014, 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.core.config.tenant; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +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.core.config.ConfigurationManagerConstants; +import org.wso2.carbon.device.mgt.core.config.util.ConfigurationManagerUtil; +import org.wso2.carbon.registry.api.Resource; +import org.wso2.carbon.registry.api.RegistryException; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import java.io.StringReader; +import java.io.StringWriter; +import java.nio.charset.Charset; + +/** + * This class implements all the functionality exposed as part of the TenantConfigurationManagementService. Main usage of + * this module is, saving/retrieving tenant configurations to the registry. + */ +public class TenantConfigurationManagementServiceImpl + implements TenantConfigurationManagementService { + + private static final Log log = LogFactory.getLog(TenantConfigurationManagementServiceImpl.class); + + @Override + public boolean saveConfiguration(TenantConfiguration tenantConfiguration, String resourcePath) + throws ConfigurationManagementException { + boolean status; + try { + if (log.isDebugEnabled()) { + log.debug("Persisting tenant configurations in Registry"); + } + StringWriter writer = new StringWriter(); + JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class); + Marshaller marshaller = context.createMarshaller(); + marshaller.marshal(tenantConfiguration, writer); + + Resource resource = ConfigurationManagerUtil.getConfigurationRegistry().newResource(); + resource.setContent(writer.toString()); + resource.setMediaType(ConfigurationManagerConstants.ContentTypes.MEDIA_TYPE_XML); + ConfigurationManagerUtil.putRegistryResource(resourcePath, resource); + status = true; + } catch (RegistryException e) { + throw new ConfigurationManagementException( + "Error occurred while persisting the Registry resource of Tenant Configuration : " + e.getMessage(), e); + } catch (JAXBException e) { + throw new ConfigurationManagementException( + "Error occurred while parsing the Tenant configuration : " + e.getMessage(), e); + } + return status; + } + + @Override + public TenantConfiguration getConfiguration(String resourcePath) + throws ConfigurationManagementException { + Resource resource; + try { + resource = ConfigurationManagerUtil.getRegistryResource(resourcePath); + if(resource != null){ + JAXBContext context = JAXBContext.newInstance(TenantConfiguration.class); + Unmarshaller unmarshaller = context.createUnmarshaller(); + return (TenantConfiguration) unmarshaller.unmarshal( + new StringReader(new String((byte[]) resource.getContent(), Charset + .forName(ConfigurationManagerConstants.CharSets.CHARSET_UTF8)))); + } + return new TenantConfiguration(); + } catch (JAXBException e) { + throw new ConfigurationManagementException( + "Error occurred while parsing the Tenant configuration : " + e.getMessage(), e); + } catch (RegistryException e) { + throw new ConfigurationManagementException( + "Error occurred while retrieving the Registry resource of Tenant Configuration : " + e.getMessage(), e); + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/util/ConfigurationManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/util/ConfigurationManagerUtil.java new file mode 100644 index 0000000000..58a54ef0f0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/util/ConfigurationManagerUtil.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2014, 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.core.config.util; + +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; +import org.wso2.carbon.registry.api.RegistryException; +import org.wso2.carbon.registry.api.Resource; +import org.wso2.carbon.registry.core.Registry; + +public class ConfigurationManagerUtil { + + public static Registry getConfigurationRegistry() throws ConfigurationManagementException { + try { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + return DeviceManagementDataHolder.getInstance().getRegistryService() + .getConfigSystemRegistry( + tenantId); + } catch (RegistryException e) { + throw new ConfigurationManagementException( + "Error in retrieving governance registry instance: " + + e.getMessage(), e); + } + } + + public static Resource getRegistryResource(String path) throws ConfigurationManagementException { + try { + if(ConfigurationManagerUtil.getConfigurationRegistry().resourceExists(path)){ + return ConfigurationManagerUtil.getConfigurationRegistry().get(path); + } + return null; + } catch (RegistryException e) { + throw new ConfigurationManagementException("Error in retrieving registry resource : " + + e.getMessage(), e); + } + } + + public static boolean putRegistryResource(String path, + Resource resource) + throws ConfigurationManagementException { + boolean status; + try { + ConfigurationManagerUtil.getConfigurationRegistry().beginTransaction(); + ConfigurationManagerUtil.getConfigurationRegistry().put(path, resource); + ConfigurationManagerUtil.getConfigurationRegistry().commitTransaction(); + status = true; + } catch (RegistryException e) { + throw new ConfigurationManagementException( + "Error occurred while persisting registry resource : " + + e.getMessage(), e); + } + return status; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index 6acdd01d5b..4e54268916 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -24,6 +24,7 @@ import org.osgi.service.component.ComponentContext; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; @@ -36,6 +37,7 @@ import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfiguration 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; +import org.wso2.carbon.device.mgt.core.config.tenant.TenantConfigurationManagementServiceImpl; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; @@ -171,6 +173,11 @@ public class DeviceManagementServiceComponent { DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProvider); bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null); + /* Registering Tenant Configuration Management Service */ + TenantConfigurationManagementService + tenantConfiguration = new TenantConfigurationManagementServiceImpl(); + bundleContext.registerService(TenantConfigurationManagementService.class.getName(), tenantConfiguration, null); + /* Registering App Management service */ try { AppManagementConfigurationManager.getInstance().initConfig();