Partially commiting due to update

revert-70aa11f8
geethkokila 9 years ago
parent 12a2e1f11f
commit 44b496d350

@ -19,9 +19,12 @@ package org.wso2.carbon.device.mgt.common;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.List; import java.util.List;
public class Device { public class Device implements Serializable{
private static final long serialVersionUID = 1998101711L;
private int id; private int id;
private String name; private String name;

@ -18,7 +18,11 @@
*/ */
package org.wso2.carbon.device.mgt.common; 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 { public enum Status {
CREATED, ACTIVE, INACTIVE, UNREACHABLE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED, DISENROLLMENT_REQUESTED CREATED, ACTIVE, INACTIVE, UNREACHABLE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED, DISENROLLMENT_REQUESTED

@ -42,6 +42,8 @@ public class Policy implements Comparable<Policy>, Serializable {
private String ownershipType; // Ownership type (COPE, BYOD, CPE) private String ownershipType; // Ownership type (COPE, BYOD, CPE)
private List<Device> devices; // Individual devices this policy should be applied private List<Device> devices; // Individual devices this policy should be applied
private List<String> users; private List<String> users;
private boolean active;
private boolean updated;
/* Compliance data*/ /* Compliance data*/
@ -53,19 +55,6 @@ public class Policy implements Comparable<Policy>, Serializable {
private List<PolicyCriterion> policyCriterias; private List<PolicyCriterion> 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 tenantId;
private int profileId; private int profileId;
@ -163,6 +152,24 @@ public class Policy implements Comparable<Policy>, Serializable {
this.users = users; 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 @XmlElement
public List<PolicyCriterion> getPolicyCriterias() { public List<PolicyCriterion> getPolicyCriterias() {
return policyCriterias; return policyCriterias;
@ -172,6 +179,7 @@ public class Policy implements Comparable<Policy>, Serializable {
this.policyCriterias = policyCriterias; this.policyCriterias = policyCriterias;
} }
@XmlElement
public String getCompliance() { public String getCompliance() {
return Compliance; return Compliance;
} }
@ -180,59 +188,6 @@ public class Policy implements Comparable<Policy>, Serializable {
Compliance = compliance; 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 @XmlElement
public Map<String, Object> getAttributes() { public Map<String, Object> getAttributes() {
return attributes; return attributes;
@ -252,18 +207,6 @@ public class Policy implements Comparable<Policy>, Serializable {
} }
/* static final Comparator<Policy> PRIORITY_ORDER =
new Comparator<Policy>() {
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 @Override
public int compareTo(Policy o) { public int compareTo(Policy o) {
if (this.priorityId == o.priorityId) if (this.priorityId == o.priorityId)

@ -40,9 +40,15 @@ public interface PolicyAdministratorPoint {
boolean updatePolicyPriorities(List<Policy> policies) throws PolicyManagementException; boolean updatePolicyPriorities(List<Policy> policies) throws PolicyManagementException;
void activatePolicy(int policyId) throws PolicyManagementException;
void inactivatePolicy(int policyId) throws PolicyManagementException;
boolean deletePolicy(Policy policy) throws PolicyManagementException; boolean deletePolicy(Policy policy) throws PolicyManagementException;
boolean deletePolicy(int policyId) 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. * This method adds a policy per device which should be implemented by the related plugins.
*/ */

@ -23,6 +23,8 @@ import java.util.List;
public interface PolicyFilter { public interface PolicyFilter {
List<Policy> filterActivePolicies(List<Policy> policies);
List<Policy> filterRolesBasedPolicies(String roles[], List<Policy> policies); List<Policy> filterRolesBasedPolicies(String roles[], List<Policy> policies);
List<Policy> filterOwnershipTypeBasedPolicies(String ownershipType, List<Policy> policies); List<Policy> filterOwnershipTypeBasedPolicies(String ownershipType, List<Policy> policies);

@ -42,6 +42,16 @@ public interface PolicyDAO {
boolean updatePolicyPriorities(List<Policy> policies) throws PolicyManagerDAOException; boolean updatePolicyPriorities(List<Policy> policies) throws PolicyManagerDAOException;
void activatePolicy(int policyId) throws PolicyManagerDAOException;
void activatePolicies(List<Integer> policyIds) throws PolicyManagerDAOException;
void markPoliciesAsUpdated(List<Integer> policyIds) throws PolicyManagerDAOException;
void inactivatePolicy(int policyId) throws PolicyManagerDAOException;
HashMap<Integer, Integer> getUpdatedPolicyIdandDeviceTypeId() throws PolicyManagerDAOException;
Criterion addCriterion(Criterion criteria) throws PolicyManagerDAOException; Criterion addCriterion(Criterion criteria) throws PolicyManagerDAOException;
Criterion updateCriterion(Criterion criteria) throws PolicyManagerDAOException; Criterion updateCriterion(Criterion criteria) throws PolicyManagerDAOException;
@ -64,6 +74,12 @@ public interface PolicyDAO {
Policy updatePolicy(Policy policy) throws PolicyManagerDAOException; Policy updatePolicy(Policy policy) throws PolicyManagerDAOException;
void recordUpdatedPolicy(Policy policy) throws PolicyManagerDAOException;
void recordUpdatedPolicies(List<Policy> policies) throws PolicyManagerDAOException;
void removeRecordsAboutUpdatedPolicies() throws PolicyManagerDAOException;
Policy getPolicy(int policyId) throws PolicyManagerDAOException; Policy getPolicy(int policyId) throws PolicyManagerDAOException;
Policy getPolicyByProfileID(int profileId) throws PolicyManagerDAOException; Policy getPolicyByProfileID(int profileId) throws PolicyManagerDAOException;
@ -107,4 +123,6 @@ public interface PolicyDAO {
Policy getAppliedPolicy(int deviceId) throws PolicyManagerDAOException; Policy getAppliedPolicy(int deviceId) throws PolicyManagerDAOException;
HashMap<Integer, Integer> getAppliedPolicyIds(List<Integer> deviceIds) throws PolicyManagerDAOException; HashMap<Integer, Integer> getAppliedPolicyIds(List<Integer> deviceIds) throws PolicyManagerDAOException;
HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagerDAOException;
} }

@ -144,13 +144,14 @@ public class PolicyDAOImpl implements PolicyDAO {
try { try {
conn = this.getConnection(); 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); stmt = conn.prepareStatement(query);
for (Policy policy : policies) { for (Policy policy : policies) {
stmt.setInt(1, policy.getPriorityId()); stmt.setInt(1, policy.getPriorityId());
stmt.setInt(2, policy.getId()); stmt.setInt(2, 1);
stmt.setInt(3, tenantId); stmt.setInt(3, policy.getId());
stmt.setInt(4, tenantId);
stmt.addBatch(); stmt.addBatch();
} }
stmt.executeBatch(); stmt.executeBatch();
@ -162,6 +163,137 @@ public class PolicyDAOImpl implements PolicyDAO {
return true; 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<Integer> 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<Integer> 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<Integer, Integer> getUpdatedPolicyIdandDeviceTypeId() throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
HashMap<Integer, Integer> 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 @Override
public Criterion addCriterion(Criterion criteria) throws PolicyManagerDAOException { public Criterion addCriterion(Criterion criteria) throws PolicyManagerDAOException {
@ -477,15 +609,16 @@ public class PolicyDAOImpl implements PolicyDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "UPDATE DM_POLICY SET NAME= ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?" + String query = "UPDATE DM_POLICY SET NAME = ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?," +
" WHERE ID = ? AND TENANT_ID = ?"; " UPDATED = ? WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setString(1, policy.getPolicyName()); stmt.setString(1, policy.getPolicyName());
stmt.setInt(2, policy.getProfile().getProfileId()); stmt.setInt(2, policy.getProfile().getProfileId());
stmt.setInt(3, policy.getPriorityId()); stmt.setInt(3, policy.getPriorityId());
stmt.setString(4, policy.getCompliance()); stmt.setString(4, policy.getCompliance());
stmt.setInt(5, policy.getId()); stmt.setInt(5, 1);
stmt.setInt(6, tenantId); stmt.setInt(6, policy.getId());
stmt.setInt(7, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
@ -497,6 +630,77 @@ public class PolicyDAOImpl implements PolicyDAO {
return policy; 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<Policy> 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 @Override
public Policy getPolicy(int policyId) throws PolicyManagerDAOException { public Policy getPolicy(int policyId) throws PolicyManagerDAOException {
Connection conn; Connection conn;
@ -585,6 +789,8 @@ public class PolicyDAOImpl implements PolicyDAO {
policy.setPriorityId(resultSet.getInt("PRIORITY")); policy.setPriorityId(resultSet.getInt("PRIORITY"));
policy.setCompliance(resultSet.getString("COMPLIANCE")); policy.setCompliance(resultSet.getString("COMPLIANCE"));
policy.setOwnershipType(resultSet.getString("OWNERSHIP_TYPE")); policy.setOwnershipType(resultSet.getString("OWNERSHIP_TYPE"));
policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED")));
policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE")));
policies.add(policy); policies.add(policy);
} }
return policies; return policies;
@ -884,12 +1090,16 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, policyId); stmt.setInt(1, policyId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
stmt.executeUpdate(); int deleted = stmt.executeUpdate();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Policy (" + policyId + ") delete from database."); log.debug("Policy (" + policyId + ") delete from database.");
} }
if (deleted > 0) {
return true; return true;
} else {
return false;
}
} catch (SQLException e) { } catch (SQLException e) {
throw new PolicyManagerDAOException("Unable to delete the policy (" + policyId + ") from database", e); throw new PolicyManagerDAOException("Unable to delete the policy (" + policyId + ") from database", e);
} finally { } finally {
@ -948,8 +1158,9 @@ public class PolicyDAOImpl implements PolicyDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE)" + String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," +
" VALUES (?, ?, ?, ?, ?, ?)"; " " +
"UPDATED, ACTIVE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1, policy.getPolicyName()); stmt.setString(1, policy.getPolicyName());
@ -958,6 +1169,8 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setInt(4, readHighestPriorityOfPolicies()); stmt.setInt(4, readHighestPriorityOfPolicies());
stmt.setString(5, policy.getCompliance()); stmt.setString(5, policy.getCompliance());
stmt.setString(6, policy.getOwnershipType()); stmt.setString(6, policy.getOwnershipType());
stmt.setInt(7, 0);
stmt.setInt(8, 0);
int affectedRows = stmt.executeUpdate(); int affectedRows = stmt.executeUpdate();
@ -1183,4 +1396,31 @@ public class PolicyDAOImpl implements PolicyDAO {
return devicePolicyIds; return devicePolicyIds;
} }
@Override
public HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagerDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
HashMap<Integer, Integer> 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;
}
} }

@ -91,19 +91,19 @@ public class ProfileDAOImpl implements ProfileDAO {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet generatedKeys = null; // ResultSet generatedKeys = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "UPDATE DM_PROFILE SET PROFILE_NAME = ? ,TENANT_ID = ?, DEVICE_TYPE_ID = ? , UPDATED_TIME = ? " + String query = "UPDATE DM_PROFILE SET PROFILE_NAME = ? , DEVICE_TYPE_ID = ? , UPDATED_TIME = ? " +
"WHERE ID = ?"; "WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); stmt = conn.prepareStatement(query);
stmt.setString(1, profile.getProfileName()); stmt.setString(1, profile.getProfileName());
stmt.setInt(2, tenantId); stmt.setLong(2, profile.getDeviceType().getId());
stmt.setLong(3, profile.getDeviceType().getId()); stmt.setTimestamp(3, profile.getUpdatedDate());
stmt.setTimestamp(4, profile.getUpdatedDate()); stmt.setInt(4, profile.getProfileId());
stmt.setInt(5, profile.getProfileId()); stmt.setInt(5, tenantId);
int affectedRows = stmt.executeUpdate(); int affectedRows = stmt.executeUpdate();
@ -111,22 +111,22 @@ public class ProfileDAOImpl implements ProfileDAO {
String msg = "No rows are updated on the profile table."; String msg = "No rows are updated on the profile table.";
log.debug(msg); log.debug(msg);
} }
generatedKeys = stmt.getGeneratedKeys(); // generatedKeys = stmt.getGeneratedKeys();
//
if (generatedKeys.next()) { // if (generatedKeys.next()) {
profile.setProfileId(generatedKeys.getInt(1)); // profile.setProfileId(generatedKeys.getInt(1));
} // }
// Checking the profile id here, because profile id could have been passed from the calling method. // // Checking the profile id here, because profile id could have been passed from the calling method.
if (profile.getProfileId() == 0) { // if (profile.getProfileId() == 0) {
throw new RuntimeException("Profile id is 0, this could be an issue."); // throw new RuntimeException("Profile id is 0, this could be an issue.");
} // }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while updating the profile (" + profile.getProfileName() + ") in database."; String msg = "Error occurred while updating the profile (" + profile.getProfileName() + ") in database.";
log.error(msg, e); log.error(msg, e);
throw new ProfileManagerDAOException(msg, e); throw new ProfileManagerDAOException(msg, e);
} finally { } finally {
PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys); PolicyManagementDAOUtil.cleanupResources(stmt, null);
} }
return profile; return profile;
} }

@ -22,10 +22,15 @@ import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.Policy;
import java.util.HashMap;
import java.util.List; import java.util.List;
public interface PolicyEnforcementDelegator { public interface PolicyEnforcementDelegator {
void delegate(Policy policy, List<Device> devices) throws PolicyDelegationException; void delegate() throws PolicyDelegationException;
Policy getEffectivePolicy(DeviceIdentifier identifier) throws PolicyDelegationException;
void addPolicyOperation(List<DeviceIdentifier> deviceIdentifiers, Policy policy) throws PolicyDelegationException;
} }

@ -18,33 +18,102 @@
*/ */
package org.wso2.carbon.policy.mgt.core.enforcement; 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.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; 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.OperationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; 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.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 org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; 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);
private List<Device> devices;
public PolicyEnforcementDelegatorImpl(List<Device> devices) {
log.info("Policy re-enforcing stared due to change of the policies.");
if (log.isDebugEnabled()) {
for (Device device : devices) {
log.debug("Policy re-enforcing for device :" + device.getDeviceIdentifier() + " - Type : "
+ device.getType());
}
}
this.devices = devices;
}
@Override @Override
public void delegate(Policy policy, List<Device> devices) throws PolicyDelegationException { public void delegate() throws PolicyDelegationException {
try {
List<DeviceIdentifier> deviceIds = new ArrayList<>();
for (Device device : devices) { for (Device device : devices) {
deviceIds.add(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); DeviceIdentifier identifier = new DeviceIdentifier();
identifier.setId(device.getDeviceIdentifier());
identifier.setType(device.getType());
Policy policy = this.getEffectivePolicy(identifier);
if (policy != null) {
List<DeviceIdentifier> 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<DeviceIdentifier> deviceIdentifiers, Policy policy) throws
PolicyDelegationException {
try {
OperationManager operationManager = new OperationManagerImpl();
operationManager.addOperation(PolicyManagerUtil.transformPolicy(policy), deviceIdentifiers);
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
throw new PolicyDelegationException("Error occurred while delegating policy information to " + String msg = "Error occurred while adding the operation to device.";
"the respective enforcement points", e); 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);
}
}
} }

@ -20,16 +20,20 @@ package org.wso2.carbon.policy.mgt.core.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.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.FeatureManagementException;
import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.Profile; import org.wso2.carbon.policy.mgt.common.Profile;
import org.wso2.carbon.policy.mgt.common.ProfileManagementException; 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.PolicyEnforcementDelegator;
import org.wso2.carbon.policy.mgt.core.enforcement.PolicyEnforcementDelegatorImpl; 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.FeatureManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; 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.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.PolicyManagerImpl;
import org.wso2.carbon.policy.mgt.core.mgt.impl.ProfileManagerImpl; import org.wso2.carbon.policy.mgt.core.mgt.impl.ProfileManagerImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint { public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
@ -46,13 +52,13 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
private PolicyManager policyManager; private PolicyManager policyManager;
private ProfileManager profileManager; private ProfileManager profileManager;
private FeatureManager featureManager; private FeatureManager featureManager;
private PolicyEnforcementDelegator delegator; // private PolicyEnforcementDelegator delegator;
public PolicyAdministratorPointImpl() { public PolicyAdministratorPointImpl() {
this.policyManager = new PolicyManagerImpl(); this.policyManager = new PolicyManagerImpl();
this.profileManager = new ProfileManagerImpl(); this.profileManager = new ProfileManagerImpl();
this.featureManager = new FeatureManagerImpl(); this.featureManager = new FeatureManagerImpl();
this.delegator = new PolicyEnforcementDelegatorImpl(); // this.delegator = new PolicyEnforcementDelegatorImpl();
} }
@Override @Override
@ -82,6 +88,16 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
return policyManager.updatePolicyPriorities(policies); 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 @Override
public boolean deletePolicy(Policy policy) throws PolicyManagementException { public boolean deletePolicy(Policy policy) throws PolicyManagementException {
return policyManager.deletePolicy(policy); return policyManager.deletePolicy(policy);
@ -93,7 +109,46 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
} }
@Override @Override
public Policy addPolicyToDevice(List<DeviceIdentifier> deviceIdentifierList, Policy policy) throws PolicyManagementException { public void publishChanges() throws PolicyManagementException {
List<DeviceType> 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<Device> 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<Integer, Integer> deviceIdPolicy = policyManager.getAppliedPolicyIdsDeviceIds();
List<Device> 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<DeviceIdentifier> deviceIdentifierList, Policy policy) throws
PolicyManagementException {
return policyManager.addPolicyToDevice(deviceIdentifierList, policy); return policyManager.addPolicyToDevice(deviceIdentifierList, policy);
} }
@ -185,7 +240,7 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
try { try {
return profileManager.getProfile(profileId); return profileManager.getProfile(profileId);
} catch (ProfileManagementException e) { } catch (ProfileManagementException e) {
String msg = "Error occurred while retriving profile"; String msg = "Error occurred while retrieving profile";
log.error(msg, e); log.error(msg, e);
throw new PolicyManagementException(msg, e); throw new PolicyManagementException(msg, e);
} }

@ -32,14 +32,56 @@ public class PolicyFilterImpl implements PolicyFilter {
private static final Log log = LogFactory.getLog(PolicyFilterImpl.class); private static final Log log = LogFactory.getLog(PolicyFilterImpl.class);
@Override
public List<Policy> filterActivePolicies(List<Policy> 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<Policy> temp = new ArrayList<Policy>();
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 @Override
public List<Policy> filterRolesBasedPolicies(String roles[], List<Policy> policies) { public List<Policy> filterRolesBasedPolicies(String roles[], List<Policy> 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<Policy> temp = new ArrayList<Policy>(); List<Policy> temp = new ArrayList<Policy>();
for (Policy policy : policies) { for (Policy policy : policies) {
List<String> tempRoles = policy.getRoles(); List<String> tempRoles = policy.getRoles();
if (tempRoles.isEmpty()) { if (tempRoles.isEmpty()) {
if(log.isDebugEnabled()) {
log.debug("Roles list is empty.");
}
temp.add(policy); temp.add(policy);
continue; 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; return temp;
} }
@Override @Override
public List<Policy> filterOwnershipTypeBasedPolicies(String ownershipType, List<Policy> policies) { public List<Policy> filterOwnershipTypeBasedPolicies(String ownershipType, List<Policy> 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<Policy> temp = new ArrayList<Policy>(); List<Policy> temp = new ArrayList<Policy>();
for (Policy policy : policies) { for (Policy policy : policies) {
if (ownershipType.equalsIgnoreCase(policy.getOwnershipType()) || if (ownershipType.equalsIgnoreCase(policy.getOwnershipType()) ||
@ -70,22 +128,56 @@ public class PolicyFilterImpl implements PolicyFilter {
temp.add(policy); 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; return temp;
} }
@Override @Override
public List<Policy> filterDeviceTypeBasedPolicies(String deviceType, List<Policy> policies) { public List<Policy> filterDeviceTypeBasedPolicies(String deviceType, List<Policy> 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<Policy> temp = new ArrayList<Policy>(); List<Policy> temp = new ArrayList<Policy>();
for (Policy policy : policies) { for (Policy policy : policies) {
if (deviceType.equalsIgnoreCase(policy.getProfile().getDeviceType().getName())) { if (deviceType.equalsIgnoreCase(policy.getProfile().getDeviceType().getName())) {
temp.add(policy); 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; return temp;
} }
@Override @Override
public List<Policy> filterUserBasedPolicies(String username, List<Policy> policies) { public List<Policy> filterUserBasedPolicies(String username, List<Policy> 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<Policy> temp = new ArrayList<Policy>(); List<Policy> temp = new ArrayList<Policy>();
for (Policy policy : policies) { 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; return temp;
} }
} }

@ -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.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.common.Feature; 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.common.*;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; 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.FeatureManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; 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.FeatureManagerImpl;
import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; 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.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -93,6 +96,16 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
List<Policy> policies = policyManager.getPoliciesOfDeviceType(pipDevice.getDeviceType().getName()); List<Policy> policies = policyManager.getPoliciesOfDeviceType(pipDevice.getDeviceType().getName());
PolicyFilter policyFilter = new PolicyFilterImpl(); 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) { if (pipDevice.getDeviceType() != null) {
policies = policyFilter.filterDeviceTypeBasedPolicies(pipDevice.getDeviceType().getName(), policies); policies = policyFilter.filterDeviceTypeBasedPolicies(pipDevice.getDeviceType().getName(), policies);
} }
@ -106,6 +119,14 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
policies = policyFilter.filterUserBasedPolicies(pipDevice.getUserId(), policies); 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; return policies;
} }
@ -117,12 +138,14 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
private String[] getRoleOfDevice(Device device) throws PolicyManagementException { private String[] getRoleOfDevice(Device device) throws PolicyManagementException {
try { try {
return CarbonContext.getThreadLocalCarbonContext().getUserRealm(). UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
getUserStoreManager().getRoleListOfUser(device.getEnrolmentInfo().getOwner()); if (userRealm != null) {
return userRealm.getUserStoreManager().getRoleListOfUser(device.getEnrolmentInfo().getOwner());
} else {
return null;
}
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "Error occurred when retrieving roles related to user name."; throw new PolicyManagementException("Error occurred when retrieving roles related to user name.", e);
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} }
} }
@ -139,12 +162,11 @@ public class PolicyInformationPointImpl implements PolicyInformationPoint {
} }
} }
} }
return finalPolicies; return finalPolicies;
} }
private DeviceManagementProviderService getDeviceManagementService() { private DeviceManagementProviderService getDeviceManagementService() {
return PolicyManagementDataHolder.getInstance().getDeviceManagementService(); return new DeviceManagementProviderServiceImpl();
} }
} }

@ -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.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; 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.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.ProfileFeature; import org.wso2.carbon.policy.mgt.common.ProfileFeature;
import java.util.HashMap;
import java.util.List; import java.util.List;
public interface PolicyManager { public interface PolicyManager {
@ -37,6 +39,10 @@ public interface PolicyManager {
boolean deletePolicy(int policyId) throws PolicyManagementException; boolean deletePolicy(int policyId) throws PolicyManagementException;
void activatePolicy(int policyId) throws PolicyManagementException;
void inactivatePolicy(int policyId) throws PolicyManagementException;
Policy addPolicyToDevice(List<DeviceIdentifier> deviceIdentifierList, Policy policy) throws Policy addPolicyToDevice(List<DeviceIdentifier> deviceIdentifierList, Policy policy) throws
PolicyManagementException; PolicyManagementException;
@ -63,6 +69,8 @@ public interface PolicyManager {
void addAppliedPolicyFeaturesToDevice(DeviceIdentifier deviceIdentifier, Policy policy) void addAppliedPolicyFeaturesToDevice(DeviceIdentifier deviceIdentifier, Policy policy)
throws PolicyManagementException; throws PolicyManagementException;
List<DeviceType> applyChangesMadeToPolicies() throws PolicyManagementException;
void addAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier, Policy policy) throws PolicyManagementException; void addAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier, Policy policy) throws PolicyManagementException;
boolean checkPolicyAvailable(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; boolean checkPolicyAvailable(DeviceIdentifier deviceIdentifier) throws PolicyManagementException;
@ -72,4 +80,6 @@ public interface PolicyManager {
int getPolicyCount() throws PolicyManagementException; int getPolicyCount() throws PolicyManagementException;
Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException;
HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagementException;
} }

@ -21,39 +21,35 @@ package org.wso2.carbon.policy.mgt.core.mgt.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; 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.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; 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.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.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; 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.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; 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.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.ComplianceData;
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceDecisionPoint; 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.ComplianceFeature;
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; 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.common.spi.PolicyMonitoringService;
import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAO; import org.wso2.carbon.policy.mgt.core.dao.*;
import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAOException;
import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl; import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; 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.MonitoringManager;
import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import java.sql.SQLException; 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 { public class MonitoringManagerImpl implements MonitoringManager {
@ -81,8 +77,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
PolicyManager manager = new PolicyManagerImpl(); PolicyManager manager = new PolicyManagerImpl();
Device device = service.getDevice(deviceIdentifier); Device device = service.getDevice(deviceIdentifier);
Policy policy = manager.getAppliedPolicyToDevice(deviceIdentifier); //policyDAO.getAppliedPolicy(device Policy policy = manager.getAppliedPolicyToDevice(deviceIdentifier);
// .getId());
if (policy != null) { if (policy != null) {
PolicyMonitoringService monitoringService = PolicyManagementDataHolder.getInstance(). PolicyMonitoringService monitoringService = PolicyManagementDataHolder.getInstance().
getPolicyMonitoringService(deviceIdentifier.getType()); getPolicyMonitoringService(deviceIdentifier.getType());
@ -115,7 +110,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Compliance status primary key " + complianceData.getId()); log.debug("Compliance status primary key " + complianceData.getId());
} }
// complianceData.setId(cmf.getId());
monitoringDAO.addNoneComplianceFeatures(complianceData.getId(), device.getId(), complianceFeatures); monitoringDAO.addNoneComplianceFeatures(complianceData.getId(), device.getId(), complianceFeatures);
PolicyManagementDAOFactory.commitTransaction(); PolicyManagementDAOFactory.commitTransaction();
complianceDecisionPoint.validateDevicePolicyCompliance(deviceIdentifier, complianceData); complianceDecisionPoint.validateDevicePolicyCompliance(deviceIdentifier, complianceData);
@ -130,7 +124,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
} else { } else {
PolicyManagementDAOFactory.beginTransaction(); PolicyManagementDAOFactory.beginTransaction();
monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId()); monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId());
//complianceData.setId(cmf.getId());
monitoringDAO.deleteNoneComplianceData(complianceData.getId()); monitoringDAO.deleteNoneComplianceData(complianceData.getId());
PolicyManagementDAOFactory.commitTransaction(); PolicyManagementDAOFactory.commitTransaction();
} }
@ -162,7 +155,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
try { try {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier); Device device = service.getDevice(deviceIdentifier);
//deviceDAO.getDevice(deviceIdentifier, tenantId);
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
ComplianceData complianceData = monitoringDAO.getCompliance(device.getId()); ComplianceData complianceData = monitoringDAO.getCompliance(device.getId());
if (complianceData == null || !complianceData.isStatus()) { if (complianceData == null || !complianceData.isStatus()) {

@ -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.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; 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.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.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.common.*;
import org.wso2.carbon.policy.mgt.core.dao.*; 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.PolicyManager;
import org.wso2.carbon.policy.mgt.core.mgt.ProfileManager; 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.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList; import java.util.*;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
public class PolicyManagerImpl implements PolicyManager { public class PolicyManagerImpl implements PolicyManager {
@ -47,7 +46,6 @@ public class PolicyManagerImpl implements PolicyManager {
private ProfileDAO profileDAO; private ProfileDAO profileDAO;
private FeatureDAO featureDAO; private FeatureDAO featureDAO;
private DeviceDAO deviceDAO; private DeviceDAO deviceDAO;
// private DeviceTypeDAO deviceTypeDAO;
private ProfileManager profileManager; private ProfileManager profileManager;
private static Log log = LogFactory.getLog(PolicyManagerImpl.class); private static Log log = LogFactory.getLog(PolicyManagerImpl.class);
@ -56,7 +54,6 @@ public class PolicyManagerImpl implements PolicyManager {
this.profileDAO = PolicyManagementDAOFactory.getProfileDAO(); this.profileDAO = PolicyManagementDAOFactory.getProfileDAO();
this.featureDAO = PolicyManagementDAOFactory.getFeatureDAO(); this.featureDAO = PolicyManagementDAOFactory.getFeatureDAO();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
// this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
this.profileManager = new ProfileManagerImpl(); this.profileManager = new ProfileManagerImpl();
} }
@ -72,7 +69,6 @@ public class PolicyManagerImpl implements PolicyManager {
profile.setCreatedDate(currentTimestamp); profile.setCreatedDate(currentTimestamp);
profile.setUpdatedDate(currentTimestamp); profile.setUpdatedDate(currentTimestamp);
profileDAO.addProfile(profile); profileDAO.addProfile(profile);
featureDAO.addProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId()); featureDAO.addProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId());
} }
@ -110,17 +106,6 @@ public class PolicyManagerImpl implements PolicyManager {
policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias()); 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(); PolicyManagementDAOFactory.commitTransaction();
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
@ -147,7 +132,13 @@ public class PolicyManagerImpl implements PolicyManager {
try { try {
PolicyManagementDAOFactory.beginTransaction(); 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()); policyDAO.deleteAllPolicyRelatedConfigs(policy.getId());
if (policy.getUsers() != null) { if (policy.getUsers() != null) {
@ -177,23 +168,20 @@ public class PolicyManagerImpl implements PolicyManager {
policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias()); 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(); PolicyManagementDAOFactory.commitTransaction();
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction(); PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while updating the policy (" throw new PolicyManagementException("Error occurred while updating the policy ("
+ policy.getId() + " - " + policy.getPolicyName() + ")", e); + 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 { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
@ -206,6 +194,7 @@ public class PolicyManagerImpl implements PolicyManager {
try { try {
PolicyManagementDAOFactory.beginTransaction(); PolicyManagementDAOFactory.beginTransaction();
bool = policyDAO.updatePolicyPriorities(policies); bool = policyDAO.updatePolicyPriorities(policies);
policyDAO.recordUpdatedPolicies(policies);
PolicyManagementDAOFactory.commitTransaction(); PolicyManagementDAOFactory.commitTransaction();
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction(); PolicyManagementDAOFactory.rollbackTransaction();
@ -245,12 +234,13 @@ public class PolicyManagerImpl implements PolicyManager {
@Override @Override
public boolean deletePolicy(int policyId) throws PolicyManagementException { public boolean deletePolicy(int policyId) throws PolicyManagementException {
boolean bool;
try { try {
PolicyManagementDAOFactory.beginTransaction(); PolicyManagementDAOFactory.beginTransaction();
Policy policy = policyDAO.getPolicy(policyId); Policy policy = policyDAO.getPolicy(policyId);
policyDAO.deleteAllPolicyRelatedConfigs(policyId); policyDAO.deleteAllPolicyRelatedConfigs(policyId);
policyDAO.deletePolicy(policyId); bool = policyDAO.deletePolicy(policyId);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Profile ID: " + policy.getProfileId()); log.debug("Profile ID: " + policy.getProfileId());
@ -260,7 +250,7 @@ public class PolicyManagerImpl implements PolicyManager {
profileDAO.deleteProfile(policy.getProfileId()); profileDAO.deleteProfile(policy.getProfileId());
PolicyManagementDAOFactory.commitTransaction(); PolicyManagementDAOFactory.commitTransaction();
return true; return bool;
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction(); PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while deleting the policy (" + policyId + ")", e); 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 @Override
public Policy addPolicyToDevice(List<DeviceIdentifier> deviceIdentifierList, public Policy addPolicyToDevice(List<DeviceIdentifier> deviceIdentifierList,
Policy policy) throws PolicyManagementException { Policy policy) throws PolicyManagementException {
@ -391,17 +416,12 @@ public class PolicyManagerImpl implements PolicyManager {
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
policy = policyDAO.getPolicyByProfileID(profileId); 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); profile = profileDAO.getProfiles(profileId);
policy.setProfile(profile); policy.setProfile(profile);
policy.setRoles(roleNames); policy.setRoles(roleNames);
policy.setDevices(deviceList);
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting the policy related to profile ID (" + throw new PolicyManagementException("Error occurred while getting the policy related to profile ID (" +
@ -414,6 +434,10 @@ public class PolicyManagerImpl implements PolicyManager {
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
// This is due to connection close in following method too.
deviceList = getPolicyAppliedDevicesIds(policy.getId());
policy.setDevices(deviceList);
return policy; return policy;
} }
@ -427,17 +451,13 @@ public class PolicyManagerImpl implements PolicyManager {
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
policy = policyDAO.getPolicy(policyId); 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()); Profile profile = profileDAO.getProfiles(policy.getProfileId());
policy.setProfile(profile); policy.setProfile(profile);
policy.setRoles(roleNames); policy.setRoles(roleNames);
policy.setDevices(deviceList);
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting the policy related to policy ID (" + throw new PolicyManagementException("Error occurred while getting the policy related to policy ID (" +
@ -450,11 +470,16 @@ public class PolicyManagerImpl implements PolicyManager {
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
// This is done because connection close in below method too.
deviceList = this.getPolicyAppliedDevicesIds(policyId);
policy.setDevices(deviceList);
return policy; return policy;
} }
@Override @Override
public List<Policy> getPolicies() throws PolicyManagementException { public List<Policy> getPolicies() throws PolicyManagementException {
List<Policy> policyList; List<Policy> policyList;
List<Profile> profileList; List<Profile> profileList;
try { try {
@ -465,7 +490,6 @@ public class PolicyManagerImpl implements PolicyManager {
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
policyList = policyDAO.getAllPolicies(); policyList = policyDAO.getAllPolicies();
// List<Profile> profileList = profileDAO.getAllProfiles();
for (Policy policy : policyList) { for (Policy policy : policyList) {
for (Profile profile : profileList) { for (Profile profile : profileList) {
@ -473,13 +497,9 @@ public class PolicyManagerImpl implements PolicyManager {
policy.setProfile(profile); policy.setProfile(profile);
} }
} }
policy.setDevices(getPolicyAppliedDevicesIds(policy.getId()));
policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId())); policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId()));
policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId())); policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId()));
policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId())); policy.setPolicyCriterias(policyDAO.getPolicyCriteria(policy.getId()));
// policyDAO.getDatesOfPolicy(policy);
// policyDAO.getTimesOfPolicy(policy);
// policyDAO.getLocationsOfPolicy(policy);
} }
Collections.sort(policyList); Collections.sort(policyList);
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
@ -489,6 +509,13 @@ public class PolicyManagerImpl implements PolicyManager {
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); 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; return policyList;
} }
@ -612,24 +639,43 @@ public class PolicyManagerImpl implements PolicyManager {
@Override @Override
public List<Device> getPolicyAppliedDevicesIds(int policyId) throws PolicyManagementException { public List<Device> getPolicyAppliedDevicesIds(int policyId) throws PolicyManagementException {
List<Device> deviceList = new ArrayList<>(); List<Device> deviceList = new ArrayList<>();
List<Integer> deviceIds; List<Integer> deviceIds;
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
deviceIds = policyDAO.getPolicyAppliedDevicesIds(policyId); deviceIds = policyDAO.getPolicyAppliedDevicesIds(policyId);
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
List<Device> allDevices = service.getAllDevices();
HashMap<Integer, Device> allDeviceMap = new HashMap<>();
if(!allDevices.isEmpty()) {
allDeviceMap = PolicyManagerUtil.covertDeviceListToMap(allDevices);
}
for (int deviceId : deviceIds) { 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) { } catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting the device ids related to policy id (" + throw new PolicyManagementException("Error occurred while getting the device ids related to policy id (" +
policyId + ")", e); policyId + ")", e);
} catch (DeviceManagementDAOException e) {
throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" +
policyId + ")", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new PolicyManagementException("Error occurred while opening a connection to the data source", 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 { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
@ -665,6 +711,47 @@ public class PolicyManagerImpl implements PolicyManager {
} }
} }
@Override
public List<DeviceType> applyChangesMadeToPolicies() throws PolicyManagementException {
List<DeviceType> changedDeviceTypes = new ArrayList<>();
try {
//HashMap<Integer, Integer> map = policyDAO.getUpdatedPolicyIdandDeviceTypeId();
List<Policy> updatedPolicies = new ArrayList<>();
// List<Policy> activePolicies = new ArrayList<>();
// List<Policy> inactivePolicies = new ArrayList<>();
List<Integer> updatedPolicyIds = new ArrayList<>();
List<Policy> 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 @Override
public void addAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier, Policy policy) public void addAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier, Policy policy)
throws PolicyManagementException { throws PolicyManagementException {
@ -674,8 +761,6 @@ public class PolicyManagerImpl implements PolicyManager {
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device = service.getDevice(deviceIdentifier); Device device = service.getDevice(deviceIdentifier);
deviceId = device.getId(); deviceId = device.getId();
// boolean exist = policyDAO.checkPolicyAvailable(deviceId);
PolicyManagementDAOFactory.beginTransaction(); PolicyManagementDAOFactory.beginTransaction();
Policy policySaved = policyDAO.getAppliedPolicy(deviceId); Policy policySaved = policyDAO.getAppliedPolicy(deviceId);
@ -782,4 +867,18 @@ public class PolicyManagerImpl implements PolicyManager {
return policy; return policy;
} }
@Override
public HashMap<Integer, Integer> 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();
}
}
} }

@ -91,7 +91,7 @@ public class ProfileManagerImpl implements ProfileManager {
try { try {
PolicyManagementDAOFactory.beginTransaction(); PolicyManagementDAOFactory.beginTransaction();
profile = profileDAO.updateProfile(profile); profileDAO.updateProfile(profile);
featureDAO.updateProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId()); featureDAO.updateProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId());
PolicyManagementDAOFactory.commitTransaction(); PolicyManagementDAOFactory.commitTransaction();
} catch (ProfileManagerDAOException e) { } 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); throw new ProfileManagementException("Error occurred while opening a connection to the data source", e);
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
DeviceManagementDAOFactory.closeConnection();
} }
return profile; 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); throw new ProfileManagementException("Error occurred while opening a connection to the data source", e);
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
DeviceManagementDAOFactory.closeConnection();
} }
return profileList; 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); throw new ProfileManagementException("Error occurred while opening a connection to the data source", e);
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
DeviceManagementDAOFactory.closeConnection();
} }
return profileList; return profileList;
} }

@ -21,6 +21,7 @@ package org.wso2.carbon.policy.mgt.core.util;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document; 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.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; 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.File;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List; import java.util.List;
@ -140,9 +142,29 @@ public class PolicyManagerUtil {
return data; return data;
} }
public static boolean convertIntToBoolean(int x) {
if (x == 1) {
return true;
} else {
return false;
}
}
public static Cache getCacheManagerImpl() { public static Cache getCacheManagerImpl() {
return Caching.getCacheManagerFactory() return Caching.getCacheManagerFactory()
.getCacheManager(PolicyManagementConstants.DM_CACHE_MANAGER).getCache(PolicyManagementConstants.DM_CACHE); .getCacheManager(PolicyManagementConstants.DM_CACHE_MANAGER).getCache(PolicyManagementConstants
.DM_CACHE);
}
public static HashMap<Integer, Device> covertDeviceListToMap(List<Device> devices) {
HashMap<Integer, Device> deviceHashMap = new HashMap<>();
for (Device device : devices) {
deviceHashMap.put(device.getId(), device);
}
return deviceHashMap;
} }
} }

@ -49,7 +49,7 @@ public abstract class BasePolicyManagementDAOTest {
@BeforeSuite @BeforeSuite
public void setupDataSource() throws Exception { public void setupDataSource() throws Exception {
this.initDatSource(); this.initDatSource();
this.initSQLScript(); // this.initSQLScript();
} }
public void initDatSource() throws Exception { public void initDatSource() throws Exception {

@ -81,9 +81,9 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
identifier.setType(ANDROID); identifier.setType(ANDROID);
identifier.setId(devices.get(0).getDeviceIdentifier()); identifier.setId(devices.get(0).getDeviceIdentifier());
PolicyAdministratorPoint administratorPoint = new PolicyAdministratorPointImpl(); // PolicyAdministratorPoint administratorPoint = new PolicyAdministratorPointImpl();
//
administratorPoint.setPolicyUsed(identifier, policies.get(0)); // administratorPoint.setPolicyUsed(identifier, policies.get(0));
} }
@ -116,9 +116,11 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
DeviceManagementDataHolder.getInstance().setOperationManager(operationManager); DeviceManagementDataHolder.getInstance().setOperationManager(operationManager);
if (policy != null) {
log.debug(policy.getId()); log.debug(policy.getId());
log.debug(policy.getPolicyName()); log.debug(policy.getPolicyName());
log.debug(policy.getCompliance()); log.debug(policy.getCompliance());
}
MonitoringManager monitoringManager = new MonitoringManagerImpl(); MonitoringManager monitoringManager = new MonitoringManagerImpl();
@ -137,7 +139,6 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
PolicyComplianceException { PolicyComplianceException {
PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest(); PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest();
PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(), PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(),
monitoringServiceTest); monitoringServiceTest);
@ -166,7 +167,8 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
@Test(dependsOnMethods = ("checkComplianceFromMonitoringService")) @Test(dependsOnMethods = ("checkComplianceFromMonitoringService"))
public void checkCompliance() throws DeviceManagementException, PolicyComplianceException, PolicyManagementException { public void checkCompliance() throws DeviceManagementException, PolicyComplianceException,
PolicyManagementException {
PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest(); PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest();
PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(), PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(),

@ -76,25 +76,30 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO(); EnrolmentDAO enrolmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
DeviceType type = DeviceTypeCreator.getDeviceType(); DeviceType type = DeviceTypeCreator.getDeviceType();
devices = DeviceCreator.getDeviceList(type); 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) { for (Device device : devices) {
int id = deviceDAO.addDevice(type.getId(), device, -1234); int id = deviceDAO.addDevice(type.getId(), device, -1234);
enrolmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -1234); enrolmentDAO.addEnrollment(id, device.getEnrolmentInfo(), -1234);
} }
List<Device> devices = deviceDAO.getDevices(-1234); // List<Device> devices = deviceDAO.getDevices(-1234);
//
log.debug("--- Printing device taken by calling the device dao layer by tenant id."); // log.debug("--- Printing device taken by calling the device dao layer by tenant id.");
for (Device device : devices) { // for (Device device : devices) {
log.debug(device.getDeviceIdentifier()); // log.debug(device.getDeviceIdentifier());
} // }
//
//
log.debug("--- Printing device taken by calling the device dao layer by tenant id and device type."); // log.debug("--- Printing device taken by calling the device dao layer by tenant id and device type.");
List<Device> devices2 = deviceDAO.getDevices("android", -1234); // List<Device> devices2 = deviceDAO.getDevices("android", -1234);
//
for (Device device : devices2) { // for (Device device : devices2) {
log.debug(device.getDeviceIdentifier()); // log.debug(device.getDeviceIdentifier());
} // }
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); 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."); log.debug("Printing device taken by calling the service layer with device type.");
List<Device> devices3 = service.getAllDevices("android"); List<Device> devices3 = service.getAllDevices("android");
log.debug("Device list size ..........................!" + devices3.size());
for (Device device : devices3) { for (Device device : devices3) {
log.debug(device.getDeviceIdentifier()); log.debug(device.getDeviceIdentifier());
} }
@ -125,15 +131,15 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
public void addProfileFeatures() throws ProfileManagementException { public void addProfileFeatures() throws ProfileManagementException {
ProfileManager profileManager = new ProfileManagerImpl(); ProfileManager profileManager = new ProfileManagerImpl();
profile = ProfileCreator.getProfile(featureList); Profile profile = ProfileCreator.getProfile2(FeatureCreator.getFeatureList2());
profileManager.addProfile(profile); // profileManager.addProfile(profile);
profileFeatureList = profile.getProfileFeaturesList(); // profileFeatureList = profile.getProfileFeaturesList();
} }
@Test(dependsOnMethods = ("addProfileFeatures")) @Test(dependsOnMethods = ("addProfileFeatures"))
public void addPolicy() throws PolicyManagementException, ProfileManagementException { public void addPolicy() throws PolicyManagementException, ProfileManagementException {
ProfileManager profileManager = new ProfileManagerImpl(); ProfileManager profileManager = new ProfileManagerImpl();
profile = ProfileCreator.getProfile(featureList); Profile profile = ProfileCreator.getProfile5(FeatureCreator.getFeatureList5());
profileManager.addProfile(profile); profileManager.addProfile(profile);
PolicyManager policyManager = new PolicyManagerImpl(); PolicyManager policyManager = new PolicyManagerImpl();
policy = PolicyCreator.createPolicy(profile); policy = PolicyCreator.createPolicy(profile);
@ -171,10 +177,10 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
@Test(dependsOnMethods = ("addPolicyToDevice")) @Test(dependsOnMethods = ("addPolicyToDevice"))
public void addNewPolicy() throws PolicyManagementException, ProfileManagementException { public void addNewPolicy() throws PolicyManagementException, ProfileManagementException {
ProfileManager profileManager = new ProfileManagerImpl(); ProfileManager profileManager = new ProfileManagerImpl();
profile = ProfileCreator.getProfile(featureList); Profile profile = ProfileCreator.getProfile3(FeatureCreator.getFeatureList3());
profileManager.addProfile(profile); profileManager.addProfile(profile);
PolicyManager policyManager = new PolicyManagerImpl(); PolicyManager policyManager = new PolicyManagerImpl();
policy = PolicyCreator.createPolicy2(profile); Policy policy = PolicyCreator.createPolicy2(profile);
policyManager.addPolicy(policy); policyManager.addPolicy(policy);
} }
@ -182,10 +188,10 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
@Test(dependsOnMethods = ("addPolicyToDevice")) @Test(dependsOnMethods = ("addPolicyToDevice"))
public void addThirdPolicy() throws PolicyManagementException, ProfileManagementException { public void addThirdPolicy() throws PolicyManagementException, ProfileManagementException {
ProfileManager profileManager = new ProfileManagerImpl(); ProfileManager profileManager = new ProfileManagerImpl();
profile = ProfileCreator.getProfile(featureList); Profile profile = ProfileCreator.getProfile4(FeatureCreator.getFeatureList4());
profileManager.addProfile(profile); profileManager.addProfile(profile);
PolicyManager policyManager = new PolicyManagerImpl(); PolicyManager policyManager = new PolicyManagerImpl();
policy = PolicyCreator.createPolicy4(profile); Policy policy = PolicyCreator.createPolicy4(profile);
policyManager.addPolicy(policy); policyManager.addPolicy(policy);
} }
@ -279,14 +285,28 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
@Test(dependsOnMethods = ("getRoleRelatedPolicy")) @Test(dependsOnMethods = ("getRoleRelatedPolicy"))
public void addSecondPolicy() throws PolicyManagementException, ProfileManagementException { public void addSecondPolicy() throws PolicyManagementException, ProfileManagementException {
ProfileManager profileManager = new ProfileManagerImpl(); ProfileManager profileManager = new ProfileManagerImpl();
profile = ProfileCreator.getProfile(featureList); Profile profile = ProfileCreator.getProfile(FeatureCreator.getFeatureList());
profileManager.addProfile(profile); profileManager.addProfile(profile);
PolicyManager policyManager = new PolicyManagerImpl(); PolicyManager policyManager = new PolicyManagerImpl();
policy = PolicyCreator.createPolicy3(profile); Policy policy = PolicyCreator.createPolicy3(profile);
policyManager.addPolicy(policy); 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<String> users = new ArrayList<>();
users.add("Udara");
users.add("Dileesha");
policy.setUsers(users);
policyManager.updatePolicy(policy);
}
@Test(dependsOnMethods = ("updatedPolicy"))
public void getRoleRelatedPolicySecondTime() throws PolicyManagementException { public void getRoleRelatedPolicySecondTime() throws PolicyManagementException {
PolicyAdministratorPoint policyAdministratorPoint = new PolicyAdministratorPointImpl(); PolicyAdministratorPoint policyAdministratorPoint = new PolicyAdministratorPointImpl();
@ -369,6 +389,8 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
log.debug(device.getDeviceIdentifier() + " ----- D"); log.debug(device.getDeviceIdentifier() + " ----- D");
} }
} }
} }

@ -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<Policy> 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<Device> 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<Policy> 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<Policy> policyList) {
Collections.sort(policyList);
}
}

@ -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<Policy> 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<ProfileFeature> getEffectiveFeatures(DeviceIdentifier deviceIdentifier) throws PolicyEvaluationException {
return null;
}
public void sortPolicies(List<Policy> policyList) throws PolicyEvaluationException {
Collections.sort(policyList);
}
}

@ -27,10 +27,12 @@ import java.util.List;
public class DeviceCreator { public class DeviceCreator {
private static List<Device> deviceList = new ArrayList<Device>(); //private static ;
public static List<Device> getDeviceList(DeviceType deviceType) { public static List<Device> getDeviceList(DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
Device device = new Device(); Device device = new Device();
device.setId(1); device.setId(1);
device.setType(deviceType.getName()); device.setType(deviceType.getName());
@ -42,25 +44,131 @@ public class DeviceCreator {
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setEnrolmentInfo(enrolmentInfo); device.setEnrolmentInfo(enrolmentInfo);
Device device1 = new Device(); // Device device1 = new Device();
device1.setId(1); // device1.setId(2);
device1.setType(deviceType.getName()); // device1.setType(deviceType.getName());
device1.setName("Nexus 5"); // device1.setName("Nexus 5");
device1.setDeviceIdentifier("def456"); // device1.setDeviceIdentifier("def456");
EnrolmentInfo enrolmentInfo1 = new EnrolmentInfo(); // EnrolmentInfo enrolmentInfo1 = new EnrolmentInfo();
enrolmentInfo1.setOwner("Manoj"); // enrolmentInfo1.setOwner("Manoj");
enrolmentInfo1.setOwnership(EnrolmentInfo.OwnerShip.BYOD); // enrolmentInfo1.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo1.setStatus(EnrolmentInfo.Status.ACTIVE); // enrolmentInfo1.setStatus(EnrolmentInfo.Status.ACTIVE);
device1.setEnrolmentInfo(enrolmentInfo); // device1.setEnrolmentInfo(enrolmentInfo);
deviceList.add(device);
// deviceList.add(device1);
return deviceList;
}
public static List<Device> getDeviceList2 (DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
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<Device> getDeviceList3 (DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
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<Device> getDeviceList4 (DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
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<Device> getDeviceList5 (DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
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(device);
// deviceList.add(device2); return deviceList;
}
public static List<Device> getDeviceList6 (DeviceType deviceType) {
List<Device> deviceList = new ArrayList<Device>();
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; return deviceList;
} }
public static Device getSingleDevice() { 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;
} }
} }

@ -21,10 +21,15 @@ package org.wso2.carbon.policy.mgt.core.util;
import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.Feature;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
public class FeatureCreator { public class FeatureCreator {
private static List<Feature> featureList = new ArrayList<Feature>();
private static HashMap<Integer, Feature> featureMap = new HashMap<>();
public static List<Feature> getFeatureList() { public static List<Feature> getFeatureList() {
Feature feature1 = new Feature(); Feature feature1 = new Feature();
@ -119,7 +124,7 @@ public class FeatureCreator {
feature11.setDeviceType("android"); feature11.setDeviceType("android");
List<Feature> featureList = new ArrayList<Feature>(); List<Feature> featureList2 = new ArrayList<Feature>();
featureList.add(feature1); featureList.add(feature1);
featureList.add(feature2); featureList.add(feature2);
featureList.add(feature3); featureList.add(feature3);
@ -132,6 +137,70 @@ public class FeatureCreator {
featureList.add(feature10); featureList.add(feature10);
featureList.add(feature11); 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<Feature> getFeatureList2() {
List<Feature> featureList2 = new ArrayList<Feature>();
featureList2.add(featureMap.get(3));
featureList2.add(featureMap.get(4));
return featureList2;
}
public static List<Feature> getFeatureList3() {
List<Feature> featureList2 = new ArrayList<Feature>();
featureList2.add(featureMap.get(5));
featureList2.add(featureMap.get(6));
featureList2.add(featureMap.get(7));
return featureList2;
}
public static List<Feature> getFeatureList4() {
List<Feature> featureList2 = new ArrayList<Feature>();
featureList2.add(featureMap.get(7));
featureList2.add(featureMap.get(8));
featureList2.add(featureMap.get(9));
return featureList2;
}
public static List<Feature> getFeatureList5() {
List<Feature> featureList2 = new ArrayList<Feature>();
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<Feature> getFeatureList6() {
List<Feature> featureList2 = new ArrayList<Feature>();
featureList2.add(featureMap.get(3));
featureList2.add(featureMap.get(8));
featureList2.add(featureMap.get(9));
featureList2.add(featureMap.get(5));
return featureList2;
}
}

@ -50,7 +50,7 @@ public class PolicyCreator {
policy.setPolicyName("Test_Policy_02"); policy.setPolicyName("Test_Policy_02");
policy.setGeneric(true); policy.setGeneric(true);
policy.setProfile(profile); policy.setProfile(profile);
policy.setDevices(DeviceCreator.getDeviceList(DeviceTypeCreator.getDeviceType())); policy.setDevices(DeviceCreator.getDeviceList2(DeviceTypeCreator.getDeviceType()));
policy.setCompliance("ENFORCE"); policy.setCompliance("ENFORCE");
@ -99,7 +99,7 @@ public class PolicyCreator {
policy.setPolicyName("Test_Policy_03"); policy.setPolicyName("Test_Policy_03");
policy.setGeneric(true); policy.setGeneric(true);
policy.setProfile(profile); policy.setProfile(profile);
policy.setDevices(DeviceCreator.getDeviceList(DeviceTypeCreator.getDeviceType())); policy.setDevices(DeviceCreator.getDeviceList3(DeviceTypeCreator.getDeviceType()));
List<String> roles = new ArrayList<String>(); List<String> roles = new ArrayList<String>();
roles.add("Role_01"); roles.add("Role_01");
@ -138,7 +138,7 @@ public class PolicyCreator {
policy.setPolicyName("Test_Policy_04"); policy.setPolicyName("Test_Policy_04");
policy.setGeneric(true); policy.setGeneric(true);
policy.setProfile(profile); policy.setProfile(profile);
policy.setDevices(DeviceCreator.getDeviceList(DeviceTypeCreator.getDeviceType())); policy.setDevices(DeviceCreator.getDeviceList4(DeviceTypeCreator.getDeviceType()));
policy.setCompliance("MONITOR"); policy.setCompliance("MONITOR");
policy.setOwnershipType("BYOD"); policy.setOwnershipType("BYOD");

@ -41,4 +41,66 @@ public class ProfileCreator {
return profile; return profile;
} }
public static Profile getProfile2(List<Feature> 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<Feature> 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<Feature> 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<Feature> 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;
}
}

@ -23,18 +23,18 @@
<!-- For H2 --> <!-- For H2 -->
<Url>jdbc:h2:mem:cdm-test-db;DB_CLOSE_DELAY=-1</Url> <!--<Url>jdbc:h2:mem:cdm-test-db;DB_CLOSE_DELAY=-1</Url>-->
<DriverClassName>org.h2.Driver</DriverClassName> <!--<DriverClassName>org.h2.Driver</DriverClassName>-->
<User>wso2carbon</User> <!--<User>wso2carbon</User>-->
<Password>wso2carbon</Password> <!--<Password>wso2carbon</Password>-->
<!-- For MySql --> <!-- For MySql -->
<!--<Url>jdbc:mysql://localhost:3306/WSO2CDM</Url>--> <Url>jdbc:mysql://localhost:3306/WSO2CDM</Url>
<!--<DriverClassName>com.mysql.jdbc.Driver</DriverClassName>--> <DriverClassName>com.mysql.jdbc.Driver</DriverClassName>
<!--<userName>root</userName>--> <User>root</User>
<!--<pwd></pwd>--> <Password></Password>
</DataSourceConfig> </DataSourceConfig>

@ -109,7 +109,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATIONS (
APPLICATIONS BLOB DEFAULT NULL, APPLICATIONS BLOB DEFAULT NULL,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_applications_device FOREIGN KEY (DEVICE_ID) REFERENCES 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 ---- --- POLICY RELATED TABLES ----
@ -144,6 +144,8 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
OWNERSHIP_TYPE VARCHAR(45) NULL, OWNERSHIP_TYPE VARCHAR(45) NULL,
COMPLIANCE VARCHAR(100) 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) , PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID ) FOREIGN KEY (PROFILE_ID )
@ -345,6 +347,19 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES (
ON UPDATE NO ACTION 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 -- -- POLICY RELATED TABLES FINISHED --

@ -27,6 +27,7 @@
<classes> <classes>
<class name="org.wso2.carbon.policy.mgt.core.PolicyDAOTestCase"/> <class name="org.wso2.carbon.policy.mgt.core.PolicyDAOTestCase"/>
<class name="org.wso2.carbon.policy.mgt.core.MonitoringTestCase" /> <class name="org.wso2.carbon.policy.mgt.core.MonitoringTestCase" />
<class name="org.wso2.carbon.policy.mgt.core.PolicyEvaluationTestCase" />
</classes> </classes>
</test> </test>
</suite> </suite>
Loading…
Cancel
Save