Adding test cases and fixing some logic issues and fixing the null pointer from the policy core

revert-70aa11f8
geethkokila 10 years ago
parent 149b743a2e
commit 90f8f4aab6

@ -94,7 +94,7 @@ public class PolicyManagerServiceImpl implements PolicyManagerService {
Policy policy = PolicyManagementDataHolder.getInstance().getPolicyEvaluationPoint(). Policy policy = PolicyManagementDataHolder.getInstance().getPolicyEvaluationPoint().
getEffectivePolicy(deviceIdentifier); getEffectivePolicy(deviceIdentifier);
if (policy != null) { if (policy == null) {
return null; return null;
} }
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<DeviceIdentifier>(); List<DeviceIdentifier> deviceIdentifiers = new ArrayList<DeviceIdentifier>();

@ -37,9 +37,9 @@ public interface MonitoringDAO {
*/ */
void addComplianceDetails(Map<Integer, Integer> devicePolicyMap) throws MonitoringDAOException; void addComplianceDetails(Map<Integer, Integer> devicePolicyMap) throws MonitoringDAOException;
int setDeviceAsNoneCompliance(int deviceId, int policyId) throws MonitoringDAOException; void setDeviceAsNoneCompliance(int deviceId, int policyId) throws MonitoringDAOException;
int setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException; void setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException;
void addNoneComplianceFeatures(int policyComplianceStatusId, int deviceId, List<ComplianceFeature> void addNoneComplianceFeatures(int policyComplianceStatusId, int deviceId, List<ComplianceFeature>
complianceFeatures) complianceFeatures)

@ -128,6 +128,15 @@ public class PolicyManagementDAOFactory {
e); e);
} }
} }
// if (log.isDebugEnabled()) {
// log.debug(" Print the connction : ::::::: " + currentConnection.get().toString());
// StackTraceElement[] sts = Thread.currentThread().getStackTrace();
// for (StackTraceElement st: sts) {
// log.debug(st.getClassName() + " -- " + st.getLineNumber());
//// break;
// }
// log.debug(Thread.currentThread().getStackTrace());
// }
return currentConnection.get(); return currentConnection.get();
} }

