Remove attempt count incrementing logic to optimize performance

reporting
Charitha Goonetilleke 5 years ago
parent 4ff9b326b7
commit a1a313608f

@ -35,7 +35,6 @@ public class NonComplianceData {
private Timestamp lastRequestedTime; private Timestamp lastRequestedTime;
private Timestamp lastSucceededTime; private Timestamp lastSucceededTime;
private Timestamp lastFailedTime; private Timestamp lastFailedTime;
private int attempts;
private String message; private String message;
/** /**
@ -85,14 +84,6 @@ public class NonComplianceData {
this.lastFailedTime = lastFailedTime; this.lastFailedTime = lastFailedTime;
} }
public int getAttempts() {
return attempts;
}
public void setAttempts(int attempts) {
this.attempts = attempts;
}
public int getDeviceId() { public int getDeviceId() {
return deviceId; return deviceId;
} }

@ -55,7 +55,7 @@ public interface MonitoringDAO {
List<NonComplianceData> getCompliance(List<Integer> deviceIds) throws MonitoringDAOException; List<NonComplianceData> getCompliance(List<Integer> deviceIds) throws MonitoringDAOException;
List<NonComplianceData> getCompliance() throws MonitoringDAOException; Map<Integer, NonComplianceData> getCompliance() throws MonitoringDAOException;
List<ComplianceData> getAllComplianceDevices( List<ComplianceData> getAllComplianceDevices(
PaginationRequest paginationRequest, String policyId, boolean complianceStatus, boolean isPending, String fromDate, String toDate) PaginationRequest paginationRequest, String policyId, boolean complianceStatus, boolean isPending, String fromDate, String toDate)
@ -65,8 +65,4 @@ public interface MonitoringDAO {
void deleteNoneComplianceData(int policyComplianceStatusId) throws MonitoringDAOException; void deleteNoneComplianceData(int policyComplianceStatusId) throws MonitoringDAOException;
boolean updateAttempts(int deviceId, boolean reset) throws MonitoringDAOException;
void updateAttempts(List<Integer> deviceId, boolean reset) throws MonitoringDAOException;
} }

@ -49,15 +49,14 @@ public class MonitoringDAOImpl implements MonitoringDAO {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
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, " +
"LAST_REQUESTED_TIME, TENANT_ID) VALUES (?, ?, ?,?, ?, ?) "; "LAST_REQUESTED_TIME, TENANT_ID) VALUES (?, ?, ?,?, ?) ";
stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
stmt.setInt(2, policyId); stmt.setInt(2, policyId);
stmt.setInt(3, 1); stmt.setInt(3, 1);
stmt.setInt(4, 1); stmt.setTimestamp(4, currentTimestamp);
stmt.setTimestamp(5, currentTimestamp); stmt.setInt(5, tenantId);
stmt.setInt(6, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
generatedKeys = stmt.getGeneratedKeys(); generatedKeys = stmt.getGeneratedKeys();
@ -90,16 +89,15 @@ public class MonitoringDAOImpl implements MonitoringDAO {
} }
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, " +
"LAST_REQUESTED_TIME, TENANT_ID) VALUES (?, ?, ?,?, ?, ?) "; "LAST_REQUESTED_TIME, TENANT_ID) VALUES (?, ?, ?, ?, ?) ";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
for (Map.Entry<Integer, Integer> map : devicePolicyMap.entrySet()) { for (Map.Entry<Integer, Integer> map : devicePolicyMap.entrySet()) {
stmt.setInt(1, map.getKey()); stmt.setInt(1, map.getKey());
stmt.setInt(2, map.getValue()); stmt.setInt(2, map.getValue());
stmt.setInt(3, 1); stmt.setInt(3, 1);
stmt.setInt(4, 1); stmt.setTimestamp(4, currentTimestamp);
stmt.setTimestamp(5, currentTimestamp); stmt.setInt(5, tenantId);
stmt.setInt(6, tenantId);
stmt.addBatch(); stmt.addBatch();
} }
stmt.executeBatch(); stmt.executeBatch();
@ -125,17 +123,16 @@ public class MonitoringDAOImpl implements MonitoringDAO {
} }
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, " +
"LAST_REQUESTED_TIME, TENANT_ID, ENROLMENT_ID) VALUES (?, ?, ?, ?, ?, ?, ?) "; "LAST_REQUESTED_TIME, TENANT_ID, ENROLMENT_ID) VALUES (?, ?, ?, ?, ?, ?) ";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
for (PolicyDeviceWrapper wrapper : policyDeviceWrapper) { for (PolicyDeviceWrapper wrapper : policyDeviceWrapper) {
stmt.setInt(1, wrapper.getDeviceId()); stmt.setInt(1, wrapper.getDeviceId());
stmt.setInt(2, wrapper.getPolicyId()); stmt.setInt(2, wrapper.getPolicyId());
stmt.setInt(3, 1); stmt.setInt(3, 1);
stmt.setInt(4, 1); stmt.setTimestamp(4, currentTimestamp);
stmt.setTimestamp(5, currentTimestamp); stmt.setInt(5, tenantId);
stmt.setInt(6, tenantId); stmt.setInt(6, wrapper.getEnrolmentId());
stmt.setInt(7, wrapper.getEnrolmentId());
stmt.addBatch(); stmt.addBatch();
} }
stmt.executeBatch(); stmt.executeBatch();
@ -155,8 +152,8 @@ public class MonitoringDAOImpl implements MonitoringDAO {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try { try {
conn = this.getConnection(); conn = this.getConnection();
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 = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?"; "WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setTimestamp(1, currentTimestamp); stmt.setTimestamp(1, currentTimestamp);
stmt.setInt(2, policyId); stmt.setInt(2, policyId);
@ -182,7 +179,7 @@ public class MonitoringDAOImpl implements MonitoringDAO {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try { try {
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 = ?, LAST_SUCCESS_TIME = ?" +
" WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?"; " WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, 1); stmt.setInt(1, 1);
@ -260,9 +257,9 @@ public class MonitoringDAOImpl implements MonitoringDAO {
while (resultSet.next()) { while (resultSet.next()) {
complianceData.setId(resultSet.getInt("ID")); complianceData.setId(resultSet.getInt("ID"));
complianceData.setDeviceId(resultSet.getInt("DEVICE_ID")); complianceData.setDeviceId(resultSet.getInt("DEVICE_ID"));
complianceData.setEnrolmentId(resultSet.getInt("ENROLMENT_ID"));
complianceData.setPolicyId(resultSet.getInt("POLICY_ID")); complianceData.setPolicyId(resultSet.getInt("POLICY_ID"));
complianceData.setStatus(resultSet.getBoolean("STATUS")); complianceData.setStatus(resultSet.getBoolean("STATUS"));
complianceData.setAttempts(resultSet.getInt("ATTEMPTS"));
complianceData.setLastRequestedTime(resultSet.getTimestamp("LAST_REQUESTED_TIME")); complianceData.setLastRequestedTime(resultSet.getTimestamp("LAST_REQUESTED_TIME"));
complianceData.setLastSucceededTime(resultSet.getTimestamp("LAST_SUCCESS_TIME")); complianceData.setLastSucceededTime(resultSet.getTimestamp("LAST_SUCCESS_TIME"));
complianceData.setLastFailedTime(resultSet.getTimestamp("LAST_FAILED_TIME")); complianceData.setLastFailedTime(resultSet.getTimestamp("LAST_FAILED_TIME"));
@ -298,7 +295,6 @@ public class MonitoringDAOImpl implements MonitoringDAO {
complianceData.setEnrolmentId(resultSet.getInt("ENROLMENT_ID")); complianceData.setEnrolmentId(resultSet.getInt("ENROLMENT_ID"));
complianceData.setPolicyId(resultSet.getInt("POLICY_ID")); complianceData.setPolicyId(resultSet.getInt("POLICY_ID"));
complianceData.setStatus(resultSet.getBoolean("STATUS")); complianceData.setStatus(resultSet.getBoolean("STATUS"));
complianceData.setAttempts(resultSet.getInt("ATTEMPTS"));
complianceData.setLastRequestedTime(resultSet.getTimestamp("LAST_REQUESTED_TIME")); complianceData.setLastRequestedTime(resultSet.getTimestamp("LAST_REQUESTED_TIME"));
complianceData.setLastSucceededTime(resultSet.getTimestamp("LAST_SUCCESS_TIME")); complianceData.setLastSucceededTime(resultSet.getTimestamp("LAST_SUCCESS_TIME"));
complianceData.setLastFailedTime(resultSet.getTimestamp("LAST_FAILED_TIME")); complianceData.setLastFailedTime(resultSet.getTimestamp("LAST_FAILED_TIME"));
@ -314,11 +310,11 @@ public class MonitoringDAOImpl implements MonitoringDAO {
} }
@Override @Override
public List<NonComplianceData> getCompliance() throws MonitoringDAOException { public Map<Integer, NonComplianceData> getCompliance() throws MonitoringDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<NonComplianceData> complianceDataList = new ArrayList<>(); Map<Integer, NonComplianceData> complianceDataList = new HashMap<>();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -327,19 +323,19 @@ public class MonitoringDAOImpl implements MonitoringDAO {
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
NonComplianceData complianceData;
while (resultSet.next()) { while (resultSet.next()) {
NonComplianceData complianceData = new NonComplianceData(); complianceData = new NonComplianceData();
complianceData.setId(resultSet.getInt("ID")); complianceData.setId(resultSet.getInt("ID"));
complianceData.setDeviceId(resultSet.getInt("DEVICE_ID")); complianceData.setDeviceId(resultSet.getInt("DEVICE_ID"));
complianceData.setEnrolmentId(resultSet.getInt("ENROLMENT_ID")); complianceData.setEnrolmentId(resultSet.getInt("ENROLMENT_ID"));
complianceData.setPolicyId(resultSet.getInt("POLICY_ID")); complianceData.setPolicyId(resultSet.getInt("POLICY_ID"));
complianceData.setStatus(resultSet.getBoolean("STATUS")); complianceData.setStatus(resultSet.getBoolean("STATUS"));
complianceData.setAttempts(resultSet.getInt("ATTEMPTS"));
complianceData.setLastRequestedTime(resultSet.getTimestamp("LAST_REQUESTED_TIME")); complianceData.setLastRequestedTime(resultSet.getTimestamp("LAST_REQUESTED_TIME"));
complianceData.setLastSucceededTime(resultSet.getTimestamp("LAST_SUCCESS_TIME")); complianceData.setLastSucceededTime(resultSet.getTimestamp("LAST_SUCCESS_TIME"));
complianceData.setLastFailedTime(resultSet.getTimestamp("LAST_FAILED_TIME")); complianceData.setLastFailedTime(resultSet.getTimestamp("LAST_FAILED_TIME"));
complianceDataList.add(complianceData); complianceDataList.put(complianceData.getEnrolmentId(), complianceData);
} }
return complianceDataList; return complianceDataList;
} catch (SQLException e) { } catch (SQLException e) {
@ -492,68 +488,6 @@ public class MonitoringDAOImpl implements MonitoringDAO {
} }
@Override
public boolean updateAttempts(int deviceId, boolean reset) throws MonitoringDAOException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "";
if (reset) {
query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET ATTEMPTS = 0, LAST_REQUESTED_TIME = ? " +
"WHERE DEVICE_ID = ? AND TENANT_ID = ?";
} else {
query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET ATTEMPTS = ATTEMPTS + 1, LAST_REQUESTED_TIME = ? " +
"WHERE DEVICE_ID = ? AND TENANT_ID = ?";
}
stmt = conn.prepareStatement(query);
stmt.setTimestamp(1, currentTimestamp);
stmt.setInt(2, deviceId);
stmt.setInt(3, tenantId);
stmt.executeUpdate();
status = true;
} catch (SQLException e) {
throw new MonitoringDAOException("Unable to update the attempts data in database.", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public void updateAttempts(List<Integer> deviceIds, boolean reset) throws MonitoringDAOException {
Connection conn;
PreparedStatement stmt = null;
Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
conn = this.getConnection();
String query = "";
if (reset) {
query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET ATTEMPTS = 0, LAST_REQUESTED_TIME = ? " +
"WHERE DEVICE_ID = ? AND TENANT_ID = ?";
} else {
query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET ATTEMPTS = ATTEMPTS + 1, LAST_REQUESTED_TIME = ? " +
"WHERE DEVICE_ID = ? AND TENANT_ID = ?";
}
stmt = conn.prepareStatement(query);
for (int deviceId : deviceIds) {
stmt.setTimestamp(1, currentTimestamp);
stmt.setInt(2, deviceId);
stmt.setInt(3, tenantId);
stmt.addBatch();
}
stmt.executeBatch();
} catch (SQLException e) {
throw new MonitoringDAOException("Unable to update the attempts data in database.", e);
} finally {
PolicyManagementDAOUtil.cleanupResources(stmt, null);
}
}
private Connection getConnection() throws MonitoringDAOException { private Connection getConnection() throws MonitoringDAOException {
return PolicyManagementDAOFactory.getConnection(); return PolicyManagementDAOFactory.getConnection();
} }

@ -1778,13 +1778,13 @@ public class PolicyDAOImpl implements PolicyDAO {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE TENANT_ID = ?"; String query = "SELECT POLICY_ID, ENROLMENT_ID FROM DM_DEVICE_POLICY_APPLIED WHERE TENANT_ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
devicePolicyIds.put(resultSet.getInt("DEVICE_ID"), resultSet.getInt("POLICY_ID")); devicePolicyIds.put(resultSet.getInt("ENROLMENT_ID"), resultSet.getInt("POLICY_ID"));
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new PolicyManagerDAOException("Error occurred while getting the applied policy", e); throw new PolicyManagerDAOException("Error occurred while getting the applied policy", e);
@ -1805,7 +1805,7 @@ public class PolicyDAOImpl implements PolicyDAO {
try { try {
conn = this.getConnection(); conn = this.getConnection();
String query = "SELECT * FROM DM_DEVICE_POLICY_APPLIED WHERE TENANT_ID = ?"; String query = "SELECT POLICY_ID, DEVICE_ID FROM DM_DEVICE_POLICY_APPLIED WHERE TENANT_ID = ?";
stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query);
stmt.setInt(1, tenantId); stmt.setInt(1, tenantId);
resultSet = stmt.executeQuery(); resultSet = stmt.executeQuery();

@ -44,15 +44,8 @@ public interface MonitoringManager {
NonComplianceData getDevicePolicyCompliance(Device device) throws PolicyComplianceException; NonComplianceData getDevicePolicyCompliance(Device device) throws PolicyComplianceException;
void addMonitoringOperation(List<Device> devices) throws PolicyComplianceException; void addMonitoringOperation(String deviceType, List<Device> devices) throws PolicyComplianceException;
List<String> getDeviceTypes() throws PolicyComplianceException; List<String> getDeviceTypes() throws PolicyComplianceException;
PaginationResult getPolicyCompliance(
PaginationRequest paginationRequest, String policyId, boolean complianceStatus, boolean isPending,
String fromDate, String toDate) throws PolicyComplianceException;
List<ComplianceFeature> getNoneComplianceFeatures(int complianceStatusId)
throws PolicyComplianceException;
} }

@ -32,6 +32,7 @@ import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager;
import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceData; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceData;
import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
@ -58,9 +59,9 @@ import java.util.Map;
public class MonitoringManagerImpl implements MonitoringManager { public class MonitoringManagerImpl implements MonitoringManager {
private PolicyDAO policyDAO; private final PolicyDAO policyDAO;
private MonitoringDAO monitoringDAO; private final MonitoringDAO monitoringDAO;
private ComplianceDecisionPoint complianceDecisionPoint; private final ComplianceDecisionPoint complianceDecisionPoint;
private static final Log log = LogFactory.getLog(MonitoringManagerImpl.class); private static final Log log = LogFactory.getLog(MonitoringManagerImpl.class);
private static final String OPERATION_MONITOR = "MONITOR"; private static final String OPERATION_MONITOR = "MONITOR";
@ -113,6 +114,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
complianceData.setPolicy(policy); complianceData.setPolicy(policy);
complianceFeatures = complianceData.getComplianceFeatures(); complianceFeatures = complianceData.getComplianceFeatures();
complianceData.setDeviceId(device.getId()); complianceData.setDeviceId(device.getId());
complianceData.setEnrolmentId(cmd.getEnrolmentId());
complianceData.setPolicyId(policy.getId()); complianceData.setPolicyId(policy.getId());
} }
@ -121,7 +123,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
} catch (MonitoringDAOException e) { } catch (MonitoringDAOException e) {
throw new PolicyComplianceException( throw new PolicyComplianceException(
"Unable to add the none compliance features to database for device " + "Unable to add the none compliance features to database for device " +
device.getDeviceIdentifier() + " - " + device.getType(), e); deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e);
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
@ -145,7 +147,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
PolicyManagementDAOFactory.rollbackTransaction(); PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyComplianceException( throw new PolicyComplianceException(
"Unable to add the none compliance features to database for device " + "Unable to add the none compliance features to database for device " +
device.getDeviceIdentifier() + " - " + device.getType(), e); deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e);
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
@ -253,106 +255,46 @@ public class MonitoringManagerImpl implements MonitoringManager {
} }
@Override @Override
public void addMonitoringOperation(List<Device> devices) throws PolicyComplianceException { public void addMonitoringOperation(String deviceType, List<Device> devices) throws PolicyComplianceException {
//int tenantId = PolicyManagerUtil.getTenantId(); Map<Integer, Device> notifiableDeviceEnrollments = new HashMap<>();
Map<Integer, Device> deviceIds = new HashMap<>(); List<PolicyDeviceWrapper> firstTimeComplianceData = new ArrayList<>();
List<NonComplianceData> complianceDatas = new ArrayList<>();
HashMap<Integer, Integer> devicePolicyIdMap = new HashMap<>();
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
//TODO: Return a map from getCompliance to reduce O(n^2) -> O(n)
List<NonComplianceData> cd = monitoringDAO.getCompliance();
Map<Integer, NonComplianceData> persistedComplianceData = monitoringDAO.getCompliance();
HashMap<Integer, Integer> appliedPolicyIds = policyDAO.getAppliedPolicyIds();
int enrollmentId;
for (Device device : devices) { for (Device device : devices) {
deviceIds.put(device.getId(), device); enrollmentId = device.getEnrolmentInfo().getId();
if (persistedComplianceData.containsKey(enrollmentId)) {
for (NonComplianceData data : cd) { notifiableDeviceEnrollments.put(enrollmentId, device);
if (device.getId() == data.getDeviceId() && device.getEnrolmentInfo().getId() == data } else if (appliedPolicyIds.containsKey(enrollmentId)){
.getEnrolmentId()) { PolicyDeviceWrapper policyDeviceWrapper = new PolicyDeviceWrapper();
complianceDatas.add(data); policyDeviceWrapper.setDeviceId(device.getId());
} policyDeviceWrapper.setEnrolmentId(device.getEnrolmentInfo().getId());
} policyDeviceWrapper.setPolicyId(appliedPolicyIds.get(enrollmentId));
} firstTimeComplianceData.add(policyDeviceWrapper);
List<Integer> deviceIDs = new ArrayList<>(deviceIds.keySet()); notifiableDeviceEnrollments.put(enrollmentId, device);
HashMap<Integer, Integer> temp = policyDAO.getAppliedPolicyIds();
for (Integer id : deviceIDs) {
if (temp != null && !temp.isEmpty() && temp.containsKey(id)) {
devicePolicyIdMap.put(id, temp.get(id));
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e); throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e);
} catch (MonitoringDAOException e) { } catch (MonitoringDAOException e) {
throw new PolicyComplianceException("SQL error occurred while getting monitoring details.", e); throw new PolicyComplianceException("Error occurred while getting monitoring details.", e);
} catch (PolicyManagerDAOException e) { } catch (PolicyManagerDAOException e) {
throw new PolicyComplianceException("SQL error occurred while getting policy details.", e); throw new PolicyComplianceException("SQL error occurred while getting policy details.", e);
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
Map<Integer, Device> deviceIdsToAddOperation = new HashMap<>();
Map<Integer, Device> deviceIdsWithExistingOperation = new HashMap<>();
List<PolicyDeviceWrapper> firstTimeDevices = new ArrayList<>();
Map<Integer, NonComplianceData> tempMap = new HashMap<>();
try { try {
if (complianceDatas != null || !complianceDatas.isEmpty()) {
for (NonComplianceData complianceData : complianceDatas) {
tempMap.put(complianceData.getDeviceId(), complianceData);
if (complianceData.getAttempts() == 0) {
deviceIdsToAddOperation.put(complianceData.getDeviceId(),
deviceIds.get(complianceData.getDeviceId()));
} else {
deviceIdsWithExistingOperation.put(complianceData.getDeviceId(),
deviceIds.get(complianceData.getDeviceId()));
}
}
}
for (Device device : devices) {
if ((!tempMap.containsKey(device.getId())) && (devicePolicyIdMap.containsKey(device.getId()))) {
deviceIdsToAddOperation.put(device.getId(), device);
PolicyDeviceWrapper policyDeviceWrapper = new PolicyDeviceWrapper();
policyDeviceWrapper.setDeviceId(device.getId());
policyDeviceWrapper.setEnrolmentId(device.getEnrolmentInfo().getId());
policyDeviceWrapper.setPolicyId(devicePolicyIdMap.get(device.getId()));
firstTimeDevices.add(policyDeviceWrapper);
// firstTimeDeviceIdsWithPolicyIds.put(device.getId(), devicePolicyIdMap.get(device.getId()));
}
}
if (log.isDebugEnabled()) {
log.debug("These devices are in the system for the first time");
for (PolicyDeviceWrapper wrapper : firstTimeDevices) {
log.debug("First time device primary key : " + wrapper.getDeviceId() + " & policy id " +
wrapper.getPolicyId());
}
}
PolicyManagementDAOFactory.beginTransaction(); PolicyManagementDAOFactory.beginTransaction();
if (!firstTimeComplianceData.isEmpty()) {
if (!deviceIdsToAddOperation.isEmpty()) { monitoringDAO.addComplianceDetails(firstTimeComplianceData);
// monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds);
monitoringDAO.addComplianceDetails(firstTimeDevices);
monitoringDAO.updateAttempts(new ArrayList<>(deviceIdsToAddOperation.keySet()), false);
}
if (!deviceIdsWithExistingOperation.isEmpty()) {
monitoringDAO.updateAttempts(new ArrayList<>(deviceIdsWithExistingOperation.keySet()), false);
}
PolicyManagementDAOFactory.commitTransaction(); PolicyManagementDAOFactory.commitTransaction();
}
} catch (MonitoringDAOException e) { } catch (MonitoringDAOException e) {
PolicyManagementDAOFactory.rollbackTransaction(); PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyComplianceException("Error occurred from monitoring dao.", e); throw new PolicyComplianceException("Error occurred from monitoring dao.", e);
@ -363,9 +305,9 @@ public class MonitoringManagerImpl implements MonitoringManager {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
if (!deviceIdsToAddOperation.isEmpty()) { if (!notifiableDeviceEnrollments.isEmpty()) {
try { try {
this.addMonitoringOperationsToDatabase(new ArrayList<>(deviceIdsToAddOperation.values())); this.addMonitoringOperationsToDatabase(deviceType, new ArrayList<>(notifiableDeviceEnrollments.values()));
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
throw new PolicyComplianceException("Invalid Device Identifiers found.", e); throw new PolicyComplianceException("Invalid Device Identifiers found.", e);
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
@ -381,8 +323,8 @@ public class MonitoringManagerImpl implements MonitoringManager {
try { try {
//when shutdown, it sets DeviceManagementService to null, therefore need to have a null check //when shutdown, it sets DeviceManagementService to null, therefore need to have a null check
if (PolicyManagementDataHolder.getInstance().getDeviceManagementService() != null) { if (PolicyManagementDataHolder.getInstance().getDeviceManagementService() != null) {
deviceTypes = deviceTypes = PolicyManagementDataHolder.getInstance().getDeviceManagementService()
PolicyManagementDataHolder.getInstance().getDeviceManagementService().getPolicyMonitoringEnableDeviceTypes(); .getPolicyMonitoringEnableDeviceTypes();
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
throw new PolicyComplianceException("Error occurred while getting the device types.", e); throw new PolicyComplianceException("Error occurred while getting the device types.", e);
@ -436,32 +378,17 @@ public class MonitoringManagerImpl implements MonitoringManager {
return complianceFeatureList; return complianceFeatureList;
} }
private void addMonitoringOperationsToDatabase(List<Device> devices) private void addMonitoringOperationsToDatabase(String deviceType, List<Device> devices)
throws PolicyComplianceException, OperationManagementException, InvalidDeviceException { throws OperationManagementException, InvalidDeviceException {
List<DeviceIdentifier> deviceIdentifiers = this.getDeviceIdentifiersFromDevices(devices); List<DeviceIdentifier> deviceIdentifiers = this.getDeviceIdentifiersFromDevices(devices);
CommandOperation monitoringOperation = new CommandOperation(); CommandOperation monitoringOperation = new CommandOperation();
monitoringOperation.setEnabled(true); monitoringOperation.setEnabled(true);
monitoringOperation.setType(Operation.Type.COMMAND); monitoringOperation.setType(Operation.Type.COMMAND);
monitoringOperation.setCode(OPERATION_MONITOR); monitoringOperation.setCode(OPERATION_MONITOR);
// CommandOperation infoOperation = new CommandOperation(); monitoringOperation.setControl(Operation.Control.NO_REPEAT);
// infoOperation.setEnabled(true); PolicyManagementDataHolder.getInstance().getDeviceManagementService()
// infoOperation.setType(Operation.Type.COMMAND);\\ .addOperation(deviceType, monitoringOperation, deviceIdentifiers);
// infoOperation.setCode(OPERATION_INFO);
// CommandOperation appListOperation = new CommandOperation();
// appListOperation.setEnabled(true);
// appListOperation.setType(Operation.Type.COMMAND);
// appListOperation.setCode(OPERATION_APP_LIST);
//TODO: Fix this properly later adding device type to be passed in when the task manage executes "addOperations()"
String type = null;
if (deviceIdentifiers.size() > 0) {
type = deviceIdentifiers.get(0).getType();
}
DeviceManagementProviderService service = PolicyManagementDataHolder.getInstance().getDeviceManagementService();
service.addOperation(type, monitoringOperation, deviceIdentifiers);
// service.addOperation(infoOperation, deviceIdentifiers);
// service.addOperation(appListOperation, deviceIdentifiers);
} }
private List<DeviceIdentifier> getDeviceIdentifiersFromDevices(List<Device> devices) { private List<DeviceIdentifier> getDeviceIdentifiersFromDevices(List<Device> devices) {

@ -23,7 +23,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.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.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
@ -40,7 +40,7 @@ import java.util.Map;
public class MonitoringTask implements Task { public class MonitoringTask implements Task {
private static Log log = LogFactory.getLog(MonitoringTask.class); private static final Log log = LogFactory.getLog(MonitoringTask.class);
Map<String, String> properties; Map<String, String> properties;
private boolean executeForTenants = false; private boolean executeForTenants = false;
@ -83,10 +83,7 @@ public class MonitoringTask implements Task {
private boolean isPlatformExist(String deviceType) { private boolean isPlatformExist(String deviceType) {
PolicyMonitoringManager policyMonitoringManager = PolicyManagementDataHolder.getInstance() PolicyMonitoringManager policyMonitoringManager = PolicyManagementDataHolder.getInstance()
.getDeviceManagementService().getPolicyMonitoringManager(deviceType); .getDeviceManagementService().getPolicyMonitoringManager(deviceType);
if (policyMonitoringManager != null) { return policyMonitoringManager != null;
return true;
}
return false;
} }
private void executeforAllTenants() { private void executeforAllTenants() {
@ -158,13 +155,14 @@ public class MonitoringTask implements Task {
} }
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Following devices selected to send the notification for " + deviceType); log.debug("Following '" + deviceType + "' devices selected to send the notification " +
"for policy monitoring");
for (Device device : notifiableDevices) { for (Device device : notifiableDevices) {
log.debug(device.getDeviceIdentifier()); log.debug(device.getDeviceIdentifier());
} }
} }
if (!notifiableDevices.isEmpty()) { if (!notifiableDevices.isEmpty()) {
monitoringManager.addMonitoringOperation(notifiableDevices); monitoringManager.addMonitoringOperation(deviceType, notifiableDevices);
} }
} }
} }
@ -178,4 +176,5 @@ public class MonitoringTask implements Task {
log.info("No device types registered currently. So did not run the monitoring task."); log.info("No device types registered currently. So did not run the monitoring task.");
} }
} }
} }

@ -259,7 +259,7 @@ public class PolicyManagerServiceImplTest extends BasePolicyManagementDAOTest {
deviceList.add(device); deviceList.add(device);
MonitoringManager manager = new MonitoringManagerImpl(); MonitoringManager manager = new MonitoringManagerImpl();
manager.addMonitoringOperation(deviceList); manager.addMonitoringOperation(DEVICE_TYPE_A, deviceList);
policyManagerService.checkCompliance(new DeviceIdentifier(DEVICE1, DEVICE_TYPE_A), complianceFeatures); policyManagerService.checkCompliance(new DeviceIdentifier(DEVICE1, DEVICE_TYPE_A), complianceFeatures);
boolean deviceCompliance = policyManagerService.isCompliant(new DeviceIdentifier(DEVICE1, DEVICE_TYPE_A)); boolean deviceCompliance = policyManagerService.isCompliant(new DeviceIdentifier(DEVICE1, DEVICE_TYPE_A));
@ -289,7 +289,7 @@ public class PolicyManagerServiceImplTest extends BasePolicyManagementDAOTest {
deviceList.add(device); deviceList.add(device);
MonitoringManager manager = new MonitoringManagerImpl(); MonitoringManager manager = new MonitoringManagerImpl();
manager.addMonitoringOperation(deviceList); manager.addMonitoringOperation(DEVICE_TYPE_A, deviceList);
policyManagerService.checkCompliance(new DeviceIdentifier(DEVICE1, DEVICE_TYPE_A), complianceFeatures); policyManagerService.checkCompliance(new DeviceIdentifier(DEVICE1, DEVICE_TYPE_A), complianceFeatures);
boolean deviceCompliance = policyManagerService.isCompliant(new DeviceIdentifier(DEVICE1, DEVICE_TYPE_A)); boolean deviceCompliance = policyManagerService.isCompliant(new DeviceIdentifier(DEVICE1, DEVICE_TYPE_A));

@ -316,7 +316,7 @@ public class MonitoringManagerImplTest extends BasePolicyManagementDAOTest{
@Test @Test
public void testAddMonitoringOperation() throws Exception { public void testAddMonitoringOperation() throws Exception {
monitoringManager.addMonitoringOperation(deviceMgtService.getAllDevices()); monitoringManager.addMonitoringOperation(DEVICE_TYPE_E, deviceMgtService.getAllDevices());
} }
@Test @Test

Loading…
Cancel
Save