Add payload parsing for old type corrective actions

corrective-policy
Pahansith 5 years ago
parent 2724d8ac03
commit a24879f551

@ -49,6 +49,12 @@ import java.util.List;
+ "Wrappers") + "Wrappers")
public class PolicyWrapper { public class PolicyWrapper {
@ApiModelProperty(
name = "payloadVersion",
value = "Payload version of the Policy")
@Size(max = 45)
private String payloadVersion;
@ApiModelProperty( @ApiModelProperty(
name = "policyName", name = "policyName",
value = "The name of the policy", value = "The name of the policy",
@ -126,6 +132,18 @@ public class PolicyWrapper {
@NotNull @NotNull
private String policyType; private String policyType;
@ApiModelProperty(name = "correctiveActions",
value = "List of corrective actions to be applied when the policy is violated")
private List<CorrectiveAction> correctiveActions;
public String getPayloadVersion() {
return payloadVersion;
}
public void setPayloadVersion(String payloadVersion) {
this.payloadVersion = payloadVersion;
}
public String getPolicyType() { public String getPolicyType() {
return policyType; return policyType;
} }
@ -213,4 +231,12 @@ public class PolicyWrapper {
public void setDeviceGroups(List<DeviceGroupWrapper> deviceGroups) { public void setDeviceGroups(List<DeviceGroupWrapper> deviceGroups) {
this.deviceGroups = deviceGroups; this.deviceGroups = deviceGroups;
} }
public List<CorrectiveAction> getCorrectiveActions() {
return correctiveActions;
}
public void setCorrectiveActions(List<CorrectiveAction> correctiveActions) {
this.correctiveActions = correctiveActions;
}
} }

@ -60,8 +60,7 @@ public class ProfileFeature implements Serializable {
required = true) required = true)
private String payLoad; private String payLoad;
@ApiModelProperty(name = "correctiveActions", @ApiModelProperty(name = "correctiveActions",
value = "List of corrective actions to be applied when the policy is violated", value = "List of corrective actions to be applied when the policy is violated")
required = true)
private List<CorrectiveAction> correctiveActions; private List<CorrectiveAction> correctiveActions;
public int getId() { public int getId() {

@ -147,6 +147,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
policy.setCompliance(policyWrapper.getCompliance()); policy.setCompliance(policyWrapper.getCompliance());
policy.setDeviceGroups(policyWrapper.getDeviceGroups()); policy.setDeviceGroups(policyWrapper.getDeviceGroups());
policy.setPolicyType(policyWrapper.getPolicyType()); policy.setPolicyType(policyWrapper.getPolicyType());
policy.setPolicyPayloadVersion(policyWrapper.getPayloadVersion());
policy.setCorrectiveActions(policyWrapper.getCorrectiveActions());
//TODO iterates the device identifiers to create the object. need to implement a proper DAO layer here. //TODO iterates the device identifiers to create the object. need to implement a proper DAO layer here.
List<Device> devices = new ArrayList<Device>(); List<Device> devices = new ArrayList<Device>();
List<DeviceIdentifier> deviceIdentifiers = policyWrapper.getDeviceIdentifiers(); List<DeviceIdentifier> deviceIdentifiers = policyWrapper.getDeviceIdentifiers();

@ -55,7 +55,9 @@ public class CorrectiveAction implements Serializable {
) )
private List<ProfileFeature> operations; private List<ProfileFeature> operations;
private int featureId; private Integer featureId;
private Integer associatedGeneralPolicyId;
public String getActionType() { public String getActionType() {
return actionType; return actionType;
@ -81,11 +83,19 @@ public class CorrectiveAction implements Serializable {
this.operations = operations; this.operations = operations;
} }
public int getFeatureId() { public Integer getFeatureId() {
return featureId; return featureId;
} }
public void setFeatureId(int featureId) { public void setFeatureId(Integer featureId) {
this.featureId = featureId; this.featureId = featureId;
} }
public Integer getAssociatedGeneralPolicyId() {
return associatedGeneralPolicyId;
}
public void setAssociatedGeneralPolicyId(Integer associatedGeneralPolicyId) {
this.associatedGeneralPolicyId = associatedGeneralPolicyId;
}
} }

@ -53,6 +53,12 @@ public class Policy implements Comparable<Policy>, Serializable {
private static final long serialVersionUID = 19981017L; private static final long serialVersionUID = 19981017L;
@ApiModelProperty(
name = "payloadVersion",
value = "Payload version of the Policy",
example = "1")
private String policyPayloadVersion;
@ApiModelProperty( @ApiModelProperty(
name = "id", name = "id",
value = "The policy ID", value = "The policy ID",
@ -201,6 +207,19 @@ public class Policy implements Comparable<Policy>, Serializable {
example = "GENERAL") example = "GENERAL")
private String policyType; private String policyType;
@ApiModelProperty(name = "correctiveActions",
value = "List of corrective actions to be applied when the policy is violated")
private List<CorrectiveAction> correctiveActions;
@XmlElement
public String getPolicyPayloadVersion() {
return policyPayloadVersion;
}
public void setPolicyPayloadVersion(String policyPayloadVersion) {
this.policyPayloadVersion = policyPayloadVersion;
}
@XmlElement @XmlElement
public int getId() { public int getId() {
return id; return id;
@ -372,6 +391,14 @@ public class Policy implements Comparable<Policy>, Serializable {
this.policyType = policyType; this.policyType = policyType;
} }
public List<CorrectiveAction> getCorrectiveActions() {
return correctiveActions;
}
public void setCorrectiveActions(List<CorrectiveAction> correctiveActions) {
this.correctiveActions = correctiveActions;
}
@Override @Override
public int compareTo(Policy o) { public int compareTo(Policy o) {
if (this.priorityId == o.priorityId) if (this.priorityId == o.priorityId)

@ -63,7 +63,10 @@ policyModule = function () {
policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"]; policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"];
policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"]; policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"];
policyObjectFromRestEndpoint["policyType"] = policyListFromRestEndpoint["policyType"]; policyObjectFromRestEndpoint["policyType"] = policyListFromRestEndpoint["policyType"];
policyObjectFromRestEndpoint["correctiveActions"] = policyListFromRestEndpoint["correctiveActions"]; var payloadVersion = policyObjectFromRestEndpoint["policyPayloadVersion"];
if (!parseFloat(payloadVersion) >= 2.0) {
policyObjectFromRestEndpoint["correctiveActions"] = policyListFromRestEndpoint["correctiveActions"];
}
if (policyObjectToView["platform"] == "ios") { if (policyObjectToView["platform"] == "ios") {
policyObjectToView["deviceTypeIcon"] = "apple"; policyObjectToView["deviceTypeIcon"] = "apple";
} else { } else {

@ -2,8 +2,7 @@
{{#if isAuthorized}} {{#if isAuthorized}}
<span id="logged-in-user" class="hidden" data-username="{{@user.username}}" data-domain="{{@user.domain}}" <span id="logged-in-user" class="hidden" data-username="{{@user.username}}" data-domain="{{@user.domain}}"
data-tenant-id="{{@user.tenantId}}" data-iscloud="{{isCloud}}" data-tenant-id="{{@user.tenantId}}" data-iscloud="{{isCloud}}"
data-isDeviceOwnerEnabled="{{isDeviceOwnerEnabled}}" data-storeapps="{{storeApps}}" data-isDeviceOwnerEnabled="{{isDeviceOwnerEnabled}}" data-storeapps="{{storeApps}}">
data-corrective-policies="{{correctivePolicies}}">
</span> </span>
<div class="row"> <div class="row">
<div class="col-md-12"> <div class="col-md-12">

@ -161,7 +161,6 @@ skipStep["policy-platform"] = function (policyPayloadObj) {
currentlyEffected["users"] = policyPayloadObj.users; currentlyEffected["users"] = policyPayloadObj.users;
currentlyEffected["groups"] = []; currentlyEffected["groups"] = [];
currentlyEffected["policyType"] = policyPayloadObj.policyType; currentlyEffected["policyType"] = policyPayloadObj.policyType;
currentlyEffected["correctiveActions"] = policyPayloadObj.correctiveActions;
if (policyPayloadObj.deviceGroups) { if (policyPayloadObj.deviceGroups) {
var deviceGroups = policyPayloadObj.deviceGroups; var deviceGroups = policyPayloadObj.deviceGroups;

@ -109,6 +109,12 @@ public interface PolicyDAO {
int featureId) int featureId)
throws PolicyManagerDAOException; throws PolicyManagerDAOException;
/**
* This method is used get all corrective actions from DB
* @throws PolicyManagerDAOException is thrown when there is an error in deleting corrective actions to database
*/
List<CorrectiveAction> getAllCorrectiveActions() throws PolicyManagerDAOException;
Policy updateUserOfPolicy(List<String> usersToAdd, Policy policy) throws PolicyManagerDAOException; Policy updateUserOfPolicy(List<String> usersToAdd, Policy policy) throws PolicyManagerDAOException;
Policy addPolicyToDevice(List<Device> devices, Policy policy) throws PolicyManagerDAOException; Policy addPolicyToDevice(List<Device> devices, Policy policy) throws PolicyManagerDAOException;

@ -40,10 +40,10 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; 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.policy.mgt.CorrectiveAction; import org.wso2.carbon.device.mgt.common.policy.mgt.CorrectiveAction;
import org.wso2.carbon.policy.mgt.common.Criterion;
import org.wso2.carbon.device.mgt.common.policy.mgt.DeviceGroupWrapper; import org.wso2.carbon.device.mgt.common.policy.mgt.DeviceGroupWrapper;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyCriterion; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyCriterion;
import org.wso2.carbon.policy.mgt.common.Criterion;
import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO; 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.PolicyManagementDAOFactory;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
@ -54,8 +54,17 @@ import org.wso2.carbon.policy.mgt.core.util.SetReferenceTransformer;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.sql.*; import java.sql.Connection;
import java.util.*; import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
public class PolicyDAOImpl implements PolicyDAO { public class PolicyDAOImpl implements PolicyDAO {
@ -277,7 +286,11 @@ public class PolicyDAOImpl implements PolicyDAO {
insertStmt.setString(1, correctiveAction.getActionType()); insertStmt.setString(1, correctiveAction.getActionType());
insertStmt.setInt(2, correctiveAction.getPolicyId()); insertStmt.setInt(2, correctiveAction.getPolicyId());
insertStmt.setInt(3, policyId); insertStmt.setInt(3, policyId);
insertStmt.setInt(4, featureId); if (featureId == -1) {
insertStmt.setNull(4, Types.INTEGER);
} else {
insertStmt.setInt(4, featureId);
}
insertStmt.addBatch(); insertStmt.addBatch();
} }
insertStmt.executeBatch(); insertStmt.executeBatch();
@ -293,24 +306,14 @@ public class PolicyDAOImpl implements PolicyDAO {
public List<CorrectiveAction> getCorrectiveActionsOfPolicy(int policyId) throws PolicyManagerDAOException { public List<CorrectiveAction> getCorrectiveActionsOfPolicy(int policyId) throws PolicyManagerDAOException {
try { try {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String query = "SELECT " + String query = "SELECT * " +
"ACTION_TYPE, " + "FROM DM_POLICY_CORRECTIVE_ACTION " +
"CORRECTIVE_POLICY_ID, " + "WHERE POLICY_ID = ?";
"FEATURE_ID "+
"FROM DM_POLICY_CORRECTIVE_ACTION " +
"WHERE POLICY_ID = ?";
try (PreparedStatement selectStmt = conn.prepareStatement(query)) { try (PreparedStatement selectStmt = conn.prepareStatement(query)) {
List<CorrectiveAction> correctiveActions = new ArrayList<>(); List<CorrectiveAction> correctiveActions = new ArrayList<>();
selectStmt.setInt(1, policyId); selectStmt.setInt(1, policyId);
try (ResultSet rs = selectStmt.executeQuery()) { try (ResultSet rs = selectStmt.executeQuery()) {
CorrectiveAction correctiveAction; extractCorrectivePolicies(selectStmt, correctiveActions);
while (rs.next()) {
correctiveAction = new CorrectiveAction();
correctiveAction.setActionType(rs.getString("ACTION_TYPE"));
correctiveAction.setPolicyId(rs.getInt("CORRECTIVE_POLICY_ID"));
correctiveAction.setFeatureId(rs.getInt("FEATURE_ID"));
correctiveActions.add(correctiveAction);
}
} }
return correctiveActions; return correctiveActions;
} }
@ -321,22 +324,62 @@ public class PolicyDAOImpl implements PolicyDAO {
} }
} }
@Override
public List<CorrectiveAction> getAllCorrectiveActions() throws PolicyManagerDAOException {
try {
Connection conn = this.getConnection();
String query = "SELECT * " +
"FROM DM_POLICY_CORRECTIVE_ACTION ";
try (PreparedStatement stmt = conn.prepareStatement(query)) {
List<CorrectiveAction> correctiveActions = new ArrayList<>();
extractCorrectivePolicies(stmt, correctiveActions);
return correctiveActions;
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving all corrective actions";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
}
}
private void extractCorrectivePolicies(PreparedStatement stmt, List<CorrectiveAction>
correctiveActions) throws SQLException {
try (ResultSet rs = stmt.executeQuery()) {
CorrectiveAction correctiveAction;
while (rs.next()) {
correctiveAction = new CorrectiveAction();
correctiveAction.setActionType(rs.getString("ACTION_TYPE"));
correctiveAction.setPolicyId(rs.getInt("CORRECTIVE_POLICY_ID"));
correctiveAction.setFeatureId(rs.getInt("FEATURE_ID"));
correctiveAction.setAssociatedGeneralPolicyId(rs.getInt("POLICY_ID"));
correctiveActions.add(correctiveAction);
}
}
}
@Override @Override
public void updateCorrectiveActionsOfPolicy(List<CorrectiveAction> correctiveActions, public void updateCorrectiveActionsOfPolicy(List<CorrectiveAction> correctiveActions,
int policyId, int featureId) int policyId, int featureId)
throws PolicyManagerDAOException { throws PolicyManagerDAOException {
try { try {
boolean isFeatureIdContains = false;
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String query = "UPDATE DM_POLICY_CORRECTIVE_ACTION " + String query = "UPDATE DM_POLICY_CORRECTIVE_ACTION " +
"SET CORRECTIVE_POLICY_ID = ? " + "SET CORRECTIVE_POLICY_ID = ? " +
"WHERE ACTION_TYPE = ? " + "WHERE ACTION_TYPE = ? " +
"AND POLICY_ID = ? AND FEATURE_ID = ?"; "AND POLICY_ID = ? ";
if (featureId != -1) {
isFeatureIdContains = true;
query = query.concat("AND FEATURE_ID = ?");
}
try (PreparedStatement updateStmt = conn.prepareStatement(query)) { try (PreparedStatement updateStmt = conn.prepareStatement(query)) {
for (CorrectiveAction correctiveAction : correctiveActions) { for (CorrectiveAction correctiveAction : correctiveActions) {
updateStmt.setInt(1, correctiveAction.getPolicyId()); updateStmt.setInt(1, correctiveAction.getPolicyId());
updateStmt.setString(2, correctiveAction.getActionType()); updateStmt.setString(2, correctiveAction.getActionType());
updateStmt.setInt(3, policyId); updateStmt.setInt(3, policyId);
updateStmt.setInt(4, featureId); if (isFeatureIdContains) {
updateStmt.setInt(4, featureId);
}
updateStmt.addBatch(); updateStmt.addBatch();
} }
updateStmt.executeBatch(); updateStmt.executeBatch();
@ -356,12 +399,19 @@ public class PolicyDAOImpl implements PolicyDAO {
Connection conn = this.getConnection(); Connection conn = this.getConnection();
String query = "DELETE FROM DM_POLICY_CORRECTIVE_ACTION " + String query = "DELETE FROM DM_POLICY_CORRECTIVE_ACTION " +
"WHERE ACTION_TYPE = ? " + "WHERE ACTION_TYPE = ? " +
"AND POLICY_ID = ? AND FEATURE_ID = ?"; "AND POLICY_ID = ? ";
boolean isFeatueIdContains = false;
if (featureId != -1) {
isFeatueIdContains = true;
query = query.concat("AND FEATURE_ID = ?");
}
try (PreparedStatement deleteStmt = conn.prepareStatement(query)) { try (PreparedStatement deleteStmt = conn.prepareStatement(query)) {
for (CorrectiveAction correctiveAction : correctiveActions) { for (CorrectiveAction correctiveAction : correctiveActions) {
deleteStmt.setString(1, correctiveAction.getActionType()); deleteStmt.setString(1, correctiveAction.getActionType());
deleteStmt.setInt(2, policyId); deleteStmt.setInt(2, policyId);
deleteStmt.setInt(3, featureId); if (isFeatueIdContains) {
deleteStmt.setInt(3, featureId);
}
deleteStmt.addBatch(); deleteStmt.addBatch();
} }
deleteStmt.executeBatch(); deleteStmt.executeBatch();
@ -929,7 +979,8 @@ 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 = ?," +
" UPDATED = ?, DESCRIPTION = ?, OWNERSHIP_TYPE = ?, POLICY_TYPE = ? WHERE ID = ? AND TENANT_ID = ?"; " UPDATED = ?, DESCRIPTION = ?, OWNERSHIP_TYPE = ?, POLICY_TYPE = ?, " +
"PAYLOAD_VERSION = ? 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());
@ -939,8 +990,9 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setString(6, policy.getDescription()); stmt.setString(6, policy.getDescription());
stmt.setString(7, policy.getOwnershipType()); stmt.setString(7, policy.getOwnershipType());
stmt.setString(8, policy.getPolicyType()); stmt.setString(8, policy.getPolicyType());
stmt.setInt(9, policy.getId()); stmt.setString(9, policy.getPolicyPayloadVersion());
stmt.setInt(10, tenantId); stmt.setInt(10, policy.getId());
stmt.setInt(11, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
@ -1049,6 +1101,7 @@ public class PolicyDAOImpl implements PolicyDAO {
policy.setPolicyType(resultSet.getString("POLICY_TYPE")); policy.setPolicyType(resultSet.getString("POLICY_TYPE"));
policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED"))); policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED")));
policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE"))); policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE")));
policy.setPolicyPayloadVersion(resultSet.getString("PAYLOAD_VERSION"));
} }
return policy; return policy;
@ -1560,8 +1613,10 @@ 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, " +
"UPDATED, ACTIVE, DESCRIPTION, POLICY_TYPE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; "PRIORITY, COMPLIANCE, OWNERSHIP_TYPE, " +
"UPDATED, ACTIVE, DESCRIPTION, POLICY_TYPE, PAYLOAD_VERSION) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query, new String[]{"id"}); stmt = conn.prepareStatement(query, new String[]{"id"});
stmt.setString(1, policy.getPolicyName()); stmt.setString(1, policy.getPolicyName());
@ -1574,6 +1629,7 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setInt(8, 0); stmt.setInt(8, 0);
stmt.setString(9, policy.getDescription()); stmt.setString(9, policy.getDescription());
stmt.setString(10, policy.getPolicyType()); stmt.setString(10, policy.getPolicyType());
stmt.setString(11, policy.getPolicyPayloadVersion());
int affectedRows = stmt.executeUpdate(); int affectedRows = stmt.executeUpdate();
@ -1878,6 +1934,7 @@ public class PolicyDAOImpl implements PolicyDAO {
policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE"))); policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE")));
policy.setDescription(resultSet.getString("DESCRIPTION")); policy.setDescription(resultSet.getString("DESCRIPTION"));
policy.setPolicyType(resultSet.getString("POLICY_TYPE")); policy.setPolicyType(resultSet.getString("POLICY_TYPE"));
policy.setPolicyPayloadVersion(resultSet.getString("PAYLOAD_VERSION"));
policies.add(policy); policies.add(policy);
} }
return policies; return policies;

@ -35,7 +35,7 @@
package org.wso2.carbon.policy.mgt.core.mgt.impl; package org.wso2.carbon.policy.mgt.core.mgt.impl;
import org.apache.commons.collections.map.HashedMap; import org.apache.commons.lang.StringUtils;
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.Device;
@ -58,18 +58,32 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
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.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.common.Criterion;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.ProfileManagementException;
import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl; import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl;
import org.wso2.carbon.policy.mgt.core.dao.*; import org.wso2.carbon.policy.mgt.core.dao.FeatureDAO;
import org.wso2.carbon.policy.mgt.core.dao.FeatureManagerDAOException;
import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
import org.wso2.carbon.policy.mgt.core.dao.ProfileDAO;
import org.wso2.carbon.policy.mgt.core.dao.ProfileManagerDAOException;
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.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.mgt.bean.UpdatedPolicyDeviceListBean; import org.wso2.carbon.policy.mgt.core.mgt.bean.UpdatedPolicyDeviceListBean;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; 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.*; import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PolicyManagerImpl implements PolicyManager { public class PolicyManagerImpl implements PolicyManager {
@ -102,6 +116,7 @@ public class PolicyManagerImpl implements PolicyManager {
profileDAO.addProfile(profile); profileDAO.addProfile(profile);
featureDAO.addProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId()); featureDAO.addProfileFeatures(profile.getProfileFeaturesList(), profile.getProfileId());
} }
policy.setPolicyPayloadVersion("2.0");
policy = policyDAO.addPolicy(policy); policy = policyDAO.addPolicy(policy);
if (policy.getProfile() != null) { if (policy.getProfile() != null) {
Profile profile = policy.getProfile(); Profile profile = policy.getProfile();
@ -213,13 +228,7 @@ public class PolicyManagerImpl implements PolicyManager {
// Checks for the existing features // Checks for the existing features
for (ProfileFeature feature : updatedFeatureList) { for (ProfileFeature feature : updatedFeatureList) {
if (feature.getCorrectiveActions() != null) {
updatedCorrectiveActionsMap.put(feature.getId(), feature.getCorrectiveActions());
}
for (ProfileFeature fe : existingProfileFeaturesList) { for (ProfileFeature fe : existingProfileFeaturesList) {
if (fe.getCorrectiveActions() != null) {
existingCorrectiveActionsMap.put(fe.getId(), fe.getCorrectiveActions());
}
if (feature.getFeatureCode().equalsIgnoreCase(fe.getFeatureCode())) { if (feature.getFeatureCode().equalsIgnoreCase(fe.getFeatureCode())) {
existingFeaturesList.add(feature); existingFeaturesList.add(feature);
temp.add(feature.getFeatureCode()); temp.add(feature.getFeatureCode());
@ -248,7 +257,8 @@ public class PolicyManagerImpl implements PolicyManager {
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
policy.getProfile().setUpdatedDate(currentTimestamp); policy.getProfile().setUpdatedDate(currentTimestamp);
policy.setPriorityId(previousPolicy.getPriorityId()); policy.setPriorityId(previousPolicy.getPriorityId());
policyDAO.updatePolicy(policy); policy.setPolicyPayloadVersion(previousPolicy.getPolicyPayloadVersion());
Policy updatedPolicy = policyDAO.updatePolicy(policy);
profileDAO.updateProfile(policy.getProfile()); profileDAO.updateProfile(policy.getProfile());
featureDAO.updateProfileFeatures(existingFeaturesList, profileId); featureDAO.updateProfileFeatures(existingFeaturesList, profileId);
@ -294,84 +304,40 @@ public class PolicyManagerImpl implements PolicyManager {
policyDAO.addPolicyCriteria(policy); policyDAO.addPolicyCriteria(policy);
policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias()); policyDAO.addPolicyCriteriaProperties(policy.getPolicyCriterias());
} }
String policyPayloadVersion = previousPolicy.getPolicyPayloadVersion();
float payloadVersion = 0f;
if (policyPayloadVersion != null && !StringUtils.isEmpty(policyPayloadVersion)) {
payloadVersion = Float.parseFloat(policyPayloadVersion);
}
/*List<CorrectiveAction> updatedCorrectiveActions = policy.getCorrectiveActions(); List<ProfileFeature> updatedFeatures = policy.getProfile().getProfileFeaturesList();
List<CorrectiveAction> existingCorrectiveActions = previousPolicy.getCorrectiveActions();*/ List<ProfileFeature> features = featureDAO.getFeaturesForProfile(profileId);
for (ProfileFeature updatedFeature : updatedFeatures) {
//Iterate all corrective actions in the new policy payload against it's features for (ProfileFeature feature : features) {
for (Integer featureId : updatedCorrectiveActionsMap.keySet()) { if (updatedFeature.getFeatureCode().equals(feature.getFeatureCode())) {
List<CorrectiveAction> correctiveActionsToUpdate = new ArrayList<>(); updatedFeature.setId(feature.getId());
List<CorrectiveAction> correctiveActionsToDelete = new ArrayList<>(); break;
List<CorrectiveAction> correctiveActionsToAdd = new ArrayList<>();
List<String> correctiveActionTypesToUpdate = new ArrayList<>();
List<String> existingCorrectiveActionTypes = new ArrayList<>();
List<CorrectiveAction> updatedCorrectiveActions = updatedCorrectiveActionsMap.get(featureId);
//Check this feature already have a corrective action
if (existingCorrectiveActionsMap.containsKey(featureId)) {
//Existing corrective actions of the selected feature
List<CorrectiveAction> existingCorrectiveActions = existingCorrectiveActionsMap.get(featureId);
for (CorrectiveAction updatedCorrectiveAction : updatedCorrectiveActions) {
for (CorrectiveAction existingCorrectiveAction : existingCorrectiveActions) {
if (updatedCorrectiveAction.getActionType().equals(existingCorrectiveAction.getActionType())) {
//If old action type is same as new action type, put them into
// updating list
correctiveActionsToUpdate.add(updatedCorrectiveAction);
existingCorrectiveActionTypes.add(updatedCorrectiveAction.getActionType());
}
}
//Newly added action types added to this list
correctiveActionTypesToUpdate.add(updatedCorrectiveAction.getActionType());
}
for (CorrectiveAction existingCorrectiveAction : existingCorrectiveActions) {
if (!correctiveActionTypesToUpdate.contains(existingCorrectiveAction.getActionType())) {
correctiveActionsToDelete.add(existingCorrectiveAction);
}
}
}
for (CorrectiveAction updatedCorrectiveAction : updatedCorrectiveActions) {
if (!existingCorrectiveActionTypes.contains(updatedCorrectiveAction.getActionType())) {
correctiveActionsToAdd.add(updatedCorrectiveAction);
} }
} }
if (log.isDebugEnabled()) { if (updatedFeature.getCorrectiveActions() != null) {
log.debug("Updating corrective actions for policy " + policy.getPolicyName() + updatedCorrectiveActionsMap.put(updatedFeature.getId(),
" having policy id " + policy.getId()); updatedFeature.getCorrectiveActions());
}
if (!correctiveActionsToUpdate.isEmpty()) {
policyDAO.updateCorrectiveActionsOfPolicy(correctiveActionsToUpdate,
previousPolicy.getId(), featureId);
}
if (!correctiveActionsToAdd.isEmpty()) {
policyDAO.addCorrectiveActionsOfPolicy(correctiveActionsToAdd,
previousPolicy.getId(), featureId);
}
if (!correctiveActionsToDelete.isEmpty()) {
policyDAO.deleteCorrectiveActionsOfPolicy(correctiveActionsToDelete,
previousPolicy.getId(), featureId);
} }
} }
for (ProfileFeature fe : existingProfileFeaturesList) {
/*for (CorrectiveAction updatedCorrectiveAction : updatedCorrectiveActions) { if (fe.getCorrectiveActions() != null && !fe.getCorrectiveActions().isEmpty()) {
if (!existingCorrectiveActionTypes.contains(updatedCorrectiveAction.getActionType())) { existingCorrectiveActionsMap.put(fe.getId(), fe.getCorrectiveActions());
correctiveActionsToAdd.add(updatedCorrectiveAction);
} }
} }
for (CorrectiveAction existingCorrectiveAction : existingCorrectiveActions) { if (payloadVersion >= 2.0f) {
if (!correctiveActionTypesToUpdate.contains(existingCorrectiveAction.getActionType())) { updateMultipleCorrectiveActions(updatedCorrectiveActionsMap,
correctiveActionsToDelete.add(existingCorrectiveAction); existingCorrectiveActionsMap, policy, previousPolicy);
} } else {
}*/ updateSingleCorrectiveActionList(policy, previousPolicy);
}
PolicyManagementDAOFactory.commitTransaction(); PolicyManagementDAOFactory.commitTransaction();
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction(); PolicyManagementDAOFactory.rollbackTransaction();
@ -392,6 +358,218 @@ public class PolicyManagerImpl implements PolicyManager {
return policy; return policy;
} }
private void updateSingleCorrectiveActionList(Policy policy, Policy previousPolicy)
throws PolicyManagerDAOException {
List<CorrectiveAction> updatedCorrectiveActions = policy.getCorrectiveActions();
List<CorrectiveAction> existingCorrectiveActions = previousPolicy.getCorrectiveActions();
List<CorrectiveAction> correctiveActionsToUpdate = new ArrayList<>();
List<CorrectiveAction> correctiveActionsToDelete = new ArrayList<>();
List<CorrectiveAction> correctiveActionsToAdd = new ArrayList<>();
List<String> correctiveActionTypesToUpdate = new ArrayList<>();
List<String> existingCorrectiveActionTypes = new ArrayList<>();
if (updatedCorrectiveActions != null) {
for (CorrectiveAction updatedCorrectiveAction : updatedCorrectiveActions) {
for (CorrectiveAction existingCorrectiveAction : existingCorrectiveActions) {
if (updatedCorrectiveAction.getActionType()
.equals(existingCorrectiveAction.getActionType())) {
correctiveActionsToUpdate.add(updatedCorrectiveAction);
existingCorrectiveActionTypes.add(updatedCorrectiveAction.getActionType());
}
}
correctiveActionTypesToUpdate.add(updatedCorrectiveAction.getActionType());
}
for (CorrectiveAction updatedCorrectiveAction : updatedCorrectiveActions) {
if (!existingCorrectiveActionTypes.contains(updatedCorrectiveAction
.getActionType())) {
correctiveActionsToAdd.add(updatedCorrectiveAction);
}
}
}
for (CorrectiveAction existingCorrectiveAction : existingCorrectiveActions) {
if (!correctiveActionTypesToUpdate.contains(existingCorrectiveAction.getActionType())) {
correctiveActionsToDelete.add(existingCorrectiveAction);
}
}
if (log.isDebugEnabled()) {
log.debug("Updating corrective actions for policy " + policy.getPolicyName() +
" having policy id " + policy.getId());
}
if (!correctiveActionsToUpdate.isEmpty()) {
try {
policyDAO.updateCorrectiveActionsOfPolicy(correctiveActionsToUpdate,
previousPolicy.getId(), -1);
} catch (PolicyManagerDAOException e) {
String msg = "Error occurred while updating corrective policies of the policy" +
" "+ previousPolicy.getId();
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
}
}
if (!correctiveActionsToAdd.isEmpty()) {
try {
policyDAO.addCorrectiveActionsOfPolicy(correctiveActionsToAdd,
previousPolicy.getId(), -1);
} catch (PolicyManagerDAOException e) {
String msg = "Error occurred while adding new corrective policies to the " +
"policy the policy " + previousPolicy.getId();
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
}
}
if (!correctiveActionsToDelete.isEmpty()) {
try {
policyDAO.deleteCorrectiveActionsOfPolicy(correctiveActionsToDelete,
previousPolicy.getId(), -1);
} catch (PolicyManagerDAOException e) {
String msg = "Error occurred while deleting corrective actions from the " +
"policy " + previousPolicy.getId();
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
}
}
}
private void updateMultipleCorrectiveActions(
Map<Integer, List<CorrectiveAction>> updatedCorrectiveActionsMap,
Map<Integer, List<CorrectiveAction>> existingCorrectiveActionsMap,
Policy policy, Policy previousPolicy) throws PolicyManagerDAOException {
Map<Integer, List<CorrectiveAction>> correctiveActionsToUpdate = new HashMap<>();
Map<Integer, List<String>> existingCorrectiveActionTypes = new HashMap<>();
Map<Integer, List<String>> correctiveActionTypesToUpdate = new HashMap<>();
Map<Integer, List<CorrectiveAction>> correctiveActionsToAdd = new HashMap<>();
Map<Integer, List<CorrectiveAction>> correctiveActionsToDelete = new HashMap<>();
for (Integer featureId : updatedCorrectiveActionsMap.keySet()) {
List<CorrectiveAction> correctiveActionListToUpdate = new ArrayList<>();
List<CorrectiveAction> updatedCorrectiveActions = updatedCorrectiveActionsMap
.get(featureId);
for (CorrectiveAction updatedCorrectiveAction : updatedCorrectiveActions) {
List<CorrectiveAction> existingCorrectiveActions = existingCorrectiveActionsMap
.get(featureId);
if (existingCorrectiveActions != null) {
for (CorrectiveAction existingCorrectiveAction : existingCorrectiveActions) {
if (existingCorrectiveAction.getActionType().equals(updatedCorrectiveAction
.getActionType())) {
correctiveActionListToUpdate.add(updatedCorrectiveAction);
List<String> existingTypes = existingCorrectiveActionTypes
.get(featureId);
if (existingTypes == null) {
existingTypes = new ArrayList<>();
}
existingTypes.add(updatedCorrectiveAction.getActionType());
existingCorrectiveActionTypes.put(featureId, existingTypes);
}
}
}
List<String> toUpdateTypes = correctiveActionTypesToUpdate.get(featureId);
if (toUpdateTypes == null) {
toUpdateTypes = new ArrayList<>();
}
toUpdateTypes.add(updatedCorrectiveAction.getActionType());
correctiveActionTypesToUpdate.put(featureId, toUpdateTypes);
}
if (!correctiveActionListToUpdate.isEmpty()) {
correctiveActionsToUpdate.put(featureId, correctiveActionListToUpdate);
}
List<String> existingTypes = existingCorrectiveActionTypes.get(featureId);
for (CorrectiveAction updatedCorrectiveAction : updatedCorrectiveActions) {
if (existingTypes == null || !existingTypes.contains(updatedCorrectiveAction
.getActionType())) {
List<CorrectiveAction> correctiveActions = correctiveActionsToAdd
.get(featureId);
if (correctiveActions == null) {
correctiveActions = new ArrayList<>();
}
correctiveActions.add(updatedCorrectiveAction);
correctiveActionsToAdd.put(featureId, correctiveActions);
}
}
}
for (Integer featureId : existingCorrectiveActionsMap.keySet()) {
List<CorrectiveAction> existingCorrectiveActions = existingCorrectiveActionsMap
.get(featureId);
List<String> actionTypesToUpdate = correctiveActionTypesToUpdate.get(featureId);
for (CorrectiveAction existingCorrectiveAction : existingCorrectiveActions) {
if (actionTypesToUpdate == null ||
!actionTypesToUpdate.contains(existingCorrectiveAction.getActionType())) {
List<CorrectiveAction> correctiveActionListToDelete = correctiveActionsToDelete
.get(featureId);
if (correctiveActionListToDelete == null) {
correctiveActionListToDelete = new ArrayList<>();
}
correctiveActionListToDelete.add(existingCorrectiveAction);
correctiveActionsToDelete.put(featureId, correctiveActionListToDelete);
}
}
}
if (log.isDebugEnabled()) {
log.debug("Updating corrective actions for policy " + policy.getPolicyName() +
" having policy id " + policy.getId());
}
if (!correctiveActionsToUpdate.isEmpty()) {
try {
for (Integer featureId : correctiveActionsToUpdate.keySet()) {
List<CorrectiveAction> correctiveActions = correctiveActionsToUpdate
.get(featureId);
policyDAO.updateCorrectiveActionsOfPolicy(correctiveActions,
previousPolicy.getId(), featureId);
}
} catch (PolicyManagerDAOException e) {
String msg = "Error occurred while updating corrective policies of the policy" +
" "+ previousPolicy.getId();
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
}
}
if (!correctiveActionsToAdd.isEmpty()) {
try {
for (Integer featureId : correctiveActionsToAdd.keySet()) {
List<CorrectiveAction> correctiveActions = correctiveActionsToAdd
.get(featureId);
policyDAO.addCorrectiveActionsOfPolicy(correctiveActions,
previousPolicy.getId(), featureId);
}
} catch (PolicyManagerDAOException e) {
String msg = "Error occurred while adding new corrective policies to the " +
"policy the policy " + previousPolicy.getId();
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
}
}
if (!correctiveActionsToDelete.isEmpty()) {
try {
for (Integer featureId : correctiveActionsToDelete.keySet()) {
List<CorrectiveAction> correctiveActions = correctiveActionsToDelete
.get(featureId);
policyDAO.deleteCorrectiveActionsOfPolicy(correctiveActions,
previousPolicy.getId(), featureId);
}
} catch (PolicyManagerDAOException e) {
String msg = "Error occurred while deleting corrective actions from the " +
"policy " + previousPolicy.getId();
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
}
}
}
@Override @Override
public boolean updatePolicyPriorities(List<Policy> policies) throws PolicyManagementException { public boolean updatePolicyPriorities(List<Policy> policies) throws PolicyManagementException {
boolean bool; boolean bool;
@ -733,14 +911,16 @@ public class PolicyManagerImpl implements PolicyManager {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
List<CorrectiveAction> correctiveActionsOfPolicy = policyDAO List<CorrectiveAction> correctiveActionsOfPolicy = policyDAO
.getCorrectiveActionsOfPolicy(policyId); .getCorrectiveActionsOfPolicy(policyId);
for (ProfileFeature profileFeature : policy.getProfile().getProfileFeaturesList()) { String policyPayloadVersion = policy.getPolicyPayloadVersion();
List<CorrectiveAction> correctiveActions = new ArrayList<>(); float payloadVersion = 0f;
for (CorrectiveAction correctiveAction : correctiveActionsOfPolicy) { if (policyPayloadVersion != null && !StringUtils.isEmpty(policyPayloadVersion)) {
if (correctiveAction.getFeatureId() == profileFeature.getId()) { payloadVersion = Float.parseFloat(policyPayloadVersion);
correctiveActions.add(correctiveAction); }
} if (payloadVersion >= 2.0f) {
} setMultipleCorrectiveActions(correctiveActionsOfPolicy, policy.getProfile());
profileFeature.setCorrectiveActions(correctiveActions); } else {
policy.setCorrectiveActions(getSingleCorrectiveAction
(correctiveActionsOfPolicy, policyId));
} }
} catch (ProfileManagementException e) { } catch (ProfileManagementException e) {
throw new PolicyManagementException("Error occurred while getting the profile related to policy ID (" + throw new PolicyManagementException("Error occurred while getting the profile related to policy ID (" +
@ -750,10 +930,14 @@ public class PolicyManagerImpl implements PolicyManager {
// } finally { // } finally {
// PolicyManagementDAOFactory.closeConnection(); // PolicyManagementDAOFactory.closeConnection();
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
throw new PolicyManagementException("Error occurred while getting the corrective " + String msg = "Error occurred while getting the corrective actions related to policy " +
"actions related to policy ID (" + policyId + ")", e); "ID (" + policyId + ")";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); String msg = "Error occurred while opening DB connection";
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
@ -1342,27 +1526,32 @@ public class PolicyManagerImpl implements PolicyManager {
} }
private void buildPolicyList(List<Policy> policyList, List<Profile> profileList) private void buildPolicyList(List<Policy> policyList, List<Profile> profileList)
throws PolicyManagerDAOException, GroupManagementException { throws PolicyManagerDAOException, GroupManagementException, PolicyManagementException {
List<CorrectiveAction> allCorrectiveActions = policyDAO.getAllCorrectiveActions();
for (Policy policy : policyList) { for (Policy policy : policyList) {
List<CorrectiveAction> correctiveActionsOfPolicy = policyDAO String policyPayloadVersion = policy.getPolicyPayloadVersion();
.getCorrectiveActionsOfPolicy(policy.getId()); float payloadVersion = 0f;
if (policyPayloadVersion != null &&
!StringUtils.isEmpty(policyPayloadVersion)) {
payloadVersion = Float.parseFloat(policyPayloadVersion);
}
for (Profile profile : profileList) { for (Profile profile : profileList) {
if (policy.getProfileId() == profile.getProfileId()) { if (policy.getProfileId() == profile.getProfileId()) {
policy.setProfile(profile); policy.setProfile(profile);
for (ProfileFeature profileFeature : profile.getProfileFeaturesList()) { if (payloadVersion >= 2.0f && PolicyManagementConstants.GENERAL_POLICY_TYPE
List<CorrectiveAction> correctiveActionList = new ArrayList<>(); .equals(policy.getPolicyType())) {
for (CorrectiveAction correctiveAction : correctiveActionsOfPolicy) { setMultipleCorrectiveActions(allCorrectiveActions, profile);
if (profileFeature.getId() == correctiveAction.getFeatureId()) {
correctiveActionList.add(correctiveAction);
}
}
profileFeature.setCorrectiveActions(correctiveActionList);
} }
} }
} }
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()));
if (payloadVersion < 2.0f && PolicyManagementConstants.GENERAL_POLICY_TYPE
.equals(policy.getPolicyType())) {
policy.setCorrectiveActions
(getSingleCorrectiveAction(allCorrectiveActions, policy.getId()));
}
List<DeviceGroupWrapper> deviceGroupWrappers = policyDAO.getDeviceGroupsOfPolicy(policy.getId()); List<DeviceGroupWrapper> deviceGroupWrappers = policyDAO.getDeviceGroupsOfPolicy(policy.getId());
if (!deviceGroupWrappers.isEmpty()) { if (!deviceGroupWrappers.isEmpty()) {
@ -1376,4 +1565,37 @@ public class PolicyManagerImpl implements PolicyManager {
} }
Collections.sort(policyList); Collections.sort(policyList);
} }
private List<CorrectiveAction> getSingleCorrectiveAction
(List<CorrectiveAction> allCorrectiveActions, int policyId) {
List<CorrectiveAction> correctiveActionsOfPolicy = new ArrayList<>();
for (CorrectiveAction correctiveAction : allCorrectiveActions) {
if (correctiveAction.getAssociatedGeneralPolicyId() != null &&
correctiveAction.getAssociatedGeneralPolicyId() == policyId) {
clearMetaDataValues(correctiveAction);
correctiveActionsOfPolicy.add(correctiveAction);
}
}
return correctiveActionsOfPolicy;
}
private void setMultipleCorrectiveActions(List<CorrectiveAction> allCorrectiveActions,
Profile profile) {
for (ProfileFeature profileFeature : profile.getProfileFeaturesList()) {
List<CorrectiveAction> correctiveActionList = new ArrayList<>();
for (CorrectiveAction correctiveAction : allCorrectiveActions) {
if (correctiveAction.getFeatureId() != null &&
profileFeature.getId() == correctiveAction.getFeatureId()) {
clearMetaDataValues(correctiveAction);
correctiveActionList.add(correctiveAction);
}
}
profileFeature.setCorrectiveActions(correctiveActionList);
}
}
private void clearMetaDataValues(CorrectiveAction correctiveAction) {
correctiveAction.setAssociatedGeneralPolicyId(null); //avoiding send in payload
correctiveAction.setFeatureId(null); //avoiding send in payload
}
} }

@ -67,6 +67,7 @@ public final class PolicyManagementConstants {
public static final String POLICY_CORRECTIVE_ACTION_TYPE = "POLICY"; public static final String POLICY_CORRECTIVE_ACTION_TYPE = "POLICY";
public static final String POLICY_FEATURE_CODE = "POLICY_ACTION"; public static final String POLICY_FEATURE_CODE = "POLICY_ACTION";
public static final String POLICY_ACTIONS = "POLICY_ACTIONS"; public static final String POLICY_ACTIONS = "POLICY_ACTIONS";
public static final String CORRECTIVE_POLICY_FEATURE_CODE = "CORRECTIVE_POLICY";
/** /**
Caller would reference the constants using PolicyManagementConstants.DEVICE_CONFIG_XML_NAME, Caller would reference the constants using PolicyManagementConstants.DEVICE_CONFIG_XML_NAME,

@ -35,6 +35,8 @@
package org.wso2.carbon.policy.mgt.core.util; package org.wso2.carbon.policy.mgt.core.util;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
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;
@ -146,13 +148,81 @@ public class PolicyManagerUtil {
policyOperation.setProfileOperations(createProfileOperations(effectiveFeatures)); policyOperation.setProfileOperations(createProfileOperations(effectiveFeatures));
if (policy.getPolicyType() != null && if (policy.getPolicyType() != null &&
PolicyManagementConstants.GENERAL_POLICY_TYPE.equals(policy.getPolicyType())) { PolicyManagementConstants.GENERAL_POLICY_TYPE.equals(policy.getPolicyType())) {
setCorrectiveActions(effectiveFeatures, policyOperation, policy); String policyPayloadVersion = policy.getPolicyPayloadVersion();
float payloadVersion = 0f;
if (policyPayloadVersion != null && !StringUtils.isEmpty(policyPayloadVersion)) {
payloadVersion = Float.parseFloat(policyPayloadVersion);
}
if (payloadVersion >= 2.0f) {
setMultipleCorrectiveActions(effectiveFeatures, policyOperation, policy);
} else {
setSingleCorrectiveAction(policy, effectiveFeatures);
}
} }
policyOperation.setPayLoad(policyOperation.getProfileOperations()); policyOperation.setPayLoad(policyOperation.getProfileOperations());
return policyOperation; return policyOperation;
} }
private static void setCorrectiveActions(List<ProfileFeature> features, /**
* This method is used for generate single corrective action set for a single policy which is
* bind to the policy payload
* @param policy regarding policy object
* @param effectiveFeatures effective feature list
* @throws PolicyTransformException when transforming of the policy have issues
*/
private static void setSingleCorrectiveAction(Policy policy, List<ProfileFeature>
effectiveFeatures) throws PolicyTransformException {
if (policy.getCorrectiveActions() != null) {
for (CorrectiveAction correctiveAction : policy.getCorrectiveActions()) {
if (PolicyManagementConstants.POLICY_CORRECTIVE_ACTION_TYPE
.equalsIgnoreCase(correctiveAction.getActionType())) {
PolicyAdministratorPoint pap = new PolicyAdministratorPointImpl();
try {
Policy correctivePolicy = pap.getPolicy(correctiveAction.getPolicyId());
if (correctivePolicy == null ||
!(PolicyManagementConstants.CORRECTIVE_POLICY_TYPE
.equalsIgnoreCase(correctivePolicy.getPolicyType()))) {
String msg = "No corrective policy was found for the policy "
+ policy.getPolicyName() + " and policy ID " + policy.getId();
log.error(msg);
throw new PolicyTransformException(msg);
} else {
List<ProfileOperation> correctiveProfileOperations =
createProfileOperations(correctivePolicy.getProfile()
.getProfileFeaturesList());
ProfileFeature correctivePolicyFeature = new ProfileFeature();
correctivePolicyFeature.setProfileId(correctivePolicy.getProfileId());
correctivePolicyFeature.setContent(new Gson()
.toJson(correctiveProfileOperations));
correctivePolicyFeature.setDeviceType(correctivePolicy
.getProfile().getDeviceType());
correctivePolicyFeature.setFeatureCode(
PolicyManagementConstants.CORRECTIVE_POLICY_FEATURE_CODE);
correctivePolicyFeature.setId(correctivePolicy.getId());
effectiveFeatures.add(correctivePolicyFeature);
}
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving corrective " +
"policy for policy " + policy.getPolicyName() + " and policy ID " +
policy.getId();
log.error(msg, e);
throw new PolicyTransformException(msg, e);
}
break;
}
}
}
}
/**
* This method is use for generate multiple corrective actions per policy which is attached
* to the feature of the policy
* @param features regarding feature list of the policy
* @param policyOperation operation list which to be sent to the device
* @param policy regarding policy
* @throws PolicyTransformException
*/
private static void setMultipleCorrectiveActions(List<ProfileFeature> features,
PolicyOperation policyOperation, Policy policy) PolicyOperation policyOperation, Policy policy)
throws PolicyTransformException { throws PolicyTransformException {
ProfileOperation correctiveProfileOperation = new ProfileOperation(); ProfileOperation correctiveProfileOperation = new ProfileOperation();
@ -190,6 +260,12 @@ public class PolicyManagerUtil {
} }
} }
/**
* This method is using for generate profile operations list which to be sent to the device.
* this method is only using multiple corrective actions
* @param correctivePolicy regarding corrective policy
* @param correctiveOperationList regarding operations list of the corrective policy
*/
private static void createCorrectiveProfileOperations(Policy correctivePolicy, private static void createCorrectiveProfileOperations(Policy correctivePolicy,
ProfileOperation correctiveOperationList) { ProfileOperation correctiveOperationList) {
ProfileOperation profileOperation = new ProfileOperation(); ProfileOperation profileOperation = new ProfileOperation();
@ -222,11 +298,13 @@ public class PolicyManagerUtil {
profileOperation.setStatus(org.wso2.carbon.device.mgt.common.operation.mgt.Operation.Status.PENDING); profileOperation.setStatus(org.wso2.carbon.device.mgt.common.operation.mgt.Operation.Status.PENDING);
profileOperation.setType(org.wso2.carbon.device.mgt.common.operation.mgt.Operation.Type.PROFILE); profileOperation.setType(org.wso2.carbon.device.mgt.common.operation.mgt.Operation.Type.PROFILE);
profileOperation.setPayLoad(feature.getContent()); profileOperation.setPayLoad(feature.getContent());
for (CorrectiveAction correctiveAction : feature.getCorrectiveActions()) { if (feature.getCorrectiveActions() != null) {
if (profileOperation.getCorrectiveActionIds() == null) { for (CorrectiveAction correctiveAction : feature.getCorrectiveActions()) {
profileOperation.setCorrectiveActionIds(new ArrayList<>()); if (profileOperation.getCorrectiveActionIds() == null) {
profileOperation.setCorrectiveActionIds(new ArrayList<>());
}
profileOperation.getCorrectiveActionIds().add(correctiveAction.getPolicyId());
} }
profileOperation.getCorrectiveActionIds().add(correctiveAction.getPolicyId());
} }
profileOperations.add(profileOperation); profileOperations.add(profileOperation);
} }

@ -182,6 +182,7 @@ DROP TABLE IF EXISTS DM_POLICY;
CREATE TABLE IF NOT EXISTS DM_POLICY ( CREATE TABLE IF NOT EXISTS DM_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT , ID INT(11) NOT NULL AUTO_INCREMENT ,
NAME VARCHAR(45) DEFAULT NULL , NAME VARCHAR(45) DEFAULT NULL ,
PAYLOAD_VERSION VARCHAR (45) DEFAULT NULL,
DESCRIPTION VARCHAR(1000) NULL, DESCRIPTION VARCHAR(1000) NULL,
TENANT_ID INT(11) NOT NULL , TENANT_ID INT(11) NOT NULL ,
PROFILE_ID INT(11) NOT NULL , PROFILE_ID INT(11) NOT NULL ,

@ -63,6 +63,7 @@ DROP TABLE IF EXISTS `WSO2CDM`.`DM_POLICY` ;
CREATE TABLE IF NOT EXISTS `WSO2CDM`.`DM_POLICY` ( CREATE TABLE IF NOT EXISTS `WSO2CDM`.`DM_POLICY` (
`ID` INT(11) NOT NULL AUTO_INCREMENT, `ID` INT(11) NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(45) NULL DEFAULT NULL, `NAME` VARCHAR(45) NULL DEFAULT NULL,
`PAYLOAD_VERSION` VARCHAR(45) NULL DEFAULT NULL,
`TENANT_ID` INT(11) NOT NULL, `TENANT_ID` INT(11) NOT NULL,
`PROFILE_ID` INT(11) NOT NULL, `PROFILE_ID` INT(11) NOT NULL,
`COMPLIANCE` VARCHAR(100) NULL, `COMPLIANCE` VARCHAR(100) NULL,
@ -212,17 +213,12 @@ CREATE TABLE IF NOT EXISTS `WSO2CDM`.`DM_POLICY_CORRECTIVE_ACTION` (
`ACTION_TYPE` VARCHAR(45) NOT NULL, `ACTION_TYPE` VARCHAR(45) NOT NULL,
`CORRECTIVE_POLICY_ID` INT(11) DEFAULT NULL, `CORRECTIVE_POLICY_ID` INT(11) DEFAULT NULL,
`POLICY_ID` INT(11) NOT NULL, `POLICY_ID` INT(11) NOT NULL,
`FEATURE_ID` INT(11) NOT NULL, `FEATURE_ID` INT(11) DEFAULT NULL,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION
FOREIGN KEY (POLICY_ID) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION_FEATURE
FOREIGN KEY (FEATURE_ID)
REFERENCES DM_PROFILE_FEATURES (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
)ENGINE = InnoDB )ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1; DEFAULT CHARACTER SET = latin1;

@ -178,6 +178,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT , ID INT(11) NOT NULL AUTO_INCREMENT ,
NAME VARCHAR(45) DEFAULT NULL , NAME VARCHAR(45) DEFAULT NULL ,
DESCRIPTION VARCHAR(1000) NULL, DESCRIPTION VARCHAR(1000) NULL,
PAYLOAD_VERSION VARCHAR (45) NULL,
TENANT_ID INT(11) NOT NULL , TENANT_ID INT(11) NOT NULL ,
PROFILE_ID INT(11) NOT NULL , PROFILE_ID INT(11) NOT NULL ,
OWNERSHIP_TYPE VARCHAR(45) NULL, OWNERSHIP_TYPE VARCHAR(45) NULL,
@ -245,17 +246,12 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION (
ACTION_TYPE VARCHAR(45) NOT NULL, ACTION_TYPE VARCHAR(45) NOT NULL,
CORRECTIVE_POLICY_ID INT(11) DEFAULT NULL, CORRECTIVE_POLICY_ID INT(11) DEFAULT NULL,
POLICY_ID INT(11) NOT NULL, POLICY_ID INT(11) NOT NULL,
FEATURE_ID INT(11) NOT NULL, FEATURE_ID INT(11) DEFAULT NULL,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION
FOREIGN KEY (POLICY_ID) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION_FEATURE
FOREIGN KEY (FEATURE_ID)
REFERENCES DM_PROFILE_FEATURES (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );

@ -229,6 +229,7 @@ IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[D
CREATE TABLE DM_POLICY ( CREATE TABLE DM_POLICY (
ID INTEGER IDENTITY(1,1) NOT NULL, ID INTEGER IDENTITY(1,1) NOT NULL,
NAME VARCHAR(45) DEFAULT NULL , NAME VARCHAR(45) DEFAULT NULL ,
PAYLOAD_VERSION VARCHAR (45) DEFAULT NULL,
DESCRIPTION VARCHAR(1000) NULL, DESCRIPTION VARCHAR(1000) NULL,
TENANT_ID INTEGER NOT NULL , TENANT_ID INTEGER NOT NULL ,
PROFILE_ID INTEGER NOT NULL , PROFILE_ID INTEGER NOT NULL ,
@ -286,17 +287,12 @@ CREATE TABLE DM_POLICY_CORRECTIVE_ACTION (
ACTION_TYPE VARCHAR(45) NOT NULL, ACTION_TYPE VARCHAR(45) NOT NULL,
CORRECTIVE_POLICY_ID INTEGER DEFAULT NULL, CORRECTIVE_POLICY_ID INTEGER DEFAULT NULL,
POLICY_ID INTEGER NOT NULL, POLICY_ID INTEGER NOT NULL,
FEATURE_ID INTEGER NOT NULL, FEATURE_ID INTEGER DEFAULT NULL,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION
FOREIGN KEY (POLICY_ID) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION_FEATURE
FOREIGN KEY (FEATURE_ID)
REFERENCES DM_PROFILE_FEATURES (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
); );

@ -212,6 +212,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY (
ID INT(11) NOT NULL AUTO_INCREMENT , ID INT(11) NOT NULL AUTO_INCREMENT ,
NAME VARCHAR(45) DEFAULT NULL , NAME VARCHAR(45) DEFAULT NULL ,
DESCRIPTION VARCHAR(1000) NULL, DESCRIPTION VARCHAR(1000) NULL,
PAYLOAD_VERSION VARCHAR (45) DEFAULT NULL,
TENANT_ID INT(11) NOT NULL , TENANT_ID INT(11) NOT NULL ,
PROFILE_ID INT(11) NOT NULL , PROFILE_ID INT(11) NOT NULL ,
OWNERSHIP_TYPE VARCHAR(45) NULL, OWNERSHIP_TYPE VARCHAR(45) NULL,
@ -282,17 +283,12 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_CORRECTIVE_ACTION (
ACTION_TYPE VARCHAR(45) NOT NULL, ACTION_TYPE VARCHAR(45) NOT NULL,
CORRECTIVE_POLICY_ID INT(11) DEFAULT NULL, CORRECTIVE_POLICY_ID INT(11) DEFAULT NULL,
POLICY_ID INT(11) NOT NULL, POLICY_ID INT(11) NOT NULL,
FEATURE_ID INT(11) NOT NULL, FEATURE_ID INT(11) DEFAULT NULL,
PRIMARY KEY (ID), PRIMARY KEY (ID),
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION
FOREIGN KEY (POLICY_ID) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID) REFERENCES DM_POLICY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION_FEATURE
FOREIGN KEY (FEATURE_ID)
REFERENCES DM_PROFILE_FEATURES (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION ON UPDATE NO ACTION
)ENGINE = InnoDB; )ENGINE = InnoDB;

@ -320,6 +320,7 @@ CREATE TABLE DM_POLICY (
ID NUMBER(10) NOT NULL , ID NUMBER(10) NOT NULL ,
NAME VARCHAR2(45) DEFAULT NULL , NAME VARCHAR2(45) DEFAULT NULL ,
DESCRIPTION VARCHAR2(1000) NULL, DESCRIPTION VARCHAR2(1000) NULL,
PAYLOAD_VERSION VARCHAR(45) DEFAULT NULL,
TENANT_ID NUMBER(10) NOT NULL , TENANT_ID NUMBER(10) NOT NULL ,
PROFILE_ID NUMBER(10) NOT NULL , PROFILE_ID NUMBER(10) NOT NULL ,
OWNERSHIP_TYPE VARCHAR2(45) NULL, OWNERSHIP_TYPE VARCHAR2(45) NULL,
@ -411,14 +412,11 @@ CREATE TABLE DM_POLICY_CORRECTIVE_ACTION (
ACTION_TYPE VARCHAR2(45) NOT NULL, ACTION_TYPE VARCHAR2(45) NOT NULL,
CORRECTIVE_POLICY_ID NUMBER(10) DEFAULT NULL, CORRECTIVE_POLICY_ID NUMBER(10) DEFAULT NULL,
POLICY_ID NUMBER(10) NOT NULL, POLICY_ID NUMBER(10) NOT NULL,
FEATURE_ID NUMBER(10) NOT NULL, FEATURE_ID NUMBER(10) DEFAULT NULL,
CONSTRAINT PK_DM_POLICY_CORRECTIVE_ACTION PRIMARY KEY (ID), CONSTRAINT PK_DM_POLICY_CORRECTIVE_ACTION PRIMARY KEY (ID),
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION
FOREIGN KEY (POLICY_ID) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID), REFERENCES DM_POLICY (ID)
CONSTRAINT FK_DM_POLICY_DM_POLICY_CORRECTIVE_ACTION_FEATURE
FOREIGN KEY (FEATURE_ID)
REFERENCES DM_PROFILE_FEATURES (ID)
) )
/ /

@ -219,15 +219,16 @@ CREATE SEQUENCE DM_POLICY_seq;
CREATE TABLE IF NOT EXISTS DM_POLICY ( CREATE TABLE IF NOT EXISTS DM_POLICY (
ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_POLICY_seq') , ID INTEGER NOT NULL DEFAULT NEXTVAL ('DM_POLICY_seq') ,
NAME VARCHAR(45) DEFAULT NULL , NAME VARCHAR(45) DEFAULT NULL ,
DESCRIPTION VARCHAR(1000) NULL, PAYLOAD_VERSION VARCHAR(45) DEFAULT NULL,
TENANT_ID INTEGER NOT NULL , DESCRIPTION VARCHAR(1000) NULL,
PROFILE_ID INTEGER NOT NULL , TENANT_ID INTEGER NOT NULL ,
OWNERSHIP_TYPE VARCHAR(45) NULL, PROFILE_ID INTEGER NOT NULL ,
COMPLIANCE VARCHAR(100) NULL, OWNERSHIP_TYPE VARCHAR(45) NULL,
PRIORITY INTEGER NOT NULL, COMPLIANCE VARCHAR(100) NULL,
ACTIVE INTEGER NOT NULL, PRIORITY INTEGER NOT NULL,
UPDATED INTEGER NULL, ACTIVE INTEGER NOT NULL,
PRIMARY KEY (ID) , UPDATED INTEGER NULL,
PRIMARY KEY (ID) ,
CONSTRAINT FK_DM_PROFILE_DM_POLICY CONSTRAINT FK_DM_PROFILE_DM_POLICY
FOREIGN KEY (PROFILE_ID ) FOREIGN KEY (PROFILE_ID )
REFERENCES DM_PROFILE (ID ) REFERENCES DM_PROFILE (ID )

Loading…
Cancel
Save