@ -29,6 +29,7 @@ import org.wso2.carbon.policy.mgt.core.dao.FeatureManagerDAOException;
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;
import org.wso2.carbon.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import org.wso2.carbon.policy.mgt.core.dao.util.PolicyManagementDAOUtil;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
@ -177,9 +178,9 @@ public class FeatureDAOImpl implements FeatureDAO {
stmt.setString(2, feature.getFeatureCode()); stmt.setString(2, feature.getFeatureCode());
stmt.setInt(3, feature.getDeviceTypeId()); stmt.setInt(3, feature.getDeviceTypeId());
if (conn.getMetaData().getDriverName().contains("H2")) { if (conn.getMetaData().getDriverName().contains("H2")) {
stmt.setObject(4, feature.getContent(), Types.JAVA_OBJECT); stmt.setBytes(4, PolicyManagerUtil.getBytes(feature.getContent()));
} else { } else {
stmt.setObject(4, feature.getContent()); stmt.setBytes(4, PolicyManagerUtil.getBytes(feature.getContent()));
} }
stmt.addBatch(); stmt.addBatch();
//Not adding the logic to check the size of the stmt and execute if the size records added is over 1000 //Not adding the logic to check the size of the stmt and execute if the size records added is over 1000
@ -198,6 +199,10 @@ public class FeatureDAOImpl implements FeatureDAO {
String msg = "Error occurred while adding the feature list to the database."; String msg = "Error occurred while adding the feature list to the database.";
log.error(msg, e); log.error(msg, e);
throw new FeatureManagerDAOException(msg, e); throw new FeatureManagerDAOException(msg, e);
} catch (IOException e) {
String msg = "Error occurred while adding the feature list to the database.";
log.error(msg, e);
throw new FeatureManagerDAOException(msg, e);
} finally { } finally {
PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys); PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
} }
@ -217,9 +222,9 @@ public class FeatureDAOImpl implements FeatureDAO {
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
for (ProfileFeature feature : features) { for (ProfileFeature feature : features) {
if (conn.getMetaData().getDriverName().contains("H2")) { if (conn.getMetaData().getDriverName().contains("H2")) {
stmt.setObject(1, feature.getContent(), Types.JAVA_OBJECT); stmt.setBytes(1, PolicyManagerUtil.getBytes(feature.getContent()));
} else { } else {
stmt.setObject(1, feature.getContent()); stmt.setBytes(1, PolicyManagerUtil.getBytes(feature.getContent()));
} }
stmt.setInt(2, profileId); stmt.setInt(2, profileId);
stmt.setString(3, feature.getFeatureCode()); stmt.setString(3, feature.getFeatureCode());
@ -232,6 +237,10 @@ public class FeatureDAOImpl implements FeatureDAO {
String msg = "Error occurred while adding the feature list to the database."; String msg = "Error occurred while adding the feature list to the database.";
log.error(msg, e); log.error(msg, e);
throw new FeatureManagerDAOException(msg, e); throw new FeatureManagerDAOException(msg, e);
} catch (IOException e) {
String msg = "Error occurred while adding the feature list to the database.";
log.error(msg, e);
throw new FeatureManagerDAOException(msg, e);
} finally { } finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null); PolicyManagementDAOUtil.cleanupResources(stmt, null);
} }
@ -313,7 +322,7 @@ public class FeatureDAOImpl implements FeatureDAO {
contentBytes = (byte[]) resultSet.getBytes("CONTENT"); contentBytes = (byte[]) resultSet.getBytes("CONTENT");
bais = new ByteArrayInputStream(contentBytes); bais = new ByteArrayInputStream(contentBytes);
ois = new ObjectInputStream(bais); ois = new ObjectInputStream(bais);
profileFeature.setContent(ois.readObject().toString()); profileFeature.setContent((Object) ois.readObject().toString());
} finally { } finally {
if (bais != null) { if (bais != null) {
try { try {

@ -78,6 +78,13 @@ public class MonitoringDAOImpl implements MonitoringDAO {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet generatedKeys = null; ResultSet generatedKeys = null;
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
if (log.isDebugEnabled()) {
log.debug("Adding the compliance details for devices and policies");
for (Map.Entry<Integer, Integer> map : devicePolicyMap.entrySet()) {
log.debug(map.getKey() + " -- " + map.getValue());
}
}
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS, ATTEMPTS, " + String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS, ATTEMPTS, " +
@ -104,7 +111,8 @@ public class MonitoringDAOImpl implements MonitoringDAO {
} }
@Override @Override
public int setDeviceAsNoneCompliance(int deviceId, int policyId) throws MonitoringDAOException { public void setDeviceAsNoneCompliance(int deviceId, int policyId) throws
MonitoringDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -112,24 +120,15 @@ public class MonitoringDAOImpl implements MonitoringDAO {
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
try { try {
conn = this.getConnection(); conn = this.getConnection();
// String query = "INSERT INTO DM_POLICY_COMPLIANCE_STATUS (DEVICE_ID, POLICY_ID, STATUS,
// LAST_FAILED_TIME, " +
// "ATTEMPTS) VALUES (?, ?, ?, ?, ?) ";
String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = 0, LAST_FAILED_TIME = ?, POLICY_ID = ?," + String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = 0, LAST_FAILED_TIME = ?, POLICY_ID = ?," +
" ATTEMPTS=0 WHERE DEVICE_ID = ?"; " ATTEMPTS=0 WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); stmt = conn.prepareStatement(query);
stmt.setTimestamp(1, currentTimestamp); stmt.setTimestamp(1, currentTimestamp);
stmt.setInt(2, policyId); stmt.setInt(2, policyId);
stmt.setInt(3, deviceId); stmt.setInt(3, deviceId);
stmt.executeUpdate(); stmt.executeUpdate();
generatedKeys = stmt.getGeneratedKeys();
if (generatedKeys.next()) {
return generatedKeys.getInt(1);
} else {
return 0;
}
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while updating the none compliance to the database."; String msg = "Error occurred while updating the none compliance to the database.";
@ -142,7 +141,7 @@ public class MonitoringDAOImpl implements MonitoringDAO {
} }
@Override @Override
public int setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException { public void setDeviceAsCompliance(int deviceId, int policyId) throws MonitoringDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -152,19 +151,19 @@ public class MonitoringDAOImpl implements MonitoringDAO {
conn = this.getConnection(); conn = this.getConnection();
String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = ?, ATTEMPTS=0, LAST_SUCCESS_TIME = ?" + String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = ?, ATTEMPTS=0, LAST_SUCCESS_TIME = ?" +
" WHERE DEVICE_ID = ?"; " WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); stmt = conn.prepareStatement(query);
stmt.setInt(1, 1); stmt.setInt(1, 1);
stmt.setTimestamp(2, currentTimestamp); stmt.setTimestamp(2, currentTimestamp);
stmt.setInt(3, deviceId); stmt.setInt(3, deviceId);
stmt.executeUpdate(); stmt.executeUpdate();
generatedKeys = stmt.getGeneratedKeys(); // generatedKeys = stmt.getGeneratedKeys();
if (generatedKeys.next()) { // if (generatedKeys.next()) {
return generatedKeys.getInt(1); // return generatedKeys.getInt(1);
} else { // } else {
return 0; // return 0;
} // }
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while deleting the none compliance to the database."; String msg = "Error occurred while deleting the none compliance to the database.";
@ -214,7 +213,7 @@ public class MonitoringDAOImpl implements MonitoringDAO {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
ComplianceData complianceData = null; ComplianceData complianceData = new ComplianceData();
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "SELECT * FROM DM_POLICY_COMPLIANCE_STATUS WHERE DEVICE_ID = ?"; String query = "SELECT * FROM DM_POLICY_COMPLIANCE_STATUS WHERE DEVICE_ID = ?";

@ -444,7 +444,7 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt.setInt(1, criterion.getId()); stmt.setInt(1, criterion.getId());
stmt.setString(2, name); stmt.setString(2, name);
stmt.setString(3, prop.getProperty(name)); stmt.setString(3, prop.getProperty(name));
stmt.setObject(4, criterion.getObjectMap()); stmt.setBytes(4, PolicyManagerUtil.getBytes(criterion.getObjectMap()));
stmt.addBatch(); stmt.addBatch();
} }
stmt.executeBatch(); stmt.executeBatch();
@ -455,6 +455,10 @@ public class PolicyDAOImpl implements PolicyDAO {
String msg = "Error occurred while inserting the criterion properties to database."; String msg = "Error occurred while inserting the criterion properties to database.";
log.error(msg, e); log.error(msg, e);
throw new PolicyManagerDAOException(msg, e); throw new PolicyManagerDAOException(msg, e);
} catch (IOException e) {
String msg = "Error occurred while inserting the criterion properties to database.";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally { } finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null); PolicyManagementDAOUtil.cleanupResources(stmt, null);
} }
@ -760,7 +764,7 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
stmt.setInt(2, policy.getId()); stmt.setInt(2, policy.getId());
stmt.setObject(3, policy); stmt.setBytes(3, PolicyManagerUtil.getBytes(policy));
stmt.setTimestamp(4, currentTimestamp); stmt.setTimestamp(4, currentTimestamp);
stmt.setTimestamp(5, currentTimestamp); stmt.setTimestamp(5, currentTimestamp);
stmt.setInt(6, tenantId); stmt.setInt(6, tenantId);
@ -771,6 +775,10 @@ public class PolicyDAOImpl implements PolicyDAO {
String msg = "Error occurred while adding the evaluated feature list to device."; String msg = "Error occurred while adding the evaluated feature list to device.";
log.error(msg, e); log.error(msg, e);
throw new PolicyManagerDAOException(msg, e); throw new PolicyManagerDAOException(msg, e);
} catch (IOException e) {
String msg = "Error occurred while adding the evaluated feature list to device.";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally { } finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null); PolicyManagementDAOUtil.cleanupResources(stmt, null);
} }
@ -816,7 +824,7 @@ public class PolicyDAOImpl implements PolicyDAO {
"APPLIED = ? WHERE DEVICE_ID = ?"; "APPLIED = ? WHERE DEVICE_ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, policy.getId()); stmt.setInt(1, policy.getId());
stmt.setObject(2, policy); stmt.setBytes(2, PolicyManagerUtil.getBytes(policy));
stmt.setTimestamp(3, currentTimestamp); stmt.setTimestamp(3, currentTimestamp);
stmt.setBoolean(4, false); stmt.setBoolean(4, false);
stmt.setInt(5, deviceId); stmt.setInt(5, deviceId);
@ -826,6 +834,10 @@ public class PolicyDAOImpl implements PolicyDAO {
String msg = "Error occurred while updating the evaluated feature list to device."; String msg = "Error occurred while updating the evaluated feature list to device.";
log.error(msg, e); log.error(msg, e);
throw new PolicyManagerDAOException(msg, e); throw new PolicyManagerDAOException(msg, e);
} catch (IOException e) {
String msg = "Error occurred while updating the evaluated feature list to device.";
log.error(msg, e);
throw new PolicyManagerDAOException(msg, e);
} finally { } finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null); PolicyManagementDAOUtil.cleanupResources(stmt, null);
} }
@ -1243,6 +1255,12 @@ public class PolicyDAOImpl implements PolicyDAO {
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
// log.debug("Logging the statement................." + stmt.toString());
// log.debug("+++++++++++++++++++++++++++++");
// log.debug(conn.toString());
// log.debug("+++++++++++++++++++++++++++++");
while (resultSet.next()) { while (resultSet.next()) {
ByteArrayInputStream bais = null; ByteArrayInputStream bais = null;
@ -1288,6 +1306,15 @@ public class PolicyDAOImpl implements PolicyDAO {
PolicyManagementDAOUtil.cleanupResources(stmt, resultSet); PolicyManagementDAOUtil.cleanupResources(stmt, resultSet);
this.closeConnection(); this.closeConnection();
} }
//
// if (policy != null && log.isDebugEnabled()) {
// log.debug("Applied policy logging details started ------------------");
// log.debug("Applied policy name " + policy.getPolicyName() + "for the device id " + deviceId);
// log.debug(policy.getCompliance());
// log.debug(policy.getId());
// log.debug(policy.getPriorityId());
// log.debug("Applied policy logging details finished....");
// }
return policy; return policy;
} }

@ -75,30 +75,42 @@ public class MonitoringManagerImpl implements MonitoringManager {
public List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, public List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier,
Object deviceResponse) throws PolicyComplianceException { Object deviceResponse) throws PolicyComplianceException {
List<ComplianceFeature> complianceFeatures; List<ComplianceFeature> complianceFeatures = new ArrayList<>();
try { try {
PolicyManagementDAOFactory.beginTransaction();
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); //policyDAO.getAppliedPolicy(device
// .getId()); // .getId());
if (policy != null) {
PolicyMonitoringService monitoringService = PolicyManagementDataHolder.getInstance(). PolicyMonitoringService monitoringService = PolicyManagementDataHolder.getInstance().
getPolicyMonitoringService(deviceIdentifier.getType()); getPolicyMonitoringService(deviceIdentifier.getType());
ComplianceData complianceData = monitoringService.checkPolicyCompliance(deviceIdentifier, ComplianceData complianceData;
// This was retrieved from database because compliance id must be present for other dao operations to
// run.
ComplianceData cmd = monitoringDAO.getCompliance(device.getId());
complianceData = monitoringService.checkPolicyCompliance(deviceIdentifier,
policy, deviceResponse); policy, deviceResponse);
complianceData.setId(cmd.getId());
complianceData.setPolicy(policy); complianceData.setPolicy(policy);
complianceFeatures = complianceData.getComplianceFeatures(); complianceFeatures = complianceData.getComplianceFeatures();
complianceData.setDeviceId(device.getId()); complianceData.setDeviceId(device.getId());
complianceData.setPolicyId(policy.getId()); complianceData.setPolicyId(policy.getId());
PolicyManagementDAOFactory.beginTransaction();
//This was added because update query below that did not return the update table primary key.
if (!complianceFeatures.isEmpty()) { if (!complianceFeatures.isEmpty()) {
int complianceId = monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId());
complianceData.setId(complianceId); monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId());
monitoringDAO.addNoneComplianceFeatures(complianceId, device.getId(), complianceFeatures); if (log.isDebugEnabled()) {
log.debug("Compliance status primary key " + complianceData.getId());
}
// complianceData.setId(cmf.getId());
monitoringDAO.addNoneComplianceFeatures(complianceData.getId(), device.getId(), complianceFeatures);
complianceDecisionPoint.validateDevicePolicyCompliance(deviceIdentifier, complianceData); complianceDecisionPoint.validateDevicePolicyCompliance(deviceIdentifier, complianceData);
List<ProfileFeature> profileFeatures = policy.getProfile().getProfileFeaturesList(); List<ProfileFeature> profileFeatures = policy.getProfile().getProfileFeaturesList();
for (ComplianceFeature compFeature : complianceFeatures) { for (ComplianceFeature compFeature : complianceFeatures) {
@ -110,12 +122,18 @@ public class MonitoringManagerImpl implements MonitoringManager {
} }
} else { } else {
int complianceId = monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId()); monitoringDAO.setDeviceAsCompliance(device.getId(), policy.getId());
complianceData.setId(complianceId); //complianceData.setId(cmf.getId());
monitoringDAO.deleteNoneComplianceData(complianceId); monitoringDAO.deleteNoneComplianceData(complianceData.getId());
} }
PolicyManagementDAOFactory.commitTransaction(); PolicyManagementDAOFactory.commitTransaction();
} else {
if (log.isDebugEnabled()) {
log.debug("There is no policy applied to this device, hence compliance monitoring was not called.");
}
}
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
try { try {
PolicyManagementDAOFactory.rollbackTransaction(); PolicyManagementDAOFactory.rollbackTransaction();
@ -220,7 +238,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
public void addMonitoringOperation(List<Device> devices) throws PolicyComplianceException { public void addMonitoringOperation(List<Device> devices) throws PolicyComplianceException {
try { try {
PolicyManagementDAOFactory.beginTransaction();
ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl(); ComplianceDecisionPoint decisionPoint = new ComplianceDecisionPointImpl();
@ -238,7 +256,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
Map<Integer, Device> deviceIdsToAddOperation = new HashMap<>(); Map<Integer, Device> deviceIdsToAddOperation = new HashMap<>();
Map<Integer, Device> deviceIdsWithExistingOperation = new HashMap<>(); Map<Integer, Device> deviceIdsWithExistingOperation = new HashMap<>();
Map<Integer, Device> inactiveDeviceIds = new HashMap<>(); Map<Integer, Device> inactiveDeviceIds = new HashMap<>();
Map<Integer, Integer> firstTimeDeviceId = new HashMap<>(); Map<Integer, Integer> firstTimeDeviceIdsWithPolicyIds = new HashMap<>();
Map<Integer, ComplianceData> tempMap = new HashMap<>(); Map<Integer, ComplianceData> tempMap = new HashMap<>();
@ -265,13 +283,23 @@ public class MonitoringManagerImpl implements MonitoringManager {
for (Device device : devices) { for (Device device : devices) {
if (!tempMap.containsKey(device.getId())) { if (!tempMap.containsKey(device.getId())) {
deviceIdsToAddOperation.put(device.getId(), device); deviceIdsToAddOperation.put(device.getId(), device);
firstTimeDeviceId.put(device.getId(), devicePolicyIdMap.get(device.getId())); firstTimeDeviceIdsWithPolicyIds.put(device.getId(), devicePolicyIdMap.get(device.getId()));
}
}
if (log.isDebugEnabled()) {
log.debug("These devices are in the system for the first time");
for (Map.Entry<Integer, Integer> map : firstTimeDeviceIdsWithPolicyIds.entrySet()) {
log.debug("First time device primary key : " + map.getKey() + " & policy id " + map.getValue());
} }
} }
PolicyManagementDAOFactory.beginTransaction();
if (!deviceIdsToAddOperation.isEmpty()) { if (!deviceIdsToAddOperation.isEmpty()) {
this.addMonitoringOperationsToDatabase(new ArrayList<>(deviceIdsToAddOperation.values())); this.addMonitoringOperationsToDatabase(new ArrayList<>(deviceIdsToAddOperation.values()));
monitoringDAO.addComplianceDetails(firstTimeDeviceId); monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds);
} }
if (!deviceIdsWithExistingOperation.isEmpty()) { if (!deviceIdsWithExistingOperation.isEmpty()) {

@ -94,11 +94,16 @@ public class PolicyManagerImpl implements PolicyManager {
if (policy.getPolicyCriterias() != null) { if (policy.getPolicyCriterias() != null) {
List<PolicyCriterion> criteria = policy.getPolicyCriterias(); List<PolicyCriterion> criteria = policy.getPolicyCriterias();
for (PolicyCriterion criterion : criteria) { for (PolicyCriterion criterion : criteria) {
if (!policyDAO.checkCriterionExists(criterion.getName())) {
Criterion cr = policyDAO.getCriterion(criterion.getName());
if (cr.getId() == 0) {
Criterion criteriaObj = new Criterion(); Criterion criteriaObj = new Criterion();
criteriaObj.setName(criterion.getName()); criteriaObj.setName(criterion.getName());
policyDAO.addCriterion(criteriaObj); policyDAO.addCriterion(criteriaObj);
criterion.setCriteriaId(criteriaObj.getId()); criterion.setCriteriaId(criteriaObj.getId());
} else {
criterion.setCriteriaId(cr.getId());
} }
} }
@ -751,11 +756,12 @@ 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); // boolean exist = policyDAO.checkPolicyAvailable(deviceId);
PolicyManagementDAOFactory.beginTransaction();
if (exist) {
Policy policySaved = policyDAO.getAppliedPolicy(deviceId); Policy policySaved = policyDAO.getAppliedPolicy(deviceId);
if (!policy.equals(policySaved)) {
PolicyManagementDAOFactory.beginTransaction();
if (policySaved != null && policySaved.getId() != 0) {
if (policy.getId() != policySaved.getId()){
policyDAO.updateEffectivePolicyToDevice(deviceId, policy); policyDAO.updateEffectivePolicyToDevice(deviceId, policy);
} }
} else { } else {

@ -34,7 +34,9 @@ import org.wso2.carbon.policy.mgt.core.dao.util.PolicyManagementDAOUtil;
import javax.sql.DataSource; import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.ObjectOutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List; import java.util.List;
@ -123,4 +125,15 @@ public class PolicyManagerUtil {
return policyOperation; return policyOperation;
} }
public static byte[] getBytes(Object obj) throws java.io.IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
byte[] data = bos.toByteArray();
return data;
}
} }

@ -59,7 +59,7 @@ public abstract class BasePolicyManagementDAOTest {
OperationManagementDAOFactory.init(dataSource); OperationManagementDAOFactory.init(dataSource);
} }
public void initiatePriviledgeCaronContext() throws Exception { public void initiatePrivilegedCaronContext() throws Exception {
if (System.getProperty("carbon.home") == null) { if (System.getProperty("carbon.home") == null) {

@ -93,13 +93,18 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
PolicyManager manager = new PolicyManagerImpl(); PolicyManager manager = new PolicyManagerImpl();
Policy policy = manager.getAppliedPolicyToDevice(identifier); Policy policy = manager.getAppliedPolicyToDevice(identifier);
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());
} else {
log.debug("Applied policy was a null object.");
}
} }
@Test(dependsOnMethods = ("testMonitorDao"))
@Test(dependsOnMethods = ("getDeviceAppliedPolicy"))
public void addComplianceOperation() throws PolicyManagementException, DeviceManagementException, public void addComplianceOperation() throws PolicyManagementException, DeviceManagementException,
PolicyComplianceException { PolicyComplianceException {
@ -131,47 +136,44 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
public void checkComplianceFromMonitoringService() throws PolicyManagementException, DeviceManagementException, public void checkComplianceFromMonitoringService() throws PolicyManagementException, DeviceManagementException,
PolicyComplianceException { PolicyComplianceException {
PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest(); PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest();
PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(), PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(),
monitoringServiceTest); monitoringServiceTest);
DeviceManagementProviderService adminService = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService adminService = new DeviceManagementProviderServiceImpl();
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); // PolicyManager policyManagerService = new PolicyManagerImpl();
List<Device> devices = adminService.getAllDevices(); List<Device> devices = adminService.getAllDevices();
for (Device device : devices) {
log.debug(device.getDeviceIdentifier());
log.debug(device.getType());
log.debug(device.getName());
}
monitoringServiceTest.notifyDevices(devices); monitoringServiceTest.notifyDevices(devices);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); PolicyManager manager = new PolicyManagerImpl();
deviceIdentifier.setId(devices.get(0).getDeviceIdentifier()); Policy policy = manager.getAppliedPolicyToDevice(identifier);
deviceIdentifier.setType(devices.get(0).getType());
Policy policy = policyManagerService.getAppliedPolicyToDevice(deviceIdentifier);
Object ob = new Object(); Object ob = new Object();
monitoringServiceTest.checkPolicyCompliance(identifier, policy, ob);
// This has to be removed, until milan sends the full request.
policy = policyManagerService.getPolicies(ANDROID).get(0);
// remove above
monitoringServiceTest.checkPolicyCompliance(deviceIdentifier, policy, ob);
// MonitoringTask task = new MonitoringTask();
// task.execute();
} }
@Test(dependsOnMethods = ("checkComplianceFromMonitoringService")) @Test(dependsOnMethods = ("checkComplianceFromMonitoringService"))
public void checkCompliance() throws DeviceManagementException, PolicyComplianceException { public void checkCompliance() throws DeviceManagementException, PolicyComplianceException, PolicyManagementException {
PolicyMonitoringServiceTest monitoringServiceTest = new PolicyMonitoringServiceTest();
PolicyManagementDataHolder.getInstance().setPolicyMonitoringService(monitoringServiceTest.getType(),
monitoringServiceTest);
DeviceManagementProviderService adminService = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService adminService = new DeviceManagementProviderServiceImpl();
List<Device> devices = adminService.getAllDevices(); List<Device> devices = adminService.getAllDevices();
@ -183,7 +185,10 @@ public class MonitoringTestCase extends BasePolicyManagementDAOTest {
MonitoringManager monitoringManager = new MonitoringManagerImpl(); MonitoringManager monitoringManager = new MonitoringManagerImpl();
monitoringManager.checkPolicyCompliance(deviceIdentifier, ob); log.debug(identifier.getId());
log.debug(identifier.getType());
monitoringManager.checkPolicyCompliance(identifier, ob);
} }
} }

@ -57,7 +57,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
public void init() throws Exception { public void init() throws Exception {
initDatSource(); initDatSource();
// System.setProperty("GetTenantIDForTest", "Super"); // System.setProperty("GetTenantIDForTest", "Super");
initiatePriviledgeCaronContext(); initiatePrivilegedCaronContext();
} }
@ -82,23 +82,26 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest {
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.");
for (Device device : devices) { for (Device device : devices) {
log.debug(device.getDeviceIdentifier() + " ----- X"); log.debug(device.getDeviceIdentifier());
} }
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() + " ----- XX"); log.debug(device.getDeviceIdentifier());
} }
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
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");
for (Device device : devices3) { for (Device device : devices3) {
log.debug(device.getDeviceIdentifier() + " ----- XXX"); log.debug(device.getDeviceIdentifier());
} }
} }

@ -18,8 +18,23 @@
--> -->
<DataSourceConfig> <DataSourceConfig>
<!-- Only of these two can be active at a given time-->
<!-- 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 -->
<!--<Url>jdbc:mysql://localhost:3306/WSO2CDM</Url>-->
<!--<DriverClassName>com.mysql.jdbc.Driver</DriverClassName>-->
<!--<userName>root</userName>-->
<!--<pwd></pwd>-->
</DataSourceConfig> </DataSourceConfig>

@ -320,6 +320,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS (
LAST_FAILED_TIME TIMESTAMP NULL, LAST_FAILED_TIME TIMESTAMP NULL,
ATTEMPTS INT NULL, ATTEMPTS INT NULL,
PRIMARY KEY (ID), PRIMARY KEY (ID),
UNIQUE INDEX DEVICE_ID_UNIQUE (DEVICE_ID ASC),
CONSTRAINT FK_POLICY_COMPLIANCE_STATUS_POLICY CONSTRAINT FK_POLICY_COMPLIANCE_STATUS_POLICY
FOREIGN KEY (POLICY_ID) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID) REFERENCES DM_POLICY (ID)

@ -306,6 +306,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS (
LAST_FAILED_TIME TIMESTAMP NULL, LAST_FAILED_TIME TIMESTAMP NULL,
ATTEMPTS INT NULL, ATTEMPTS INT NULL,
PRIMARY KEY (ID), PRIMARY KEY (ID),
UNIQUE INDEX DEVICE_ID_UNIQUE (DEVICE_ID ASC),
CONSTRAINT FK_POLICY_COMPLIANCE_STATUS_POLICY CONSTRAINT FK_POLICY_COMPLIANCE_STATUS_POLICY
FOREIGN KEY (POLICY_ID) FOREIGN KEY (POLICY_ID)
REFERENCES DM_POLICY (ID) REFERENCES DM_POLICY (ID)

Loading…
Cancel
Save